tekartik / sembast.dart

Simple io database
BSD 2-Clause "Simplified" License
780 stars 64 forks source link

Store record with custom key #379

Closed nutella closed 2 months ago

nutella commented 4 months ago

I've code like this (repeated for about 10 records):

await dbCateg.record(42).add(db, {'key': 42, 'order': 2, 'name': 'Pencil', 'isActive': false});

The keys are not sequential.

The records are stored correctly but... if I use Chrome dev tools, I see that in the IndexDB tab, the Primary key for the first record is 1 and not 42 as specified in the record(). Even more, if I read the records into a list, then if I'll try to access the "position" 42, I got the error "Index out of range".

What's wrong? Where is my error?

Thanks.

alextekartik commented 4 months ago

if I use Chrome dev tools, I see that in the IndexDB tab, the Primary key for the first record is 1 and not 42 as specified in the record()

sembast manages the key itself on top of indexeddb (all records are store in a single database so 2 records in two different stores can have the same sembast primary key but a different indexeddb key)

Even more, if I read the records into a list, then if I'll try to access the "position" 42

Indeed if the list is smaller than 42 items (you said the keys are not sequential) it will crash if you try to access it at this index.

You should either

// Get the record by key
var record = await dbCateg.record(42).get(db);

or

// Read all records
var records = await dbCateg.find(db);
// find record with key 42
var record42 = records.firstWhere((element) => element.key == 42);