File tree Expand file tree Collapse file tree 1 file changed +37
-3
lines changed Expand file tree Collapse file tree 1 file changed +37
-3
lines changed Original file line number Diff line number Diff line change @@ -108,12 +108,46 @@ The most common way to use transactions is through an ``async with`` statement:
108
108
109
109
.. code-block :: python
110
110
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)" )
113
113
114
114
115
115
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
+
117
151
118
152
.. _savepoint : https://www.postgresql.org/docs/current/static/sql-savepoint.html
119
153
You can’t perform that action at this time.
0 commit comments