sqla-fancy-core 1.1.2__py3-none-any.whl → 1.2.1__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.

@@ -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 FancyEngineWrapper, AsyncFancyEngineWrapper, fancy # noqa
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
@@ -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, create a new one.
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,97 @@ 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
+ return self.tx(
210
+ self._ATOMIC_TX_CONN.get(),
211
+ statement,
212
+ parameters,
213
+ execution_options=execution_options,
214
+ )
215
+
112
216
 
113
217
  class AsyncFancyEngineWrapper:
114
218
  """A wrapper around SQLAlchemy AsyncEngine with additional features."""
115
219
 
220
+ _ATOMIC_TX_CONN: ContextVar[Optional[AsyncConnection]] = ContextVar( # type: ignore
221
+ "fancy_global_transaction", default=None
222
+ )
223
+
116
224
  def __init__(self, engine: AsyncEngine) -> None:
117
225
  self.engine = engine
118
226
 
227
+ @asynccontextmanager
228
+ async def atomic(self):
229
+ """An async context manager that provides a transactional connection."""
230
+ global_txn_conn = self._ATOMIC_TX_CONN.get()
231
+ if global_txn_conn is not None:
232
+ yield global_txn_conn
233
+ else:
234
+ async with self.engine.begin() as connection:
235
+ token = self._ATOMIC_TX_CONN.set(connection)
236
+ try:
237
+ yield connection
238
+ finally:
239
+ self._ATOMIC_TX_CONN.reset(token)
240
+
241
+ @overload
242
+ async def ax(
243
+ self,
244
+ statement: TypedReturnsRows[_T],
245
+ parameters: Optional[_CoreAnyExecuteParams] = None,
246
+ *,
247
+ execution_options: Optional[CoreExecuteOptionsParameter] = None,
248
+ ) -> CursorResult[_T]: ...
249
+ @overload
250
+ async def ax(
251
+ self,
252
+ statement: Executable,
253
+ parameters: Optional[_CoreAnyExecuteParams] = None,
254
+ *,
255
+ execution_options: Optional[CoreExecuteOptionsParameter] = None,
256
+ ) -> CursorResult[Any]: ...
257
+ async def ax(
258
+ self,
259
+ statement: Executable,
260
+ parameters: Optional[_CoreAnyExecuteParams] = None,
261
+ *,
262
+ execution_options: Optional[CoreExecuteOptionsParameter] = None,
263
+ ) -> CursorResult[Any]:
264
+ """Execute the query within the atomic context and return the result.
265
+
266
+ It must be called within the `atomic` context manager. Else an error is raised.
267
+ """
268
+ connection = self._ATOMIC_TX_CONN.get()
269
+ if connection:
270
+ return await connection.execute(
271
+ statement, parameters, execution_options=execution_options
272
+ )
273
+ else:
274
+ raise AtomicContextError()
275
+
119
276
  @overload
120
277
  async def x(
121
278
  self,
@@ -184,8 +341,10 @@ class AsyncFancyEngineWrapper:
184
341
  ) -> CursorResult[Any]:
185
342
  """Execute the query within a transaction and return the result.
186
343
 
187
- If a connection is provided, use it; otherwise, create a new one.
344
+ If a connection is provided, use it; otherwise, use the global atomic
345
+ context or create a new one.
188
346
  """
347
+ connection = connection or self._ATOMIC_TX_CONN.get()
189
348
  if connection:
190
349
  if connection.in_transaction():
191
350
  return await connection.execute(
@@ -202,6 +361,37 @@ class AsyncFancyEngineWrapper:
202
361
  statement, parameters, execution_options=execution_options
203
362
  )
204
363
 
364
+ @overload
365
+ async def atx(
366
+ self,
367
+ statement: TypedReturnsRows[_T],
368
+ parameters: Optional[_CoreAnyExecuteParams] = None,
369
+ *,
370
+ execution_options: Optional[CoreExecuteOptionsParameter] = None,
371
+ ) -> CursorResult[_T]: ...
372
+ @overload
373
+ async def atx(
374
+ self,
375
+ statement: Executable,
376
+ parameters: Optional[_CoreAnyExecuteParams] = None,
377
+ *,
378
+ execution_options: Optional[CoreExecuteOptionsParameter] = None,
379
+ ) -> CursorResult[Any]: ...
380
+ async def atx(
381
+ self,
382
+ statement: Executable,
383
+ parameters: Optional[_CoreAnyExecuteParams] = None,
384
+ *,
385
+ execution_options: Optional[CoreExecuteOptionsParameter] = None,
386
+ ) -> CursorResult[Any]:
387
+ """If within an atomic context, execute the query there; else, create a new transaction."""
388
+ return await self.tx(
389
+ self._ATOMIC_TX_CONN.get(),
390
+ statement,
391
+ parameters,
392
+ execution_options=execution_options,
393
+ )
394
+
205
395
 
206
396
  @overload
207
397
  def fancy(obj: Engine, /) -> FancyEngineWrapper: ...
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sqla-fancy-core
3
- Version: 1.1.2
3
+ Version: 1.2.1
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 two primary methods:
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.
@@ -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=7ZpcVydWprIC6R78mJqvsGo9-XXZNDT34bjGPly8dAc,14636
5
+ sqla_fancy_core-1.2.1.dist-info/METADATA,sha256=Fxvmy5NZLQcRdjmpamrPBHth0YhM4EX3nLahhj6d7ps,17732
6
+ sqla_fancy_core-1.2.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
7
+ sqla_fancy_core-1.2.1.dist-info/licenses/LICENSE,sha256=XcYXJ0ipvwOn-nzko6p_xoCCbke8tAhmlIN04rUZDLk,1068
8
+ sqla_fancy_core-1.2.1.dist-info/RECORD,,
@@ -1,8 +0,0 @@
1
- sqla_fancy_core/__init__.py,sha256=iCfZrKbdoAG65CeHGducjiA1p4zYLgFSrxGDzQEhM8U,256
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=TesGKm9ddsd7dJwbkonZPl46Huvqeh7AfUwB623qRwA,8165
5
- sqla_fancy_core-1.1.2.dist-info/METADATA,sha256=dWdZEq6fwzkvrK9zoYpAdh5QQLtMd1lc5NATrp2-1Yo,14419
6
- sqla_fancy_core-1.1.2.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
7
- sqla_fancy_core-1.1.2.dist-info/licenses/LICENSE,sha256=XcYXJ0ipvwOn-nzko6p_xoCCbke8tAhmlIN04rUZDLk,1068
8
- sqla_fancy_core-1.1.2.dist-info/RECORD,,