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/signals.py CHANGED
@@ -121,6 +121,10 @@ class SignalContext:
121
121
  """
122
122
  return self.instance is not None
123
123
 
124
+ async def on_commit(self, callback: Callable[[], Any], *, robust: bool = False) -> None:
125
+ """Defer an effect until this signal's database transaction commits."""
126
+ await self.session.on_commit(callback, robust=robust)
127
+
124
128
 
125
129
  class SignalMixin:
126
130
  """Mixin class that provides signal handling capabilities to model classes.
@@ -225,15 +229,44 @@ def emit_signals(operation: Operation, is_bulk: bool = False):
225
229
  """
226
230
 
227
231
  def decorator(func: F) -> F:
232
+ signature = inspect.signature(func)
233
+
228
234
  @functools.wraps(func)
229
235
  async def wrapper(*args, **kwargs):
230
- # Extract self/cls and session from arguments
231
236
  self_or_cls = args[0]
232
- session = _extract_session(self_or_cls, kwargs)
237
+ arguments = signature.bind_partial(*args, **kwargs)
238
+ session = _extract_session(self_or_cls, arguments.arguments)
239
+
240
+ if is_bulk and hasattr(self_or_cls, "_executor"):
241
+ # QuerySet write signals share the same transaction as the SQL.
242
+ self_or_cls._validate_write_query()
243
+ async with session.transaction() as transaction:
244
+ arguments.arguments[next(iter(signature.parameters))] = self_or_cls.using(transaction)
245
+ return await invoke(arguments, transaction)
246
+ if (
247
+ not is_bulk
248
+ and "session" in signature.parameters
249
+ and getattr(session, "auto_commit", False)
250
+ and not getattr(session, "readonly", True)
251
+ ):
252
+ # Instance writes on an implicit session own one transaction that
253
+ # spans the hooks and the SQL, so context.on_commit() runs after
254
+ # the row is actually committed rather than before it is written.
255
+ async with session.transaction() as transaction:
256
+ arguments.arguments["session"] = transaction
257
+ return await invoke(arguments, transaction)
258
+ return await invoke(arguments, session)
259
+
260
+ async def invoke(arguments, session):
261
+ self_or_cls = arguments.args[0]
233
262
 
234
263
  # Create signal context with original operation
235
264
  context = _create_signal_context(
236
- operation=operation, session=session, self_or_cls=self_or_cls, is_bulk=is_bulk, kwargs=kwargs
265
+ operation=operation,
266
+ session=session,
267
+ self_or_cls=self_or_cls,
268
+ is_bulk=is_bulk,
269
+ kwargs=arguments.arguments,
237
270
  )
238
271
 
239
272
  # For SAVE operations, determine actual CREATE/UPDATE type
@@ -246,20 +279,10 @@ def emit_signals(operation: Operation, is_bulk: bool = False):
246
279
  # Emit pre signal
247
280
  await _emit_pre_signal(self_or_cls, context, is_bulk)
248
281
 
249
- try:
250
- # Execute original method
251
- result = await func(*args, **kwargs)
252
-
253
- # Update context with result if needed
254
- _update_context_with_result(context, result)
255
-
256
- # Emit post signal
257
- await _emit_post_signal(self_or_cls, context, is_bulk)
258
-
259
- return result
260
-
261
- except Exception:
262
- raise
282
+ result = await func(*arguments.args, **arguments.kwargs)
283
+ _update_context_with_result(context, result)
284
+ await _emit_post_signal(self_or_cls, context, is_bulk)
285
+ return result
263
286
 
264
287
  return wrapper # type: ignore
265
288
 
@@ -294,19 +317,24 @@ def _extract_session(self_or_cls, kwargs) -> Any:
294
317
  Database session for the operation
295
318
  """
296
319
  # Try to get session from kwargs first
297
- if "session" in kwargs:
320
+ if kwargs.get("session") is not None:
298
321
  return kwargs["session"]
299
322
 
323
+ if hasattr(self_or_cls, "get_session"):
324
+ return self_or_cls.get_session(readonly=False)
325
+
300
326
  # Try to get session from instance/class - support both property and method
301
327
  if hasattr(self_or_cls, "_session"):
302
328
  session_attr = self_or_cls._session # noqa
303
329
  # Handle both property and method cases
304
330
  return session_attr() if callable(session_attr) else session_attr
305
331
  elif hasattr(self_or_cls, "_get_session"):
306
- return self_or_cls._get_session() # noqa
332
+ return self_or_cls._get_session(readonly=False) # noqa
333
+ elif hasattr(self_or_cls, "_executor"):
334
+ return self_or_cls._executor._get_session("update") # noqa
307
335
 
308
336
  # Fallback to default session
309
- return get_session()
337
+ return get_session(readonly=False)
310
338
 
311
339
 
312
340
  def _create_signal_context(operation: Operation, session, self_or_cls, is_bulk: bool, kwargs: dict) -> SignalContext:
@@ -324,7 +352,9 @@ def _create_signal_context(operation: Operation, session, self_or_cls, is_bulk:
324
352
  """
325
353
  if is_bulk:
326
354
  # Bulk operation context - support ObjectsManager and QuerySet
327
- if hasattr(self_or_cls, "_model"):
355
+ if hasattr(self_or_cls, "_model_class"):
356
+ model_class = self_or_cls._model_class # noqa
357
+ elif hasattr(self_or_cls, "_model"):
328
358
  model_class = self_or_cls._model # noqa
329
359
  elif hasattr(self_or_cls, "__table__"):
330
360
  model_class = self_or_cls.__class__
@@ -421,29 +451,26 @@ async def _emit_signal(target, timing: str, context: SignalContext) -> None:
421
451
  save_signal_name = f"{timing}_{bulk_prefix}save"
422
452
  save_handler = getattr(target, save_signal_name, None)
423
453
  if save_handler and callable(save_handler):
424
- if inspect.iscoroutinefunction(save_handler):
425
- await save_handler(context)
426
- else:
427
- save_handler(context)
454
+ result = save_handler(context)
455
+ if inspect.isawaitable(result):
456
+ await result
428
457
 
429
458
  # Then emit specific CREATE/UPDATE signal
430
459
  specific_signal_name = f"{timing}_{bulk_prefix}{context.actual_operation.value}"
431
460
  specific_handler = getattr(target, specific_signal_name, None)
432
461
  if specific_handler and callable(specific_handler):
433
- if inspect.iscoroutinefunction(specific_handler):
434
- await specific_handler(context)
435
- else:
436
- specific_handler(context)
462
+ result = specific_handler(context)
463
+ if inspect.isawaitable(result):
464
+ await result
437
465
  else:
438
466
  # For non-SAVE operations, emit the specific signal
439
467
  signal_name = f"{timing}_{bulk_prefix}{context.operation.value}"
440
468
  handler = getattr(target, signal_name, None)
441
469
 
442
470
  if handler and callable(handler):
443
- if inspect.iscoroutinefunction(handler):
444
- await handler(context)
445
- else:
446
- handler(context)
471
+ result = handler(context)
472
+ if inspect.isawaitable(result):
473
+ await result
447
474
 
448
475
 
449
476
  def _update_context_with_result(context: SignalContext, result):
sqlobjects/sql_logging.py CHANGED
@@ -15,9 +15,15 @@ from __future__ import annotations
15
15
  import inspect
16
16
  import logging
17
17
  import os
18
- from collections.abc import Mapping
18
+ from collections.abc import Iterator, Mapping
19
+ from time import perf_counter
20
+ from types import FrameType
19
21
  from typing import Any
20
22
 
23
+ from greenlet import getcurrent
24
+ from sqlalchemy import event
25
+ from sqlalchemy.engine import Engine
26
+
21
27
 
22
28
  __all__ = ["get_caller_frame", "ObjectLogger"]
23
29
 
@@ -57,6 +63,23 @@ def _should_skip_frame(
57
63
  return False
58
64
 
59
65
 
66
+ def _caller_frames() -> Iterator[FrameType]:
67
+ """Walk Python frames, including parents suspended by SQLAlchemy's greenlet."""
68
+ current = getcurrent()
69
+ frame = inspect.currentframe()
70
+ try:
71
+ while True:
72
+ while frame is not None:
73
+ yield frame
74
+ frame = frame.f_back
75
+ current = current.parent
76
+ if current is None:
77
+ break
78
+ frame = current.gr_frame
79
+ finally:
80
+ del frame
81
+
82
+
60
83
  def _find_user_frame(
61
84
  extra_skip_packages: list[str] | None = None,
62
85
  ) -> inspect.FrameInfo | None:
@@ -66,10 +89,10 @@ def _find_user_frame(
66
89
  FrameInfo instead of a formatted string. Returns None if no frame found.
67
90
  """
68
91
  extra_skip_prefixes: tuple[str, ...] = tuple(extra_skip_packages) if extra_skip_packages else ()
69
- for frame_info in inspect.stack():
70
- module = frame_info.frame.f_globals.get("__name__", "")
71
- if not _should_skip_frame(frame_info.filename, module, extra_skip_prefixes):
72
- return frame_info
92
+ for frame in _caller_frames():
93
+ module = frame.f_globals.get("__name__", "")
94
+ if not _should_skip_frame(frame.f_code.co_filename, module, extra_skip_prefixes):
95
+ return inspect.FrameInfo(frame, *inspect.getframeinfo(frame, context=0))
73
96
  return None
74
97
 
75
98
 
@@ -97,12 +120,12 @@ def get_caller_frame(
97
120
  extra_skip_prefixes: tuple[str, ...] = tuple(extra_skip_packages) if extra_skip_packages else ()
98
121
  frames: list[str] = []
99
122
 
100
- for frame_info in inspect.stack():
101
- module = frame_info.frame.f_globals.get("__name__", "")
102
- if _should_skip_frame(frame_info.filename, module, extra_skip_prefixes):
123
+ for frame in _caller_frames():
124
+ module = frame.f_globals.get("__name__", "")
125
+ if _should_skip_frame(frame.f_code.co_filename, module, extra_skip_prefixes):
103
126
  continue
104
- rel_path = _relative_path(frame_info.filename)
105
- frames.append(f"{rel_path}:{frame_info.lineno} in {frame_info.function}")
127
+ rel_path = _relative_path(frame.f_code.co_filename)
128
+ frames.append(f"{rel_path}:{frame.f_lineno} in {frame.f_code.co_name}")
106
129
  if len(frames) >= max_frames:
107
130
  break
108
131
 
@@ -196,5 +219,71 @@ def _install_object_logger(name: str) -> ObjectLogger:
196
219
  return logger
197
220
 
198
221
 
199
- # Module-level instance — imported by executor.py and usable by callers
222
+ # Module-level instance shared by all database engines and usable by callers.
200
223
  _sql_logger: ObjectLogger = _install_object_logger("sqlobjects.sql")
224
+
225
+
226
+ def _install_query_logging(engine: Engine, db_name: str) -> None:
227
+ """Observe physical cursor executions without recompilation or row fetching."""
228
+ timing_key = "_sqlobjects_query_timing"
229
+
230
+ def start(context, statement, parameters, executemany):
231
+ if context is not None and _sql_logger.isEnabledFor(logging.DEBUG):
232
+ setattr(
233
+ context,
234
+ timing_key,
235
+ (perf_counter(), statement, None if engine.hide_parameters else parameters, executemany),
236
+ )
237
+
238
+ def do_execute(cursor, statement, parameters, context):
239
+ start(context, statement, parameters, False)
240
+
241
+ def do_executemany(cursor, statement, parameters, context):
242
+ start(context, statement, parameters, True)
243
+
244
+ def do_execute_no_params(cursor, statement, context):
245
+ start(context, statement, None, False)
246
+
247
+ def emit(context, cursor=None, error=None):
248
+ if context is None:
249
+ return
250
+ timing = context.__dict__.pop(timing_key, None)
251
+ if timing is None or not _sql_logger.isEnabledFor(logging.DEBUG):
252
+ return
253
+ started, statement, parameters, executemany = timing
254
+ duration_ms = (perf_counter() - started) * 1000
255
+ try:
256
+ _sql_logger.debug(
257
+ statement,
258
+ extra={
259
+ "sql": statement,
260
+ "params": None if engine.hide_parameters else parameters,
261
+ "duration_ms": duration_ms,
262
+ "db_name": db_name,
263
+ "dialect": engine.dialect.name,
264
+ "executemany": executemany,
265
+ "rowcount": cursor.rowcount if cursor is not None and error is None else None,
266
+ "success": error is None,
267
+ "error_type": type(error).__name__ if error is not None else None,
268
+ },
269
+ )
270
+ except Exception:
271
+ # Diagnostics must not roll back a successful write or replace a DB error.
272
+ pass
273
+
274
+ def after_execute(conn, cursor, statement, parameters, context, executemany):
275
+ emit(context, cursor)
276
+
277
+ def handle_error(exception_context):
278
+ emit(
279
+ exception_context.execution_context,
280
+ error=exception_context.original_exception,
281
+ )
282
+
283
+ # Dialect events receive each batch's actual SQL/params. For insertmanyvalues,
284
+ # after_cursor_execute receives the original unbatched statement/params.
285
+ event.listen(engine, "do_execute", do_execute)
286
+ event.listen(engine, "do_executemany", do_executemany)
287
+ event.listen(engine, "do_execute_no_params", do_execute_no_params)
288
+ event.listen(engine, "after_cursor_execute", after_execute)
289
+ event.listen(engine, "handle_error", handle_error)
@@ -1,7 +1,23 @@
1
+ import hashlib
1
2
  import re
2
3
 
3
4
 
4
- __all__ = ["to_snake_case", "to_camel_case"]
5
+ __all__ = ["to_snake_case", "to_camel_case", "schema_name"]
6
+
7
+
8
+ def schema_name(name: str, *, disambiguator: str | None = None) -> str:
9
+ """Keep generated schema identifiers within PostgreSQL's 63-byte limit.
10
+
11
+ The same physical name is used on every supported backend and in migrations.
12
+ Hash the complete name so identifiers sharing a long prefix remain distinct.
13
+ """
14
+ encoded = name.encode("utf-8")
15
+ if len(encoded) <= 63 and disambiguator is None:
16
+ return name
17
+ identity = encoded if disambiguator is None else encoded + b"\0" + disambiguator.encode("utf-8")
18
+ digest = hashlib.sha256(identity).hexdigest()[:10]
19
+ prefix = encoded[:52].decode("utf-8", errors="ignore")
20
+ return f"{prefix}_{digest}"
5
21
 
6
22
 
7
23
  def to_snake_case(name: str) -> str:
@@ -88,6 +88,33 @@ if has_session("analytics"):
88
88
 
89
89
  ## Best Practices
90
90
 
91
+ ### Database Events
92
+
93
+ - `db.on(name, **options)` targets that database's `engine.sync_engine`, with native
94
+ SQLAlchemy Engine/Pool/Dialect event names and callback arguments.
95
+ - Handlers must be synchronous and must not return awaitables. Declared async
96
+ functions, callable objects and async generators are rejected at registration.
97
+ - `commit` and `rollback` run before the driver completes the operation. Use
98
+ `await session.on_commit(callback)` for effects after successful commit.
99
+ - `before_commit`, `after_commit`, `before_rollback` and `after_rollback` are not
100
+ Engine events and are rejected; do not register them through `db.on()`.
101
+ - Pass native listener options such as `named=True` or `retval=True` where the
102
+ event supports them. Remove a listener with
103
+ `sqlalchemy.event.remove(db.engine.sync_engine, name, handler)`.
104
+ - Register before opening connections. Listener failures follow SQLAlchemy's
105
+ propagation rules. See the [event guide](../features/01-database-setup.md#database-events).
106
+
107
+ ### Async task ownership
108
+
109
+ - Open a separate `ctx_session()` inside each `asyncio.gather()` / `create_task()` worker.
110
+ - A copied ContextVar still references the parent's session; using or joining it
111
+ from another live task raises `TransactionError`.
112
+ - Keep operations in one transaction sequential in its owning task. Use
113
+ `asyncio.timeout()` for time limits without creating a different task.
114
+ - `has_session()` reports only an open session usable by the current task.
115
+ - A closed session cannot be reused. Background work must open a new context.
116
+ - Cancellation rolls back request/context transactions and releases their connections.
117
+
91
118
  ### ✅ Do
92
119
 
93
120
  - **Use context managers** for explicit transaction control
@@ -347,7 +374,7 @@ async def get_user(user_id: int, session: AsyncSession = Depends(get_db_session)
347
374
  ## SQL Logging
348
375
 
349
376
  SQLObjects ships zero-config SQL logging through the standard library `logging`
350
- module. Every executed statement is logged at `DEBUG` level to the logger named
377
+ module. Driver cursor executions are logged at `DEBUG` level to the logger named
351
378
  **`sqlobjects.sql`**. This logger is an `ObjectLogger` (installed automatically
352
379
  on import) that rewrites each record's caller fields — `pathname`, `filename`,
353
380
  `funcName`, `lineno` — to the first user-code frame, skipping internal
@@ -381,10 +408,22 @@ handler.setFormatter(logging.Formatter("%(pathname)s:%(lineno)d - %(message)s"))
381
408
  sql_logger.addHandler(handler)
382
409
  ```
383
410
 
384
- Statement compilation only happens when the logger is actually enabled for
385
- `DEBUG`, so leaving logging off has no runtime cost. Each record carries the
386
- compiled SQL as the message plus an `extra` dict with `sql`, `params`, and
387
- `duration_ms`.
411
+ Logging is installed on each database engine and covers reads, writes, bulk,
412
+ raw SQL and streaming. It does not compile statements again. Disabled logging
413
+ skips timing and frame inspection; enabled logging resolves the user frame
414
+ across the async greenlet bridge.
415
+
416
+ Each record carries `sql`, driver-format `params`, `duration_ms`, `db_name`,
417
+ `dialect`, `executemany`, `rowcount`, `success`, and `error_type`. Parameters may
418
+ be a dictionary, tuple or a sequence of parameter sets. `hide_parameters=True`
419
+ in `init_db()` makes `params` null, including on failure; raw SQL literals are
420
+ not redacted. Errors include only the exception class, not its message.
421
+
422
+ Records count driver calls, not ORM methods or returned rows. Timing excludes
423
+ pool checkout, compilation, later fetching, hydration and commit. `rowcount` can
424
+ be `-1` when unknown or null on failure. Driver failures and cancellation are
425
+ logged without replacing the original exception; ordinary handler failures do
426
+ not affect the database operation.
388
427
 
389
428
  ### Public API
390
429
 
@@ -10,6 +10,17 @@
10
10
 
11
11
  ## Common Usage
12
12
 
13
+ ### Application metadata and migrations
14
+
15
+ - Declare `__registry__ = ModelRegistry()` on an abstract application base before
16
+ defining models to isolate tables. Import it from `sqlobjects.metadata`.
17
+ - Subclasses inherit the registry; omitting it preserves the shared default.
18
+ - Pass the registry directly to Alembic as `target_metadata`, after importing all
19
+ application models. Set an explicit ownership filter for reflected tables.
20
+ - `create_tables()` creates missing tables; use Alembic revisions for schema changes.
21
+ - Migration revisions use historical Core table definitions, not current models
22
+ or ORM signals. Review autogenerated changes and add explicit data backfills.
23
+
13
24
  ### Basic Model
14
25
 
15
26
  ```python
@@ -89,6 +100,13 @@ class User(ObjectModel):
89
100
  ]
90
101
  ```
91
102
 
103
+ Automatic constraint and SQLObjects index names are limited to 63 UTF-8 bytes,
104
+ using a readable prefix and a stable hash when needed. Short, non-conflicting
105
+ names remain unchanged. Explicit names and SQLAlchemy convention names retain
106
+ control over their own naming rules. Partial-index identity includes bound values.
107
+ When upgrading an existing schema with long or conflicting generated names, inspect
108
+ the physical names and write a migration; pin names explicitly to preserve them.
109
+
92
110
  ### Named & Composite Foreign Keys
93
111
 
94
112
  For composite foreign keys, custom constraint names, or explicit referential
@@ -297,6 +315,13 @@ class User(ObjectModel):
297
315
  ]
298
316
  ```
299
317
 
318
+ Index order, expressions, sort direction, collation and dialect options are part
319
+ of an index definition. Keep both composite orders when both query patterns need
320
+ them. Use SQLAlchemy `Index` in `Config.indexes` for expressions. Deduplication
321
+ removes equivalent definitions; a unique index only replaces a plain index with
322
+ matching expressions and options. Conditional DDL indexes are preserved.
323
+ See [index definitions](../features/02-model-definition.md#index-definitions-and-deduplication).
324
+
300
325
  ## Troubleshooting
301
326
 
302
327
  ### Field Not in Constructor
@@ -111,10 +111,39 @@ users = await User.objects.annotate(
111
111
  ).all()
112
112
  ```
113
113
 
114
+ `aggregate()` evaluates filtered/joined rows after DISTINCT and LIMIT/OFFSET.
115
+ Hydration hints (`only()`/`defer()`) do not hide aggregate inputs. It shares its
116
+ statement with SQL rendering, scalar subqueries and EXPLAIN. Use
117
+ `.scalar_subquery()` for a single aggregate; single-field expressions also work
118
+ in column comparisons. Empty inputs keep SQL defaults (COUNT zero, SUM/AVG null).
119
+
120
+ For annotation inputs use `func.sum(sqlalchemy.column("alias"))`. After ordinary
121
+ DISTINCT, joined/scalar inputs must already be projected through `annotate()`;
122
+ adding an unselected input would change deduplication and raises `QueryError`.
123
+ Field-specific DISTINCT remains PostgreSQL-only. With `group_by()`, `aggregate()`
124
+ summarizes the resulting group rows, preserving HAVING and slices. Use grouping
125
+ keys or `sqlalchemy.column("annotation_alias")` as outer aggregate inputs; raw
126
+ model fields outside GROUP BY raise `QueryError`. Annotation aliases must not
127
+ shadow model columns. HAVING without explicit grouping and row locking are rejected.
128
+
114
129
  ### Grouping
115
130
 
116
- Grouped aggregation returns **one row per group**, not model instances — use
117
- values-mode: list the grouping columns and aggregate aliases in `.values()`.
131
+ Use `values()` to return individual groups. Use `aggregate()` to summarize them:
132
+
133
+ ```python
134
+ from sqlalchemy import column
135
+
136
+ summary = await User.objects.annotate(member_count=func.count()).group_by("department").aggregate(
137
+ departments=func.count(), average_members=func.avg(column("member_count"))
138
+ )
139
+ ```
140
+
141
+ `departments` counts groups. Order by an annotation alias (for example
142
+ `order_by("-member_count")`) before slicing to aggregate the selected groups.
143
+ Grouping expressions retain their SQL and table identity.
144
+
145
+ For **one row per group**, use values-mode: list the grouping columns and
146
+ aggregate aliases in `.values()`.
118
147
 
119
148
  ```python
120
149
  # Group by with aggregation → list[dict], one dict per group
@@ -207,7 +236,7 @@ count = await User.objects.skip_default_ordering().count()
207
236
 
208
237
  ```python
209
238
  # Scalar subquery (single value)
210
- avg_age = User.objects.aggregate(avg_age=func.avg(User.age)).subquery(query_type="scalar")
239
+ avg_age = User.objects.aggregate(avg_age=func.avg(User.age)).scalar_subquery()
211
240
  older_users = await User.objects.filter(User.age > avg_age).all()
212
241
 
213
242
  # EXISTS subquery (boolean condition)
@@ -452,7 +481,7 @@ users = await User.objects.only(
452
481
  ).order_by("-created_at").limit(10).offset(20).all()
453
482
 
454
483
  # Subquery
455
- avg_age = User.objects.aggregate(avg_age=func.avg(User.age)).subquery(query_type="scalar")
484
+ avg_age = User.objects.aggregate(avg_age=func.avg(User.age)).scalar_subquery()
456
485
  older_users = await User.objects.filter(User.age > avg_age).all()
457
486
 
458
487
  # Performance optimization
@@ -69,26 +69,48 @@ comments = await Comment.objects.select_related("post__author").all()
69
69
 
70
70
  ### Advanced prefetch_related
71
71
 
72
+ Dynamic relationships (`lazy="dynamic"`) cannot be eagerly loaded. See the
73
+ dynamic collection contract below before choosing this strategy.
74
+
75
+ Custom queryset keys must name declared relationships. Filtering and ordering are
76
+ supported; sliced querysets and arbitrary output aliases are rejected.
77
+
72
78
  ```python
73
- # Custom QuerySet for filtering and ordering
74
79
  users = await User.objects.prefetch_related(
75
- published_posts=Post.objects.filter(Post.is_published == True)
76
- .order_by('-created_at')
77
- .limit(5)
80
+ posts=Post.objects.filter(Post.is_published == True).order_by('-created_at')
78
81
  ).all()
79
82
 
80
- # Access prefetched data
81
83
  for user in users:
82
- recent_posts = await user.published_posts.fetch()
84
+ published_posts = await user.load_relation("posts")
83
85
 
84
- # Multiple advanced prefetch configurations
85
86
  users = await User.objects.prefetch_related(
86
- active_posts=Post.objects.filter(Post.status == "active"),
87
- draft_posts=Post.objects.filter(Post.status == "draft"),
88
- recent_comments=Comment.objects.order_by('-created_at').limit(10)
87
+ posts=Post.objects.filter(Post.status == "active"),
88
+ comments=Comment.objects.order_by('-created_at')
89
89
  ).all()
90
90
  ```
91
91
 
92
+ ### Dynamic Collections
93
+
94
+ - Define a one-to-many or many-to-many relationship with `lazy="dynamic"`; use
95
+ `RelatedQuerySet["Model"]` from `sqlobjects.fields` for its annotation.
96
+ - Query with `await parent.children.filter(...).all()`, `.count()`, `.exists()`,
97
+ projections, slices or `async for`. Query construction does not execute SQL.
98
+ - `.fetch()` and `load_relation()` requery without caching a list. Synchronous
99
+ iteration, `len()` and truthiness are rejected.
100
+ - New queries use the parent's current keys and database/session binding.
101
+ Existing QuerySets keep their original conditions and binding.
102
+ - A complete parent primary key is required. Load deferred relation keys before
103
+ constructing a query; null reference values yield an empty query.
104
+ - `remote_fields` selects the child FK when several point to the parent. Composite
105
+ FK mappings and non-primary references are supported. Existing M2M tables use
106
+ membership subqueries to prevent duplicate targets.
107
+ - Custom join conditions and scalar dynamic relationships are rejected. Use
108
+ `uselist=True` with `remote_fields` for self-referential child collections.
109
+ - QuerySet writes affect target rows, not M2M links. This proxy does not supply
110
+ relationship add/remove/set or manager creation methods.
111
+
112
+ See the [dynamic collection examples](../features/05-relationships.md#dynamic-collections).
113
+
92
114
  ### Accessing Relationships
93
115
 
94
116
  ```python
@@ -131,7 +153,7 @@ posts = await Post.objects.select_related(Post.author).all()
131
153
 
132
154
  # Good: Filtered prefetch
133
155
  users = await User.objects.prefetch_related(
134
- recent_posts=Post.objects.filter(
156
+ posts=Post.objects.filter(
135
157
  Post.created_at >= datetime.now(timezone.utc) - timedelta(days=7)
136
158
  ).order_by('-created_at')
137
159
  ).all()
@@ -349,7 +371,7 @@ posts = await Post.objects.select_related("author").defer(
349
371
 
350
372
  # Filter prefetched relationships
351
373
  users = await User.objects.prefetch_related(
352
- recent_posts=Post.objects.filter(
374
+ posts=Post.objects.filter(
353
375
  Post.created_at >= datetime.now(timezone.utc) - timedelta(days=7)
354
376
  ).order_by('-created_at').limit(10)
355
377
  ).all()
@@ -477,11 +499,11 @@ posts = await Post.objects.select_related("author").prefetch_related("comments",
477
499
 
478
500
  # Advanced prefetch with filtering
479
501
  users = await User.objects.prefetch_related(
480
- recent_posts=Post.objects.filter(
502
+ posts=Post.objects.filter(
481
503
  Post.created_at >= datetime.now(timezone.utc) - timedelta(days=7)
482
- ).order_by('-created_at').limit(5)
504
+ ).order_by('-created_at')
483
505
  ).all()
484
506
 
485
507
  for user in users:
486
- recent_posts = await user.recent_posts.fetch()
508
+ recent_posts = await user.load_relation("posts")
487
509
  ```
@@ -10,6 +10,23 @@
10
10
 
11
11
  ## Common Usage
12
12
 
13
+ ### Commit callbacks
14
+
15
+ - `after_*` signals describe operation completion, not transaction commit.
16
+ - Use `await context.on_commit(callback)` for external effects from an instance or bulk
17
+ signal, or `await session.on_commit(callback)` / `await on_commit(callback)`
18
+ from `sqlobjects.session` in application code.
19
+ - Pass a callable. Sync functions and awaitable return values run inline after
20
+ successful commit, in registration order. Rollback discards pending callbacks,
21
+ including those registered in a rolled-back savepoint.
22
+ - Manager `create()`, bulk methods and QuerySet writes provide transaction
23
+ boundaries for their hooks. For direct instance `save()`, use `ctx_session()`
24
+ when registering from `before_*`. Outside a transaction registration executes immediately.
25
+ - `robust=True` logs ordinary callback errors and continues. Callback errors never
26
+ undo an already committed transaction; cancellation is not swallowed.
27
+ - Open a new session for database work in callbacks. Use an outbox if delivery
28
+ must survive a process crash between commit and callback execution.
29
+
13
30
  ### Field-level Validation
14
31
 
15
32
  ```python
@@ -55,6 +72,10 @@ class User(ObjectModel):
55
72
 
56
73
  ### Instance-level Signals
57
74
 
75
+ `objects.create()` emits save/create instance hooks around an INSERT, including
76
+ when a primary key is supplied. Before hooks run before validation and SQL;
77
+ after hooks see the persisted instance. Sync handlers may return an awaitable.
78
+
58
79
  ```python
59
80
  from sqlobjects.model import ObjectModel
60
81
  from sqlobjects.signals import SignalContext
@@ -104,6 +125,17 @@ class User(ObjectModel):
104
125
 
105
126
  ### Bulk Operation Signals
106
127
 
128
+ Manager bulk methods emit class hooks once per batch, with no instance hooks.
129
+ Create/update also emit generic bulk-save hooks. Before counts are input sizes;
130
+ after counts match each batch's successful result count. Empty input emits no
131
+ hooks. QuerySet update/delete hooks run once per call; before counts are unknown,
132
+ and only QuerySet update supplies uniform `update_data`.
133
+
134
+ Use `context.session` for work in the batch transaction and `context.on_commit()`
135
+ for effects after its commit. Hook failures propagate even with `IGNORE` or
136
+ `COLLECT`; earlier committed batches remain stored. See the
137
+ [full signal contract](../features/06-validation-signals.md#bulk-operation-signals).
138
+
107
139
  ```python
108
140
  class User(ObjectModel):
109
141
  @classmethod