Do you need to do batches as a transaction?

Updating a collection of rows can be done WAY more quickly using the anvil.tables.batch_update context manager.

If I use this, are those updates automatically done as a single transaction, or should I still include the transaction context manager if I care about an all or nothing write?

my_changes = {
    row_1: {"field_a": "new_value"}, 
    row_2: {"field_b": "some_other_value"
}
with tables.Transaction(): # does this do anything?
    with anvil.tables.batch_update:
         for row, changes in my_changes.items():
              row.update(**changes)

My guess is that you need to define an explicit transaction that starts and ends when you decide it.

I may want multiple batch operations in the same transaction, and I wouldn’t want each to automatically open its own transaction, savepoint or whatever it is, when I have an easy way to explicitly wrap them.

1 Like

Hi Dan.

I think that this forum thread, between @hugetim, @meredydd, and @stucork a couple years ago, implies an answer (yes, you’d need to use a context manager to treat batch updates as a single, all-or-nothing transaction) and provides additional info with respect to implementation.

2 Likes