sqlobjects 2.0.0__py3-none-any.whl → 2.1.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.
Files changed (42) hide show
  1. sqlobjects/__init__.py +1 -1
  2. sqlobjects/cascade.py +22 -31
  3. sqlobjects/contrib/asgi.py +5 -3
  4. sqlobjects/database/manager.py +44 -30
  5. sqlobjects/expressions/aggregate.py +144 -83
  6. sqlobjects/expressions/scalar.py +5 -9
  7. sqlobjects/fields/__init__.py +2 -0
  8. sqlobjects/fields/core.py +3 -2
  9. sqlobjects/fields/proxies.py +78 -30
  10. sqlobjects/fields/relations/descriptors.py +4 -2
  11. sqlobjects/fields/relations/prefetch.py +62 -63
  12. sqlobjects/fields/relations/utils.py +50 -11
  13. sqlobjects/internal/results.py +1 -1
  14. sqlobjects/metadata.py +124 -29
  15. sqlobjects/mixins.py +24 -5
  16. sqlobjects/model.py +45 -72
  17. sqlobjects/objects/bulk.py +159 -245
  18. sqlobjects/objects/core.py +62 -58
  19. sqlobjects/objects/upsert.py +85 -8
  20. sqlobjects/queries/builder.py +77 -145
  21. sqlobjects/queries/dialect.py +4 -4
  22. sqlobjects/queries/executor.py +105 -209
  23. sqlobjects/queryset.py +64 -45
  24. sqlobjects/session.py +342 -38
  25. sqlobjects/signals.py +60 -33
  26. sqlobjects/sql_logging.py +100 -11
  27. sqlobjects/utils/naming.py +17 -1
  28. {sqlobjects-2.0.0.data → sqlobjects-2.1.0.data}/data/share/sqlobjects/rules/01-database-session-guide.md +44 -5
  29. {sqlobjects-2.0.0.data → sqlobjects-2.1.0.data}/data/share/sqlobjects/rules/02-model-definition-guide.md +25 -0
  30. {sqlobjects-2.0.0.data → sqlobjects-2.1.0.data}/data/share/sqlobjects/rules/03-query-operations-guide.md +33 -4
  31. {sqlobjects-2.0.0.data → sqlobjects-2.1.0.data}/data/share/sqlobjects/rules/05-relationships-guide.md +37 -15
  32. {sqlobjects-2.0.0.data → sqlobjects-2.1.0.data}/data/share/sqlobjects/rules/06-validation-signals-guide.md +32 -0
  33. {sqlobjects-2.0.0.dist-info → sqlobjects-2.1.0.dist-info}/METADATA +9 -2
  34. sqlobjects-2.1.0.dist-info/RECORD +75 -0
  35. sqlobjects-2.0.0.dist-info/RECORD +0 -75
  36. {sqlobjects-2.0.0.data → sqlobjects-2.1.0.data}/data/share/sqlobjects/rules/04-crud-operations-guide.md +0 -0
  37. {sqlobjects-2.0.0.data → sqlobjects-2.1.0.data}/data/share/sqlobjects/rules/07-performance-guide.md +0 -0
  38. {sqlobjects-2.0.0.data → sqlobjects-2.1.0.data}/data/share/sqlobjects/rules/README.md +0 -0
  39. {sqlobjects-2.0.0.dist-info → sqlobjects-2.1.0.dist-info}/WHEEL +0 -0
  40. {sqlobjects-2.0.0.dist-info → sqlobjects-2.1.0.dist-info}/entry_points.txt +0 -0
  41. {sqlobjects-2.0.0.dist-info → sqlobjects-2.1.0.dist-info}/licenses/LICENSE +0 -0
  42. {sqlobjects-2.0.0.dist-info → sqlobjects-2.1.0.dist-info}/top_level.txt +0 -0
sqlobjects/session.py CHANGED
@@ -1,23 +1,44 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
1
4
  import contextvars
5
+ import inspect
2
6
  import logging
3
- from collections.abc import AsyncGenerator
4
- from contextlib import asynccontextmanager
5
- from typing import Any
7
+ from collections.abc import AsyncGenerator, Callable
8
+ from contextlib import AsyncExitStack, asynccontextmanager
9
+ from dataclasses import dataclass
10
+ from typing import Any, cast
6
11
 
7
12
  from sqlalchemy import CursorResult, text
8
13
  from sqlalchemy.exc import SQLAlchemyError
9
- from sqlalchemy.ext.asyncio import AsyncConnection, AsyncResult
14
+ from sqlalchemy.ext.asyncio import AsyncConnection, AsyncResult, AsyncTransaction
15
+ from sqlalchemy.sql import ClauseElement, visitors
10
16
 
11
17
  from .database.manager import get_database, get_default
12
- from .exceptions import convert_sqlalchemy_error
18
+ from .exceptions import QueryError, TransactionError, convert_sqlalchemy_error
13
19
 
14
20
 
15
- __all__ = ["AsyncSession", "ctx_session", "ctx_sessions", "get_session", "has_session"]
21
+ __all__ = ["AsyncSession", "ctx_session", "ctx_sessions", "get_session", "has_session", "on_commit"]
16
22
 
17
23
  logger = logging.getLogger("sqlobjects.session")
18
24
 
19
25
  # Explicit session management (highest priority)
20
- _explicit_sessions: contextvars.ContextVar[dict[str, "AsyncSession"]] = contextvars.ContextVar("explicit_sessions")
26
+ _explicit_sessions: contextvars.ContextVar[dict[str, AsyncSession]] = contextvars.ContextVar("explicit_sessions")
27
+
28
+
29
+ def _current_task() -> asyncio.Task[Any] | None:
30
+ """Allow session construction and context inspection outside an event loop."""
31
+ try:
32
+ return asyncio.current_task()
33
+ except RuntimeError:
34
+ return None
35
+
36
+
37
+ @dataclass
38
+ class _CommitHook:
39
+ callback: Callable[[], Any]
40
+ robust: bool
41
+ savepoints: tuple[_SessionSavepoint, ...] = ()
21
42
 
22
43
 
23
44
  class AsyncSession:
@@ -41,6 +62,35 @@ class AsyncSession:
41
62
  self.auto_commit = auto_commit and not readonly # readonly sessions never auto-commit
42
63
  self._conn: AsyncConnection | None = None
43
64
  self._trans = None
65
+ self._rollback_only = False
66
+ self._owner_task = _current_task()
67
+ self._closed = False
68
+ self._commit_hooks: list[_CommitHook] = []
69
+ self._savepoints: list[_SessionSavepoint] = []
70
+ self._running_commit_hooks = False
71
+
72
+ def _usable_in_current_task(self) -> bool:
73
+ return not self._closed and (
74
+ self._owner_task is None or self._owner_task is _current_task() or self._owner_task.done()
75
+ )
76
+
77
+ def _check_owner(self) -> None:
78
+ """Reject concurrent sharing before touching a connection or transaction."""
79
+ if self._closed:
80
+ raise TransactionError("Session is closed; open a new ctx_session()")
81
+ task = _current_task()
82
+ if self._owner_task is None or self._owner_task.done():
83
+ # Sequential handoff is safe once the previous task has finished.
84
+ self._owner_task = task
85
+ elif self._owner_task is not task:
86
+ raise TransactionError(
87
+ "Session belongs to another asyncio task; open a separate ctx_session() in each task"
88
+ )
89
+
90
+ def _check_database_operation(self) -> None:
91
+ self._check_owner()
92
+ if self._running_commit_hooks:
93
+ raise TransactionError("An on_commit callback must use a new session for database operations")
44
94
 
45
95
  @property
46
96
  def db_name(self) -> str:
@@ -65,13 +115,30 @@ class AsyncSession:
65
115
  # Return engine if no connection yet
66
116
  return get_database(self._db_name).engine
67
117
 
68
- async def execute(self, statement: Any, parameters: Any = None) -> "CursorResult[Any]":
118
+ def _validate_statement_dialect(self, statement: Any) -> None:
119
+ if not isinstance(statement, ClauseElement) or self.bind.dialect.name == "postgresql":
120
+ return
121
+ # Check nested SELECTs too: counts, scalar subqueries and CTEs must not
122
+ # silently lose DISTINCT ON when SQLAlchemy compiles another dialect.
123
+ if any(getattr(part, "_distinct_on", ()) for part in visitors.iterate(statement)):
124
+ raise QueryError(
125
+ "distinct(*fields) requires PostgreSQL; use distinct() with values()/values_list() instead"
126
+ )
127
+
128
+ async def execute(self, statement: Any, parameters: Any = None) -> CursorResult[Any]:
69
129
  """Execute statement with automatic transaction management.
70
130
 
71
131
  Supports both SQLAlchemy statement objects and raw SQL strings.
72
132
  Raw SQL strings are automatically wrapped with text().
73
133
  """
134
+ self._check_database_operation()
135
+ if self._rollback_only:
136
+ raise TransactionError("Transaction failed; roll it back before executing more statements")
137
+ if self.readonly and getattr(statement, "is_dml", False):
138
+ raise TransactionError("Cannot execute a write using a readonly session")
139
+ self._validate_statement_dialect(statement)
74
140
  await self._ensure_connection()
141
+ assert self._conn is not None
75
142
 
76
143
  # Auto-wrap string SQL with text()
77
144
  if isinstance(statement, str):
@@ -79,13 +146,17 @@ class AsyncSession:
79
146
 
80
147
  # Auto-begin transaction for non-readonly sessions
81
148
  if not self.readonly and self._trans is None:
82
- self._trans = await self._conn.begin() # type: ignore
149
+ self._trans = await self._conn.begin()
83
150
 
84
151
  try:
85
- result = await self._conn.execute(statement, parameters) # type: ignore
152
+ try:
153
+ result = await self._conn.execute(statement, parameters)
154
+ except Exception as e:
155
+ await self._handle_exception(e)
156
+ raise
86
157
 
87
158
  # Auto-commit for implicit sessions
88
- if self.auto_commit:
159
+ if self.auto_commit and not self._conn.in_nested_transaction():
89
160
  await self.commit()
90
161
 
91
162
  # Buffer rows before closing so the connection can be returned to the pool.
@@ -96,14 +167,11 @@ class AsyncSession:
96
167
  result = result.freeze()()
97
168
 
98
169
  return result # type: ignore[return-value]
99
- except Exception as e:
100
- await self._handle_exception(e)
101
- raise # unreachable, _handle_exception always raises
102
170
  finally:
103
171
  # Auto-close connection for implicit sessions to prevent resource leaks
104
172
  # This covers both auto_commit write sessions and readonly sessions
105
- if self.auto_commit or self.readonly:
106
- await self.close()
173
+ if (self.auto_commit or self.readonly) and self._conn and not self._conn.in_nested_transaction():
174
+ await self._release_connection()
107
175
 
108
176
  async def stream(self, statement: Any, parameters: Any = None) -> AsyncResult[Any]:
109
177
  """Execute statement and return streaming result.
@@ -114,11 +182,15 @@ class AsyncSession:
114
182
  Note: stream() is not supported with auto_commit=True sessions.
115
183
  Use explicit sessions (ctx_session) for streaming operations.
116
184
  """
185
+ self._check_database_operation()
186
+ if self._rollback_only:
187
+ raise TransactionError("Transaction failed; roll it back before executing more statements")
117
188
  if self.auto_commit:
118
189
  raise ValueError(
119
190
  "stream() not supported with auto_commit=True. Use ctx_session() or explicit session management."
120
191
  )
121
192
 
193
+ self._validate_statement_dialect(statement)
122
194
  await self._ensure_connection()
123
195
 
124
196
  # Auto-wrap string SQL with text()
@@ -136,18 +208,116 @@ class AsyncSession:
136
208
 
137
209
  async def commit(self):
138
210
  """Commit transaction if exists and not readonly."""
139
- if self._trans and not self.readonly:
140
- await self._trans.commit()
141
- self._trans = None
211
+ self._check_database_operation()
212
+ if self._rollback_only:
213
+ raise TransactionError("Cannot commit a failed transaction; roll it back")
214
+ try:
215
+ if self._trans and not self.readonly:
216
+ await self._trans.commit()
217
+ self._trans = None
218
+ except BaseException:
219
+ self._commit_hooks.clear()
220
+ self._rollback_only = True
221
+ raise
222
+ self._savepoints.clear()
223
+ if self._commit_hooks:
224
+ hooks, self._commit_hooks = self._commit_hooks, []
225
+ # Return the connection first, including for pools with only one slot.
226
+ await self._release_connection()
227
+ await self._run_commit_hooks(hooks)
228
+
229
+ async def on_commit(self, callback: Callable[[], Any], *, robust: bool = False) -> None:
230
+ """Await a callback after commit, or immediately outside a write transaction.
231
+
232
+ Explicit writable sessions queue callbacks even before the first SQL
233
+ statement. Pass a callable, not an already-created coroutine. Rollback
234
+ discards callbacks; robust=True logs ordinary errors and continues.
235
+ """
236
+ self._check_owner()
237
+ if not callable(callback):
238
+ raise TypeError("on_commit requires a callable")
239
+ if self.readonly or self._rollback_only:
240
+ raise TransactionError("on_commit requires a writable, non-failed session")
241
+ hook = _CommitHook(callback, robust, tuple(self._savepoints))
242
+ if self._running_commit_hooks or (self.auto_commit and not self.in_transaction):
243
+ await self._run_commit_hook(hook)
244
+ else:
245
+ self._commit_hooks.append(hook)
246
+
247
+ @staticmethod
248
+ async def _run_commit_hook(hook: _CommitHook) -> None:
249
+ try:
250
+ result = hook.callback()
251
+ if inspect.isawaitable(result):
252
+ await result
253
+ except Exception:
254
+ if not hook.robust:
255
+ raise
256
+ name = getattr(hook.callback, "__qualname__", type(hook.callback).__name__)
257
+ logger.exception("Error in on_commit callback %s", name)
258
+
259
+ async def _run_commit_hooks(self, hooks: list[_CommitHook]) -> None:
260
+ # ORM calls in a callback must not join a transaction that has just ended.
261
+ sessions = _explicit_sessions.get({}).copy()
262
+ sessions.pop(self.db_name, None)
263
+ token = _explicit_sessions.set(sessions)
264
+ self._running_commit_hooks = True
265
+ try:
266
+ for hook in hooks:
267
+ await self._run_commit_hook(hook)
268
+ finally:
269
+ self._running_commit_hooks = False
270
+ _explicit_sessions.reset(token)
142
271
 
143
272
  async def rollback(self):
144
273
  """Rollback transaction if exists and not readonly."""
274
+ self._check_database_operation()
275
+ self._commit_hooks.clear()
276
+ self._savepoints.clear()
145
277
  if self._trans and not self.readonly:
146
278
  await self._trans.rollback()
147
279
  self._trans = None
280
+ self._rollback_only = False
281
+
282
+ @asynccontextmanager
283
+ async def transaction(self):
284
+ """Join an explicit transaction, or own a transaction for a compound operation."""
285
+ self._check_database_operation()
286
+ if self.readonly:
287
+ raise TransactionError("A write transaction requires a writable session")
288
+ if self.auto_commit:
289
+ async with ctx_session(self.db_name) as session:
290
+ yield session
291
+ else:
292
+ yield self
148
293
 
149
294
  async def close(self):
150
295
  """Close session and cleanup resources."""
296
+ if self._closed:
297
+ return
298
+ self._check_database_operation()
299
+ await self._dispose()
300
+
301
+ async def _dispose(self) -> None:
302
+ """Release resources without the task-ownership check.
303
+
304
+ For sessions owned by internal machinery only: asyncio finalizes an
305
+ abandoned async generator (an ``iterator()`` left by ``break``) from a
306
+ different task, and refusing to clean up there would leak the connection
307
+ and its transaction. Caller-owned sessions keep the ``close()`` contract.
308
+ """
309
+ if self._closed:
310
+ return
311
+ try:
312
+ await self._release_connection()
313
+ finally:
314
+ self._closed = True
315
+ self._owner_task = None
316
+
317
+ async def _release_connection(self):
318
+ """Release resources without ending a reusable implicit session's lifetime."""
319
+ self._commit_hooks.clear()
320
+ self._savepoints.clear()
151
321
  if self._trans:
152
322
  try:
153
323
  await self._trans.rollback()
@@ -166,13 +336,49 @@ class AsyncSession:
166
336
 
167
337
  async def begin_nested(self):
168
338
  """Begin nested transaction (savepoint)."""
339
+ self._check_database_operation()
340
+ if self._rollback_only or self.readonly:
341
+ raise TransactionError("Cannot create a savepoint in a failed or readonly session")
169
342
  await self._ensure_connection()
170
343
  if not self._trans:
171
344
  self._trans = await self._conn.begin() # type: ignore
172
- return await self._conn.begin_nested() # type: ignore
345
+ assert self._conn is not None
346
+ # SQLite legacy mode may have a logical transaction but no physical BEGIN yet.
347
+ if self._conn.dialect.name == "sqlite":
348
+ sync_connection = self._conn.sync_connection
349
+ assert sync_connection is not None
350
+ driver = cast(Any, sync_connection.connection.driver_connection)
351
+ if not driver.in_transaction:
352
+ await self._conn.exec_driver_sql("BEGIN")
353
+ savepoint = _SessionSavepoint(self, await self._conn.begin_nested())
354
+ self._savepoints.append(savepoint)
355
+ return savepoint
356
+
357
+ def _finish_savepoint(self, savepoint: _SessionSavepoint, *, rolled_back: bool) -> None:
358
+ if rolled_back:
359
+ self._commit_hooks = [hook for hook in self._commit_hooks if savepoint not in hook.savepoints]
360
+ if savepoint in self._savepoints:
361
+ del self._savepoints[self._savepoints.index(savepoint) :]
362
+
363
+ async def _complete_implicit_transaction(self) -> None:
364
+ """Commit the transaction an implicit session opened only for savepoints.
365
+
366
+ Statements on an auto_commit session commit individually, so once the
367
+ outermost savepoint has been released or rolled back nothing else is
368
+ pending and the owned transaction must end; otherwise ``close()`` would
369
+ roll back the released savepoint's work.
370
+ """
371
+ if not self.auto_commit or self._savepoints or not self._trans:
372
+ return
373
+ try:
374
+ await self.commit()
375
+ finally:
376
+ if self._conn and not self._conn.in_nested_transaction():
377
+ await self._release_connection()
173
378
 
174
379
  async def _ensure_connection(self):
175
380
  """Ensure connection is available with health check."""
381
+ self._check_database_operation()
176
382
  if self._conn is None or self._conn.closed:
177
383
  engine = get_database(self._db_name).engine
178
384
  self._conn = await engine.connect()
@@ -183,7 +389,14 @@ class AsyncSession:
183
389
 
184
390
  async def _handle_exception(self, exc: Exception):
185
391
  """Handle exceptions with unified error processing."""
186
- await self.rollback()
392
+ nested = bool(self._conn and self._conn.in_nested_transaction())
393
+ if self.auto_commit and not nested:
394
+ await self.rollback()
395
+ elif not self.readonly and not nested:
396
+ # Readonly sessions never hold a transaction and release their
397
+ # connection after every statement, so a failed query must not
398
+ # make the session unusable.
399
+ self._rollback_only = True
187
400
 
188
401
  # Log detailed error for debugging when echo is enabled
189
402
  if hasattr(self.bind, "echo") and getattr(self.bind, "echo", False):
@@ -195,10 +408,11 @@ class AsyncSession:
195
408
 
196
409
  if isinstance(exc, SQLAlchemyError):
197
410
  raise convert_sqlalchemy_error(exc) from exc
198
- raise
411
+ raise exc
199
412
 
200
- async def __aenter__(self) -> "AsyncSession":
413
+ async def __aenter__(self) -> AsyncSession:
201
414
  """Async context manager entry."""
415
+ self._check_owner()
202
416
  return self
203
417
 
204
418
  async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
@@ -213,10 +427,85 @@ class AsyncSession:
213
427
  def __getattr__(self, name: str) -> Any:
214
428
  """Proxy AsyncConnection methods."""
215
429
  if self._conn and hasattr(self._conn, name):
216
- return getattr(self._conn, name)
430
+ self._check_owner()
431
+ attribute = getattr(self._conn, name)
432
+ if inspect.iscoroutinefunction(attribute):
433
+
434
+ async def guarded(*args, **kwargs):
435
+ self._check_database_operation()
436
+ return await attribute(*args, **kwargs)
437
+
438
+ return guarded
439
+ return attribute
217
440
  raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'")
218
441
 
219
442
 
443
+ class _SessionSavepoint:
444
+ """A started savepoint that also tracks callback scope and task ownership."""
445
+
446
+ def __init__(self, session: AsyncSession, transaction: AsyncTransaction):
447
+ self._session = session
448
+ self._transaction = transaction
449
+
450
+ @property
451
+ def is_active(self) -> bool:
452
+ return self._transaction.is_active
453
+
454
+ @property
455
+ def is_valid(self) -> bool:
456
+ return self._transaction.is_valid
457
+
458
+ @property
459
+ def connection(self) -> AsyncConnection:
460
+ self._session._check_database_operation()
461
+ return self._transaction.connection
462
+
463
+ def _check_scope(self) -> None:
464
+ self._session._check_database_operation()
465
+ if self.is_active and (not self._session._savepoints or self._session._savepoints[-1] is not self):
466
+ raise TransactionError("Savepoints must be finished in reverse creation order")
467
+
468
+ async def commit(self) -> None:
469
+ self._check_scope()
470
+ try:
471
+ await self._transaction.commit()
472
+ except BaseException:
473
+ self._session._finish_savepoint(self, rolled_back=True)
474
+ self._session._rollback_only = True
475
+ raise
476
+ self._session._finish_savepoint(self, rolled_back=False)
477
+ await self._session._complete_implicit_transaction()
478
+
479
+ async def rollback(self) -> None:
480
+ self._check_scope()
481
+ if not self.is_active:
482
+ return
483
+ try:
484
+ await self._transaction.rollback()
485
+ except BaseException:
486
+ self._session._rollback_only = True
487
+ raise
488
+ finally:
489
+ self._session._finish_savepoint(self, rolled_back=True)
490
+ await self._session._complete_implicit_transaction()
491
+
492
+ async def close(self) -> None:
493
+ await self.rollback()
494
+
495
+ async def __aenter__(self) -> _SessionSavepoint:
496
+ self._session._check_database_operation()
497
+ if not self.is_active:
498
+ raise TransactionError("Savepoint is no longer active")
499
+ return self
500
+
501
+ async def __aexit__(self, exc_type, exc_value, traceback) -> None:
502
+ if self.is_active:
503
+ if exc_type is None:
504
+ await self.commit()
505
+ else:
506
+ await self.rollback()
507
+
508
+
220
509
  class _SessionContextManager:
221
510
  """Internal multi-database session context manager.
222
511
 
@@ -254,7 +543,9 @@ class _SessionContextManager:
254
543
  try:
255
544
  explicit_sessions = _explicit_sessions.get({})
256
545
  if name in explicit_sessions:
257
- return explicit_sessions[name]
546
+ session = explicit_sessions[name]
547
+ session._check_owner()
548
+ return session
258
549
  except LookupError:
259
550
  pass
260
551
 
@@ -264,7 +555,7 @@ class _SessionContextManager:
264
555
  @classmethod
265
556
  def set_session(
266
557
  cls, session: AsyncSession, db_name: str | None = None
267
- ) -> contextvars.Token[dict[str, "AsyncSession"]]:
558
+ ) -> contextvars.Token[dict[str, AsyncSession]]:
268
559
  """Set active session in current context.
269
560
 
270
561
  Returns a Token that can be used with reset_session() to restore the
@@ -280,7 +571,7 @@ class _SessionContextManager:
280
571
  return _explicit_sessions.set(new_sessions)
281
572
 
282
573
  @classmethod
283
- def reset_session(cls, token: contextvars.Token[dict[str, "AsyncSession"]]) -> None:
574
+ def reset_session(cls, token: contextvars.Token[dict[str, AsyncSession]]) -> None:
284
575
  """Restore ContextVar to a previous state using a token from set_session()."""
285
576
  _explicit_sessions.reset(token)
286
577
 
@@ -321,7 +612,7 @@ async def ctx_session(db_name: str | None = None, *, join_ambient: bool = False)
321
612
  """
322
613
  name = db_name or get_default()
323
614
 
324
- if join_ambient and has_session(name):
615
+ if join_ambient and name in _explicit_sessions.get({}):
325
616
  yield get_session(name, readonly=False)
326
617
  return
327
618
 
@@ -343,14 +634,16 @@ async def ctx_session(db_name: str | None = None, *, join_ambient: bool = False)
343
634
  yield session
344
635
  # Auto-commit on successful exit
345
636
  await session.commit()
346
- except Exception:
637
+ except BaseException:
347
638
  # Auto-rollback on exception
348
639
  await session.rollback()
349
640
  raise
350
641
  finally:
351
642
  # Cleanup
352
- await session.close()
353
- _SessionContextManager.reset_session(token)
643
+ try:
644
+ await session.close()
645
+ finally:
646
+ _SessionContextManager.reset_session(token)
354
647
 
355
648
 
356
649
  @asynccontextmanager
@@ -385,7 +678,7 @@ async def ctx_sessions(*db_names: str) -> AsyncGenerator[dict[str, AsyncSession]
385
678
  for session in sessions.values():
386
679
  await session.commit()
387
680
 
388
- except Exception:
681
+ except BaseException:
389
682
  # Auto-rollback all sessions on exception
390
683
  for session in sessions.values():
391
684
  await session.rollback()
@@ -393,11 +686,14 @@ async def ctx_sessions(*db_names: str) -> AsyncGenerator[dict[str, AsyncSession]
393
686
 
394
687
  finally:
395
688
  # Cleanup all sessions
396
- for session in sessions.values():
397
- await session.close()
398
- # Reset tokens in reverse order
399
- for token in reversed(tokens):
400
- _SessionContextManager.reset_session(token)
689
+ try:
690
+ async with AsyncExitStack() as cleanup:
691
+ for session in sessions.values():
692
+ cleanup.push_async_callback(session.close)
693
+ finally:
694
+ # Reset tokens even if closing a connection fails.
695
+ for token in reversed(tokens):
696
+ _SessionContextManager.reset_session(token)
401
697
 
402
698
 
403
699
  def get_session(
@@ -419,6 +715,7 @@ def get_session(
419
715
  - Create a new AsyncSession with specified parameters if no explicit session
420
716
  """
421
717
  if isinstance(db_or_name, AsyncSession):
718
+ db_or_name._check_owner()
422
719
  return db_or_name
423
720
  return _SessionContextManager.get_session(db_or_name, readonly, auto_commit)
424
721
 
@@ -435,6 +732,13 @@ def has_session(db_name: str | None = None) -> bool:
435
732
  name = db_name or get_default()
436
733
  try:
437
734
  explicit_sessions = _explicit_sessions.get({})
438
- return name in explicit_sessions
735
+ return name in explicit_sessions and explicit_sessions[name]._usable_in_current_task()
439
736
  except LookupError:
440
737
  return False
738
+
739
+
740
+ async def on_commit(
741
+ callback: Callable[[], Any], db_or_session: str | AsyncSession | None = None, *, robust: bool = False
742
+ ) -> None:
743
+ """Register a callback on the selected writable session, or run it immediately."""
744
+ await get_session(db_or_session, readonly=False).on_commit(callback, robust=robust)