snake-orm 0.1.0b1__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.
- snake_orm-0.1.0b1.dist-info/METADATA +366 -0
- snake_orm-0.1.0b1.dist-info/RECORD +198 -0
- snake_orm-0.1.0b1.dist-info/WHEEL +4 -0
- snake_orm-0.1.0b1.dist-info/entry_points.txt +2 -0
- snake_orm-0.1.0b1.dist-info/licenses/LICENSE +21 -0
- snakeorm/__init__.py +214 -0
- snakeorm/advisor.py +109 -0
- snakeorm/cli/__init__.py +3 -0
- snakeorm/cli/app.py +992 -0
- snakeorm/cli/discovery.py +179 -0
- snakeorm/cli/hooks.py +86 -0
- snakeorm/compiler/__init__.py +3 -0
- snakeorm/compiler/compiler.py +330 -0
- snakeorm/connection.py +228 -0
- snakeorm/contrib/__init__.py +17 -0
- snakeorm/contrib/asgi.py +192 -0
- snakeorm/contrib/config.py +264 -0
- snakeorm/contrib/deliver.py +256 -0
- snakeorm/contrib/django.py +245 -0
- snakeorm/contrib/sidecar.py +44 -0
- snakeorm/contrib/wsgi.py +176 -0
- snakeorm/core/__init__.py +1 -0
- snakeorm/core/config.py +173 -0
- snakeorm/core/converters.py +172 -0
- snakeorm/core/exceptions.py +175 -0
- snakeorm/core/placement.py +15 -0
- snakeorm/core/sentinels.py +37 -0
- snakeorm/core/signals.py +114 -0
- snakeorm/debug/__init__.py +42 -0
- snakeorm/debug/assets/css/panel.css +616 -0
- snakeorm/debug/assets/css/snake_orm_app.css +293 -0
- snakeorm/debug/assets/img/icon.svg +5 -0
- snakeorm/debug/assets/js/history.js +425 -0
- snakeorm/debug/assets/js/language.js +283 -0
- snakeorm/debug/assets/js/panel.js +241 -0
- snakeorm/debug/assets/js/snake_orm_app.js +82 -0
- snakeorm/debug/assets/pages/cli.html +28 -0
- snakeorm/debug/assets/pages/config.html +34 -0
- snakeorm/debug/assets/pages/database_first.html +29 -0
- snakeorm/debug/assets/pages/help.html +21 -0
- snakeorm/debug/assets/pages/history.html +27 -0
- snakeorm/debug/capture.py +234 -0
- snakeorm/debug/channel.py +131 -0
- snakeorm/debug/collector.py +144 -0
- snakeorm/debug/config.py +149 -0
- snakeorm/debug/html.py +578 -0
- snakeorm/debug/matrix.py +60 -0
- snakeorm/debug/origin.py +42 -0
- snakeorm/debug/otel/__init__.py +68 -0
- snakeorm/debug/otel/context.py +43 -0
- snakeorm/debug/otel/exporter.py +277 -0
- snakeorm/debug/otel/payload.py +97 -0
- snakeorm/debug/otel/report.py +29 -0
- snakeorm/debug/otel/spans.py +393 -0
- snakeorm/debug/otel/summary.py +59 -0
- snakeorm/debug/record.py +54 -0
- snakeorm/debug/report.py +311 -0
- snakeorm/debug/testing.py +23 -0
- snakeorm/decorators/__init__.py +13 -0
- snakeorm/decorators/abstract.py +26 -0
- snakeorm/decorators/db_first.py +104 -0
- snakeorm/decorators/function.py +28 -0
- snakeorm/decorators/model.py +268 -0
- snakeorm/decorators/polymorphic.py +140 -0
- snakeorm/decorators/result.py +167 -0
- snakeorm/decorators/row.py +90 -0
- snakeorm/decorators/trigger.py +47 -0
- snakeorm/decorators/view.py +149 -0
- snakeorm/dialects/__init__.py +6 -0
- snakeorm/dialects/base.py +373 -0
- snakeorm/dialects/capabilities.py +571 -0
- snakeorm/dialects/literals.py +46 -0
- snakeorm/dialects/matrix.py +384 -0
- snakeorm/dialects/mysql.py +519 -0
- snakeorm/dialects/postgres.py +504 -0
- snakeorm/dialects/sqlite.py +417 -0
- snakeorm/drivers/__init__.py +18 -0
- snakeorm/drivers/asyncbase.py +73 -0
- snakeorm/drivers/asyncdecorators.py +244 -0
- snakeorm/drivers/asyncpool.py +228 -0
- snakeorm/drivers/asyncpsycopg.py +124 -0
- snakeorm/drivers/asyncpymysql.py +50 -0
- snakeorm/drivers/asyncsqlite.py +30 -0
- snakeorm/drivers/base.py +76 -0
- snakeorm/drivers/failures.py +181 -0
- snakeorm/drivers/logging.py +167 -0
- snakeorm/drivers/pool.py +352 -0
- snakeorm/drivers/psycopg.py +188 -0
- snakeorm/drivers/pymysql.py +176 -0
- snakeorm/drivers/savepoints.py +46 -0
- snakeorm/drivers/sqlite.py +170 -0
- snakeorm/drivers/threaded.py +143 -0
- snakeorm/drivers/timeout.py +87 -0
- snakeorm/dto/__init__.py +55 -0
- snakeorm/dto/read.py +231 -0
- snakeorm/dto/region.py +326 -0
- snakeorm/dto/resolve.py +354 -0
- snakeorm/dto/spec.py +201 -0
- snakeorm/expressions/__init__.py +88 -0
- snakeorm/expressions/conditional.py +178 -0
- snakeorm/expressions/expression.py +810 -0
- snakeorm/expressions/functions.py +71 -0
- snakeorm/expressions/keys.py +299 -0
- snakeorm/expressions/paths.py +43 -0
- snakeorm/expressions/scalar.py +293 -0
- snakeorm/expressions/window.py +248 -0
- snakeorm/fields/__init__.py +68 -0
- snakeorm/fields/check.py +79 -0
- snakeorm/fields/column.py +316 -0
- snakeorm/fields/enum.py +64 -0
- snakeorm/fields/index.py +46 -0
- snakeorm/fields/relationship.py +738 -0
- snakeorm/fields/typed.py +736 -0
- snakeorm/helpers/__init__.py +1 -0
- snakeorm/helpers/annotations.py +21 -0
- snakeorm/helpers/inheritance.py +41 -0
- snakeorm/helpers/pyliteral.py +52 -0
- snakeorm/helpers/pytype.py +50 -0
- snakeorm/introspection/__init__.py +13 -0
- snakeorm/introspection/base.py +30 -0
- snakeorm/introspection/drift.py +78 -0
- snakeorm/introspection/models.py +633 -0
- snakeorm/introspection/mysql.py +367 -0
- snakeorm/introspection/postgres.py +397 -0
- snakeorm/introspection/sqlite.py +217 -0
- snakeorm/introspection/unsupported.py +94 -0
- snakeorm/linker/__init__.py +3 -0
- snakeorm/linker/linker.py +521 -0
- snakeorm/metadata/__init__.py +41 -0
- snakeorm/metadata/check.py +37 -0
- snakeorm/metadata/column.py +201 -0
- snakeorm/metadata/enum_storage.py +33 -0
- snakeorm/metadata/fk_action.py +19 -0
- snakeorm/metadata/foreign_key.py +26 -0
- snakeorm/metadata/index.py +43 -0
- snakeorm/metadata/index_method.py +19 -0
- snakeorm/metadata/int_size.py +20 -0
- snakeorm/metadata/json_storage.py +21 -0
- snakeorm/metadata/polymorphic.py +30 -0
- snakeorm/metadata/primary_key.py +23 -0
- snakeorm/metadata/relationship.py +60 -0
- snakeorm/metadata/relationship_kind.py +43 -0
- snakeorm/metadata/routine.py +26 -0
- snakeorm/metadata/server_default.py +20 -0
- snakeorm/metadata/table.py +97 -0
- snakeorm/metadata/table_kind.py +23 -0
- snakeorm/metadata/trigger.py +62 -0
- snakeorm/metadata/type_params.py +348 -0
- snakeorm/migration/__init__.py +88 -0
- snakeorm/migration/asyncrunner.py +168 -0
- snakeorm/migration/autodetect.py +96 -0
- snakeorm/migration/ddl.py +1172 -0
- snakeorm/migration/diff.py +701 -0
- snakeorm/migration/loader.py +77 -0
- snakeorm/migration/operations.py +952 -0
- snakeorm/migration/planner.py +78 -0
- snakeorm/migration/realize.py +420 -0
- snakeorm/migration/renames.py +153 -0
- snakeorm/migration/render.py +1095 -0
- snakeorm/migration/runner.py +314 -0
- snakeorm/migration/squash.py +60 -0
- snakeorm/migration/state.py +107 -0
- snakeorm/model.py +162 -0
- snakeorm/py.typed +0 -0
- snakeorm/query/__init__.py +9 -0
- snakeorm/query/compound.py +288 -0
- snakeorm/query/join_kind.py +19 -0
- snakeorm/query/joined.py +143 -0
- snakeorm/query/query.py +1001 -0
- snakeorm/query/recursive.py +244 -0
- snakeorm/registry/__init__.py +5 -0
- snakeorm/registry/by_module.py +163 -0
- snakeorm/registry/registry.py +166 -0
- snakeorm/session/__init__.py +8 -0
- snakeorm/session/asyncsession.py +638 -0
- snakeorm/session/coercion.py +306 -0
- snakeorm/session/factory.py +29 -0
- snakeorm/session/guards.py +269 -0
- snakeorm/session/isolation.py +23 -0
- snakeorm/session/mapper.py +213 -0
- snakeorm/session/planning.py +815 -0
- snakeorm/session/retry.py +96 -0
- snakeorm/session/session.py +871 -0
- snakeorm/session/shared.py +355 -0
- snakeorm/sql/__init__.py +18 -0
- snakeorm/sql/adapt.py +104 -0
- snakeorm/sql/aggregate.py +232 -0
- snakeorm/sql/condition.py +359 -0
- snakeorm/sql/delete.py +46 -0
- snakeorm/sql/insert.py +149 -0
- snakeorm/sql/joins.py +158 -0
- snakeorm/sql/pk_subquery.py +54 -0
- snakeorm/sql/refs.py +19 -0
- snakeorm/sql/resolver.py +28 -0
- snakeorm/sql/select.py +175 -0
- snakeorm/sql/update.py +82 -0
- snakeorm/sql/value.py +552 -0
- snakeorm/times.py +276 -0
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
"""Query composition (`UNION`/`EXCEPT`/`INTERSECT`): it composes two whole SELECTs, not a clause.
|
|
2
|
+
|
|
3
|
+
`SnakeCompound` is the composable object: each node produces `(sql, params)` and composing is
|
|
4
|
+
concatenating in TEXTUAL ORDER (Postgres' positional `%s` matches by position: any other order would
|
|
5
|
+
give wrong rows). It fulfils the same contract as `SnakeQuery`, so the session runs it just the same.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import dataclass, replace
|
|
11
|
+
from enum import Enum
|
|
12
|
+
from typing import TYPE_CHECKING, Any, Generic, TypeAlias, TypeVar
|
|
13
|
+
|
|
14
|
+
from snakeorm.dialects import SnakeDialect
|
|
15
|
+
from snakeorm.core.exceptions import SnakeEmitError
|
|
16
|
+
from snakeorm.expressions import SnakeExpr, SnakeOrder
|
|
17
|
+
from snakeorm.sql.value import emit_order_key, guard_untabled_order_keys
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from snakeorm.query.query import SnakeQuery
|
|
21
|
+
from snakeorm.query.recursive import SnakeRecursive
|
|
22
|
+
|
|
23
|
+
T = TypeVar("T")
|
|
24
|
+
|
|
25
|
+
SnakeCompoundBranch: TypeAlias = "SnakeQuery[T] | SnakeCompound[T] | SnakeRecursive[T]"
|
|
26
|
+
"""What can be a BRANCH of a set operation (the recursive one included).
|
|
27
|
+
|
|
28
|
+
It was verified against Postgres that `(SELECT ...) UNION (WITH RECURSIVE ...)` is valid. All three
|
|
29
|
+
fulfil the same contract (`model`, `has_includes`, `has_lock`, `to_sql`), which is what `_compose` needs."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class SnakeSetOp(Enum):
|
|
33
|
+
"""Set operation (standard SQL, agnostic).
|
|
34
|
+
|
|
35
|
+
`UNION` deduplicates (which forces sorting/hashing everything) and `UNION ALL` does not:
|
|
36
|
+
different enum values, to force a CHOICE instead of inheriting a default.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
UNION = "UNION"
|
|
40
|
+
UNION_ALL = "UNION ALL"
|
|
41
|
+
EXCEPT = "EXCEPT"
|
|
42
|
+
INTERSECT = "INTERSECT"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True, slots=True)
|
|
46
|
+
class SnakeCompound(Generic[T]):
|
|
47
|
+
"""Two queries joined by a set operation, with ordering and bounding belonging to the SET.
|
|
48
|
+
|
|
49
|
+
`order_by`/`limit`/`offset` belong to the set, and are emitted after the last branch. Closed over
|
|
50
|
+
itself: a compound recomposes with no special cases.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
operator: SnakeSetOp
|
|
54
|
+
left: SnakeCompoundBranch[T]
|
|
55
|
+
right: SnakeCompoundBranch[T]
|
|
56
|
+
order_by_keys: tuple[SnakeOrder, ...] = ()
|
|
57
|
+
limit_value: int | None = None
|
|
58
|
+
offset_value: int | None = None
|
|
59
|
+
|
|
60
|
+
@property
|
|
61
|
+
def model(self) -> type[T]:
|
|
62
|
+
"""The model of the rows. Taken from the left one (both are of the same model, guaranteed by
|
|
63
|
+
the type and by `_compose`): SQL only demands that the columns line up, so without that
|
|
64
|
+
guarantee it would instantiate the rows wrong.
|
|
65
|
+
"""
|
|
66
|
+
return self.left.model
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def projected_columns(self) -> frozenset[str] | None:
|
|
70
|
+
"""The columns the branches PROJECT, or `None` when they bring whole rows.
|
|
71
|
+
|
|
72
|
+
The session maps by asking for this instead of counting the row's width, and a compound
|
|
73
|
+
that could not answer was read as whole rows: the values of a narrowed branch landed on the
|
|
74
|
+
wrong attributes. Both branches project the same set (`_compose` refuses anything else), so
|
|
75
|
+
the left one answers for the pair.
|
|
76
|
+
"""
|
|
77
|
+
return self.left.projected_columns
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def has_includes(self) -> bool:
|
|
81
|
+
"""Never: a compound loads no relationships. It is rejected at build time, not here."""
|
|
82
|
+
return False
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def has_lock(self) -> bool:
|
|
86
|
+
"""Never: a compound locks no rows. It is rejected at build time, not here."""
|
|
87
|
+
return False
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def has_bounds(self) -> bool:
|
|
91
|
+
"""Tells whether the SET carries `limit`/`offset` of its own, so a compound nested in
|
|
92
|
+
another one answers the same question a query does."""
|
|
93
|
+
return self.limit_value is not None or self.offset_value is not None
|
|
94
|
+
|
|
95
|
+
@property
|
|
96
|
+
def has_order(self) -> bool:
|
|
97
|
+
"""Tells whether the SET carries `order_by` of its own."""
|
|
98
|
+
return bool(self.order_by_keys)
|
|
99
|
+
|
|
100
|
+
@property
|
|
101
|
+
def has_cte(self) -> bool:
|
|
102
|
+
"""Whether a `WITH RECURSIVE` is hiding anywhere inside. It travels UP: a recursion nested
|
|
103
|
+
two compounds deep still ends up written inside a branch of the outer one."""
|
|
104
|
+
return self.left.has_cte or self.right.has_cte
|
|
105
|
+
|
|
106
|
+
def order_by(self, *keys: SnakeExpr[Any] | SnakeOrder) -> SnakeCompound[T]:
|
|
107
|
+
"""Orders the SET. A bare column orders ascending, just like in `SnakeQuery`.
|
|
108
|
+
|
|
109
|
+
The key has to name a column the set HAS: refused here, where the caller still knows what
|
|
110
|
+
they typed, rather than in the emitter where it turned into another column's name.
|
|
111
|
+
"""
|
|
112
|
+
normalized = tuple(
|
|
113
|
+
key if isinstance(key, SnakeOrder) else key.asc() for key in keys
|
|
114
|
+
)
|
|
115
|
+
guard_untabled_order_keys(
|
|
116
|
+
normalized,
|
|
117
|
+
self.projected_columns,
|
|
118
|
+
"A UNION/EXCEPT/INTERSECT",
|
|
119
|
+
"Order the branches' own query by it and compose the ids, or bring the column into "
|
|
120
|
+
"the projection of both branches and order by that.",
|
|
121
|
+
)
|
|
122
|
+
return replace(self, order_by_keys=self.order_by_keys + normalized)
|
|
123
|
+
|
|
124
|
+
def limit(self, limit: int) -> SnakeCompound[T]:
|
|
125
|
+
"""Bounds the SET (it replaces the previous one). Returns a new compound."""
|
|
126
|
+
return replace(self, limit_value=limit)
|
|
127
|
+
|
|
128
|
+
def offset(self, offset: int) -> SnakeCompound[T]:
|
|
129
|
+
"""Skips rows of the SET (it replaces the previous one). Returns a new compound."""
|
|
130
|
+
return replace(self, offset_value=offset)
|
|
131
|
+
|
|
132
|
+
def union(self, other: SnakeCompoundBranch[T]) -> SnakeCompound[T]:
|
|
133
|
+
"""`UNION`: the rows of both, WITHOUT duplicates."""
|
|
134
|
+
return _compose(SnakeSetOp.UNION, self, other)
|
|
135
|
+
|
|
136
|
+
def union_all(self, other: SnakeCompoundBranch[T]) -> SnakeCompound[T]:
|
|
137
|
+
"""`UNION ALL`: the rows of both, KEEPING duplicates. It does not deduplicate, and is cheaper."""
|
|
138
|
+
return _compose(SnakeSetOp.UNION_ALL, self, other)
|
|
139
|
+
|
|
140
|
+
def except_(self, other: SnakeCompoundBranch[T]) -> SnakeCompound[T]:
|
|
141
|
+
"""`EXCEPT`: the left-hand ones that are NOT in the right-hand one. With a trailing underscore: it is a reserved word."""
|
|
142
|
+
return _compose(SnakeSetOp.EXCEPT, self, other)
|
|
143
|
+
|
|
144
|
+
def intersect(self, other: SnakeCompoundBranch[T]) -> SnakeCompound[T]:
|
|
145
|
+
"""`INTERSECT`: only the ones that are in BOTH."""
|
|
146
|
+
return _compose(SnakeSetOp.INTERSECT, self, other)
|
|
147
|
+
|
|
148
|
+
def to_sql(self, dialect: SnakeDialect) -> tuple[str, tuple[object, ...]]:
|
|
149
|
+
"""Compiles to `(sql, params)` concatenating the branches in textual order.
|
|
150
|
+
|
|
151
|
+
Each branch inside parentheses: without them a branch's `LIMIT` would read as the set's. The
|
|
152
|
+
`ORDER BY` goes UNqualified: the result is no table, its columns are the projection's.
|
|
153
|
+
"""
|
|
154
|
+
params: list[object] = []
|
|
155
|
+
left_sql = self._branch_sql(self.left, dialect, params, regroups=False)
|
|
156
|
+
right_sql = self._branch_sql(self.right, dialect, params, regroups=True)
|
|
157
|
+
sql = f"{left_sql} {self.operator.value} {right_sql}"
|
|
158
|
+
|
|
159
|
+
if self.order_by_keys:
|
|
160
|
+
keys = ", ".join(
|
|
161
|
+
emit_order_key(key, dialect, params, None) for key in self.order_by_keys
|
|
162
|
+
)
|
|
163
|
+
sql = f"{sql} ORDER BY {keys}"
|
|
164
|
+
|
|
165
|
+
clause = dialect.limit_offset(self.limit_value, self.offset_value, params)
|
|
166
|
+
if clause:
|
|
167
|
+
sql = f"{sql} {clause}"
|
|
168
|
+
return sql, tuple(params)
|
|
169
|
+
|
|
170
|
+
@staticmethod
|
|
171
|
+
def _branch_sql(
|
|
172
|
+
branch: SnakeCompoundBranch[T],
|
|
173
|
+
dialect: SnakeDialect,
|
|
174
|
+
params: list[object],
|
|
175
|
+
*,
|
|
176
|
+
regroups: bool,
|
|
177
|
+
) -> str:
|
|
178
|
+
"""Compiles one branch and accumulates its params into the shared list, in textual order.
|
|
179
|
+
|
|
180
|
+
The parentheses (only if the engine admits them) keep the branch's own tail —and its own
|
|
181
|
+
grouping— inside the branch. Where they are not available, what cannot be written is
|
|
182
|
+
REFUSED instead of emitted as something else. `regroups` says whether this position needs
|
|
183
|
+
the grouping preserved: see `_refuse_what_cannot_be_written`.
|
|
184
|
+
"""
|
|
185
|
+
_refuse_what_cannot_be_written(branch, dialect, regroups=regroups)
|
|
186
|
+
sql, branch_params = branch.to_sql(dialect)
|
|
187
|
+
params.extend(branch_params)
|
|
188
|
+
if dialect.supports_parenthesised_compound:
|
|
189
|
+
return f"({sql})"
|
|
190
|
+
return sql
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _refuse_what_cannot_be_written(
|
|
194
|
+
branch: SnakeCompoundBranch[T],
|
|
195
|
+
dialect: SnakeDialect,
|
|
196
|
+
*,
|
|
197
|
+
regroups: bool,
|
|
198
|
+
) -> None:
|
|
199
|
+
"""Stops a branch this engine cannot express, before it turns into SQL that means something else.
|
|
200
|
+
|
|
201
|
+
THREE refusals, and the middle one is the expensive one:
|
|
202
|
+
|
|
203
|
+
- A CTE in a branch. Only Postgres takes it; SQLite answers `near "WITH": syntax error` and
|
|
204
|
+
MySQL 1064, which is the driver complaining about SQL the user never wrote.
|
|
205
|
+
- A branch that is ITSELF a set, in the position where the grouping matters. Without
|
|
206
|
+
parentheses the engine reads the operators left to right, so `A UNION (B EXCEPT C)` becomes
|
|
207
|
+
`(A UNION B) EXCEPT C`: valid SQL, different rows, no error anywhere. Measured over the 4x4
|
|
208
|
+
operator matrix against the three engines, 12 of the 16 pairs disagreed. Nesting to the LEFT
|
|
209
|
+
is not refused, because left-to-right IS the grouping the bare text already has.
|
|
210
|
+
- A branch with its own `order_by`/`limit`/`offset`: without parentheses the tail reads as
|
|
211
|
+
belonging to the whole set. The bound was guarded and the ordering was not, though the two
|
|
212
|
+
need the same parentheses.
|
|
213
|
+
"""
|
|
214
|
+
if branch.has_cte and not dialect.supports_cte_in_compound_branch:
|
|
215
|
+
raise SnakeEmitError(
|
|
216
|
+
"This engine does not accept a WITH RECURSIVE inside a branch of a "
|
|
217
|
+
"UNION/EXCEPT/INTERSECT, so a recursion cannot be composed with a set operation here "
|
|
218
|
+
"(only Postgres takes it). Run the recursion as its own query and combine the rows "
|
|
219
|
+
"afterwards."
|
|
220
|
+
)
|
|
221
|
+
if dialect.supports_parenthesised_compound:
|
|
222
|
+
return
|
|
223
|
+
if regroups and isinstance(branch, SnakeCompound):
|
|
224
|
+
raise SnakeEmitError(
|
|
225
|
+
"This engine does not accept parentheses around the branches of a "
|
|
226
|
+
"UNION/EXCEPT/INTERSECT, so a branch that is itself a UNION/EXCEPT/INTERSECT is "
|
|
227
|
+
"inexpressible: without the parentheses the engine reads the operators left to right "
|
|
228
|
+
"and composes a DIFFERENT set, with no error. Chain to the left instead "
|
|
229
|
+
"(a.union(b).except_(c)), which means what it says on every engine, or run the inner "
|
|
230
|
+
"set as its own query."
|
|
231
|
+
)
|
|
232
|
+
if branch.has_bounds or branch.has_order:
|
|
233
|
+
raise SnakeEmitError(
|
|
234
|
+
"This engine does not accept parentheses around the branches of a "
|
|
235
|
+
"UNION/EXCEPT/INTERSECT, so a branch with its own limit()/offset()/order_by() is "
|
|
236
|
+
"inexpressible: the tail would read as belonging to the whole set. Drop it from the "
|
|
237
|
+
"branch, or order and bound the set with .order_by()/.limit() on the compound."
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _compose(
|
|
242
|
+
operator: SnakeSetOp,
|
|
243
|
+
left: SnakeCompoundBranch[T],
|
|
244
|
+
right: SnakeCompoundBranch[T],
|
|
245
|
+
) -> SnakeCompound[T]:
|
|
246
|
+
"""Builds the compound, rejecting whatever does not survive a set operation.
|
|
247
|
+
|
|
248
|
+
An `include(...)` (relationships by JOIN) and a `for_update()` do not survive: the set's columns
|
|
249
|
+
are the projection's. They are rejected at COMPOSE time, when the user still knows why they wrote it.
|
|
250
|
+
"""
|
|
251
|
+
for branch in (left, right):
|
|
252
|
+
if branch.has_includes:
|
|
253
|
+
raise SnakeEmitError(
|
|
254
|
+
"A query with include(...) cannot be composed with UNION/EXCEPT/INTERSECT: the "
|
|
255
|
+
"columns of the set are those of the projection, so the loaded relationships "
|
|
256
|
+
"would be lost. Compose the queries without include and load the relationships "
|
|
257
|
+
"afterwards."
|
|
258
|
+
)
|
|
259
|
+
if branch.has_lock:
|
|
260
|
+
raise SnakeEmitError(
|
|
261
|
+
"A query with for_update() cannot be composed with UNION/EXCEPT/INTERSECT: the "
|
|
262
|
+
"result of a set is not the rows of a specific table, so there is nothing to "
|
|
263
|
+
"lock (Postgres forbids it explicitly). Lock the rows in a separate query on "
|
|
264
|
+
"the table you want to reserve."
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
# RUNTIME BACKUP to the type lock: `.union` already demands the SAME model statically, but SQL
|
|
268
|
+
# only demands that the number and types of the columns line up, so a UNION between similar
|
|
269
|
+
# tables runs and the session instantiates every row as the first branch's model, with no error.
|
|
270
|
+
if left.model is not right.model:
|
|
271
|
+
raise SnakeEmitError(
|
|
272
|
+
f"UNION/EXCEPT/INTERSECT demands that both queries be of the SAME model, and here "
|
|
273
|
+
f"they are {left.model.__name__} and {right.model.__name__}. SQL only checks that the "
|
|
274
|
+
f"columns line up, so this would run and return rows of one table instantiated as "
|
|
275
|
+
f"the other, with the values in the wrong fields."
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
# THE SAME GUARD ONE LEVEL DOWN, over the columns instead of the table. `SELECT id, amount UNION
|
|
279
|
+
# SELECT id, status` compiles wherever the types agree, and the session hydrates every row
|
|
280
|
+
# against ONE of the two projections.
|
|
281
|
+
if left.projected_columns != right.projected_columns:
|
|
282
|
+
raise SnakeEmitError(
|
|
283
|
+
"UNION/EXCEPT/INTERSECT demands that both queries project the SAME columns, and here "
|
|
284
|
+
"they do not. SQL lines two projections up by position, so this would run and return "
|
|
285
|
+
"rows with their values in the wrong fields. Say the same only()/defer() on both "
|
|
286
|
+
"branches, or narrow neither."
|
|
287
|
+
)
|
|
288
|
+
return SnakeCompound(operator=operator, left=left, right=right)
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Kind of explicit JOIN onto a collection: INNER and LEFT only (never RIGHT nor FULL)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from enum import Enum
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class SnakeJoin(Enum):
|
|
9
|
+
"""How a collection is joined in an explicit `.join()` (projection only). INNER and LEFT only.
|
|
10
|
+
|
|
11
|
+
Both preserve the ROOT as the non-nullable side (every row has its parent). RIGHT/FULL would
|
|
12
|
+
bring up rows with the root at NULL, impossible to hydrate: illegal states unrepresentable.
|
|
13
|
+
|
|
14
|
+
- INNER: only parents with at least one matching child (one row per child).
|
|
15
|
+
- LEFT: on top of that, each childless parent once with the child's columns at NULL.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
INNER = "INNER"
|
|
19
|
+
LEFT = "LEFT"
|
snakeorm/query/joined.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""SnakeJoinedQuery: a query with EXPLICIT JOIN(s) onto a collection.
|
|
2
|
+
|
|
3
|
+
A JOIN onto a collection MULTIPLIES rows (one per child): correct for TUPLES, a disaster for models.
|
|
4
|
+
That is why `.join()` returns a DIFFERENT type that only projects (no `.all()`/`.first()`):
|
|
5
|
+
hydrating multiplied models is a type error.
|
|
6
|
+
|
|
7
|
+
THE ALIAS PROBLEM: `Maker.name` gives the path `("name",)`, which in a query rooted at Nation would
|
|
8
|
+
be qualified with the ROOT's alias (wrong SQL). `joined.right` is a `SnakePathProxy` over the JOIN's
|
|
9
|
+
prefix: `joined.right.name` gives `("makers", "name")`, qualified with the JOIN's alias. Statically
|
|
10
|
+
`right` is `type[M]`; at runtime it is the proxy (the same trick as `SnakeToOne.__get__`).
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from collections.abc import Sequence
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from typing import Any, Generic, TypeVar, cast
|
|
18
|
+
|
|
19
|
+
from snakeorm.dialects import SnakeDialect
|
|
20
|
+
from snakeorm.core.exceptions import SnakeRegistryError
|
|
21
|
+
from snakeorm.expressions import SnakeCondition, SnakeExpr, SnakeOrder, SnakeValue
|
|
22
|
+
from snakeorm.fields.relationship import (
|
|
23
|
+
SnakeCollection,
|
|
24
|
+
SnakePathProxy,
|
|
25
|
+
_registry_of,
|
|
26
|
+
)
|
|
27
|
+
from snakeorm.metadata import SnakeTableInfo
|
|
28
|
+
from snakeorm.query.join_kind import SnakeJoin
|
|
29
|
+
from snakeorm.query.query import SnakeQuery, _include_path, _relationship
|
|
30
|
+
from snakeorm.registry import registry
|
|
31
|
+
|
|
32
|
+
T = TypeVar("T")
|
|
33
|
+
M = TypeVar("M")
|
|
34
|
+
N = TypeVar("N")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True, slots=True)
|
|
38
|
+
class _JoinSpec:
|
|
39
|
+
"""An explicit JOIN, already resolved: prefix (relative to the root), whether it is LEFT, and the child table."""
|
|
40
|
+
|
|
41
|
+
prefix: tuple[str, ...]
|
|
42
|
+
left: bool
|
|
43
|
+
child_table: SnakeTableInfo
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _child_table_for(root: SnakeTableInfo, prefix: tuple[str, ...]) -> SnakeTableInfo:
|
|
47
|
+
"""Resolves the table reached by a prefix of relationships from the root (it walks the graph)."""
|
|
48
|
+
table = root
|
|
49
|
+
for step in prefix:
|
|
50
|
+
relationship = _relationship(table, step)
|
|
51
|
+
target = registry.resolve_relationship(relationship)[0]
|
|
52
|
+
if target is None:
|
|
53
|
+
raise SnakeRegistryError(
|
|
54
|
+
f"The target '{relationship.target}' of relationship '{step}' is not registered."
|
|
55
|
+
)
|
|
56
|
+
table = target
|
|
57
|
+
return table
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _resolve_join(
|
|
61
|
+
root_model: type[Any], collection: SnakeCollection[Any], how: SnakeJoin
|
|
62
|
+
) -> _JoinSpec:
|
|
63
|
+
"""Builds the `_JoinSpec` of a `.join()`: it extracts the prefix and resolves the child table.
|
|
64
|
+
|
|
65
|
+
`collection` is the class access to a to-many: a real `SnakeCollection` (`.path`) on the first
|
|
66
|
+
`.join()`, or a `SnakePathProxy` with the accumulated prefix on a chained `.join()`.
|
|
67
|
+
"""
|
|
68
|
+
root_table = registry.table_of(root_model)
|
|
69
|
+
if root_table is None:
|
|
70
|
+
raise SnakeRegistryError(
|
|
71
|
+
f"{root_model.__name__} is not registered: is it missing @snake_model?"
|
|
72
|
+
)
|
|
73
|
+
prefix = _include_path(collection)
|
|
74
|
+
child_table = _child_table_for(root_table, prefix)
|
|
75
|
+
return _JoinSpec(prefix=prefix, left=how is SnakeJoin.LEFT, child_table=child_table)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class SnakeJoinedQuery(Generic[T, M]):
|
|
79
|
+
"""Query with explicit JOIN(s) onto collections. Projectable only; immutable.
|
|
80
|
+
|
|
81
|
+
`T` is the ROOT model; `M` that of the last joined child (exposed by `.right`). It delegates the
|
|
82
|
+
normal state to a wrapped `SnakeQuery[T]` and adds the list of explicit JOINs.
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
__slots__ = ("_query", "_joins")
|
|
86
|
+
|
|
87
|
+
def __init__(self, query: SnakeQuery[T], joins: tuple[_JoinSpec, ...]) -> None:
|
|
88
|
+
self._query = query
|
|
89
|
+
self._joins = joins
|
|
90
|
+
|
|
91
|
+
@property
|
|
92
|
+
def model(self) -> type[T]:
|
|
93
|
+
"""The ROOT model. The session uses it to qualify/coerce the projection."""
|
|
94
|
+
return self._query.model
|
|
95
|
+
|
|
96
|
+
@property
|
|
97
|
+
def right(self) -> type[M]:
|
|
98
|
+
"""Right-hand side of the LAST JOIN, with the path already prefixed with the right alias.
|
|
99
|
+
|
|
100
|
+
Statically `type[M]` (`joined.right.name` re-triggers the class access -> `SnakeExpr`); at
|
|
101
|
+
runtime a `SnakePathProxy` whose path (`("makers","name")`) is qualified with the JOIN's
|
|
102
|
+
alias, not the root's.
|
|
103
|
+
"""
|
|
104
|
+
spec = self._joins[-1]
|
|
105
|
+
proxy = SnakePathProxy(spec.child_table, spec.prefix, _registry_of(self.model))
|
|
106
|
+
return cast("type[M]", proxy)
|
|
107
|
+
|
|
108
|
+
def filter(self, *conditions: SnakeCondition) -> SnakeJoinedQuery[T, M]:
|
|
109
|
+
"""Adds conditions (AND) to the WHERE. Returns a NEW query; the current one is untouched."""
|
|
110
|
+
return SnakeJoinedQuery(self._query.filter(*conditions), self._joins)
|
|
111
|
+
|
|
112
|
+
def order_by(self, *keys: SnakeExpr[Any] | SnakeOrder) -> SnakeJoinedQuery[T, M]:
|
|
113
|
+
"""Adds ordering keys. It can order by the child's columns (`joined.right.col`)."""
|
|
114
|
+
return SnakeJoinedQuery(self._query.order_by(*keys), self._joins)
|
|
115
|
+
|
|
116
|
+
def limit(self, limit: int) -> SnakeJoinedQuery[T, M]:
|
|
117
|
+
"""Sets the LIMIT (it replaces the previous one). Returns a new query."""
|
|
118
|
+
return SnakeJoinedQuery(self._query.limit(limit), self._joins)
|
|
119
|
+
|
|
120
|
+
def offset(self, offset: int) -> SnakeJoinedQuery[T, M]:
|
|
121
|
+
"""Sets the OFFSET (it replaces the previous one). Returns a new query."""
|
|
122
|
+
return SnakeJoinedQuery(self._query.offset(offset), self._joins)
|
|
123
|
+
|
|
124
|
+
def distinct(self) -> SnakeJoinedQuery[T, M]:
|
|
125
|
+
"""Marks the projection as `SELECT DISTINCT`. Returns a new query."""
|
|
126
|
+
return SnakeJoinedQuery(self._query.distinct(), self._joins)
|
|
127
|
+
|
|
128
|
+
def join(
|
|
129
|
+
self, collection: SnakeCollection[N], how: SnakeJoin = SnakeJoin.INNER
|
|
130
|
+
) -> SnakeJoinedQuery[T, N]:
|
|
131
|
+
"""Chains ANOTHER explicit JOIN (starting from `joined.right.<collection>`).
|
|
132
|
+
|
|
133
|
+
The new child `N` becomes the right-hand side of `.right`, with its accumulated prefix.
|
|
134
|
+
"""
|
|
135
|
+
spec = _resolve_join(self._query.model, collection, how)
|
|
136
|
+
return SnakeJoinedQuery(self._query, (*self._joins, spec))
|
|
137
|
+
|
|
138
|
+
def to_project_sql(
|
|
139
|
+
self, dialect: SnakeDialect, columns: Sequence[SnakeValue[Any]]
|
|
140
|
+
) -> tuple[str, tuple[object, ...]]:
|
|
141
|
+
"""Compiles the projection combining the explicit JOINs with the column/WHERE/order paths."""
|
|
142
|
+
explicit = tuple((spec.prefix, spec.left) for spec in self._joins)
|
|
143
|
+
return self._query.to_project_sql(dialect, columns, explicit_joins=explicit)
|