importDatabase function

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

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.

The custom types are decoded in the encoding given by the export header (type_prefix, see exportDatabaseLines), a legacy export (no type_prefix) by the database codec. options can give the stores to import (overriding storeNames) and restrict the accepted type encodings (a legacy export being SembastExportTypeEncoding.at), all are accepted by default; another one throws a FormatException.

Implementation

Future<Database> importDatabase(
  Map srcData,
  DatabaseFactory dstFactory,
  String dstPath, {
  SembastCodec? codec,
  List<String>? storeNames,
  SembastImportOptions? options,
}) async {
  storeNames = options?.storeNames ?? storeNames;
  // Checked before deleting the destination.
  var typeEncoding = sembastExportHeaderTypeEncoding(
    srcData,
    allowed: options?.allowedTypeEncodings,
  );
  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;
  var fromJsonEncodable = typeEncoding == null
      ? sembastDatabase.fromJsonEncodable
      : sembastExportTypeEncodingCodec(
          typeEncoding,
          jsonEncodableCodecAdapters(
            _databaseJsonEncodableCodec(sembastDatabase),
          ),
        ).decode;
  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, fromJsonEncodable(values[i]), key);
        }
      }
    }
  });
  return db;
}