How to use IndexedDB count method with composite keys? - google-chrome

I have an IDB object store "feeditems" with the keypath ["feed_id","item_id"], and inserting objects with os.put({feed_id:1,item_id:2,text:"foo"}); works fine.
Now I'd like to get a count of all feeditems where the feed_id is 13. The problem is that even the usually good MDN docs at https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore only say that the key parameter is "The key or key range that identifies the records to be counted.", yet a os.count({feed_id:13}) fails with a DataError exception "The parameter is not a valid key.".
So, how do I get the count of (and later, how do I iterate through) all the items with feed_id==x?
Note that the uniqueness is only combined for feed_id and item_id - there may very well be one entry with {feed_id:1,item_id:1} and one with {feed_id:2,item_id:1}!

You still need to index the field, feed_id, that you want to query. An then count the index. Compound index is irrelevant for this query.
var index = objectStore.index('feed_id');
var req = index.count(IDBKeyRange.only(13);

Related

I need to create a key in lua consisting of 2 IDS which I can put a check on to occur together only once. What datastructure I should use and how?

I've recently started working in lua. I'm trying to create function in which I needd to create a composite key consisting of 2 elements which should occur only once together. They can occur multiple times but with different combinations. One combination should be unique. Suggest me what data structure I should go for and how?
I'd suggest you to go with a table where your key is the actual position in the table.
as in:
my_super_duper_key = key1..key2
my_super_duper_key2 = key2..key1
if table[my_super_duper_key] == nil and table[my_super_duper_key2] == nil then
table[my_super_duper_key] = true
table[my_super_duper_key2] = true
end
If your keys are always in the same order or if it's a different key depending which is first you can throw the _key2 out of it... :)

How to get records with last dates in Django ORM(MySQL)?

I have models:
class Reference(models.Model):
name = models.CharField(max_length=50)
class Search(models.Model):
reference = models.ForeignKey(Reference)
update_time = models.DateTimeField(auto_now_add=True)
I have an instance of Reference and i need to get all last searches for the reference. Now i am doing it in this way:
record = Search.objects.filter(reference=reference)\
.aggregate(max_date=Max('update_time'))
if record:
update_time = record['max_date']
searches = reference.search_set.filter(update_time=self.update_time)
It is not a big deal to use 2 queries except the one but what if i need to get last searches for each reference on a page? I would have got 2x(count of references) queries and it would not be good.
I was trying to use this solution https://stackoverflow.com/a/9838438/293962 but it didn't work with filter by reference
You probably want to use the latest method.
From the docs, "Returns the latest object in the table, by date, using the field_name provided as the date field."
https://docs.djangoproject.com/en/1.8/ref/models/querysets/#latest
so your query would be
Search.objects.filter(reference=reference).latest('update_time')
I implemented a snippet from someone in gist but I don't remember the user neither have the link.
A bit of context:
I have a model named Medicion that contains the register of mensuration of a machine, machines are created in a model instance of Equipo, Medicion instances have besides of a Foreign key to Equipo, a foreign key to Odometro, this model serves as a kind of clock or metre, that's why when I want to retrieve data (measurements aka instances of Medicion model) for a certain machine, I need to indicate the clock as well, otherwise it would retrieve me a lot of messy and unreadable data.
Here is my implementation:
First I retrieve the last dates:
ult_fechas_reg = Medicion.objects.values('odometro').annotate(max_fecha=Max('fecha')).order_by()
Then I instance an Q object:
mega_statement = Q() # This works as 'AND' Sql Statement
Then looping in every date retrieved in the queryset(annotation) and establishing the Q statement:
for r in ult_fechas_reg:
mega_statement |= (Q(odometro__exact=r['odometro']) & Q(fecha=r['max_fecha']))
Finally passed this mega statement to the queryset that pursues to retrieve the last record of a model filtered by two fields:
resultados = Medicion.objects.filter(mega_query).filter(
equipo=equipo,
odometro__in=lista_odometros).order_by('odometro', 'fecha') # lista_odometros is a python list containing pks of another model, don't worry about it.

IndexedDB - boolean index

Is it possible to create an index on a Boolean type field?
Lets say the schema of the records I want to store is:
{
id:1,
name:"Kris",
_dirty:true
}
I created normal not unique index (onupgradeneeded):
...
store.createIndex("dirty","_dirty",{ unique: false })
...
The index is created, but it is empty! - In the index IndexedDB browser there are no records with Boolean values - only Strings, Numbers and Dates or even Arrays.
I am using Chrome 25 canary
I would like to find all records that have _dirty attribute set to true - do I have to modify _dirty to string or int then?
Yes, boolean is not a valid key.
If you must, of course you can resolve to 1 and 0.
But it is for good reason. Indexing boolean value is not informative. In your above case, you can do table scan and filter on-the-fly, rather than index query.
The answer marked as checked is not entirely correct.
You cannot create an index on a property that contains values of the Boolean JavaScript type. That part of the other answer is correct. If you have an object like var obj = {isActive: true};, trying to create an index on obj.isActive will not work and the browser will report an error message.
However, you can easily simulate the desired result. indexedDB does not insert properties that are not present in an object into an index. Therefore, you can define a property to represent true, and not define the property to represent false. When the property exists, the object will appear in the index. When the property does not exist, the object will not appear in the index.
Example
For example, suppose you have an object store of 'obj' objects. Suppose you want to create a boolean-like index on the isActive property of these objects.
Start by creating an index on the isActive property. In the onupgradeneeded callback function, use store.createIndex('isActive','isActive');
To represent 'true' for an object, simply use obj.isActive = 1;. Then add or put the object into the object store. When you want to query for all objects where isActive is set, you simply use db.transaction('store').index('isActive').openCursor();.
To represent false, simply use delete obj.isActive; and then add or or put the object into the object store.
When you query for all objects where isActive is set, these objects that are missing the isActive property (because it was deleted or never set) will not appear when iterating with the cursor.
Voila, a boolean index.
Performance notes
Opening a cursor on an index like was done in the example used here will provide good performance. The difference in performance is not noticeable with small data, but it is extremely noticeable when storing a larger amount of objects. There is no need to adopt some third party library to accomplish 'boolean indices'. This is a mundane and simple feature you can do on your own. You should try to use the native functionality as much as possible.
Boolean properties describe the exclusive state (Active/Inactive), 'On/Off', 'Enabled/Disabled', 'Yes/No'. You can use these value pairs instead of Boolean in JS data model for readability. Also this tactic allow to add other states ('NotSet', for situation if something was not configured in object, etc.)...
I've used 0 and 1 instead of boolean type.

SQL Alchemy return list of ids

I am using SQL Alchemy and I want to return a list of Document Ids. The Ids are the primary key in the documents table. My current query returns a list of tuples.
userDocs = session.query(Document.idDocument).filter(Document.User_idUser == user.idUser).all()
The reason I want a list of ids is so that I can search another table using in_(userDocs).
So another solution would be to be able to search using tuples. I am currently returning nothing from my second query using userDocs.
Thank you!!
You don't need to do an intermediate query, you can do this all in one shot!
things = session.query(Things) \
.join(Thing.documents) \
.filter(Document.User_idUser==user.idUser)
You just query on the properties of the Document through its relationship() on the intended entity.

Why do associated collections contain null values? (Hibernate, Annotation, Spring)

[Edit: Apparently, this is only an issue for arrays and FoxyBOA's answer might direct to (or even is) the answer.]
My question relates to these software: Hibernate3+Annotation, Spring MVC, MySQL and in this example also Spring Security.
I was wondering, why collections, which are automatically associated by Hibernate contain null values for each row number of the child table (besides the elements which are correct). My Example:
I have a users and an authorities table, the primary key of the users table is username which serves as foreign key. Right now, there are 13 rows in my authorities table. When I retrieve a user from the database (MySQL InnoDB) and Hibernate automatically retrieves the user's authorities corresponding to this mapping:
#OneToMany
#JoinColumn(name = "username")
#IndexColumn(name="id") // "id" was the primary key and is used to sort the elements
public Authority[] getAuthorities() {
return authorities;
}
public void setAuthorities(Authority[] authorities) {
this.authorities = authorities;
}
... I end up with a collection "authorities" containing 14 (0-13) elements of which only four are not-null (four rows in the database table belong to that specific user, so that is correct). As far as I realize, I am using Hibernate defaults for properties like Fetchmode etc. I am getting the user like this:
Criteria criteria = getSession().createCriteria(User.class);
criteria.add(Restrictions.eq("username",username));
User user = (User) criteria.uniqueResult();
The logging information from org.hibernate.loader.loader correctly "mentions" four rows for the resultset. Still, the user created has the four correct elements plus ten null values in the Array. In my specific example, this results in this exception:
java.lang.IllegalArgumentException: Granted authority element 0 is null - GrantedAuthority[] cannot contain any null elements
The answer lies in the #IndexColumn annotation. It is using the value of id as the array index, thus the number of elements in the Array is basically going to be the value of the highest ID in the Authorities table.
see the hibernate documentation on indexed collections
try removing the annotation.
Also just as a thought; have you considered using a Set for the mapping? it isn't strictly necessary, it just a bit more common form of mapping that's all.
I can recommend you check your data. If you have a missed indexes (id column in your case), then instead of missed id you'll get null in your array.
I.e.
table authorities:
username id
bob 1
bob 3
bob 5
As a result you will have an array:
{0=null, 1=bob, 2=null, 3=bob, 4=null, 5=bob}
UPDATE:
I met the situation in two cases:
Missed key values in indexed column id at authorities table (e.g. 0,1,3,4,5 - missing value 2. Hibernate will automatically add to an array value with key 2 and value null).
Indexed values are in order, but select criteria filter part of them (e.g. your HQL similar to that "from user u join u.authorities a where a.id=2". In that case hibernate load a user, but in authorities array you will have only 3 values: 0 - null, 1 - null, 2 - authority with id 2).