Search code examples
pythonsqlitepeewee

Peewee mid-air collision detection with SQLite


I have a couple models that I want to update at the same time. First I get their data from the db with a simple:

s = Store.get(Store.id == store_id)
new_book = Book.get(Book.id == data[book_id'])
old_book = Book.get(Book.id == s.books.id)

The actual schema is irrelevant here. Then I do some updates to these models and at the end I save all three of them with:

s.save()
new_book.save()
old_book.save()

The function that handles these operations uses the @db.atomic() decorator so the writes are bunched into a single transaction. The problem is that what if, between the point where I get() the data from the DB and the point where I save the modified data, another process changed something with these models in the DB already. Is there a way to execute those writes (.save() operations) only if the underlying DB rows have not been changed? I could read their last_changed value but again, is there a way to do this and update at the same time? And if data has been changed, simply throw an exception?


Solution

  • Turns out there is a solution for this in the official docs called Optimistic Locking.