Skip to content

Commit cd409ef

Browse files
committed
docs: Better document transactions
1 parent 3c5bba4 commit cd409ef

File tree

1 file changed

+37
-3
lines changed

1 file changed

+37
-3
lines changed

docs/api/index.rst

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -108,12 +108,46 @@ The most common way to use transactions is through an ``async with`` statement:
108108

109109
.. code-block:: python
110110
111-
with connection.transaction():
112-
connection.execute("INSERT INTO mytable VALUES(1, 2, 3)")
111+
async with connection.transaction():
112+
await connection.execute("INSERT INTO mytable VALUES(1, 2, 3)")
113113
114114
115115
asyncpg supports nested transactions (a nested transaction context will create
116-
a `savepoint`_.)
116+
a `savepoint`_.):
117+
118+
.. code-block:: python
119+
120+
async with connection.transaction():
121+
await connection.execute('CREATE TABLE mytab (a int)')
122+
123+
try:
124+
# Create a nested transaction:
125+
async with connection.transaction():
126+
await connection.execute('INSERT INTO mytab (a) VALUES (1), (2)')
127+
# This nested transaction will be automatically rolled back:
128+
raise Exception
129+
except:
130+
# Ignore exception
131+
pass
132+
133+
# Because the nested transaction was rolled back, there
134+
# will be nothing in `mytab`.
135+
assert await connection.fetch('SELECT a FROM mytab') == []
136+
137+
Alternatively, transactions can be used without an ``async with`` block:
138+
139+
.. code-block:: python
140+
141+
tr = connection.transaction()
142+
await tr.start()
143+
try:
144+
...
145+
except:
146+
await tr.rollback()
147+
raise
148+
finally:
149+
await tr.commit()
150+
117151
118152
.. _savepoint: https://www.postgresql.org/docs/current/static/sql-savepoint.html
119153

0 commit comments

Comments
 (0)