importDatabase function

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

Import the exported data (using exportDatabase) into a new database

An optional storeNames can specify the list of stores to import. If null All stores are exported.

If a codec was used, you must specify the same codec for import.

Implementation

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

  // check signature
  _checkMeta(srcData);

  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;

        // Filter store
        if (storeNames != null) {
          if (!storeNames.contains(storeName)) {
            continue;
          }
        }

        final keys = (storeExport[_keys] as Iterable).toList(growable: false);
        final values = List<Object>.from(storeExport[_values] as Iterable);

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