getCrudBatch method

Future<CrudBatch?> getCrudBatch({
  1. dynamic limit = 100,
})

Get a batch of crud data to upload.

Returns null if there is no data to upload.

Use this from the PowerSyncBackendConnector.uploadData` callback.

Once the data have been successfully uploaded, call CrudBatch.complete before requesting the next batch.

Use limit to specify the maximum number of updates to return in a single batch.

This method does include transaction ids in the result, but does not group data by transaction. One batch may contain data from multiple transactions, and a single transaction may be split over multiple batches.

Implementation

Future<CrudBatch?> getCrudBatch({limit = 100}) async {
  final rows = await getAll(
      'SELECT id, tx_id, data FROM ps_crud ORDER BY id ASC LIMIT ?',
      [limit + 1]);
  List<CrudEntry> all = [for (var row in rows) CrudEntry.fromRow(row)];

  var haveMore = false;
  if (all.length > limit) {
    all.removeLast();
    haveMore = true;
  }
  if (all.isEmpty) {
    return null;
  }
  final last = all[all.length - 1];
  return CrudBatch(
      crud: all,
      haveMore: haveMore,
      complete: ({String? writeCheckpoint}) async {
        await writeTransaction((db) async {
          await db
              .execute('DELETE FROM ps_crud WHERE id <= ?', [last.clientId]);
          if (writeCheckpoint != null &&
              await db.getOptional('SELECT 1 FROM ps_crud LIMIT 1') == null) {
            await db.execute(
                'UPDATE ps_buckets SET target_op = $writeCheckpoint WHERE name=\'\$local\'');
          } else {
            await db.execute(
                'UPDATE ps_buckets SET target_op = $maxOpId WHERE name=\'\$local\'');
          }
        });
      });
}