Database (2.x) Singleton required?

Does the Database instance have to be the same for ALL apps currently open?
Does the Database instance have to be the same within an app?

Same questioned phrase differently: Can I have multiple instances for the same db in an app and/or across all open apps?


.In the same app — definitely.

.In multiple apps — yes, except that you won’t get notifications about changes made in another process.

Just wondering… why CBL 2 does not internally ensure that the db instance is a Singleton? (since it’s a must.)

Oh, sorry, I got my reply backwards! I meant “definitely OK”, not “definitely must be a singleton”. So:

  • It’s fine to have multiple Database instances for the same physical database file. This can improve performance if you’re using the database heavily on multiple threads, for instance.
  • Opening the same database file in multiple processes is OK; however, database- and document-change notifications are not delivered cross-process, so if another process changes the database you will not be notified, and LiveQueries will not update.

Am I glad I had a question on your answer!
So that also means (just to clarify) that even with multiple instances (of the same db) within the same app, LiveQueries and document change do indeed update.
ps. If so, I guess it would also work for multiple instances of the same document as well?

Yes, and yes.

Having multiple instances of a document can be useful, especially with multiple threads. Just be aware that MVCC (multi-version concurrency control) applies to each instance. So if you create two instances of the same document, then make changes in each one and save, the second one you save will run into a conflict with the first.