-
Hi, I am developing an application which needs to store data in multiple different instances of a database to handle multiple accounts, sometimes accessing both databases simultaneously. Currently, I have one isolate per database, but I am wondering if it is possible to just use a single isolate, with all databases on the same isolate? thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
This is what I came up with. It uses unreleased drift APIs to cleanup unused servers, you'd have to remove the final class MultiDatabaseServer {
final Map<String, DriftIsolate> _activeIsolates = {};
final ReceivePort _receiveConnections = ReceivePort();
MultiDatabaseServer() {
_receiveConnections.listen((message) {
if (message is (String, SendPort)) {
final name = message.$1;
final isolate = _activeIsolates.putIfAbsent(
name,
() {
return DriftIsolate.inCurrent(
// obviously you can pass a path instead of a name and use that to open the right NativeDatabase
() => NativeDatabase.memory(
setup: (db) => db.createFunction(
functionName: 'db_name',
function: (args) => name,
)),
beforeShutdown: () {
_activeIsolates.remove(name);
},
shutdownAfterLastDisconnect: true,
);
},
);
message.$2.send(isolate.connectPort);
}
});
}
}
Future<DatabaseConnection> connect(SendPort port, String databaseName) async {
final response = ReceivePort();
port.send((databaseName, response.sendPort));
final connectPort = await response.first as SendPort;
return DriftIsolate.fromConnectPort(connectPort, serialize: false).connect();
} You can then use this to connect different databases to that isolate ( Future<void> main() async {
final receiveConnectPort = ReceivePort();
Isolate.spawn((SendPort port) {
final server = MultiDatabaseServer();
port.send(server._receiveConnections.sendPort);
}, receiveConnectPort.sendPort);
final connectToServer = await receiveConnectPort.first as SendPort;
final db1 = Database(await connect(connectToServer, 'one'));
final db2 = Database(await connect(connectToServer, 'two'));
print((await db1.customSelect('SELECT db_name()').getSingle()).data);
print((await db2.customSelect('SELECT db_name()').getSingle()).data);
} |
Beta Was this translation helpful? Give feedback.
This is what I came up with. It uses unreleased drift APIs to cleanup unused servers, you'd have to remove the
beforeShutdown
andshutdownAfterLastDisconnect
parameters before drift 2.20 is out (hopefully soon):