copySchema function
Copy a database to another return the opened database
Implementation
Future<Database> copySchema(
Database srcDatabase, IdbFactory dstFactory, String dstDbName) async {
// Delete the existing
await dstFactory.deleteDatabase(dstDbName);
final version = srcDatabase.version;
final schemaMeta = _SchemaMeta();
// Get schema
final storeNames = List<String>.from(srcDatabase.objectStoreNames);
if (storeNames.isNotEmpty) {
final txn = srcDatabase.transactionList(storeNames, idbModeReadOnly);
for (final storeName in storeNames) {
final store = txn.objectStore(storeName);
final storeMeta = IdbObjectStoreMeta.fromObjectStore(store);
for (final indexName in store.indexNames) {
final index = store.index(indexName);
final indexMeta = IdbIndexMeta.fromIndex(index);
storeMeta.putIndex(indexMeta);
}
schemaMeta.stores.add(storeMeta);
}
await txn.completed;
}
void openOnUpgradeNeeded(VersionChangeEvent event) {
final db = event.database;
for (final storeMeta in schemaMeta.stores) {
final store = db.createObjectStore(storeMeta.name,
keyPath: storeMeta.keyPath, autoIncrement: storeMeta.autoIncrement);
for (final indexMeta in storeMeta.indecies) {
var keyPath = indexMeta.keyPath;
store.createIndex(indexMeta.name!, keyPath,
unique: indexMeta.unique, multiEntry: indexMeta.multiEntry);
}
}
}
// devPrint('Open $dstDbName version $version');
// Open and copy scheme
final dstDatabase = await dstFactory.open(dstDbName,
version: version, onUpgradeNeeded: openOnUpgradeNeeded);
return dstDatabase;
}