importDatabase function

Future<Database> importDatabase(
  1. Map srcData,
  2. DatabaseFactory dstFactory,
  3. String dstPath,
  4. {SembastCodec codec}
)

Import the exported data into a new database

Implementation

Future<Database> importDatabase(
    Map srcData, DatabaseFactory dstFactory, String dstPath,
    {SembastCodec codec}) async {
  await dstFactory.deleteDatabase(dstPath);

  // check signature
  if (srcData[_exportSignatureKey] != _exportSignatureVersion) {
    throw const FormatException('invalid export format');
  }

  final version = srcData[_dbVersion] as int;

  final db = await dstFactory.openDatabase(dstPath,
      version: version, mode: DatabaseMode.empty, codec: codec);
  var sembastDatabase = db as SembastDatabase;
  await db.transaction((txn) async {
    final storesExport =
        (srcData[_stores] as Iterable)?.toList(growable: false)?.cast<Map>();
    if (storesExport != null) {
      for (var storeExport in storesExport) {
        final storeName = storeExport[_name] as String;

        final keys = (storeExport[_keys] as Iterable)?.toList(growable: false);
        final values =
            (storeExport[_values] as Iterable)?.toList(growable: false);

        var store =
            (txn as SembastTransaction).getSembastStore(StoreRef(storeName));
        for (var i = 0; i < keys.length; i++) {
          await store.txnPut(txn as SembastTransaction,
              sembastDatabase.fromJsonEncodable(values[i]), keys[i]);
        }
      }
    }
  });
  return db;
}