You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/lifecycle.md
+12-4Lines changed: 12 additions & 4 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -20,14 +20,18 @@ database access is potentially anticipated.
20
20
The repository starts a `Session` for each _operation_, in order to maintain isolation.
21
21
This means you can create a repository object almost whenever you want.
22
22
23
-
/// details | The only exception is creating repositories in global variables!
23
+
/// details | There two exceptions: creating repositories in global variables or concurrent asyncio tasks
24
24
type: warning
25
-
The repository creates a session object, which is not thread safe, to avoid
25
+
The repository creates and maintain the lifecycle of a session object to avoid
26
26
emitting unnecessary queries to refresh the model state on new session.
27
27
28
-
Being the session object not thread safe, the repository is not thread safe as well.
28
+
The session is not thread safe, therefore the repository is not thread safe as well.
29
29
30
30
Check the [Notes on multithreaded applications](/manager/session/#note-on-multithreaded-applications)
31
+
32
+
The `AsyncSession`[is not safe on concurrent asyncio tasks](https://docs.sqlalchemy.org/en/20/orm/session_basics.html#is-the-session-thread-safe-is-asyncsession-safe-to-share-in-concurrent-tasks),
33
+
therefore the same repository instance can't be used in multiple asyncio tasks like
34
+
when using `asyncio.gather()`
31
35
///
32
36
33
37
Even using multiple repository instances will work fine, however as they will have completely
@@ -67,7 +71,7 @@ update_my_model()
67
71
```
68
72
///
69
73
70
-
The recommendation is of course to use the same repository instance where possible,
74
+
The recommendation is of course to use the same repository instance, where possible,
71
75
and structure your code in a way to match the single repository instance approach.
72
76
73
77
For example a strategy similar to this would be optimal, if possible:
@@ -77,6 +81,10 @@ For example a strategy similar to this would be optimal, if possible:
77
81
* Do the changes you need, as per business logic
78
82
* Save all the changed models as needed
79
83
84
+
/// tip | Using multiple repository instances is the only way to safely use concurrent asyncio tasks
85
+
86
+
///
87
+
80
88
### Unit of work
81
89
82
90
The Unit of Work session management follows the **same exact rules as the repository**,
0 commit comments