Search code examples
databaseflutternosqlsembast

Is it okay to use multiple concurrent read/write operations on the same database file but with different stores in Sembast?


My app has profile and work databases (and others) stored locally using Sembast DB. Please look at the two examples below, which one is a better practice for asynchronous processes?

Example 1:

final profileDBPath = p.join(appDocumentDir.path, dbDirectory, 'profile.db');
final profileDB = await databaseFactoryIo.openDatabase(profileDBPath);

final workDBPath = p.join(appDocumentDir.path, dbDirectory, 'work.db');
final workDB = await databaseFactoryIo.openDatabase(workDBPath);

final workStore = stringMapStoreFactory.store('work');
final profileStore = stringMapStoreFactory.store('profile');

Example 2:

final dbPath = p.join(appDocumentDir.path, dbDirectory, 'database.db');

final database = await databaseFactoryIo.openDatabase(dbPath);

final workStore = stringMapStoreFactory.store('work');
final profileStore = stringMapStoreFactory.store('profile');

So notice that Example 1 is opening two different database files for each profile and work. And Example 2 is using the same database file for both.

The question is which one is better in terms of stability? For coding simplicity I like Example 2 better but my worry is when in an Async operation Example 2 will crash when they write on the same file at the same time. Any ideas?

Thank you


Solution

  • Example 2 will crash when they write on the same file at the same time

    I don't know if that is something your experiment or just an assumption. Sembast database supports multiple concurrent readers and a single writer (single process and single isolate) and will properly use a kind of mutex to ensure data consistency. Concurrent writes will be serialized and should not trigger any crash. And if it does, that's bug that you should fill!

    Personally, I would go for a single database, it would allow cross stores transaction for data consistency that 2 databases cannot provide.