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
snakeorm/sql/value.py
ADDED
|
@@ -0,0 +1,552 @@
|
|
|
1
|
+
"""Polymorphic emission of VALUE expressions (column, F, Case, Cast, aggregates...) via singledispatch.
|
|
2
|
+
|
|
3
|
+
Each type registers its handler: adding one is a new handler, not a refactor. `qualify` (a
|
|
4
|
+
prefix→alias callable) qualifies a column with its table's alias (`t2."col"`) for the deep JOINs;
|
|
5
|
+
without it the column is emitted bare. The dialect only enters here; the AST nodes stay agnostic.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Callable, Sequence
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from functools import singledispatch
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from snakeorm.dialects import SnakeDialect
|
|
16
|
+
from datetime import date
|
|
17
|
+
|
|
18
|
+
from snakeorm.sql.refs import qualified
|
|
19
|
+
from snakeorm.core.exceptions import (
|
|
20
|
+
SnakeEmitError,
|
|
21
|
+
SnakeNodeError,
|
|
22
|
+
SnakeUnsupportedFeature,
|
|
23
|
+
)
|
|
24
|
+
from snakeorm.expressions import (
|
|
25
|
+
SnakeNulls,
|
|
26
|
+
SnakeAggregate,
|
|
27
|
+
SnakeArith,
|
|
28
|
+
SnakeArithOp,
|
|
29
|
+
SnakeCast,
|
|
30
|
+
SnakeDateShift,
|
|
31
|
+
SnakeCase,
|
|
32
|
+
SnakeCoalesce,
|
|
33
|
+
SnakeExpr,
|
|
34
|
+
SnakeFunc,
|
|
35
|
+
SnakeFuncCall,
|
|
36
|
+
SnakeJsonGet,
|
|
37
|
+
SnakeNullIf,
|
|
38
|
+
SnakeOrder,
|
|
39
|
+
SnakeStringAgg,
|
|
40
|
+
SnakeSubqueryAggregate,
|
|
41
|
+
SnakeValue,
|
|
42
|
+
static_type,
|
|
43
|
+
)
|
|
44
|
+
from snakeorm.expressions.window import SnakeWindow
|
|
45
|
+
|
|
46
|
+
# Resolves a relation prefix to its table alias (e.g. ("maker","nation") -> "t2").
|
|
47
|
+
Qualify = Callable[[tuple[str, ...]], str]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class ExistsAliases:
|
|
51
|
+
"""Alias allocator for correlated subqueries (e0, e1...).
|
|
52
|
+
|
|
53
|
+
Monotonic and shared by the whole statement, so that a nested `.any()` (or a `.count()`
|
|
54
|
+
alongside an EXISTS) never collides with itself nor with the outer t0...
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
__slots__ = ("_next",)
|
|
58
|
+
|
|
59
|
+
def __init__(self) -> None:
|
|
60
|
+
self._next = 0
|
|
61
|
+
|
|
62
|
+
def allocate(self) -> str:
|
|
63
|
+
"""Returns the next free subquery alias and advances the counter."""
|
|
64
|
+
alias = f"e{self._next}"
|
|
65
|
+
self._next += 1
|
|
66
|
+
return alias
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclass(frozen=True, slots=True)
|
|
70
|
+
class Correlation:
|
|
71
|
+
"""Context for emitting correlated subqueries (EXISTS and scalar COUNT).
|
|
72
|
+
|
|
73
|
+
`parent_ref`: how to reference the parent (the `t0` alias with JOINs, or the table name without
|
|
74
|
+
them). `aliases`: hands out subquery aliases, shared so that nesting never collides.
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
parent_ref: str
|
|
78
|
+
aliases: ExistsAliases
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@singledispatch
|
|
82
|
+
def emit_value(
|
|
83
|
+
expr: object,
|
|
84
|
+
dialect: SnakeDialect,
|
|
85
|
+
params: list[object],
|
|
86
|
+
qualify: Qualify | None = None,
|
|
87
|
+
correlate: Correlation | None = None,
|
|
88
|
+
) -> str:
|
|
89
|
+
"""Emits a value expression to SQL. Each type registers its handler; unknown -> error."""
|
|
90
|
+
raise SnakeNodeError(f"Value expression cannot be emitted: {type(expr).__name__}")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@emit_value.register(SnakeExpr)
|
|
94
|
+
def _emit_column(
|
|
95
|
+
expr: SnakeExpr[Any],
|
|
96
|
+
dialect: SnakeDialect,
|
|
97
|
+
params: list[object],
|
|
98
|
+
qualify: Qualify | None = None,
|
|
99
|
+
correlate: Correlation | None = None,
|
|
100
|
+
) -> str:
|
|
101
|
+
"""Column reference: does NOT consume params. With `qualify`, it prepends the alias of the relation prefix."""
|
|
102
|
+
column = dialect.quote_ident(expr.path[-1])
|
|
103
|
+
if qualify is None:
|
|
104
|
+
return column
|
|
105
|
+
return f"{qualify(expr.path[:-1])}.{column}"
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@emit_value.register(SnakeArith)
|
|
109
|
+
def _emit_arith(
|
|
110
|
+
expr: SnakeArith[Any],
|
|
111
|
+
dialect: SnakeDialect,
|
|
112
|
+
params: list[object],
|
|
113
|
+
qualify: Qualify | None = None,
|
|
114
|
+
correlate: Correlation | None = None,
|
|
115
|
+
) -> str:
|
|
116
|
+
"""Arithmetic operation `(<left> <op> <right>)`, parenthesised to preserve precedence.
|
|
117
|
+
|
|
118
|
+
Each operand: a `SnakeValue` with `emit_value` (no params); a literal with `emit_operand`
|
|
119
|
+
(placeholder).
|
|
120
|
+
|
|
121
|
+
DIVISION IS THE ONE OPERATOR THE ENGINES SPELL DIFFERENTLY. `+`, `-` and `*` mean the same
|
|
122
|
+
everywhere; `/` does not — measured, `45/50` is `0` on PostgreSQL and SQLite and `0.9000` on
|
|
123
|
+
MySQL, which keeps `DIV` for the integer one. Since the ORM declares `SnakeArith[int]` for two
|
|
124
|
+
integer operands, asking the dialect is what makes that declaration true on all three.
|
|
125
|
+
|
|
126
|
+
It only asks when both operands are PROVABLY integers. `static_type` returns `None` for anything
|
|
127
|
+
nobody wrote down, and `None` changes nothing: guessing would silently turn a decimal division
|
|
128
|
+
into an integer one, which is a worse failure than the one this closes.
|
|
129
|
+
"""
|
|
130
|
+
left = emit_expression_or_literal(expr.left, dialect, params, qualify, correlate)
|
|
131
|
+
right = emit_expression_or_literal(expr.right, dialect, params, qualify, correlate)
|
|
132
|
+
op = expr.op.value
|
|
133
|
+
if expr.op is SnakeArithOp.DIV and static_type(expr.left) is int is static_type(
|
|
134
|
+
expr.right
|
|
135
|
+
):
|
|
136
|
+
op = dialect.integer_division_op()
|
|
137
|
+
return f"({left} {op} {right})"
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@emit_value.register(SnakeDateShift)
|
|
141
|
+
def _emit_date_shift(
|
|
142
|
+
expr: SnakeDateShift[Any],
|
|
143
|
+
dialect: SnakeDialect,
|
|
144
|
+
params: list[object],
|
|
145
|
+
qualify: Qualify | None = None,
|
|
146
|
+
correlate: Correlation | None = None,
|
|
147
|
+
) -> str:
|
|
148
|
+
"""A date moved by an amount that travels as a PARAMETER, never inside the statement.
|
|
149
|
+
|
|
150
|
+
All three engines were measured to accept a placeholder for the amount, including a negative one
|
|
151
|
+
— which is what lets `snake_date_sub` be the same node with the sign flipped.
|
|
152
|
+
|
|
153
|
+
`keeps_time` comes from the compiled type of the source and only SQLite reads it: with no date
|
|
154
|
+
type to inspect, `date()` on a timestamp would silently drop the clock. When the type cannot be
|
|
155
|
+
proven the answer is "it keeps time", because losing a clock nobody asked to lose is the worse
|
|
156
|
+
of the two mistakes.
|
|
157
|
+
"""
|
|
158
|
+
source = emit_value(expr.value, dialect, params, qualify, correlate)
|
|
159
|
+
params.append(expr.amount)
|
|
160
|
+
placeholder = dialect.placeholder(len(params))
|
|
161
|
+
keeps_time = static_type(expr.value) is not date
|
|
162
|
+
return dialect.date_shift_sql(source, placeholder, expr.unit.value, keeps_time)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
@emit_value.register(SnakeStringAgg)
|
|
166
|
+
def _emit_string_agg(
|
|
167
|
+
expr: SnakeStringAgg[Any],
|
|
168
|
+
dialect: SnakeDialect,
|
|
169
|
+
params: list[object],
|
|
170
|
+
qualify: Qualify | None = None,
|
|
171
|
+
correlate: Correlation | None = None,
|
|
172
|
+
) -> str:
|
|
173
|
+
"""A group joined into one string. The dialect decides how the SEPARATOR travels.
|
|
174
|
+
|
|
175
|
+
That decision cannot live here: measured, PostgreSQL and SQLite take the separator as a normal
|
|
176
|
+
argument and parameterise it, while MySQL makes it the `SEPARATOR` keyword and rejects a
|
|
177
|
+
placeholder after it. So the dialect receives `params` and appends to it, or does not — the same
|
|
178
|
+
arrangement `limit_offset` already uses.
|
|
179
|
+
|
|
180
|
+
The ORDER BY is emitted here because its keys are ordinary values with ordinary paths.
|
|
181
|
+
"""
|
|
182
|
+
value = emit_value(expr.arg, dialect, params, qualify, correlate)
|
|
183
|
+
order_by = ", ".join(
|
|
184
|
+
emit_order_key(key, dialect, params, qualify) for key in expr.order_by
|
|
185
|
+
)
|
|
186
|
+
return dialect.string_agg_sql(value, expr.separator, order_by, params)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
@emit_value.register(SnakeCast)
|
|
190
|
+
def _emit_cast(
|
|
191
|
+
expr: SnakeCast[Any],
|
|
192
|
+
dialect: SnakeDialect,
|
|
193
|
+
params: list[object],
|
|
194
|
+
qualify: Qualify | None = None,
|
|
195
|
+
correlate: Correlation | None = None,
|
|
196
|
+
) -> str:
|
|
197
|
+
"""An explicit cast: the SOURCE is emitted here, the TYPE NAME is the dialect's.
|
|
198
|
+
|
|
199
|
+
That split is the same one as `json_get`, and it was measured rather than assumed: the three
|
|
200
|
+
engines do not agree on how to spell a float, and SQLite's `NUMERIC` would silently drop the
|
|
201
|
+
decimals this cast exists to keep.
|
|
202
|
+
"""
|
|
203
|
+
source = emit_value(expr.source, dialect, params, qualify, correlate)
|
|
204
|
+
return dialect.cast_sql(source, expr.as_type)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
@emit_value.register(SnakeSubqueryAggregate)
|
|
208
|
+
def _emit_subquery_aggregate(
|
|
209
|
+
expr: SnakeSubqueryAggregate[Any],
|
|
210
|
+
dialect: SnakeDialect,
|
|
211
|
+
params: list[object],
|
|
212
|
+
qualify: Qualify | None = None,
|
|
213
|
+
correlate: Correlation | None = None,
|
|
214
|
+
) -> str:
|
|
215
|
+
"""Scalar aggregation subquery `(SELECT FUNC(arg) FROM child AS alias WHERE child.fk = parent.pk)`.
|
|
216
|
+
|
|
217
|
+
It needs the correlation context (without it, error). A composite FK ANDs the pairs. It reuses the
|
|
218
|
+
`SnakeAggregate` node (with `arg=None` it comes out as `COUNT(*)`), re-anchored to the alias just
|
|
219
|
+
like the condition of `.any()`.
|
|
220
|
+
"""
|
|
221
|
+
if correlate is None:
|
|
222
|
+
raise SnakeNodeError(
|
|
223
|
+
"SnakeSubqueryAggregate without a correlation context: the parent cannot be referenced"
|
|
224
|
+
)
|
|
225
|
+
quote = dialect.quote_ident
|
|
226
|
+
alias = correlate.aliases.allocate()
|
|
227
|
+
# `qualified()`, not the hand-written reference: in SQLite `"public".` is invalid. Same bug
|
|
228
|
+
# as in `condition.py` — the subquery of `sum_(Brand.cars.price)` pointed at
|
|
229
|
+
# `"public"."cars"`.
|
|
230
|
+
child_ref = qualified(expr.child_schema, expr.child_name, dialect)
|
|
231
|
+
on = " AND ".join(
|
|
232
|
+
f"{alias}.{quote(child_col)} = {correlate.parent_ref}.{quote(parent_col)}"
|
|
233
|
+
for child_col, parent_col in expr.pairs
|
|
234
|
+
)
|
|
235
|
+
inner = Correlation(parent_ref=alias, aliases=correlate.aliases)
|
|
236
|
+
aggregate: SnakeAggregate[Any] = SnakeAggregate(expr.func, expr.arg)
|
|
237
|
+
projected = emit_value(aggregate, dialect, params, _child_qualify(alias), inner)
|
|
238
|
+
return f"(SELECT {projected} FROM {child_ref} AS {alias} WHERE {on})"
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _child_qualify(alias: str) -> Qualify:
|
|
242
|
+
"""Qualifies direct child columns with its alias (empty prefix): `Maker.name` → `e0."name"`.
|
|
243
|
+
|
|
244
|
+
A deep navigation inside the subquery would demand a JOIN that has not been built: it is rejected.
|
|
245
|
+
"""
|
|
246
|
+
|
|
247
|
+
def qualify(prefix: tuple[str, ...]) -> str:
|
|
248
|
+
if prefix == ():
|
|
249
|
+
return alias
|
|
250
|
+
raise SnakeUnsupportedFeature(
|
|
251
|
+
"deep column navigation inside a correlated subquery is not supported yet; filter or "
|
|
252
|
+
"aggregate by direct columns of the child"
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
return qualify
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
@emit_value.register(SnakeJsonGet)
|
|
259
|
+
def _emit_json_get(
|
|
260
|
+
expr: SnakeJsonGet[Any],
|
|
261
|
+
dialect: SnakeDialect,
|
|
262
|
+
params: list[object],
|
|
263
|
+
qualify: Qualify | None = None,
|
|
264
|
+
correlate: Correlation | None = None,
|
|
265
|
+
) -> str:
|
|
266
|
+
"""A read inside a document. The SOURCE is emitted here; the spelling is the dialect's.
|
|
267
|
+
|
|
268
|
+
It consumes no parameter, and that is not an oversight: the key is part of the STATEMENT (no
|
|
269
|
+
engine takes a placeholder inside a JSON path) and it was validated as a plain identifier when
|
|
270
|
+
the expression was built.
|
|
271
|
+
"""
|
|
272
|
+
source = emit_value(expr.source, dialect, params, qualify, correlate)
|
|
273
|
+
return dialect.json_get_sql(source, expr.key_path, expr.as_type)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
@emit_value.register(SnakeAggregate)
|
|
277
|
+
def _emit_aggregate(
|
|
278
|
+
expr: SnakeAggregate[Any],
|
|
279
|
+
dialect: SnakeDialect,
|
|
280
|
+
params: list[object],
|
|
281
|
+
qualify: Qualify | None = None,
|
|
282
|
+
correlate: Correlation | None = None,
|
|
283
|
+
) -> str:
|
|
284
|
+
"""Aggregate: `COUNT(*)`, `COUNT(DISTINCT <arg>)` or `FUNC(<arg>)`.
|
|
285
|
+
|
|
286
|
+
With no argument it is `COUNT(*)` (no params). With an argument, it is emitted with `emit_value`
|
|
287
|
+
(its literals do travel parametrised). The aggregate never interpolates values.
|
|
288
|
+
"""
|
|
289
|
+
func = expr.func.value
|
|
290
|
+
if expr.arg is None:
|
|
291
|
+
return f"{func}(*)"
|
|
292
|
+
inner = emit_value(expr.arg, dialect, params, qualify, correlate)
|
|
293
|
+
if expr.distinct:
|
|
294
|
+
return f"{func}(DISTINCT {inner})"
|
|
295
|
+
return f"{func}({inner})"
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def emit_expression_or_literal(
|
|
299
|
+
operand: object,
|
|
300
|
+
dialect: SnakeDialect,
|
|
301
|
+
params: list[object],
|
|
302
|
+
qualify: Qualify | None,
|
|
303
|
+
correlate: Correlation | None = None,
|
|
304
|
+
) -> str:
|
|
305
|
+
"""THE rule for an operand the user wrote: expression → `emit_value`; literal → `emit_operand`.
|
|
306
|
+
|
|
307
|
+
It was called `_emit_arith_operand` while arithmetic was the only caller, and the name was doing
|
|
308
|
+
harm by then: `CASE`, `COALESCE`, `NULLIF` and the function arguments had all adopted it, and the
|
|
309
|
+
place that had NOT —the right-hand side of a comparison— read as if it were a different problem
|
|
310
|
+
rather than the same one with a hole in it. `"a" > "b"` used to bind a `SnakeExpr` object into
|
|
311
|
+
`params` and let the driver be the one to complain.
|
|
312
|
+
|
|
313
|
+
An expression consumes NO parameter: it is a reference to a column, and a column reference is
|
|
314
|
+
part of the statement's text. A literal always travels in `params` and is never interpolated,
|
|
315
|
+
which is what kills injection and what makes one emitter serve three engines.
|
|
316
|
+
"""
|
|
317
|
+
if isinstance(operand, SnakeValue):
|
|
318
|
+
return emit_value(operand, dialect, params, qualify, correlate)
|
|
319
|
+
return emit_operand(operand, dialect, params)
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def emit_operand(value: object, dialect: SnakeDialect, params: list[object]) -> str:
|
|
323
|
+
"""Emits a LITERAL operand as a placeholder and stores its value in `params`.
|
|
324
|
+
|
|
325
|
+
One of the TWO places where a value enters `params` (the other is the INSERT emitter). The value
|
|
326
|
+
goes in exactly as the user wrote it; translating it to the DBAPI is the driver's business
|
|
327
|
+
(`adapt_params`), and the DDL emitter needs the originals. `SnakeValue`s do not come through here
|
|
328
|
+
(`emit_value` emits those).
|
|
329
|
+
"""
|
|
330
|
+
params.append(value)
|
|
331
|
+
return dialect.placeholder(len(params))
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def emit_order_key(
|
|
335
|
+
key: SnakeOrder,
|
|
336
|
+
dialect: SnakeDialect,
|
|
337
|
+
params: list[object],
|
|
338
|
+
qualify: Qualify | None,
|
|
339
|
+
correlate: Correlation | None = None,
|
|
340
|
+
) -> str:
|
|
341
|
+
"""Emits an order key: `<value> ASC|DESC [NULLS FIRST|LAST]`.
|
|
342
|
+
|
|
343
|
+
`NULLS` only if it was asked for: without it, the engine's default is respected.
|
|
344
|
+
|
|
345
|
+
`correlate` is what lets a statement SORT by a correlated aggregate it can already project. It
|
|
346
|
+
defaults to `None` because the other callers emit an ORDER BY where no parent row exists — a
|
|
347
|
+
compound, a recursive CTE, a window's own ordering — and there the refusal is the right answer.
|
|
348
|
+
"""
|
|
349
|
+
direction = "DESC" if key.descending else "ASC"
|
|
350
|
+
if key.nulls is not None and not dialect.syntax.has_nulls_ordering:
|
|
351
|
+
# The portable form, for an engine without the keyword. MySQL and MariaDB both answer
|
|
352
|
+
# `ERROR 1064` to `NULLS LAST` — measured on 8.4.11 and 11.8.8, because this dialect serves
|
|
353
|
+
# two engines and cannot promise what only one of them does — and both accept this, inside a
|
|
354
|
+
# UNION as well.
|
|
355
|
+
#
|
|
356
|
+
# The expression is emitted TWICE rather than reusing the string, and that is not waste:
|
|
357
|
+
# `emit_value` APPENDS to `params`, so one emission and two mentions would leave two
|
|
358
|
+
# placeholders for one value on exactly the dialects that count them.
|
|
359
|
+
#
|
|
360
|
+
# `NULLS FIRST` is nulls before, so the flag sorts ASC (False < True puts the non-nulls
|
|
361
|
+
# first for LAST, and DESC flips it).
|
|
362
|
+
nulls_first = "DESC" if key.nulls is SnakeNulls.FIRST else "ASC"
|
|
363
|
+
flag = emit_value(key.expr, dialect, params, qualify, correlate)
|
|
364
|
+
column = emit_value(key.expr, dialect, params, qualify, correlate)
|
|
365
|
+
return f"({flag} IS NULL) {nulls_first}, {column} {direction}"
|
|
366
|
+
column = emit_value(key.expr, dialect, params, qualify, correlate)
|
|
367
|
+
nulls = f" NULLS {key.nulls.value}" if key.nulls is not None else ""
|
|
368
|
+
return f"{column} {direction}{nulls}"
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def guard_untabled_order_keys(
|
|
372
|
+
keys: Sequence[SnakeOrder],
|
|
373
|
+
projected: frozenset[str] | None,
|
|
374
|
+
subject: str,
|
|
375
|
+
remedy: str,
|
|
376
|
+
) -> None:
|
|
377
|
+
"""Refuses an order key that cannot be written where there is no table to write it against.
|
|
378
|
+
|
|
379
|
+
A set operation and a `WITH RECURSIVE` order their RESULT, and a result is not a table: there is
|
|
380
|
+
no alias to qualify with and nothing to JOIN to, which is why both call `emit_order_key` with
|
|
381
|
+
`qualify=None`. Nothing checked that the key survived that, and two shapes did not:
|
|
382
|
+
|
|
383
|
+
- A key over a RELATIONSHIP. The hop was dropped and only the last segment got written, so
|
|
384
|
+
`Sale.maker.name` came out as the bare `"name"`. On a model that also owns a `name` that is a
|
|
385
|
+
DIFFERENT column, valid SQL, and the three engines sort the same wrong way — no engine can
|
|
386
|
+
disagree about it, so comparing them cannot find it.
|
|
387
|
+
- A key naming a column the projection does not carry. Here nobody agreed: SQLite, Postgres and
|
|
388
|
+
MySQL each answered their own native error about a column the caller never typed.
|
|
389
|
+
|
|
390
|
+
`projected` is `None` when the rows come whole, and then every column of the model is there.
|
|
391
|
+
"""
|
|
392
|
+
for key in keys:
|
|
393
|
+
for path in key.expr.paths():
|
|
394
|
+
if len(path) > 1:
|
|
395
|
+
raise SnakeEmitError(
|
|
396
|
+
f"{subject} cannot be ordered by {'.'.join(path)}: that key navigates a "
|
|
397
|
+
f"relationship and the result of the operation is not a table, so there is "
|
|
398
|
+
f"nothing to JOIN it to. Emitting it would sort by the bare "
|
|
399
|
+
f"'{path[-1]}' — another column entirely where the model owns one of that "
|
|
400
|
+
f"name, with no error anywhere. {remedy}"
|
|
401
|
+
)
|
|
402
|
+
# A key with no path names no column, so there is nothing to check against the
|
|
403
|
+
# projection. Spelt out because after the guard above a tuple of one is indistinguishable
|
|
404
|
+
# from an empty one to a checker, and `path[0]` would be out of range.
|
|
405
|
+
if not path:
|
|
406
|
+
continue
|
|
407
|
+
if projected is not None and path[0] not in projected:
|
|
408
|
+
raise SnakeEmitError(
|
|
409
|
+
f"{subject} cannot be ordered by {path[0]}: the branches project "
|
|
410
|
+
f"{', '.join(sorted(projected))} and the result has no other column, so the "
|
|
411
|
+
f"engine would answer its own error about a column you never asked for. Name "
|
|
412
|
+
f"the column in the only()/defer() of both branches, or order by one that is "
|
|
413
|
+
f"already there."
|
|
414
|
+
)
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
@emit_value.register(SnakeCase)
|
|
418
|
+
def _emit_case(
|
|
419
|
+
expr: SnakeCase[Any],
|
|
420
|
+
dialect: SnakeDialect,
|
|
421
|
+
params: list[object],
|
|
422
|
+
qualify: Qualify | None = None,
|
|
423
|
+
correlate: Correlation | None = None,
|
|
424
|
+
) -> str:
|
|
425
|
+
"""`CASE WHEN cond THEN value ... [ELSE default] END`, in the declared order.
|
|
426
|
+
|
|
427
|
+
Local import of the condition emitter (at module level it would be a cycle). With no default, no
|
|
428
|
+
ELSE is written (in SQL it already is NULL).
|
|
429
|
+
"""
|
|
430
|
+
from snakeorm.sql.condition import emit_condition_into
|
|
431
|
+
|
|
432
|
+
if not expr.branches:
|
|
433
|
+
raise SnakeEmitError("A CASE needs at least one branch to be emitted")
|
|
434
|
+
parts = []
|
|
435
|
+
for condition, result in expr.branches:
|
|
436
|
+
when = emit_condition_into(condition, dialect, params, qualify, correlate)
|
|
437
|
+
then = emit_expression_or_literal(result, dialect, params, qualify, correlate)
|
|
438
|
+
parts.append(f"WHEN {when} THEN {then}")
|
|
439
|
+
body = " ".join(parts)
|
|
440
|
+
if expr.has_default:
|
|
441
|
+
body = f"{body} ELSE {emit_expression_or_literal(expr.default, dialect, params, qualify, correlate)}"
|
|
442
|
+
return f"CASE {body} END"
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
@emit_value.register(SnakeCoalesce)
|
|
446
|
+
def _emit_coalesce(
|
|
447
|
+
expr: SnakeCoalesce[Any],
|
|
448
|
+
dialect: SnakeDialect,
|
|
449
|
+
params: list[object],
|
|
450
|
+
qualify: Qualify | None = None,
|
|
451
|
+
correlate: Correlation | None = None,
|
|
452
|
+
) -> str:
|
|
453
|
+
"""`COALESCE(a, b, ...)`: each argument is emitted according to whether it is a column or a literal."""
|
|
454
|
+
inner = ", ".join(
|
|
455
|
+
emit_expression_or_literal(argument, dialect, params, qualify, correlate)
|
|
456
|
+
for argument in expr.arguments
|
|
457
|
+
)
|
|
458
|
+
return f"COALESCE({inner})"
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
@emit_value.register(SnakeNullIf)
|
|
462
|
+
def _emit_nullif(
|
|
463
|
+
expr: SnakeNullIf[Any],
|
|
464
|
+
dialect: SnakeDialect,
|
|
465
|
+
params: list[object],
|
|
466
|
+
qualify: Qualify | None = None,
|
|
467
|
+
correlate: Correlation | None = None,
|
|
468
|
+
) -> str:
|
|
469
|
+
"""`NULLIF(value, sentinel)`."""
|
|
470
|
+
value = emit_value(expr.value, dialect, params, qualify, correlate)
|
|
471
|
+
sentinel = emit_expression_or_literal(
|
|
472
|
+
expr.sentinel, dialect, params, qualify, correlate
|
|
473
|
+
)
|
|
474
|
+
return f"NULLIF({value}, {sentinel})"
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
@emit_value.register(SnakeFuncCall)
|
|
478
|
+
def _emit_func_call(
|
|
479
|
+
expr: SnakeFuncCall[Any],
|
|
480
|
+
dialect: SnakeDialect,
|
|
481
|
+
params: list[object],
|
|
482
|
+
qualify: Qualify | None = None,
|
|
483
|
+
correlate: Correlation | None = None,
|
|
484
|
+
) -> str:
|
|
485
|
+
"""`FUNC(arg, ...)`, with the name translated by the dialect.
|
|
486
|
+
|
|
487
|
+
`EXTRACT` is the exception: its syntax is `EXTRACT(part FROM value)`, not a list of arguments.
|
|
488
|
+
"""
|
|
489
|
+
name = dialect.function_name(expr.func)
|
|
490
|
+
if expr.func is SnakeFunc.EXTRACT and expr.part is not None:
|
|
491
|
+
# EXTRACT(part FROM value): the part is a keyword, it is NOT parametrised.
|
|
492
|
+
value = emit_expression_or_literal(
|
|
493
|
+
expr.arguments[0], dialect, params, qualify, correlate
|
|
494
|
+
)
|
|
495
|
+
return f"{name}({expr.part.value} FROM {value})"
|
|
496
|
+
# The `part` goes FIRST and its param before the arguments: in a positional dialect the order of
|
|
497
|
+
# `params` must follow the textual order of the placeholders (it ended up swapping part and
|
|
498
|
+
# argument).
|
|
499
|
+
rendered: list[str] = []
|
|
500
|
+
if expr.part is not None:
|
|
501
|
+
rendered.append(emit_operand(expr.part.value, dialect, params))
|
|
502
|
+
rendered.extend(
|
|
503
|
+
emit_expression_or_literal(argument, dialect, params, qualify, correlate)
|
|
504
|
+
for argument in expr.arguments
|
|
505
|
+
)
|
|
506
|
+
# ROUND with a digit count: some engines have no overload for a float and want the value as a
|
|
507
|
+
# decimal first. The dialect declares the TYPE NAME; the cast is written in standard
|
|
508
|
+
# `CAST(x AS t)`, which Postgres takes as readily as its own `::`. That way no engine's
|
|
509
|
+
# spelling lives in an emitter whose whole job is to be agnostic.
|
|
510
|
+
cast_to = dialect.syntax.round_casts_first_argument_to
|
|
511
|
+
if expr.func is SnakeFunc.ROUND and len(rendered) == 2 and cast_to is not None:
|
|
512
|
+
rendered[0] = f"CAST({rendered[0]} AS {cast_to})"
|
|
513
|
+
return f"{name}({', '.join(rendered)})"
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
@emit_value.register(SnakeWindow)
|
|
517
|
+
def _emit_window(
|
|
518
|
+
expr: SnakeWindow[Any],
|
|
519
|
+
dialect: SnakeDialect,
|
|
520
|
+
params: list[object],
|
|
521
|
+
qualify: Qualify | None = None,
|
|
522
|
+
correlate: Correlation | None = None,
|
|
523
|
+
) -> str:
|
|
524
|
+
"""`<func>(<arg>[, <extra>...]) OVER ([PARTITION BY ...] [ORDER BY ...])`.
|
|
525
|
+
|
|
526
|
+
TEXTUAL emission order: Postgres's `%s` is positional, so `params` follows the order of the
|
|
527
|
+
placeholders (arguments, then partition, then order).
|
|
528
|
+
"""
|
|
529
|
+
arguments: list[str] = []
|
|
530
|
+
if expr.arg is not None:
|
|
531
|
+
arguments.append(emit_value(expr.arg, dialect, params, qualify, correlate))
|
|
532
|
+
arguments.extend(emit_operand(extra, dialect, params) for extra in expr.extra_args)
|
|
533
|
+
|
|
534
|
+
window: list[str] = []
|
|
535
|
+
if expr.partition_by:
|
|
536
|
+
keys = ", ".join(
|
|
537
|
+
emit_value(value, dialect, params, qualify, correlate)
|
|
538
|
+
for value in expr.partition_by
|
|
539
|
+
)
|
|
540
|
+
window.append(f"PARTITION BY {keys}")
|
|
541
|
+
if expr.order_by:
|
|
542
|
+
keys = ", ".join(
|
|
543
|
+
emit_order_key(key, dialect, params, qualify) for key in expr.order_by
|
|
544
|
+
)
|
|
545
|
+
window.append(f"ORDER BY {keys}")
|
|
546
|
+
if expr.frame is not None:
|
|
547
|
+
# No dialect involved, and that is measured: `ROWS BETWEEN 1 PRECEDING AND CURRENT ROW`
|
|
548
|
+
# runs unchanged on the three. The offset is IN the clause because MariaDB rejects a
|
|
549
|
+
# placeholder in a bound; it is an `int` checked non-negative when the bound was built.
|
|
550
|
+
window.append(expr.frame.sql())
|
|
551
|
+
|
|
552
|
+
return f"{expr.func}({', '.join(arguments)}) OVER ({' '.join(window)})"
|