Skip to content

Commit

Permalink
add a full example for lock_rows
Browse files Browse the repository at this point in the history
  • Loading branch information
dantownsend committed Sep 24, 2024
1 parent d3d0d30 commit 9467248
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 2 deletions.
35 changes: 35 additions & 0 deletions docs/src/piccolo/query_clauses/lock_rows.rst
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,41 @@ Using ``of``, you can specify which tables should be locked.
await Band.select().where(Band.manager.name == 'Guido').lock_rows('UPDATE', of=(Band, ))
-------------------------------------------------------------------------------

Full example
------------

If we have this table:

.. code-block:: python
class Concert(Table):
name = Varchar()
tickets_available = Integer()
And we want to make sure that ``tickets_available`` never goes below 0, we can
do the following:

.. code-block:: python
async def book_tickets(ticket_count: int):
async with Concert._meta.db.transaction():
concert = await Concert.objects().where(
Concert.name == "Awesome Concert"
).first().lock_rows()
if concert.tickets_available >= ticket_count:
await concert.update_self({
Concert.tickets_available: Concert.tickets_available - ticket_count
})
else:
raise ValueError("Not enough tickets are available!")
This means that when multiple transactions are running at the same time, it
isn't possible to book more tickets than are available.

-------------------------------------------------------------------------------

Learn more
----------
Expand Down
2 changes: 1 addition & 1 deletion docs/src/piccolo/query_types/objects.rst
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,7 @@ limit
See :ref:`limit`.

lock_rows
~~~~~~~~
~~~~~~~~~

See :ref:`lock_rows`.

Expand Down
2 changes: 1 addition & 1 deletion docs/src/piccolo/query_types/select.rst
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,7 @@ See :ref:`limit`.


lock_rows
~~~~~~~~
~~~~~~~~~

See :ref:`lock_rows`.

Expand Down

0 comments on commit 9467248

Please sign in to comment.