batch method
Runs statements inside a batch.
A batch can only run a subset of statements, and those statements must be called on the Batch instance. The statements aren't executed with a call to Batch. Instead, all generated queries are queued up and are then run and executed atomically in a transaction. If batch is called outside of a transaction call, it will implicitly start a transaction. Otherwise, the batch will re-use the transaction, and will have an effect when the transaction completes. Typically, running bulk updates (so a lot of similar statements) over a Batch is much faster than running them via the GeneratedDatabase directly.
An example that inserts users in a batch:
await batch((b) {
b.insertAll(
todos,
[
TodosCompanion.insert(content: 'Use batches'),
TodosCompanion.insert(content: 'Have fun'),
],
);
});
Each statement added to a batch is represented as a BatchedStatement instance. By using BatchedStatement.resolveResult, results of that statement can be resolved after running it:
late BatchedStatement statement;
late ReturningClause returning;
final results = await db.batch((b) {
final stmt = db.insert(db.table).values(...).returningAll();
returning = statement.returning!
statement = b.addStatement(stmt);
});
final rawResults = statement.resolveResult(results);
final rows = returning.interpretResults(db, rawResults, db.table);
Implementation
Future<BatchResult> batch(
FutureOr<void> Function(Batch batch) runInBatch,
) async {
final batch = createBatch(this);
await Future(() => runInBatch(batch));
return await runBatch(batch);
}