prune method

Future<int> prune()

Removes published changes older than retention, returning how many.

The pruned position is recorded before anything is deleted, so a consumer reading while this runs is refused rather than silently reading past the rows that vanished under it.

Implementation

Future<int> prune() async {
  await _ensureReady();
  final String cutoff = _stamp(_clock().subtract(retention));
  final List<Map<String, Object?>> newest = await _records.find(
    logTable,
    where: DVFilter.all(<DVFilter>[
      DVFilter.isNotNull('change_seq'),
      DVFilter.compare('published_at', DVCompare.less, cutoff),
    ]),
    orderBy: const <DVSort>[DVSort('change_seq', descending: true)],
    limit: 1,
    fields: const <String>['change_seq'],
  );
  if (newest.isEmpty) return 0;
  final int through = _asInt(newest.first['change_seq']);
  await _records.update(
    stateTable,
    <String, Object?>{'pruned_through': through},
    where: DVFilter.all(<DVFilter>[
      DVFilter.equals('id', _stateId),
      DVFilter.compare('pruned_through', DVCompare.less, through),
    ]),
  );
  return _records.delete(
    logTable,
    where: DVFilter.all(<DVFilter>[
      DVFilter.isNotNull('change_seq'),
      DVFilter.compare('change_seq', DVCompare.lessOrEqual, through),
    ]),
  );
}