exportDatabase function

Future<Map<String, dynamic>> exportDatabase(
  1. Database db
)

Return the data in an exported format that (can be JSONified).

Implementation

Future<Map<String, dynamic>> exportDatabase(Database db) {
  return db.transaction((txn) async {
    var export = <String, dynamic>{
      // our export signature
      _exportSignatureKey: _exportSignatureVersion,
      // the db version
      _dbVersion: db.version
    };

    final storesExport = <Map<String, dynamic>>[];

    // export all records from each store

    // Make it safe to iterate in an async way
    var sembastDatabase = (txn as SembastTransaction).database;
    var stores = List<SembastStore>.from(sembastDatabase.getCurrentStores())
      ..sort((store1, store2) => store1.name.compareTo(store2.name));
    for (var store in stores) {
      final keys = [];
      final values = [];

      final storeExport = <String, dynamic>{
        _name: store.name,
        _keys: keys,
        _values: values
      };

      for (var record in store.currentRecords) {
        keys.add(record.key);
        values.add(sembastDatabase.toJsonEncodable(record.value));
        if (sembastDatabase.cooperator.needCooperate) {
          await sembastDatabase.cooperator.cooperate();
        }
      }

      // Only add store if it has content
      if (keys.isNotEmpty) {
        storesExport.add(storeExport);
      }
    }

    if (storesExport.isNotEmpty) {
      export[_stores] = storesExport;
    }
    return export;
  });
}