purgeSynced method

  1. @override
Future<int> purgeSynced(
  1. String table, {
  2. DateTime? olderThan,
  3. int? keepLatest,
})
override

Hard-removes synced rows from table to bound the local cache, returning the number removed.

  • olderThan: only purge synced rows whose updated_at is before this.
  • keepLatest: always retain the keepLatest most-recently-updated synced rows, purging older synced ones.

With both null this is a no-op (a policy must be given).

Implementation

@override
Future<int> purgeSynced(
  String table, {
  DateTime? olderThan,
  int? keepLatest,
}) async {
  if (olderThan == null && keepLatest == null) return 0;
  final rows = _tables[table];
  if (rows == null) return 0;

  int updatedAt(Map<String, dynamic> r) =>
      (r[SyncColumns.updatedAt] as int?) ?? 0;
  bool synced(Map<String, dynamic> r) =>
      r[SyncColumns.isSynced] == 1 || r[SyncColumns.syncStatus] == 'synced';

  final syncedRows = rows.entries.where((e) => synced(e.value)).toList()
    ..sort((a, b) => updatedAt(b.value).compareTo(updatedAt(a.value)));
  final protected = keepLatest == null
      ? const <String>{}
      : syncedRows.take(keepLatest).map((e) => e.key).toSet();
  final cutoff = olderThan?.toUtc().millisecondsSinceEpoch;

  var removed = 0;
  for (final e in syncedRows) {
    if (protected.contains(e.key)) continue;
    if (cutoff != null && updatedAt(e.value) >= cutoff) continue;
    rows.remove(e.key);
    removed++;
  }
  return removed;
}