-
Hi, I read this specific feature:
But came across I am managing long-lived isolates on my own for specific use-cases such as http, websocket and sqlite. So, how can I synchronously access the database inside these isolates? I do not need any cross-isolate communication. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
You can use sqlite_async.dart/lib/src/sqlite_database.dart Lines 156 to 164 in 08495cf The factory then has a method sqlite_async.dart/lib/src/isolate_connection_factory.dart Lines 46 to 58 in 08495cf The caveat is that you don't get automatic transaction locking (relevant for writes), and don't get automatic notification of updates to other connections - it is effectively the same as opening a sqlite3 connection directly in the Isolate. You'll have to directly use the Transaction locking: If you don't use global transaction locks in every connection, it will fall back to the SQLite file-level locks. These will cause "SQLite database is locked"-style errors when attempting to create a write transaction (or any write statement) in multiple connections at the same time, instead of waiting for the other transaction to complete. You can handle these by retrying the transaction (will need the retry logic on both sides), or by using the mutex on the factory for locking (requires async code). Note that since we're using WAL mode, locks are not required for read queries/transactions. Update notifications: This is what is used for the We do something similar as part of the PowerSync SDK. The logic is scattered between other code, but you can see some relevant parts here: Spawning a new Isolate with a factory: Opening the connection: Getting a lock for write transactions: Transaction wrapper for the synchronous connection: Propagating update notifications to the upstream database: As you can see, it is unfortunately still quite a bit of messy code if you want to preserve the transaction locking and especially update notifications. If there is demand, we can add those as helper functions in this library. |
Beta Was this translation helpful? Give feedback.
You can use
db.isolateConnectionFactory()
to get a "factory" object to send over to different isolates, which allows you to open a connection in them:sqlite_async.dart/lib/src/sqlite_database.dart
Lines 156 to 164 in 08495cf
The factory then has a method
IsolateConnectionFactory.openRawDatabase()
that opens a synchronous connection: