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();
  // Not awaited one by one, all the puts are queued at once.
  final puts = <Future<Object>>[];
  try {
    for (final record in records) {
      /// If key is set don't store the key
      if (store.keyPath != null) {
        puts.add(store.put(record.value));
      } else {
        puts.add(store.put(record.value, record.key));
      }
    }
    await Future.wait(puts);
  } catch (e) {
    if (isDebug) {
      idbLog(e);
    }
    // The other put errors (the abort ones) are not reported.
    for (final put in puts) {
      put.ignore();
    }
    // The transaction abort error would hide the put error.
    try {
      await dstTransaction.completed;
    } catch (_) {}
    rethrow;
  }
  await dstTransaction.completed;
}