Attaching two databases? #1151
-
Hello We are using two databases for performance purposes. attach 'database1.db' as db1;
attach 'database2.db' as db2; If it's not possible I still can achieve it in pure SQL, but how can I use one of the referenced database using Moor? SELECT * FROM db2.table_name If that's really not possible, our last chance is to use a single database and to open two differents Isolates on the same database. But an alert message says the database may be corrupted when I try. Scary. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
@alexiswbr I had the requirement of attaching long ago and I solved it with the following. const Set<Type> kSchemaEntitiesToIgnore = {
AttachedDbTable1,
AttachedDbTable2,
};
Future<void> createAllSchemaEntities(Migrator m) async {
for (final entity in allSchemaEntities) {
if (kSchemaEntitiesToIgnore.contains(entity.runtimeType)) {
continue;
}
if (entity is TableInfo) {
await m.createTable(entity);
} else if (entity is Trigger) {
await m.createTrigger(entity);
} else if (entity is Index) {
await m.createIndex(entity);
} else if (entity is OnCreateQuery) {
await customStatement(entity.sql, const <Object>[]);
} else {
throw AssertionError('Unknown entity: $entity');
}
}
}
} Then for the attachment itself you probably have it figured out already. The only gotcha I had is that I have to try to detach it before attaching so that it plays nice with Hot Restarts Future<void> _attachToDb() async {
try {
// Detach database before attaching it, otherwise it can fail on attaching.
// For example in a Hot Restart
await customStatement("DETACH DATABASE 'attachedDb'");
} catch (e) {
// Ignore, it fails if it is not attached (first time open)
}
await customStatement("ATTACH DATABASE '/dbpath' AS attachedDb;");
} I have been using that for quite some time without any issues. Hope that works for you! I think it may be too niche for a feature on moor, but somehow there are times where @simolus3 is able to impress us all 😄 |
Beta Was this translation helpful? Give feedback.
@alexiswbr I had the requirement of attaching long ago and I solved it with the following.
Moor creates the tables for you when you define the DataClasses or moor files in your app, so what I did is make moor ignore the creation of the entities that belong to the attached database.
So instead of doing
migrator.createAll()
I have the following method, which is equivalent: