merge method
Merge changeset
with the local dataset.
Implementation
@override
Future<void> merge(CrdtChangeset changeset) async {
if (changeset.recordCount == 0) return;
// Ensure all incoming tables exist in local dataset
final badTables = changeset.keys.toSet().difference(tables);
if (badTables.isNotEmpty) {
throw 'Unknown table(s): ${badTables.join(', ')}';
}
// Ignore empty records
changeset.removeWhere((_, records) => records.isEmpty);
// Validate changeset and get new canonical time
final hlc = validateChangeset(changeset);
final newRecords = <String, Map<String, Record>>{};
for (final entry in changeset.entries) {
final table = entry.key;
for (final record in entry.value) {
final existing = getRecord(table, record['key'] as String);
if (existing == null || record['hlc'] as Hlc > existing.hlc) {
newRecords[table] ??= {};
newRecords[table]![record['key'] as String] = Record(
record['value'],
record['is_deleted'] as bool,
record['hlc'] as Hlc,
hlc,
);
}
}
}
// Write new records
await putRecords(newRecords);
onDatasetChanged(changeset.keys, hlc);
}