Skip to content
This repository was archived by the owner on Aug 19, 2025. It is now read-only.

Commit 82989d3

Browse files
Add docs for transaction decorators
1 parent 44dbf7b commit 82989d3

1 file changed

Lines changed: 54 additions & 3 deletions

File tree

README.md

Lines changed: 54 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -117,13 +117,64 @@ else:
117117
transaction.commit()
118118
```
119119

120-
For strict test isolation you will always want to rollback the test database
121-
to a clean state between each test case:
120+
You can also use `.transaction()` as a function decorator on any async function:
122121

123122
```python
124-
async with database.transaction(force_rollback=True):
123+
@database.transaction()
124+
async def create_users(request):
125125
...
126126
```
127127

128128
Transaction blocks are managed as task-local state. Nested transactions
129129
are fully supported, and are implemented using database savepoints.
130+
131+
## Connecting and disconnecting
132+
133+
You can control the database connect/disconnect, by using it as a async context manager.
134+
135+
```python
136+
async with Database(DATABASE_URL) as database:
137+
...
138+
```
139+
140+
Or by using explicit connection and disconnection:
141+
142+
```python
143+
database = Database(DATABASE_URL)
144+
await database.connect()
145+
...
146+
await database.disconnect()
147+
```
148+
149+
## Test isolation
150+
151+
For strict test isolation you will always want to rollback the test database
152+
to a clean state between each test case:
153+
154+
```python
155+
database = Database(DATABASE_URL, force_rollback=True)
156+
```
157+
158+
This will ensure that all database connections are run within a transaction
159+
that rollbacks once the database is disconnected.
160+
161+
If you're integrating against a web framework you'll typically want to
162+
use something like the following pattern:
163+
164+
```python
165+
if not TESTING:
166+
database = Database(DATABASE_URL)
167+
else:
168+
database = Database(TEST_DATABASE_URL, force_rollback=True)
169+
```
170+
171+
This will give you test cases that run against a different database to
172+
the development database, with strict test isolation so long as you make sure
173+
to connect and disconnect to the database between test cases.
174+
175+
For a lower level API you can explicitly create force-rollback transactions:
176+
177+
```python
178+
async with database.transaction(force_rollback=True):
179+
...
180+
```

0 commit comments

Comments
 (0)