sqla-fancy-core 1.1.1__py3-none-any.whl → 1.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of sqla-fancy-core might be problematic. Click here for more details.
- sqla_fancy_core/__init__.py +7 -1
- sqla_fancy_core/decorators.py +50 -14
- sqla_fancy_core/wrappers.py +188 -2
- {sqla_fancy_core-1.1.1.dist-info → sqla_fancy_core-1.2.0.dist-info}/METADATA +84 -8
- sqla_fancy_core-1.2.0.dist-info/RECORD +8 -0
- sqla_fancy_core-1.1.1.dist-info/RECORD +0 -8
- {sqla_fancy_core-1.1.1.dist-info → sqla_fancy_core-1.2.0.dist-info}/WHEEL +0 -0
- {sqla_fancy_core-1.1.1.dist-info → sqla_fancy_core-1.2.0.dist-info}/licenses/LICENSE +0 -0
sqla_fancy_core/__init__.py
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
"""SQLAlchemy core, but fancier."""
|
|
2
2
|
|
|
3
3
|
from sqla_fancy_core.factories import TableFactory # noqa
|
|
4
|
-
from sqla_fancy_core.wrappers import
|
|
4
|
+
from sqla_fancy_core.wrappers import ( # noqa
|
|
5
|
+
FancyEngineWrapper,
|
|
6
|
+
AsyncFancyEngineWrapper,
|
|
7
|
+
fancy,
|
|
8
|
+
FancyError,
|
|
9
|
+
AtomicContextError,
|
|
10
|
+
)
|
|
5
11
|
from sqla_fancy_core.decorators import transact, Inject # noqa
|
sqla_fancy_core/decorators.py
CHANGED
|
@@ -7,7 +7,9 @@ from typing import Union, overload
|
|
|
7
7
|
import sqlalchemy as sa
|
|
8
8
|
from sqlalchemy.ext.asyncio import AsyncConnection, AsyncEngine
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
from sqla_fancy_core.wrappers import AsyncFancyEngineWrapper, FancyEngineWrapper
|
|
11
|
+
|
|
12
|
+
EngineType = Union[sa.Engine, AsyncEngine, FancyEngineWrapper, AsyncFancyEngineWrapper]
|
|
11
13
|
|
|
12
14
|
|
|
13
15
|
class _Injectable:
|
|
@@ -16,9 +18,9 @@ class _Injectable:
|
|
|
16
18
|
|
|
17
19
|
|
|
18
20
|
@overload
|
|
19
|
-
def Inject(engine: sa.Engine) -> sa.Connection: ...
|
|
21
|
+
def Inject(engine: Union[sa.Engine, FancyEngineWrapper]) -> sa.Connection: ...
|
|
20
22
|
@overload
|
|
21
|
-
def Inject(engine: AsyncEngine) -> AsyncConnection: ...
|
|
23
|
+
def Inject(engine: Union[AsyncEngine, AsyncFancyEngineWrapper]) -> AsyncConnection: ...
|
|
22
24
|
def Inject(engine: EngineType): # type: ignore
|
|
23
25
|
"""A marker class for dependency injection."""
|
|
24
26
|
return _Injectable(engine)
|
|
@@ -44,7 +46,6 @@ def transact(func):
|
|
|
44
46
|
create_user(name="existing", conn=conn)
|
|
45
47
|
"""
|
|
46
48
|
|
|
47
|
-
# Find the parameter with value Inject
|
|
48
49
|
sig = inspect.signature(func)
|
|
49
50
|
inject_param_name = None
|
|
50
51
|
for name, param in sig.parameters.items():
|
|
@@ -56,8 +57,21 @@ def transact(func):
|
|
|
56
57
|
if inject_param_name is None:
|
|
57
58
|
return func # No injection needed
|
|
58
59
|
|
|
59
|
-
|
|
60
|
-
|
|
60
|
+
engine_arg = sig.parameters[inject_param_name].default.engine
|
|
61
|
+
if isinstance(engine_arg, sa.Engine):
|
|
62
|
+
is_async = False
|
|
63
|
+
engine = engine_arg
|
|
64
|
+
elif isinstance(engine_arg, FancyEngineWrapper):
|
|
65
|
+
is_async = False
|
|
66
|
+
engine = engine_arg.engine
|
|
67
|
+
elif isinstance(engine_arg, AsyncEngine):
|
|
68
|
+
is_async = True
|
|
69
|
+
engine = engine_arg
|
|
70
|
+
elif isinstance(engine_arg, AsyncFancyEngineWrapper):
|
|
71
|
+
is_async = True
|
|
72
|
+
engine = engine_arg.engine
|
|
73
|
+
else:
|
|
74
|
+
raise TypeError("Unsupported engine type")
|
|
61
75
|
|
|
62
76
|
if is_async:
|
|
63
77
|
|
|
@@ -70,8 +84,14 @@ def transact(func):
|
|
|
70
84
|
else:
|
|
71
85
|
async with conn.begin():
|
|
72
86
|
return await func(*args, **kwargs)
|
|
87
|
+
elif isinstance(conn, sa.Connection):
|
|
88
|
+
if conn.in_transaction():
|
|
89
|
+
return await func(*args, **kwargs)
|
|
90
|
+
else:
|
|
91
|
+
with conn.begin():
|
|
92
|
+
return await func(*args, **kwargs)
|
|
73
93
|
else:
|
|
74
|
-
async with engine.begin() as conn:
|
|
94
|
+
async with engine.begin() as conn: # type: ignore
|
|
75
95
|
kwargs[inject_param_name] = conn
|
|
76
96
|
return await func(*args, **kwargs)
|
|
77
97
|
|
|
@@ -88,8 +108,10 @@ def transact(func):
|
|
|
88
108
|
else:
|
|
89
109
|
with conn.begin():
|
|
90
110
|
return func(*args, **kwargs)
|
|
111
|
+
elif isinstance(conn, AsyncConnection):
|
|
112
|
+
raise TypeError("AsyncConnection cannot be used in sync function")
|
|
91
113
|
else:
|
|
92
|
-
with engine.begin() as conn:
|
|
114
|
+
with engine.begin() as conn: # type: ignore
|
|
93
115
|
kwargs[inject_param_name] = conn
|
|
94
116
|
return func(*args, **kwargs)
|
|
95
117
|
|
|
@@ -116,7 +138,6 @@ def connect(func):
|
|
|
116
138
|
count = get_user_count(conn)
|
|
117
139
|
"""
|
|
118
140
|
|
|
119
|
-
# Find the parameter with value Inject
|
|
120
141
|
sig = inspect.signature(func)
|
|
121
142
|
inject_param_name = None
|
|
122
143
|
for name, param in sig.parameters.items():
|
|
@@ -128,18 +149,31 @@ def connect(func):
|
|
|
128
149
|
if inject_param_name is None:
|
|
129
150
|
return func # No injection needed
|
|
130
151
|
|
|
131
|
-
|
|
132
|
-
|
|
152
|
+
engine_arg = sig.parameters[inject_param_name].default.engine
|
|
153
|
+
if isinstance(engine_arg, sa.Engine):
|
|
154
|
+
is_async = False
|
|
155
|
+
engine = engine_arg
|
|
156
|
+
elif isinstance(engine_arg, FancyEngineWrapper):
|
|
157
|
+
is_async = False
|
|
158
|
+
engine = engine_arg.engine
|
|
159
|
+
elif isinstance(engine_arg, AsyncEngine):
|
|
160
|
+
is_async = True
|
|
161
|
+
engine = engine_arg
|
|
162
|
+
elif isinstance(engine_arg, AsyncFancyEngineWrapper):
|
|
163
|
+
is_async = True
|
|
164
|
+
engine = engine_arg.engine
|
|
165
|
+
else:
|
|
166
|
+
raise TypeError("Unsupported engine type")
|
|
133
167
|
|
|
134
168
|
if is_async:
|
|
135
169
|
|
|
136
170
|
@functools.wraps(func)
|
|
137
171
|
async def async_wrapper(*args, **kwargs):
|
|
138
172
|
conn = kwargs.get(inject_param_name)
|
|
139
|
-
if isinstance(conn, AsyncConnection):
|
|
173
|
+
if isinstance(conn, (AsyncConnection, sa.Connection)):
|
|
140
174
|
return await func(*args, **kwargs)
|
|
141
175
|
else:
|
|
142
|
-
async with engine.connect() as conn:
|
|
176
|
+
async with engine.connect() as conn: # type: ignore
|
|
143
177
|
kwargs[inject_param_name] = conn
|
|
144
178
|
return await func(*args, **kwargs)
|
|
145
179
|
|
|
@@ -152,8 +186,10 @@ def connect(func):
|
|
|
152
186
|
conn = kwargs.get(inject_param_name)
|
|
153
187
|
if isinstance(conn, sa.Connection):
|
|
154
188
|
return func(*args, **kwargs)
|
|
189
|
+
elif isinstance(conn, AsyncConnection):
|
|
190
|
+
raise TypeError("AsyncConnection cannot be used in sync function")
|
|
155
191
|
else:
|
|
156
|
-
with engine.connect() as conn:
|
|
192
|
+
with engine.connect() as conn: # type: ignore
|
|
157
193
|
kwargs[inject_param_name] = conn
|
|
158
194
|
return func(*args, **kwargs)
|
|
159
195
|
|
sqla_fancy_core/wrappers.py
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
"""Some wrappers for fun times with SQLAlchemy core."""
|
|
2
2
|
|
|
3
|
+
from contextlib import asynccontextmanager, contextmanager
|
|
4
|
+
from contextvars import ContextVar
|
|
3
5
|
from typing import Any, Optional, TypeVar, overload
|
|
4
6
|
|
|
5
7
|
from sqlalchemy import Connection, CursorResult, Engine, Executable
|
|
@@ -16,12 +18,80 @@ from sqlalchemy.sql.selectable import TypedReturnsRows
|
|
|
16
18
|
_T = TypeVar("_T", bound=Any)
|
|
17
19
|
|
|
18
20
|
|
|
21
|
+
class FancyError(Exception):
|
|
22
|
+
"""Custom error for FancyEngineWrapper."""
|
|
23
|
+
|
|
24
|
+
pass
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class AtomicContextError(FancyError):
|
|
28
|
+
"""Error raised when ax() is called outside of an atomic context."""
|
|
29
|
+
|
|
30
|
+
def __init__(self) -> None:
|
|
31
|
+
super().__init__("ax() must be called within the atomic() context manager")
|
|
32
|
+
|
|
33
|
+
|
|
19
34
|
class FancyEngineWrapper:
|
|
20
35
|
"""A wrapper around SQLAlchemy Engine with additional features."""
|
|
21
36
|
|
|
37
|
+
_ATOMIC_TX_CONN: ContextVar[Optional[Connection]] = ContextVar( # type: ignore
|
|
38
|
+
"fancy_global_transaction", default=None
|
|
39
|
+
)
|
|
40
|
+
|
|
22
41
|
def __init__(self, engine: Engine) -> None:
|
|
23
42
|
self.engine = engine
|
|
24
43
|
|
|
44
|
+
@contextmanager
|
|
45
|
+
def atomic(self):
|
|
46
|
+
"""A context manager that provides a transactional connection."""
|
|
47
|
+
global_txn_conn = self._ATOMIC_TX_CONN.get()
|
|
48
|
+
if global_txn_conn is not None:
|
|
49
|
+
# Reuse existing transaction connection
|
|
50
|
+
yield global_txn_conn
|
|
51
|
+
else:
|
|
52
|
+
with self.engine.begin() as connection:
|
|
53
|
+
token = self._ATOMIC_TX_CONN.set(connection)
|
|
54
|
+
try:
|
|
55
|
+
yield connection
|
|
56
|
+
finally:
|
|
57
|
+
# Restore previous ContextVar state
|
|
58
|
+
self._ATOMIC_TX_CONN.reset(token)
|
|
59
|
+
|
|
60
|
+
@overload
|
|
61
|
+
def ax(
|
|
62
|
+
self,
|
|
63
|
+
statement: TypedReturnsRows[_T],
|
|
64
|
+
parameters: Optional[_CoreAnyExecuteParams] = None,
|
|
65
|
+
*,
|
|
66
|
+
execution_options: Optional[CoreExecuteOptionsParameter] = None,
|
|
67
|
+
) -> CursorResult[_T]: ...
|
|
68
|
+
@overload
|
|
69
|
+
def ax(
|
|
70
|
+
self,
|
|
71
|
+
statement: Executable,
|
|
72
|
+
parameters: Optional[_CoreAnyExecuteParams] = None,
|
|
73
|
+
*,
|
|
74
|
+
execution_options: Optional[CoreExecuteOptionsParameter] = None,
|
|
75
|
+
) -> CursorResult[Any]: ...
|
|
76
|
+
def ax(
|
|
77
|
+
self,
|
|
78
|
+
statement: Executable,
|
|
79
|
+
parameters: Optional[_CoreAnyExecuteParams] = None,
|
|
80
|
+
*,
|
|
81
|
+
execution_options: Optional[CoreExecuteOptionsParameter] = None,
|
|
82
|
+
) -> CursorResult[Any]:
|
|
83
|
+
"""Execute the query within the atomic context and return the result.
|
|
84
|
+
|
|
85
|
+
It must be called within the `atomic` context manager. Else an error is raised.
|
|
86
|
+
"""
|
|
87
|
+
connection = self._ATOMIC_TX_CONN.get()
|
|
88
|
+
if connection:
|
|
89
|
+
return connection.execute(
|
|
90
|
+
statement, parameters, execution_options=execution_options
|
|
91
|
+
)
|
|
92
|
+
else:
|
|
93
|
+
raise AtomicContextError()
|
|
94
|
+
|
|
25
95
|
@overload
|
|
26
96
|
def x(
|
|
27
97
|
self,
|
|
@@ -52,6 +122,7 @@ class FancyEngineWrapper:
|
|
|
52
122
|
|
|
53
123
|
If a connection is provided, use it; otherwise, create a new one.
|
|
54
124
|
"""
|
|
125
|
+
connection = connection
|
|
55
126
|
if connection:
|
|
56
127
|
return connection.execute(
|
|
57
128
|
statement, parameters, execution_options=execution_options
|
|
@@ -90,8 +161,10 @@ class FancyEngineWrapper:
|
|
|
90
161
|
) -> CursorResult[Any]:
|
|
91
162
|
"""Begin a transaction, execute the query, and return the result.
|
|
92
163
|
|
|
93
|
-
If a connection is provided, use it; otherwise,
|
|
164
|
+
If a connection is provided, use it; otherwise, use the global atomic
|
|
165
|
+
context or create a new one.
|
|
94
166
|
"""
|
|
167
|
+
connection = connection or self._ATOMIC_TX_CONN.get()
|
|
95
168
|
if connection:
|
|
96
169
|
if connection.in_transaction():
|
|
97
170
|
# Transaction is already active
|
|
@@ -109,13 +182,95 @@ class FancyEngineWrapper:
|
|
|
109
182
|
statement, parameters, execution_options=execution_options
|
|
110
183
|
)
|
|
111
184
|
|
|
185
|
+
@overload
|
|
186
|
+
def atx(
|
|
187
|
+
self,
|
|
188
|
+
statement: TypedReturnsRows[_T],
|
|
189
|
+
parameters: Optional[_CoreAnyExecuteParams] = None,
|
|
190
|
+
*,
|
|
191
|
+
execution_options: Optional[CoreExecuteOptionsParameter] = None,
|
|
192
|
+
) -> CursorResult[_T]: ...
|
|
193
|
+
@overload
|
|
194
|
+
def atx(
|
|
195
|
+
self,
|
|
196
|
+
statement: Executable,
|
|
197
|
+
parameters: Optional[_CoreAnyExecuteParams] = None,
|
|
198
|
+
*,
|
|
199
|
+
execution_options: Optional[CoreExecuteOptionsParameter] = None,
|
|
200
|
+
) -> CursorResult[Any]: ...
|
|
201
|
+
def atx(
|
|
202
|
+
self,
|
|
203
|
+
statement: Executable,
|
|
204
|
+
parameters: Optional[_CoreAnyExecuteParams] = None,
|
|
205
|
+
*,
|
|
206
|
+
execution_options: Optional[CoreExecuteOptionsParameter] = None,
|
|
207
|
+
) -> CursorResult[Any]:
|
|
208
|
+
"""If within an atomic context, execute the query there; else, create a new transaction."""
|
|
209
|
+
with self.atomic() as connection:
|
|
210
|
+
return connection.execute(
|
|
211
|
+
statement, parameters, execution_options=execution_options
|
|
212
|
+
)
|
|
213
|
+
|
|
112
214
|
|
|
113
215
|
class AsyncFancyEngineWrapper:
|
|
114
216
|
"""A wrapper around SQLAlchemy AsyncEngine with additional features."""
|
|
115
217
|
|
|
218
|
+
_ATOMIC_TX_CONN: ContextVar[Optional[AsyncConnection]] = ContextVar( # type: ignore
|
|
219
|
+
"fancy_global_transaction", default=None
|
|
220
|
+
)
|
|
221
|
+
|
|
116
222
|
def __init__(self, engine: AsyncEngine) -> None:
|
|
117
223
|
self.engine = engine
|
|
118
224
|
|
|
225
|
+
@asynccontextmanager
|
|
226
|
+
async def atomic(self):
|
|
227
|
+
"""An async context manager that provides a transactional connection."""
|
|
228
|
+
global_txn_conn = self._ATOMIC_TX_CONN.get()
|
|
229
|
+
if global_txn_conn is not None:
|
|
230
|
+
yield global_txn_conn
|
|
231
|
+
else:
|
|
232
|
+
async with self.engine.begin() as connection:
|
|
233
|
+
token = self._ATOMIC_TX_CONN.set(connection)
|
|
234
|
+
try:
|
|
235
|
+
yield connection
|
|
236
|
+
finally:
|
|
237
|
+
self._ATOMIC_TX_CONN.reset(token)
|
|
238
|
+
|
|
239
|
+
@overload
|
|
240
|
+
async def ax(
|
|
241
|
+
self,
|
|
242
|
+
statement: TypedReturnsRows[_T],
|
|
243
|
+
parameters: Optional[_CoreAnyExecuteParams] = None,
|
|
244
|
+
*,
|
|
245
|
+
execution_options: Optional[CoreExecuteOptionsParameter] = None,
|
|
246
|
+
) -> CursorResult[_T]: ...
|
|
247
|
+
@overload
|
|
248
|
+
async def ax(
|
|
249
|
+
self,
|
|
250
|
+
statement: Executable,
|
|
251
|
+
parameters: Optional[_CoreAnyExecuteParams] = None,
|
|
252
|
+
*,
|
|
253
|
+
execution_options: Optional[CoreExecuteOptionsParameter] = None,
|
|
254
|
+
) -> CursorResult[Any]: ...
|
|
255
|
+
async def ax(
|
|
256
|
+
self,
|
|
257
|
+
statement: Executable,
|
|
258
|
+
parameters: Optional[_CoreAnyExecuteParams] = None,
|
|
259
|
+
*,
|
|
260
|
+
execution_options: Optional[CoreExecuteOptionsParameter] = None,
|
|
261
|
+
) -> CursorResult[Any]:
|
|
262
|
+
"""Execute the query within the atomic context and return the result.
|
|
263
|
+
|
|
264
|
+
It must be called within the `atomic` context manager. Else an error is raised.
|
|
265
|
+
"""
|
|
266
|
+
connection = self._ATOMIC_TX_CONN.get()
|
|
267
|
+
if connection:
|
|
268
|
+
return await connection.execute(
|
|
269
|
+
statement, parameters, execution_options=execution_options
|
|
270
|
+
)
|
|
271
|
+
else:
|
|
272
|
+
raise AtomicContextError()
|
|
273
|
+
|
|
119
274
|
@overload
|
|
120
275
|
async def x(
|
|
121
276
|
self,
|
|
@@ -184,8 +339,10 @@ class AsyncFancyEngineWrapper:
|
|
|
184
339
|
) -> CursorResult[Any]:
|
|
185
340
|
"""Execute the query within a transaction and return the result.
|
|
186
341
|
|
|
187
|
-
If a connection is provided, use it; otherwise,
|
|
342
|
+
If a connection is provided, use it; otherwise, use the global atomic
|
|
343
|
+
context or create a new one.
|
|
188
344
|
"""
|
|
345
|
+
connection = connection or self._ATOMIC_TX_CONN.get()
|
|
189
346
|
if connection:
|
|
190
347
|
if connection.in_transaction():
|
|
191
348
|
return await connection.execute(
|
|
@@ -202,6 +359,35 @@ class AsyncFancyEngineWrapper:
|
|
|
202
359
|
statement, parameters, execution_options=execution_options
|
|
203
360
|
)
|
|
204
361
|
|
|
362
|
+
@overload
|
|
363
|
+
async def atx(
|
|
364
|
+
self,
|
|
365
|
+
statement: TypedReturnsRows[_T],
|
|
366
|
+
parameters: Optional[_CoreAnyExecuteParams] = None,
|
|
367
|
+
*,
|
|
368
|
+
execution_options: Optional[CoreExecuteOptionsParameter] = None,
|
|
369
|
+
) -> CursorResult[_T]: ...
|
|
370
|
+
@overload
|
|
371
|
+
async def atx(
|
|
372
|
+
self,
|
|
373
|
+
statement: Executable,
|
|
374
|
+
parameters: Optional[_CoreAnyExecuteParams] = None,
|
|
375
|
+
*,
|
|
376
|
+
execution_options: Optional[CoreExecuteOptionsParameter] = None,
|
|
377
|
+
) -> CursorResult[Any]: ...
|
|
378
|
+
async def atx(
|
|
379
|
+
self,
|
|
380
|
+
statement: Executable,
|
|
381
|
+
parameters: Optional[_CoreAnyExecuteParams] = None,
|
|
382
|
+
*,
|
|
383
|
+
execution_options: Optional[CoreExecuteOptionsParameter] = None,
|
|
384
|
+
) -> CursorResult[Any]:
|
|
385
|
+
"""If within an atomic context, execute the query there; else, create a new transaction."""
|
|
386
|
+
async with self.atomic() as connection:
|
|
387
|
+
return await connection.execute(
|
|
388
|
+
statement, parameters, execution_options=execution_options
|
|
389
|
+
)
|
|
390
|
+
|
|
205
391
|
|
|
206
392
|
@overload
|
|
207
393
|
def fancy(obj: Engine, /) -> FancyEngineWrapper: ...
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: sqla-fancy-core
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.2.0
|
|
4
4
|
Summary: SQLAlchemy core, but fancier
|
|
5
5
|
Project-URL: Homepage, https://github.com/sayanarijit/sqla-fancy-core
|
|
6
6
|
Author-email: Arijit Basu <sayanarijit@gmail.com>
|
|
@@ -158,13 +158,18 @@ async with engine.begin() as txn:
|
|
|
158
158
|
|
|
159
159
|
## Fancy Engine Wrappers
|
|
160
160
|
|
|
161
|
-
`sqla-fancy-core` provides `fancy` engine wrappers that simplify database interactions by automatically managing connections and transactions. The `fancy` function wraps a SQLAlchemy `Engine` or `AsyncEngine` and returns a wrapper object with
|
|
161
|
+
`sqla-fancy-core` provides `fancy` engine wrappers that simplify database interactions by automatically managing connections and transactions. The `fancy` function wraps a SQLAlchemy `Engine` or `AsyncEngine` and returns a wrapper object with the following methods:
|
|
162
162
|
|
|
163
163
|
- `x(conn, query)`: Executes a query. It uses the provided `conn` if available, otherwise it creates a new connection.
|
|
164
|
-
- `tx(conn, query)`: Executes a query within a transaction. It uses the provided `conn` if available, otherwise it creates a new connection and begins a transaction.
|
|
164
|
+
- `tx(conn, query)`: Executes a query within a transaction. It uses the provided `conn` if available, otherwise it tries to use the atomic context if within one, else creates a new connection and begins a transaction.
|
|
165
|
+
- `atomic()`: A context manager for grouping multiple operations in a single transaction scope.
|
|
166
|
+
- `ax(query)`: Executes a query using the connection from the active `atomic()` context. Raises `AtomicContextError` if called outside an `atomic()` block.
|
|
167
|
+
- `atx(query)`: Executes a query inside a transaction automatically. If already inside `atomic()`, it reuses the same connection and transaction; otherwise it opens a new transaction just for this call.
|
|
165
168
|
|
|
166
169
|
This is particularly useful for writing connection-agnostic query functions.
|
|
167
170
|
|
|
171
|
+
### Basic Examples
|
|
172
|
+
|
|
168
173
|
**Sync Example:**
|
|
169
174
|
|
|
170
175
|
```python
|
|
@@ -208,6 +213,78 @@ async def main():
|
|
|
208
213
|
assert await get_data(conn) == 1
|
|
209
214
|
```
|
|
210
215
|
|
|
216
|
+
### Using the atomic() Context Manager
|
|
217
|
+
|
|
218
|
+
The `atomic()` context manager lets you group several database operations within one transactional scope. Queries executed with `ax()` inside this context all use the same connection. Nested `atomic()` contexts reuse the outer connection automatically.
|
|
219
|
+
|
|
220
|
+
**Sync Example:**
|
|
221
|
+
|
|
222
|
+
```python
|
|
223
|
+
import sqlalchemy as sa
|
|
224
|
+
from sqla_fancy_core import fancy, TableFactory
|
|
225
|
+
|
|
226
|
+
tf = TableFactory()
|
|
227
|
+
|
|
228
|
+
class User:
|
|
229
|
+
id = tf.auto_id()
|
|
230
|
+
name = tf.string("name")
|
|
231
|
+
Table = tf("users")
|
|
232
|
+
|
|
233
|
+
engine = sa.create_engine("sqlite:///:memory:")
|
|
234
|
+
tf.metadata.create_all(engine)
|
|
235
|
+
fancy_engine = fancy(engine)
|
|
236
|
+
|
|
237
|
+
# Group operations in one transaction
|
|
238
|
+
with fancy_engine.atomic():
|
|
239
|
+
fancy_engine.ax(sa.insert(User.Table).values(name="Alice"))
|
|
240
|
+
fancy_engine.ax(sa.insert(User.Table).values(name="Bob"))
|
|
241
|
+
result = fancy_engine.ax(sa.select(sa.func.count()).select_from(User.Table))
|
|
242
|
+
count = result.scalar_one()
|
|
243
|
+
assert count == 2
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
**Async Example:**
|
|
247
|
+
|
|
248
|
+
```python
|
|
249
|
+
import sqlalchemy as sa
|
|
250
|
+
from sqlalchemy.ext.asyncio import create_async_engine
|
|
251
|
+
from sqla_fancy_core import fancy, TableFactory
|
|
252
|
+
|
|
253
|
+
tf = TableFactory()
|
|
254
|
+
|
|
255
|
+
class User:
|
|
256
|
+
id = tf.auto_id()
|
|
257
|
+
name = tf.string("name")
|
|
258
|
+
Table = tf("users")
|
|
259
|
+
|
|
260
|
+
async def run_example():
|
|
261
|
+
engine = create_async_engine("sqlite+aiosqlite:///:memory:")
|
|
262
|
+
async with engine.begin() as conn:
|
|
263
|
+
await conn.run_sync(tf.metadata.create_all)
|
|
264
|
+
|
|
265
|
+
fancy_engine = fancy(engine)
|
|
266
|
+
|
|
267
|
+
async with fancy_engine.atomic():
|
|
268
|
+
await fancy_engine.ax(sa.insert(User.Table).values(name="Alice"))
|
|
269
|
+
await fancy_engine.ax(sa.insert(User.Table).values(name="Bob"))
|
|
270
|
+
result = await fancy_engine.ax(sa.select(sa.func.count()).select_from(User.Table))
|
|
271
|
+
count = result.scalar_one()
|
|
272
|
+
assert count == 2
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
**Key Points:**
|
|
276
|
+
|
|
277
|
+
- `ax()` must be called inside an `atomic()` context. Calling it elsewhere raises `AtomicContextError`.
|
|
278
|
+
- `atx()` is a safe/ergonomic helper: it will run inside the current `atomic()` transaction when present, or create a short-lived transaction otherwise.
|
|
279
|
+
- Nesting `atomic()` contexts is safe. Inner contexts share the outer connection instead of creating a new transaction.
|
|
280
|
+
- On normal exit, the transaction commits automatically. On exception, it rolls back.
|
|
281
|
+
|
|
282
|
+
### ax vs atx vs tx
|
|
283
|
+
|
|
284
|
+
- `ax(q)`: Only valid inside `atomic()`. Uses the ambient transactional connection. Great for batch operations grouped by an outer context.
|
|
285
|
+
- `atx(q)`: Fire-and-forget in a transaction. Reuses the ambient `atomic()` connection if present; otherwise starts and commits its own transaction.
|
|
286
|
+
- `tx(conn, q)`: Low-level primitive. If `conn` is provided, it executes within it, creating a transaction when needed; if `None`, it prefers the `atomic()` connection when active or opens a new transactional connection.
|
|
287
|
+
|
|
211
288
|
## Decorators: Inject, connect, transact
|
|
212
289
|
|
|
213
290
|
When writing plain SQLAlchemy Core code, you often pass connections around and manage transactions manually. The decorators in `sqla-fancy-core` help you keep functions connection-agnostic and composable, while remaining explicit and safe.
|
|
@@ -242,27 +319,24 @@ users = sa.Table(
|
|
|
242
319
|
)
|
|
243
320
|
metadata.create_all(engine)
|
|
244
321
|
|
|
245
|
-
# 1) Ensure a connection is available (no implicit transaction)
|
|
246
322
|
@connect
|
|
247
323
|
def get_user_count(conn=Inject(engine)):
|
|
248
324
|
return conn.execute(sa.select(sa.func.count()).select_from(users)).scalar_one()
|
|
249
325
|
|
|
250
326
|
assert get_user_count() == 0
|
|
251
327
|
|
|
252
|
-
# 2) Wrap in a transaction automatically
|
|
253
328
|
@transact
|
|
254
329
|
def create_user(name: str, conn=Inject(engine)):
|
|
255
330
|
conn.execute(sa.insert(users).values(name=name))
|
|
256
331
|
|
|
332
|
+
# Without an explicit transaction
|
|
257
333
|
create_user("alice")
|
|
258
334
|
assert get_user_count() == 1
|
|
259
335
|
|
|
260
|
-
#
|
|
336
|
+
# With an explicit transaction
|
|
261
337
|
with engine.begin() as txn:
|
|
262
338
|
create_user("bob", conn=txn)
|
|
263
339
|
assert get_user_count(conn=txn) == 2
|
|
264
|
-
|
|
265
|
-
assert get_user_count() == 2
|
|
266
340
|
```
|
|
267
341
|
|
|
268
342
|
### Async examples
|
|
@@ -293,10 +367,12 @@ async def get_user_count(conn=Inject(engine)):
|
|
|
293
367
|
async def create_user(name: str, conn=Inject(engine)):
|
|
294
368
|
await conn.execute(sa.insert(users).values(name=name))
|
|
295
369
|
|
|
370
|
+
# Without an explicit transaction
|
|
296
371
|
assert await get_user_count() == 0
|
|
297
372
|
await create_user("carol")
|
|
298
373
|
assert await get_user_count() == 1
|
|
299
374
|
|
|
375
|
+
# With an explicit transaction
|
|
300
376
|
async with engine.connect() as conn:
|
|
301
377
|
await create_user("dave", conn=conn)
|
|
302
378
|
assert await get_user_count(conn=conn) == 2
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
sqla_fancy_core/__init__.py,sha256=2Zxz2oM30Vv0_JJOMulUmts1nfag8mPyRAT7o8MW-pY,313
|
|
2
|
+
sqla_fancy_core/decorators.py,sha256=VhkYf5x6qwcQnc8QCuUzKPQxMI3tNNGM7nVSPUqMkPw,6649
|
|
3
|
+
sqla_fancy_core/factories.py,sha256=EgOhc15rCo9GyIuSNhuoB1pJ6lXx_UtRR5y9hh2lEtM,6326
|
|
4
|
+
sqla_fancy_core/wrappers.py,sha256=ax3ATn7BGDZLKl0z9j3jbpYA4Snwq8Ugw09QYwwG36A,14642
|
|
5
|
+
sqla_fancy_core-1.2.0.dist-info/METADATA,sha256=PTnY2miJaAwIMfxjr9qRS2q1XPLlGrE20-ho2RO89Es,17732
|
|
6
|
+
sqla_fancy_core-1.2.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
7
|
+
sqla_fancy_core-1.2.0.dist-info/licenses/LICENSE,sha256=XcYXJ0ipvwOn-nzko6p_xoCCbke8tAhmlIN04rUZDLk,1068
|
|
8
|
+
sqla_fancy_core-1.2.0.dist-info/RECORD,,
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
sqla_fancy_core/__init__.py,sha256=iCfZrKbdoAG65CeHGducjiA1p4zYLgFSrxGDzQEhM8U,256
|
|
2
|
-
sqla_fancy_core/decorators.py,sha256=m50e7htQEAc7aWG25bhz2LET09ns_ONSYsnHQjyMdh0,5049
|
|
3
|
-
sqla_fancy_core/factories.py,sha256=EgOhc15rCo9GyIuSNhuoB1pJ6lXx_UtRR5y9hh2lEtM,6326
|
|
4
|
-
sqla_fancy_core/wrappers.py,sha256=TesGKm9ddsd7dJwbkonZPl46Huvqeh7AfUwB623qRwA,8165
|
|
5
|
-
sqla_fancy_core-1.1.1.dist-info/METADATA,sha256=h6nhdXLO5DFHuBPT67qLhSBO-Ch_D3I6EcUmiZasqUE,14473
|
|
6
|
-
sqla_fancy_core-1.1.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
7
|
-
sqla_fancy_core-1.1.1.dist-info/licenses/LICENSE,sha256=XcYXJ0ipvwOn-nzko6p_xoCCbke8tAhmlIN04rUZDLk,1068
|
|
8
|
-
sqla_fancy_core-1.1.1.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|