copyStore function

Future copyStore(
  1. Database srcDatabase,
  2. String srcStoreName,
  3. Database dstDatabase,
  4. String dstStoreName,
)

Copy a store from a database to another existing one.

Implementation

Future copyStore(Database srcDatabase, String srcStoreName,
    Database dstDatabase, String dstStoreName) async {
  // Copy all in Memory first
  final records = <_Record>[];

  final srcTransaction = srcDatabase.transaction(srcStoreName, idbModeReadOnly);
  var store = srcTransaction.objectStore(srcStoreName);
  store.openCursor(autoAdvance: true).listen((CursorWithValue cwv) {
    records.add(_Record()
      ..key = cwv.key
      ..value = cwv.value);
  });
  await srcTransaction.completed;

  final dstTransaction =
      dstDatabase.transaction(dstStoreName, idbModeReadWrite);
  store = dstTransaction.objectStore(dstStoreName);
  // clear the existing records
  await store.clear();
  try {
    for (final record in records) {
      /// If key is set don't store the key
      if (store.keyPath != null) {
        // ignore: unawaited_futures
        store.put(record.value);
      } else {
        // ignore: unawaited_futures
        store.put(record.value, record.key);
      }
    }
  } catch (e) {
    if (isDebug) {
      idbLog(e);
    }
    rethrow;
  } finally {
    await dstTransaction.completed;
  }
}