sqlobjects 2.0.1__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.
- sqlobjects/__init__.py +1 -1
- sqlobjects/cascade.py +22 -31
- sqlobjects/contrib/asgi.py +5 -3
- sqlobjects/database/manager.py +44 -30
- sqlobjects/expressions/aggregate.py +144 -83
- sqlobjects/expressions/scalar.py +5 -9
- sqlobjects/fields/__init__.py +2 -0
- sqlobjects/fields/core.py +3 -2
- sqlobjects/fields/proxies.py +78 -30
- sqlobjects/fields/relations/descriptors.py +4 -2
- sqlobjects/fields/relations/prefetch.py +62 -63
- sqlobjects/fields/relations/utils.py +50 -11
- sqlobjects/internal/results.py +1 -1
- sqlobjects/metadata.py +106 -30
- sqlobjects/mixins.py +24 -5
- sqlobjects/model.py +45 -72
- sqlobjects/objects/bulk.py +159 -245
- sqlobjects/objects/core.py +62 -58
- sqlobjects/objects/upsert.py +85 -8
- sqlobjects/queries/builder.py +77 -145
- sqlobjects/queries/dialect.py +4 -4
- sqlobjects/queries/executor.py +105 -209
- sqlobjects/queryset.py +64 -45
- sqlobjects/session.py +342 -38
- sqlobjects/signals.py +60 -33
- sqlobjects/sql_logging.py +100 -11
- sqlobjects/utils/naming.py +17 -1
- {sqlobjects-2.0.1.data → sqlobjects-2.1.0.data}/data/share/sqlobjects/rules/01-database-session-guide.md +44 -5
- {sqlobjects-2.0.1.data → sqlobjects-2.1.0.data}/data/share/sqlobjects/rules/02-model-definition-guide.md +25 -0
- {sqlobjects-2.0.1.data → sqlobjects-2.1.0.data}/data/share/sqlobjects/rules/03-query-operations-guide.md +33 -4
- {sqlobjects-2.0.1.data → sqlobjects-2.1.0.data}/data/share/sqlobjects/rules/05-relationships-guide.md +37 -15
- {sqlobjects-2.0.1.data → sqlobjects-2.1.0.data}/data/share/sqlobjects/rules/06-validation-signals-guide.md +32 -0
- {sqlobjects-2.0.1.dist-info → sqlobjects-2.1.0.dist-info}/METADATA +9 -2
- sqlobjects-2.1.0.dist-info/RECORD +75 -0
- sqlobjects-2.0.1.dist-info/RECORD +0 -75
- {sqlobjects-2.0.1.data → sqlobjects-2.1.0.data}/data/share/sqlobjects/rules/04-crud-operations-guide.md +0 -0
- {sqlobjects-2.0.1.data → sqlobjects-2.1.0.data}/data/share/sqlobjects/rules/07-performance-guide.md +0 -0
- {sqlobjects-2.0.1.data → sqlobjects-2.1.0.data}/data/share/sqlobjects/rules/README.md +0 -0
- {sqlobjects-2.0.1.dist-info → sqlobjects-2.1.0.dist-info}/WHEEL +0 -0
- {sqlobjects-2.0.1.dist-info → sqlobjects-2.1.0.dist-info}/entry_points.txt +0 -0
- {sqlobjects-2.0.1.dist-info → sqlobjects-2.1.0.dist-info}/licenses/LICENSE +0 -0
- {sqlobjects-2.0.1.dist-info → sqlobjects-2.1.0.dist-info}/top_level.txt +0 -0
sqlobjects/__init__.py
CHANGED
sqlobjects/cascade.py
CHANGED
|
@@ -355,35 +355,30 @@ class CascadeExecutor:
|
|
|
355
355
|
) -> "ObjectModel":
|
|
356
356
|
"""Execute save operation with cascade handling."""
|
|
357
357
|
if session is None:
|
|
358
|
-
session = get_session()
|
|
359
|
-
|
|
360
|
-
# Save root instance first to get primary key
|
|
361
|
-
await instance._save_internal(validate=validate, session=session) # noqa
|
|
362
|
-
|
|
363
|
-
# Process cascade relationships if needed
|
|
364
|
-
if hasattr(instance, "_state_manager"):
|
|
365
|
-
cascade_relationships = instance._state_manager.get_cascade_relationships() # noqa
|
|
366
|
-
if cascade_relationships:
|
|
367
|
-
await self._process_cascade_relationships(instance, session)
|
|
358
|
+
session = get_session(readonly=False)
|
|
368
359
|
|
|
360
|
+
async with session.transaction() as transaction:
|
|
361
|
+
await instance._save_internal(validate=validate, session=transaction)
|
|
362
|
+
if instance._state_manager.get_cascade_relationships():
|
|
363
|
+
await self._process_cascade_relationships(instance, transaction)
|
|
369
364
|
return instance
|
|
370
365
|
|
|
371
366
|
async def execute_delete_operation(
|
|
372
367
|
self, target, cascade_strategy: str = "auto", session: "AsyncSession | None" = None
|
|
373
368
|
) -> int:
|
|
374
369
|
"""Execute delete operation with cascade handling."""
|
|
370
|
+
is_queryset = hasattr(target, "_table") and hasattr(target, "_model_class")
|
|
375
371
|
if session is None:
|
|
376
|
-
session = get_session()
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
await
|
|
385
|
-
|
|
386
|
-
return 1
|
|
372
|
+
session = target._executor._get_session("delete") if is_queryset else target.get_session(readonly=False)
|
|
373
|
+
assert session is not None
|
|
374
|
+
async with session.transaction() as transaction:
|
|
375
|
+
if is_queryset:
|
|
376
|
+
target._validate_write_query()
|
|
377
|
+
return await self._execute_queryset_delete(target.using(transaction), cascade_strategy, transaction)
|
|
378
|
+
if has_cascade_delete_relations(target.__class__):
|
|
379
|
+
await self._delete_related_objects(target, transaction)
|
|
380
|
+
await target._delete_internal(session=transaction)
|
|
381
|
+
return 1
|
|
387
382
|
|
|
388
383
|
@staticmethod
|
|
389
384
|
async def execute_update_operation(queryset, values: dict, session: "AsyncSession | None" = None) -> int:
|
|
@@ -404,7 +399,7 @@ class CascadeExecutor:
|
|
|
404
399
|
if not instances:
|
|
405
400
|
return
|
|
406
401
|
if session is None:
|
|
407
|
-
session = get_session()
|
|
402
|
+
session = get_session(readonly=False)
|
|
408
403
|
|
|
409
404
|
# Filter valid instances
|
|
410
405
|
valid_instances = [
|
|
@@ -440,7 +435,7 @@ class CascadeExecutor:
|
|
|
440
435
|
if not instances:
|
|
441
436
|
return
|
|
442
437
|
if session is None:
|
|
443
|
-
session = get_session()
|
|
438
|
+
session = get_session(readonly=False)
|
|
444
439
|
valid_instances = []
|
|
445
440
|
for instance in instances:
|
|
446
441
|
if not hasattr(instance, "save"):
|
|
@@ -464,7 +459,7 @@ class CascadeExecutor:
|
|
|
464
459
|
if not instances:
|
|
465
460
|
return
|
|
466
461
|
if session is None:
|
|
467
|
-
session = get_session()
|
|
462
|
+
session = get_session(readonly=False)
|
|
468
463
|
valid_instances = []
|
|
469
464
|
for instance in instances:
|
|
470
465
|
if not hasattr(instance, "delete"):
|
|
@@ -486,7 +481,7 @@ class CascadeExecutor:
|
|
|
486
481
|
if not instances or not update_data:
|
|
487
482
|
return
|
|
488
483
|
if session is None:
|
|
489
|
-
session = get_session()
|
|
484
|
+
session = get_session(readonly=False)
|
|
490
485
|
valid_instances = []
|
|
491
486
|
for instance in instances:
|
|
492
487
|
if not hasattr(instance, "save"):
|
|
@@ -529,19 +524,15 @@ class CascadeExecutor:
|
|
|
529
524
|
|
|
530
525
|
batch_size = 50 if total_count > 100 else total_count
|
|
531
526
|
deleted_count = 0
|
|
532
|
-
offset = 0
|
|
533
|
-
|
|
534
527
|
while True:
|
|
535
|
-
batch = await queryset.
|
|
528
|
+
batch = await queryset.limit(batch_size).all()
|
|
536
529
|
if not batch:
|
|
537
530
|
break
|
|
538
531
|
|
|
539
532
|
for instance in batch:
|
|
540
|
-
await instance.using(session).delete(cascade=
|
|
533
|
+
await instance.using(session).delete(cascade=True)
|
|
541
534
|
deleted_count += 1
|
|
542
535
|
|
|
543
|
-
offset += batch_size
|
|
544
|
-
|
|
545
536
|
return deleted_count
|
|
546
537
|
|
|
547
538
|
async def _delete_with_fast_cascade(self, queryset, session: "AsyncSession") -> int:
|
sqlobjects/contrib/asgi.py
CHANGED
|
@@ -54,10 +54,12 @@ class SessionMiddleware:
|
|
|
54
54
|
await self.app(scope, receive, send)
|
|
55
55
|
if not self.readonly:
|
|
56
56
|
await session.commit()
|
|
57
|
-
except
|
|
57
|
+
except BaseException:
|
|
58
58
|
if not self.readonly:
|
|
59
59
|
await session.rollback()
|
|
60
60
|
raise
|
|
61
61
|
finally:
|
|
62
|
-
|
|
63
|
-
|
|
62
|
+
try:
|
|
63
|
+
await session.close()
|
|
64
|
+
finally:
|
|
65
|
+
_SessionContextManager.reset_session(token)
|
sqlobjects/database/manager.py
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
|
-
|
|
1
|
+
import inspect
|
|
2
|
+
from collections.abc import Callable, Mapping
|
|
2
3
|
from dataclasses import dataclass
|
|
3
|
-
from typing import Any,
|
|
4
|
+
from typing import Any, TypeVar
|
|
4
5
|
|
|
6
|
+
from sqlalchemy import event
|
|
5
7
|
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
|
|
6
8
|
|
|
9
|
+
from ..sql_logging import _install_query_logging
|
|
10
|
+
|
|
7
11
|
|
|
8
12
|
__all__ = [
|
|
9
13
|
"DatabaseConfig",
|
|
@@ -20,6 +24,9 @@ __all__ = [
|
|
|
20
24
|
]
|
|
21
25
|
|
|
22
26
|
|
|
27
|
+
_EventListener = TypeVar("_EventListener", bound=Callable[..., Any])
|
|
28
|
+
|
|
29
|
+
|
|
23
30
|
@dataclass(init=False)
|
|
24
31
|
class DatabaseConfig:
|
|
25
32
|
"""Database configuration class
|
|
@@ -130,49 +137,56 @@ class Database:
|
|
|
130
137
|
|
|
131
138
|
# Create async engine
|
|
132
139
|
self.engine: AsyncEngine = create_async_engine(config.url, **engine_kwargs)
|
|
140
|
+
_install_query_logging(self.engine.sync_engine, name)
|
|
133
141
|
|
|
134
|
-
def on(
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
"rollback",
|
|
142
|
-
"before_commit",
|
|
143
|
-
"before_rollback",
|
|
144
|
-
"after_commit",
|
|
145
|
-
"after_rollback",
|
|
146
|
-
"checkout",
|
|
147
|
-
"checkin",
|
|
148
|
-
"invalidate",
|
|
149
|
-
"soft_invalidate",
|
|
150
|
-
"close_detached",
|
|
151
|
-
],
|
|
152
|
-
):
|
|
153
|
-
"""Unified event registration method
|
|
142
|
+
def on(self, event_name: str, **options: Any) -> Callable[[_EventListener], _EventListener]:
|
|
143
|
+
"""Register a synchronous SQLAlchemy Engine, Pool or Dialect listener.
|
|
144
|
+
|
|
145
|
+
Listeners target this database's ``engine.sync_engine`` and receive
|
|
146
|
+
SQLAlchemy's native arguments. They must not return an awaitable.
|
|
147
|
+
The ``commit`` event runs before the driver commits; use
|
|
148
|
+
``await session.on_commit(callback)`` for effects after successful commit.
|
|
154
149
|
|
|
155
150
|
Args:
|
|
156
|
-
event_name:
|
|
151
|
+
event_name: Native SQLAlchemy event name, such as ``connect``,
|
|
152
|
+
``commit``, ``before_cursor_execute`` or ``handle_error``.
|
|
153
|
+
**options: Options forwarded to ``sqlalchemy.event.listen``,
|
|
154
|
+
such as ``named=True`` or ``retval=True`` where supported.
|
|
157
155
|
|
|
158
156
|
Returns:
|
|
159
|
-
|
|
157
|
+
A decorator that registers and returns the original callable.
|
|
158
|
+
|
|
159
|
+
Raises:
|
|
160
|
+
ValueError: For transaction event names that are not Engine events.
|
|
161
|
+
TypeError: For coroutine or async-generator listener functions.
|
|
162
|
+
sqlalchemy.exc.InvalidRequestError: For unknown native event names.
|
|
160
163
|
|
|
161
164
|
Examples:
|
|
162
165
|
>>> @db.on("connect")
|
|
163
166
|
... def on_connect(conn, record):
|
|
164
167
|
... print("Database connected")
|
|
165
168
|
|
|
166
|
-
>>> @db.on("
|
|
167
|
-
... def
|
|
169
|
+
>>> @db.on("commit")
|
|
170
|
+
... def committing(conn):
|
|
168
171
|
... print("About to commit transaction")
|
|
169
172
|
"""
|
|
170
|
-
|
|
173
|
+
unsupported = {
|
|
174
|
+
"before_commit": "Use db.on('commit') to intercept a commit attempt.",
|
|
175
|
+
"before_rollback": "Use db.on('rollback') to intercept a rollback attempt.",
|
|
176
|
+
"after_commit": "Use await session.on_commit(callback) for effects after a successful commit.",
|
|
177
|
+
"after_rollback": "Use db.on('rollback') for rollback attempts; it is not an after-rollback hook.",
|
|
178
|
+
}
|
|
179
|
+
if event_name in unsupported:
|
|
180
|
+
raise ValueError(f"{event_name!r} is not an Engine event. {unsupported[event_name]}")
|
|
171
181
|
|
|
172
|
-
|
|
173
|
-
|
|
182
|
+
def register(listener: _EventListener) -> _EventListener:
|
|
183
|
+
callbacks = (listener, listener.__call__)
|
|
184
|
+
if any(inspect.iscoroutinefunction(fn) or inspect.isasyncgenfunction(fn) for fn in callbacks):
|
|
185
|
+
raise TypeError("Database event listeners must be synchronous; SQLAlchemy does not await them")
|
|
186
|
+
event.listen(self.engine.sync_engine, event_name, listener, **options)
|
|
187
|
+
return listener
|
|
174
188
|
|
|
175
|
-
return
|
|
189
|
+
return register
|
|
176
190
|
|
|
177
191
|
async def create_tables(self, base_class, tables: list[type] | None = None) -> None:
|
|
178
192
|
"""Create tables defined in the model registry of SQLObjects base class
|
|
@@ -2,8 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
from typing import TYPE_CHECKING, Any
|
|
4
4
|
|
|
5
|
-
from sqlalchemy import
|
|
5
|
+
from sqlalchemy import false, select
|
|
6
|
+
from sqlalchemy.sql import visitors
|
|
7
|
+
from sqlalchemy.sql.elements import BindParameter, ColumnClause, ColumnElement
|
|
8
|
+
from sqlalchemy.sql.selectable import ScalarSelect
|
|
6
9
|
|
|
10
|
+
from ..exceptions import QueryError
|
|
7
11
|
from .base import QueryExpression
|
|
8
12
|
|
|
9
13
|
|
|
@@ -12,101 +16,158 @@ if TYPE_CHECKING:
|
|
|
12
16
|
|
|
13
17
|
|
|
14
18
|
class AggregateExpression(QueryExpression[dict[str, Any]]):
|
|
15
|
-
"""
|
|
16
|
-
|
|
17
|
-
Aggregate expressions encapsulate SQL aggregation functions like COUNT, AVG, SUM
|
|
18
|
-
and can be used both as standalone queries and as scalar subqueries in filters.
|
|
19
|
-
"""
|
|
19
|
+
"""Aggregate matching rows, with one statement shared by all evaluation paths."""
|
|
20
20
|
|
|
21
21
|
def __init__(self, builder: "QueryBuilder", aggregations: dict[str, Any], executor=None):
|
|
22
|
-
"""Initialize aggregate expression.
|
|
23
|
-
|
|
24
|
-
Args:
|
|
25
|
-
builder: Query builder containing base query conditions
|
|
26
|
-
aggregations: Dictionary of alias -> aggregation expression mappings
|
|
27
|
-
executor: Optional query executor
|
|
28
|
-
"""
|
|
29
22
|
super().__init__(executor)
|
|
23
|
+
if not aggregations:
|
|
24
|
+
raise ValueError("aggregate() requires at least one aggregation expression")
|
|
30
25
|
self._builder = builder
|
|
31
26
|
self._aggregations = aggregations
|
|
32
27
|
|
|
33
28
|
def get_query(self):
|
|
34
|
-
"""
|
|
35
|
-
|
|
29
|
+
"""Build the aggregate over the QuerySet's filtered, deduplicated, sliced rows."""
|
|
30
|
+
builder = self._builder
|
|
31
|
+
table = builder.model_class.get_table()
|
|
32
|
+
empty = builder.is_none_query
|
|
33
|
+
grouped = bool(builder.group_clauses)
|
|
34
|
+
if empty or grouped:
|
|
35
|
+
builder = builder.copy()
|
|
36
|
+
builder.is_none_query = False
|
|
37
|
+
grouping_keys = []
|
|
38
|
+
if grouped:
|
|
39
|
+
query, grouping_keys = self._build_grouped_input(builder, table)
|
|
40
|
+
else:
|
|
41
|
+
query = builder.build(table)
|
|
42
|
+
if empty:
|
|
43
|
+
query = query.where(false())
|
|
44
|
+
expressions = {
|
|
45
|
+
alias: expr.resolve(table) if hasattr(expr, "resolve") else expr
|
|
46
|
+
for alias, expr in self._aggregations.items()
|
|
47
|
+
}
|
|
48
|
+
sliced = builder.limits is not None or builder.offset_value is not None
|
|
49
|
+
if not sliced and not builder.distinct_fields:
|
|
50
|
+
query = query.order_by(None)
|
|
51
|
+
|
|
52
|
+
if not (grouped or sliced or builder.is_distinct or builder.annotations or builder.extra_columns):
|
|
53
|
+
return query.with_only_columns(
|
|
54
|
+
*(expr.label(alias) for alias, expr in expressions.items())
|
|
55
|
+
).correlate_except(table)
|
|
56
|
+
|
|
57
|
+
# Project aggregate inputs before wrapping. only()/defer() control model
|
|
58
|
+
# hydration, so base-model fields may still be used by an aggregate.
|
|
59
|
+
inputs = {}
|
|
60
|
+
|
|
61
|
+
def project_input(element: Any, **kw: Any):
|
|
62
|
+
nonlocal query
|
|
63
|
+
if (
|
|
64
|
+
grouped
|
|
65
|
+
and isinstance(element, ColumnElement)
|
|
66
|
+
and not isinstance(element, BindParameter)
|
|
67
|
+
and not element._is_singleton_constant
|
|
68
|
+
):
|
|
69
|
+
for key, alias in grouping_keys:
|
|
70
|
+
if element.compare(key):
|
|
71
|
+
inputs[element] = query.selected_columns[alias]
|
|
72
|
+
return element
|
|
73
|
+
if not isinstance(element, (ColumnClause, ScalarSelect)):
|
|
74
|
+
return None
|
|
75
|
+
if isinstance(element, ColumnClause) and element.table is None:
|
|
76
|
+
if element.name == "*":
|
|
77
|
+
return element
|
|
78
|
+
projected = query.selected_columns.get(element.name)
|
|
79
|
+
if projected is None:
|
|
80
|
+
raise QueryError(
|
|
81
|
+
f"aggregate() input {element.name!r} must be a model column or a projected annotation alias"
|
|
82
|
+
)
|
|
83
|
+
else:
|
|
84
|
+
projected = query.selected_columns.corresponding_column(element)
|
|
85
|
+
if projected is None:
|
|
86
|
+
if grouped:
|
|
87
|
+
raise QueryError("aggregate() over grouped rows requires a grouping key or an annotation alias")
|
|
88
|
+
# Adding a joined column to ordinary DISTINCT would change
|
|
89
|
+
# which rows are duplicates. Require an explicit annotation.
|
|
90
|
+
if (
|
|
91
|
+
builder.is_distinct
|
|
92
|
+
and not builder.distinct_fields
|
|
93
|
+
and getattr(element, "table", None) is not table
|
|
94
|
+
):
|
|
95
|
+
raise QueryError("aggregate() over DISTINCT requires joined or scalar inputs to be projected")
|
|
96
|
+
projected = element.label(None) if isinstance(element, ScalarSelect) else element
|
|
97
|
+
query = query.add_columns(projected)
|
|
98
|
+
inputs[element] = projected
|
|
99
|
+
# Scalar subqueries are an input value; never traverse their local
|
|
100
|
+
# columns and accidentally add their tables to the outer query.
|
|
101
|
+
return element
|
|
102
|
+
|
|
103
|
+
for expr in expressions.values():
|
|
104
|
+
visitors.replacement_traverse(expr, {}, project_input)
|
|
105
|
+
|
|
106
|
+
source = query.correlate_except(table).subquery()
|
|
107
|
+
replacements = {node: source.corresponding_column(projected) for node, projected in inputs.items()}
|
|
108
|
+
|
|
109
|
+
def replace_input(element: Any, **kw: Any):
|
|
110
|
+
return replacements.get(element)
|
|
111
|
+
|
|
112
|
+
aggregates = [
|
|
113
|
+
visitors.replacement_traverse(expr, {}, replace_input).label(alias) for alias, expr in expressions.items()
|
|
114
|
+
]
|
|
115
|
+
return select(*aggregates).select_from(source)
|
|
116
|
+
|
|
117
|
+
@staticmethod
|
|
118
|
+
def _build_grouped_input(builder, table):
|
|
119
|
+
"""Project grouping keys and annotations without adding model-row fields."""
|
|
120
|
+
aliases = list(builder.annotations)
|
|
121
|
+
shadowed = set(aliases) & set(table.c.keys())
|
|
122
|
+
if shadowed:
|
|
123
|
+
raise QueryError(f"Grouped aggregate annotation aliases shadow model columns: {sorted(shadowed)}")
|
|
124
|
+
fields = aliases + list(builder.extra_columns)
|
|
125
|
+
grouping_keys = []
|
|
126
|
+
used = set(fields) | set(table.c.keys())
|
|
127
|
+
for index, field in enumerate(builder.group_clauses):
|
|
128
|
+
if isinstance(field, str):
|
|
129
|
+
if field in table.c:
|
|
130
|
+
expression = table.c[field]
|
|
131
|
+
elif field in builder.annotations:
|
|
132
|
+
expression = builder.annotations[field]
|
|
133
|
+
else:
|
|
134
|
+
raise QueryError(f"Unknown aggregate grouping key: {field!r}")
|
|
135
|
+
else:
|
|
136
|
+
expression = field
|
|
137
|
+
if hasattr(expression, "resolve"):
|
|
138
|
+
expression = expression.resolve(table)
|
|
139
|
+
elif hasattr(expression, "__clause_element__"):
|
|
140
|
+
expression = expression.__clause_element__()
|
|
141
|
+
if not isinstance(expression, ColumnElement):
|
|
142
|
+
raise QueryError("Aggregate grouping keys must be columns, expressions or annotation aliases")
|
|
143
|
+
alias = f"_sqlobjects_group_{index}"
|
|
144
|
+
while alias in used:
|
|
145
|
+
alias += "_"
|
|
146
|
+
used.add(alias)
|
|
147
|
+
builder.annotations[alias] = expression
|
|
148
|
+
fields.append(alias)
|
|
149
|
+
grouping_keys.append((expression, alias))
|
|
150
|
+
if isinstance(expression, BindParameter) or expression._is_singleton_constant:
|
|
151
|
+
# MySQL interprets GROUP BY 1 as a select-list ordinal. Refer to
|
|
152
|
+
# the projected constant by alias to preserve one constant group.
|
|
153
|
+
builder.group_clauses[index] = alias
|
|
154
|
+
return builder.build(table, values_fields=tuple(fields)), grouping_keys
|
|
36
155
|
|
|
37
156
|
async def execute(self) -> dict[str, Any]:
|
|
38
|
-
"""Execute
|
|
39
|
-
|
|
40
|
-
Returns:
|
|
41
|
-
Dictionary mapping aggregation aliases to computed values
|
|
42
|
-
"""
|
|
157
|
+
"""Execute exactly the statement used by SQL rendering and EXPLAIN."""
|
|
43
158
|
if not self._executor:
|
|
44
159
|
raise RuntimeError("No executor available for aggregate execution")
|
|
45
|
-
|
|
46
|
-
# Build aggregation expressions
|
|
47
|
-
aggregations = []
|
|
48
|
-
labels = []
|
|
49
|
-
|
|
50
|
-
for alias, expr in self._aggregations.items():
|
|
51
|
-
if hasattr(expr, "resolve"):
|
|
52
|
-
aggregations.append(expr.resolve(self._builder.model_class.get_table()).label(alias))
|
|
53
|
-
else:
|
|
54
|
-
aggregations.append(expr.label(alias))
|
|
55
|
-
labels.append(alias)
|
|
56
|
-
|
|
57
|
-
# Build and execute query
|
|
58
|
-
query = self._builder.build(self._builder.model_class.get_table())
|
|
59
|
-
result = await self._executor.execute(query, "aggregate", aggregations=aggregations)
|
|
60
|
-
|
|
160
|
+
result = await self._executor.execute(self.get_query(), "aggregate")
|
|
61
161
|
if isinstance(result, list) and result:
|
|
62
|
-
|
|
63
|
-
return dict(zip(labels, first_result, strict=False))
|
|
162
|
+
return dict(zip(self._aggregations, result[0], strict=True))
|
|
64
163
|
return {}
|
|
65
164
|
|
|
66
|
-
def get_sql(self) -> str:
|
|
67
|
-
"""Generate SQL string for aggregate query.
|
|
68
|
-
|
|
69
|
-
Returns:
|
|
70
|
-
SQL string for the aggregation operation
|
|
71
|
-
"""
|
|
72
|
-
# Build aggregation expressions
|
|
73
|
-
aggregations = []
|
|
74
|
-
|
|
75
|
-
for alias, expr in self._aggregations.items():
|
|
76
|
-
if hasattr(expr, "resolve"):
|
|
77
|
-
aggregations.append(expr.resolve(self._builder.model_class.get_table()).label(alias))
|
|
78
|
-
else:
|
|
79
|
-
aggregations.append(expr.label(alias))
|
|
80
|
-
|
|
81
|
-
# Build base query
|
|
82
|
-
query = select(*aggregations).select_from(self._builder.model_class.get_table())
|
|
83
|
-
|
|
84
|
-
# Add conditions if present
|
|
85
|
-
if self._builder.conditions:
|
|
86
|
-
query = query.where(and_(*self._builder.conditions))
|
|
87
|
-
|
|
88
|
-
return str(query.compile(compile_kwargs={"literal_binds": True}))
|
|
89
|
-
|
|
90
165
|
def scalar_subquery(self):
|
|
91
|
-
"""Convert
|
|
92
|
-
|
|
93
|
-
Returns:
|
|
94
|
-
SQLAlchemy scalar subquery expression
|
|
95
|
-
"""
|
|
96
|
-
# For single aggregation, return scalar subquery
|
|
97
|
-
if len(self._aggregations) == 1:
|
|
98
|
-
expr = next(iter(self._aggregations.values()))
|
|
99
|
-
|
|
100
|
-
if hasattr(expr, "resolve"):
|
|
101
|
-
agg_expr = expr.resolve(self._builder.model_class.get_table())
|
|
102
|
-
else:
|
|
103
|
-
agg_expr = expr
|
|
104
|
-
|
|
105
|
-
query = select(agg_expr).select_from(self._builder.model_class.get_table())
|
|
106
|
-
|
|
107
|
-
if hasattr(self._builder, "conditions") and self._builder.conditions:
|
|
108
|
-
query = query.where(and_(*self._builder.conditions))
|
|
109
|
-
|
|
110
|
-
return query.scalar_subquery()
|
|
111
|
-
else:
|
|
166
|
+
"""Convert a single aggregate to a scalar subquery."""
|
|
167
|
+
if len(self._aggregations) != 1:
|
|
112
168
|
raise ValueError("Cannot convert multi-field aggregation to scalar subquery")
|
|
169
|
+
return self.get_query().scalar_subquery()
|
|
170
|
+
|
|
171
|
+
def __clause_element__(self):
|
|
172
|
+
"""Allow SQLAlchemy column comparisons to coerce a single aggregate."""
|
|
173
|
+
return self.scalar_subquery()
|
sqlobjects/expressions/scalar.py
CHANGED
|
@@ -26,7 +26,9 @@ class CountExpression(QueryExpression[int]):
|
|
|
26
26
|
|
|
27
27
|
def get_query(self):
|
|
28
28
|
"""Return SQLAlchemy query object."""
|
|
29
|
-
|
|
29
|
+
table = self._builder.model_class.get_table()
|
|
30
|
+
base = self._builder.build(table).order_by(None).correlate_except(table)
|
|
31
|
+
return select(func.count()).select_from(base.subquery())
|
|
30
32
|
|
|
31
33
|
async def execute(self) -> int:
|
|
32
34
|
"""Execute count query and return integer result.
|
|
@@ -47,8 +49,7 @@ class CountExpression(QueryExpression[int]):
|
|
|
47
49
|
Returns:
|
|
48
50
|
SQL string for the count operation
|
|
49
51
|
"""
|
|
50
|
-
|
|
51
|
-
return str(base_query.compile(compile_kwargs={"literal_binds": True}))
|
|
52
|
+
return str(self.get_query().compile(compile_kwargs={"literal_binds": True}))
|
|
52
53
|
|
|
53
54
|
def scalar_subquery(self):
|
|
54
55
|
"""Convert to scalar subquery for use in comparisons.
|
|
@@ -56,12 +57,7 @@ class CountExpression(QueryExpression[int]):
|
|
|
56
57
|
Returns:
|
|
57
58
|
SQLAlchemy scalar subquery expression
|
|
58
59
|
"""
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
if hasattr(self._builder, "conditions") and self._builder.conditions:
|
|
62
|
-
query = query.where(and_(*self._builder.conditions))
|
|
63
|
-
|
|
64
|
-
return query.scalar_subquery()
|
|
60
|
+
return self.get_query().scalar_subquery()
|
|
65
61
|
|
|
66
62
|
|
|
67
63
|
class ExistsExpression(QueryExpression[bool]):
|
sqlobjects/fields/__init__.py
CHANGED
|
@@ -6,6 +6,7 @@ from .proxies import (
|
|
|
6
6
|
ManyToManyRelation,
|
|
7
7
|
OneToManyRelation,
|
|
8
8
|
RelatedObject,
|
|
9
|
+
RelatedQuerySet,
|
|
9
10
|
)
|
|
10
11
|
from .relations import M2MTable, relationship
|
|
11
12
|
from .shortcuts import (
|
|
@@ -60,6 +61,7 @@ __all__ = [
|
|
|
60
61
|
"RelatedObject",
|
|
61
62
|
"OneToManyRelation",
|
|
62
63
|
"ManyToManyRelation",
|
|
64
|
+
"RelatedQuerySet",
|
|
63
65
|
# Utility functions
|
|
64
66
|
"extract_field_metadata",
|
|
65
67
|
"get_deferred_fields",
|
sqlobjects/fields/core.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"""Core field classes for SQLObjects"""
|
|
2
2
|
|
|
3
3
|
from collections.abc import Callable
|
|
4
|
+
from types import UnionType
|
|
4
5
|
from typing import TYPE_CHECKING, Any, Generic, TypeVar, Union, cast, get_args, get_origin, overload
|
|
5
6
|
|
|
6
7
|
from sqlalchemy import Column as CoreColumn
|
|
@@ -1104,8 +1105,8 @@ def _map_python_type_to_sqlalchemy(python_type) -> tuple[str, dict[str, Any]]:
|
|
|
1104
1105
|
Returns:
|
|
1105
1106
|
Tuple of (type_name, parameters_dict)
|
|
1106
1107
|
"""
|
|
1107
|
-
# Handle Optional[T]
|
|
1108
|
-
if get_origin(python_type)
|
|
1108
|
+
# Handle both Optional[T] and the PEP 604 spelling T | None.
|
|
1109
|
+
if get_origin(python_type) in (Union, UnionType):
|
|
1109
1110
|
union_args = get_args(python_type)
|
|
1110
1111
|
if len(union_args) == 2 and type(None) in union_args:
|
|
1111
1112
|
# Optional[T] case
|