cypher2sql 0.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.
- cypher2sql/__init__.py +36 -0
- cypher2sql/_ast.py +426 -0
- cypher2sql/_bind/__init__.py +46 -0
- cypher2sql/_bind/_base.py +437 -0
- cypher2sql/_bind/_binder.py +387 -0
- cypher2sql/_bind/_build.py +701 -0
- cypher2sql/_bind/_edges.py +354 -0
- cypher2sql/_bind/_names.py +72 -0
- cypher2sql/_bind/_patterns.py +633 -0
- cypher2sql/_bind/_predicates.py +560 -0
- cypher2sql/_bind/_values.py +664 -0
- cypher2sql/_compare.py +265 -0
- cypher2sql/_emit/__init__.py +42 -0
- cypher2sql/_emit/_core.py +362 -0
- cypher2sql/_emit/_walks.py +622 -0
- cypher2sql/_errors.py +396 -0
- cypher2sql/_infer.py +287 -0
- cypher2sql/_ir.py +663 -0
- cypher2sql/_lexer.py +557 -0
- cypher2sql/_limits.py +79 -0
- cypher2sql/_parser/__init__.py +90 -0
- cypher2sql/_parser/_base.py +234 -0
- cypher2sql/_parser/_clauses.py +404 -0
- cypher2sql/_parser/_grammar.py +680 -0
- cypher2sql/_plan/__init__.py +143 -0
- cypher2sql/_plan/_groups.py +282 -0
- cypher2sql/_plan/_nodes.py +562 -0
- cypher2sql/_plan/_planner.py +794 -0
- cypher2sql/_plan/_rows.py +803 -0
- cypher2sql/_plan/_scopes.py +104 -0
- cypher2sql/_plan/_uniqueness.py +84 -0
- cypher2sql/_plan/_working.py +99 -0
- cypher2sql/_schema.py +519 -0
- cypher2sql/_template.py +61 -0
- cypher2sql/_unsupported.py +170 -0
- cypher2sql/py.typed +0 -0
- cypher2sql-0.1.0.dist-info/METADATA +95 -0
- cypher2sql-0.1.0.dist-info/RECORD +40 -0
- cypher2sql-0.1.0.dist-info/WHEEL +4 -0
- cypher2sql-0.1.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,562 @@
|
|
|
1
|
+
"""The relational plan's nodes: one dataclass per SQL construct the emitter renders.
|
|
2
|
+
|
|
3
|
+
A `Select` is the target's table, its laterals, its hoisted walks, one `WHERE` and an `ORDER BY`;
|
|
4
|
+
a `Group` is a subquery body, a `Lateral` a row scope joined into the same `FROM`. Nothing here
|
|
5
|
+
decides what to select or where a predicate goes: the planner builds this tree, and `_emit` is its
|
|
6
|
+
only reader. Aliases live on the nodes, so the emitter never computes one. `_and` is the one-place
|
|
7
|
+
builder for a conjunction over an already-planned list of conjuncts.
|
|
8
|
+
|
|
9
|
+
A walk whose right end is the target is hoisted out of every row-scoped subquery: `WalkSource` is
|
|
10
|
+
one `WITH RECURSIVE` entry evaluated once per query, and `WalkIn` is the target's membership in
|
|
11
|
+
its endpoint set. `_referenced_aliases` and `_declared_aliases` let the planner prove a hoisted
|
|
12
|
+
walk's anchor reads nothing from outside itself."""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from collections.abc import Iterator
|
|
17
|
+
from dataclasses import dataclass, fields, is_dataclass
|
|
18
|
+
from typing import Final
|
|
19
|
+
|
|
20
|
+
from cypher2sql._ir import (
|
|
21
|
+
BStringOp,
|
|
22
|
+
ConstValue,
|
|
23
|
+
Op,
|
|
24
|
+
Orientation,
|
|
25
|
+
PgType,
|
|
26
|
+
declared_pg_type,
|
|
27
|
+
)
|
|
28
|
+
from cypher2sql._schema import EdgeType, NodeType
|
|
29
|
+
|
|
30
|
+
#: PostgreSQL's identifier limit: a projected column name longer than this is shortened.
|
|
31
|
+
_MAX_IDENT = 63
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True, slots=True)
|
|
35
|
+
class ColRef:
|
|
36
|
+
"""A quoted column of one alias: `n1."id"`."""
|
|
37
|
+
|
|
38
|
+
alias: str
|
|
39
|
+
column: str
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True, slots=True)
|
|
43
|
+
class Placeholder:
|
|
44
|
+
"""A bound parameter with its cast: `%s::text`, or `%s::text[]` when `array` is set."""
|
|
45
|
+
|
|
46
|
+
value_index: int
|
|
47
|
+
pg_type: PgType
|
|
48
|
+
array: bool = False
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True, slots=True)
|
|
52
|
+
class AnyEq:
|
|
53
|
+
"""`column = ANY(%s::<type>[])`: membership in a bound list, NULL when no element matches."""
|
|
54
|
+
|
|
55
|
+
column: SqlExpr
|
|
56
|
+
values: Placeholder
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass(frozen=True, slots=True)
|
|
60
|
+
class StringCall:
|
|
61
|
+
"""One string predicate as a PostgreSQL function or position test, never `LIKE`.
|
|
62
|
+
|
|
63
|
+
The column arrives as a `Collate`, so `starts_with`, `position` and the suffix `=` all run
|
|
64
|
+
by code point whatever the column's collation.
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
op: BStringOp
|
|
68
|
+
column: SqlExpr
|
|
69
|
+
operand: SqlExpr
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass(frozen=True, slots=True)
|
|
73
|
+
class Regex:
|
|
74
|
+
"""`(column COLLATE "C") ~ ('^(?:' || %s::text || ')$')`, or `!~` when negated."""
|
|
75
|
+
|
|
76
|
+
column: SqlExpr
|
|
77
|
+
pattern: SqlExpr
|
|
78
|
+
negated: bool = False
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass(frozen=True, slots=True)
|
|
82
|
+
class Bool:
|
|
83
|
+
"""A constant: `TRUE`, `FALSE` or `NULL`."""
|
|
84
|
+
|
|
85
|
+
value: ConstValue
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass(frozen=True, slots=True)
|
|
89
|
+
class Nan:
|
|
90
|
+
"""PostgreSQL's NaN, cast to the column's type: `'NaN'::double precision`."""
|
|
91
|
+
|
|
92
|
+
pg_type: PgType
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@dataclass(frozen=True, slots=True)
|
|
96
|
+
class Collate:
|
|
97
|
+
"""A string operand pinned to code-point order: `n1."name" COLLATE "C"`.
|
|
98
|
+
|
|
99
|
+
Every text column of a comparison or `IN`, of `STARTS WITH`/`ENDS WITH`/`CONTAINS`/`=~`, and
|
|
100
|
+
every text key's order operand is one of these, so neither the column's nor the database's
|
|
101
|
+
collation can change which keys come back or the order they come in. A non-text operand is
|
|
102
|
+
never collated, and a bound value stays a bare `%s::text`: the column's pin decides.
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
operand: SqlExpr
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@dataclass(frozen=True, slots=True)
|
|
109
|
+
class IsNull:
|
|
110
|
+
"""`operand IS [NOT] NULL`."""
|
|
111
|
+
|
|
112
|
+
operand: SqlExpr
|
|
113
|
+
negated: bool = False
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@dataclass(frozen=True, slots=True)
|
|
117
|
+
class Eq:
|
|
118
|
+
"""`left = right`, used by the pattern's own links."""
|
|
119
|
+
|
|
120
|
+
left: SqlExpr
|
|
121
|
+
right: SqlExpr
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@dataclass(frozen=True, slots=True)
|
|
125
|
+
class Cmp:
|
|
126
|
+
"""A comparison with the operator Cypher asked for; a text operand arrives collated."""
|
|
127
|
+
|
|
128
|
+
op: Op
|
|
129
|
+
left: SqlExpr
|
|
130
|
+
right: SqlExpr
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@dataclass(frozen=True, slots=True)
|
|
134
|
+
class Not:
|
|
135
|
+
"""`NOT operand`; an operand that is an `EXISTS` reads `NOT EXISTS (...)`."""
|
|
136
|
+
|
|
137
|
+
operand: Conjunct
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@dataclass(frozen=True, slots=True)
|
|
141
|
+
class Parity:
|
|
142
|
+
"""An n-ary exclusive disjunction, emitted as one left-associative `<>` chain."""
|
|
143
|
+
|
|
144
|
+
items: tuple[Conjunct, ...]
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
@dataclass(frozen=True, slots=True)
|
|
148
|
+
class And:
|
|
149
|
+
"""A parenthesised conjunction, used by folded comparisons and composite-key links."""
|
|
150
|
+
|
|
151
|
+
items: tuple[Conjunct, ...]
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
@dataclass(frozen=True, slots=True)
|
|
155
|
+
class Or:
|
|
156
|
+
"""A parenthesised disjunction of alternative orientations or inferred paths."""
|
|
157
|
+
|
|
158
|
+
items: tuple[Conjunct, ...]
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
@dataclass(frozen=True, slots=True)
|
|
162
|
+
class CaseNull:
|
|
163
|
+
"""`CASE WHEN guard THEN NULL ELSE value END`: a missing variable makes a predicate NULL."""
|
|
164
|
+
|
|
165
|
+
guard: Conjunct
|
|
166
|
+
value: Conjunct
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
@dataclass(frozen=True, slots=True)
|
|
170
|
+
class TupleNe:
|
|
171
|
+
"""`(left keys) <> (right keys)`: two occurrences of one edge must not reuse a row.
|
|
172
|
+
|
|
173
|
+
A text key column arrives as a `Collate` operand, like every other text comparison, so a
|
|
174
|
+
nondeterministic column collation cannot make two different keys compare equal.
|
|
175
|
+
"""
|
|
176
|
+
|
|
177
|
+
left: tuple[SqlExpr, ...]
|
|
178
|
+
right: tuple[SqlExpr, ...]
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
@dataclass(frozen=True, slots=True)
|
|
182
|
+
class Join:
|
|
183
|
+
"""`JOIN table AS alias ON condition` inside an `EXISTS`."""
|
|
184
|
+
|
|
185
|
+
table: str
|
|
186
|
+
alias: str
|
|
187
|
+
on: SqlExpr
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
@dataclass(frozen=True, slots=True)
|
|
191
|
+
class CrossJoin:
|
|
192
|
+
"""`CROSS JOIN table AS alias`, for pieces linked only by predicates."""
|
|
193
|
+
|
|
194
|
+
table: str
|
|
195
|
+
alias: str
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
@dataclass(frozen=True, slots=True)
|
|
199
|
+
class Group:
|
|
200
|
+
"""One `EXISTS` or lateral body: its `FROM`, its joins and its `WHERE` conjuncts.
|
|
201
|
+
|
|
202
|
+
`table` is `None` for a lateral body that reads no row of its own: it has no `FROM` and decides
|
|
203
|
+
its `WHERE` from columns earlier scopes expose.
|
|
204
|
+
"""
|
|
205
|
+
|
|
206
|
+
table: str | None
|
|
207
|
+
alias: str
|
|
208
|
+
joins: tuple[Join | CrossJoin, ...]
|
|
209
|
+
where: tuple[Conjunct, ...]
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
@dataclass(frozen=True, slots=True)
|
|
213
|
+
class Projection:
|
|
214
|
+
"""One select-list expression and the column name it returns.
|
|
215
|
+
|
|
216
|
+
A left-joined group exposes `n2."title" AS "n2:title"`; the outer `SELECT` projects a key
|
|
217
|
+
column, bare or as the same `Collate` operand the `ORDER BY` uses under `DISTINCT`.
|
|
218
|
+
"""
|
|
219
|
+
|
|
220
|
+
name: str
|
|
221
|
+
expr: SqlExpr
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
@dataclass(frozen=True, slots=True)
|
|
225
|
+
class Lateral:
|
|
226
|
+
"""`LEFT JOIN LATERAL (…) AS o<i> ON TRUE`: one null-tolerant row scope.
|
|
227
|
+
|
|
228
|
+
Its body is one scope's matches; when it matches nothing the join still yields one row whose
|
|
229
|
+
columns are all NULL, which is Cypher's null row, and every predicate outside the scope reads
|
|
230
|
+
it through three-valued logic. `columns` are the columns a later scope or predicate names,
|
|
231
|
+
plus `found`, which is null exactly when the body matched nothing; a required scope's `found`
|
|
232
|
+
is required in the outer `WHERE`. One target row may meet several rows of the body, so a plan
|
|
233
|
+
whose surviving scope is not pinned to its null row selects `DISTINCT` keys.
|
|
234
|
+
"""
|
|
235
|
+
|
|
236
|
+
alias: str
|
|
237
|
+
columns: tuple[Projection, ...]
|
|
238
|
+
group: Group
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
@dataclass(frozen=True, slots=True)
|
|
242
|
+
class Exists:
|
|
243
|
+
"""One correlated subquery: `EXISTS (SELECT 1 FROM ...)`."""
|
|
244
|
+
|
|
245
|
+
group: Group
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
@dataclass(frozen=True, slots=True)
|
|
249
|
+
class AnyOf:
|
|
250
|
+
"""Alternative `EXISTS` bodies or a zero-hop equality, ORed: one per path length."""
|
|
251
|
+
|
|
252
|
+
items: tuple[SqlExpr | Exists | Walk, ...]
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
@dataclass(frozen=True, slots=True)
|
|
256
|
+
class Recursive:
|
|
257
|
+
"""One correlated `WITH RECURSIVE` walk of a variable-length relationship.
|
|
258
|
+
|
|
259
|
+
The state row is one edge row (`key` identifies it for the trail, `source_columns` and
|
|
260
|
+
`target_columns` carry its two ends), `right_is_source`/`right_is_target` say which end of that
|
|
261
|
+
edge the right pattern node is (an undirected walk needs the state's `at_target` column to know
|
|
262
|
+
where it arrived), and `trail` is every row the path already read. `key_text`, `source_text` and
|
|
263
|
+
`target_text` say which of those columns compare as text — a declared edge property, or an
|
|
264
|
+
undeclared foreign key whose referenced node key is text — so the trail, the hop joins and the
|
|
265
|
+
endpoint identity all pin them to code points. `left` and `right` are the pattern node keys
|
|
266
|
+
already pinned where their declared type is text.
|
|
267
|
+
Depth is the only stopping rule, so cyclic data terminates; the trail check is semantics, not
|
|
268
|
+
cycle detection.
|
|
269
|
+
|
|
270
|
+
`include_zero` is only set for a walk hoisted into `WalkSource`: it adds the depth-0 state row
|
|
271
|
+
described there.
|
|
272
|
+
"""
|
|
273
|
+
|
|
274
|
+
cte: str
|
|
275
|
+
edge_alias: str
|
|
276
|
+
table: str
|
|
277
|
+
key: tuple[str, ...]
|
|
278
|
+
key_text: tuple[bool, ...]
|
|
279
|
+
source_columns: tuple[str, ...]
|
|
280
|
+
target_columns: tuple[str, ...]
|
|
281
|
+
source_text: tuple[bool, ...]
|
|
282
|
+
target_text: tuple[bool, ...]
|
|
283
|
+
left: tuple[SqlExpr, ...]
|
|
284
|
+
right: tuple[SqlExpr, ...]
|
|
285
|
+
right_is_source: bool
|
|
286
|
+
right_is_target: bool
|
|
287
|
+
base: tuple[Orientation, ...]
|
|
288
|
+
steps: tuple[tuple[bool, Orientation], ...]
|
|
289
|
+
seed: tuple[tuple[ColRef, ...], ...]
|
|
290
|
+
depth_min: int
|
|
291
|
+
depth_max: int
|
|
292
|
+
include_zero: bool = False
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
@dataclass(frozen=True, slots=True)
|
|
296
|
+
class WalkHop:
|
|
297
|
+
"""One declared edge row read in one direction inside an untyped walk.
|
|
298
|
+
|
|
299
|
+
`from_columns`/`to_columns` are the edge's two ends, `key` identifies its row for the trail,
|
|
300
|
+
and `tag` names the declared edge: both orientations of one edge share it. `from_types` is the
|
|
301
|
+
type each frontier component this hop reads is cast to, or `None` where the declaration cannot
|
|
302
|
+
prove a cast exact and the pinned text comparison stands. The type is resolved once at plan
|
|
303
|
+
time, from `_carried_type` over every hop that can land on the departing label — plus the left
|
|
304
|
+
node's own key type for a hoisted depth-0 row — and folded into `from_types`: a component no hop
|
|
305
|
+
produced, a producer that left the type undeclared, or two producers that disagree proves no
|
|
306
|
+
cast, and neither does a type outside the exact ones (see `_frontier_type`).
|
|
307
|
+
`landing_table` and `landing_key` let the emitter drop a non-null check that is provably true:
|
|
308
|
+
the landing columns are that table's own key columns.
|
|
309
|
+
"""
|
|
310
|
+
|
|
311
|
+
alias: str
|
|
312
|
+
table: str
|
|
313
|
+
from_label: str
|
|
314
|
+
from_columns: tuple[str, ...]
|
|
315
|
+
from_text: tuple[bool, ...]
|
|
316
|
+
from_types: tuple[PgType | None, ...]
|
|
317
|
+
to_label: str
|
|
318
|
+
to_columns: tuple[str, ...]
|
|
319
|
+
to_text: tuple[bool, ...]
|
|
320
|
+
landing_table: str
|
|
321
|
+
landing_key: tuple[str, ...]
|
|
322
|
+
key: tuple[str, ...]
|
|
323
|
+
tag: int
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
@dataclass(frozen=True, slots=True)
|
|
327
|
+
class UntypedWalk:
|
|
328
|
+
"""One correlated `WITH RECURSIVE` walk over every declared edge an untyped bound allows.
|
|
329
|
+
|
|
330
|
+
The state row is the current node's label and key, encoded as one text value (so keys of
|
|
331
|
+
different node types can never be confused), the hop count, and the edge rows the path already
|
|
332
|
+
read. `base` seeds the first hop, `steps` unions one branch per edge row the walk may read
|
|
333
|
+
next; the depth counter is the stopping rule, so cyclic data terminates, and the trail is
|
|
334
|
+
relationship uniqueness. `right_label` and `right` are the target endpoint's identity, `right`
|
|
335
|
+
already pinned where its declared type is text.
|
|
336
|
+
|
|
337
|
+
`include_zero` is only set for a walk hoisted into `WalkSource`: it adds the depth-0 state row
|
|
338
|
+
described there.
|
|
339
|
+
"""
|
|
340
|
+
|
|
341
|
+
cte: str
|
|
342
|
+
step: str
|
|
343
|
+
base: tuple[WalkHop, ...]
|
|
344
|
+
steps: tuple[WalkHop, ...]
|
|
345
|
+
left: tuple[SqlExpr, ...]
|
|
346
|
+
right: tuple[SqlExpr, ...]
|
|
347
|
+
left_label: str
|
|
348
|
+
right_label: str
|
|
349
|
+
depth_min: int
|
|
350
|
+
depth_max: int
|
|
351
|
+
seed: tuple[tuple[int, tuple[ColRef, ...]], ...]
|
|
352
|
+
include_zero: bool = False
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
@dataclass(frozen=True, slots=True)
|
|
356
|
+
class WalkSource:
|
|
357
|
+
"""One statement-level recursive walk, evaluated once per query.
|
|
358
|
+
|
|
359
|
+
The emitted statement opens with `WITH RECURSIVE`, so no row scope drives it: `anchor_cte` is
|
|
360
|
+
one non-recursive entry selecting the columns `columns` names — the walk's left end and the
|
|
361
|
+
edge rows the path already read — and `cte` is the recursive entry built over it. `alias` is
|
|
362
|
+
the name the walk's `left` and `seed` references give that anchor entry. The walk node is the
|
|
363
|
+
same one the correlated plan renders, so the CTE body is written exactly as it would be inline;
|
|
364
|
+
only its anchors moved. `WalkIn` is the target's membership in the endpoint set `cte` holds.
|
|
365
|
+
|
|
366
|
+
A walk whose bound allows zero hops (`include_zero`) also emits a depth-0 state row carrying
|
|
367
|
+
the left node's identity and an empty trail, so the zero-hop alternative is one more row of the
|
|
368
|
+
endpoint set instead of a key comparison outside the walk.
|
|
369
|
+
"""
|
|
370
|
+
|
|
371
|
+
cte: str
|
|
372
|
+
anchor_cte: str
|
|
373
|
+
alias: str
|
|
374
|
+
anchor: Group
|
|
375
|
+
columns: tuple[Projection, ...]
|
|
376
|
+
walk: Walk
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
@dataclass(frozen=True, slots=True)
|
|
380
|
+
class WalkIn:
|
|
381
|
+
"""The target's membership in one hoisted walk's endpoint set: one semi-join.
|
|
382
|
+
|
|
383
|
+
Rendered as `EXISTS (SELECT 1 FROM <cte> WHERE depth BETWEEN … AND <arrival>)`, so the target
|
|
384
|
+
is compared with the endpoint set the statement computed once and never re-runs the walk.
|
|
385
|
+
"""
|
|
386
|
+
|
|
387
|
+
source: WalkSource
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
@dataclass(frozen=True, slots=True)
|
|
391
|
+
class OrderColumn:
|
|
392
|
+
"""One `ORDER BY` operand and its direction.
|
|
393
|
+
|
|
394
|
+
The operand is a key column, wrapped in `Collate` when its declared type is `str`, so a text
|
|
395
|
+
key orders by code point whatever the database's default collation. The direction is per
|
|
396
|
+
column; the query's `DESC` sets it on every key column.
|
|
397
|
+
"""
|
|
398
|
+
|
|
399
|
+
operand: SqlExpr
|
|
400
|
+
descending: bool = False
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
@dataclass(frozen=True, slots=True)
|
|
404
|
+
class Select:
|
|
405
|
+
"""One `SELECT` over the target's table, with its top-level conjuncts in order.
|
|
406
|
+
|
|
407
|
+
`columns` is the result's key projection in key order, `order` the same keys as operands
|
|
408
|
+
(empty when the query orders nothing), and `offset`/`limit` are the bound `SKIP`/`LIMIT`
|
|
409
|
+
values emitted as `OFFSET`/`FETCH FIRST` placeholders. `walks` are the query's hoisted
|
|
410
|
+
recursive walks, in walk order: the statement's `WITH RECURSIVE` entries, written before the
|
|
411
|
+
`SELECT` so each is evaluated once and not once per target row.
|
|
412
|
+
"""
|
|
413
|
+
|
|
414
|
+
columns: tuple[Projection, ...]
|
|
415
|
+
table: str
|
|
416
|
+
alias: str
|
|
417
|
+
where: tuple[Conjunct, ...]
|
|
418
|
+
laterals: tuple[Lateral, ...] = ()
|
|
419
|
+
walks: tuple[WalkSource, ...] = ()
|
|
420
|
+
distinct: bool = False
|
|
421
|
+
order: tuple[OrderColumn, ...] = ()
|
|
422
|
+
offset: Placeholder | None = None
|
|
423
|
+
limit: Placeholder | None = None
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
type SqlExpr = (
|
|
427
|
+
ColRef
|
|
428
|
+
| Placeholder
|
|
429
|
+
| Bool
|
|
430
|
+
| Nan
|
|
431
|
+
| Collate
|
|
432
|
+
| IsNull
|
|
433
|
+
| Eq
|
|
434
|
+
| Cmp
|
|
435
|
+
| Not
|
|
436
|
+
| Parity
|
|
437
|
+
| And
|
|
438
|
+
| Or
|
|
439
|
+
| CaseNull
|
|
440
|
+
| TupleNe
|
|
441
|
+
| AnyEq
|
|
442
|
+
| StringCall
|
|
443
|
+
| Regex
|
|
444
|
+
)
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
type Walk = Recursive | UntypedWalk
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
type Conjunct = SqlExpr | Exists | AnyOf | Walk | WalkIn
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
#: Every plan node a value (as opposed to a correlated subquery) can be made of. This mirrors the
|
|
454
|
+
#: `SqlExpr` alias member for member: a `type` alias is not a runtime type, so `isinstance` cannot
|
|
455
|
+
#: use it, and the two lists must stay in step when a value node is added.
|
|
456
|
+
_VALUE_EXPRS = (
|
|
457
|
+
ColRef,
|
|
458
|
+
Placeholder,
|
|
459
|
+
Bool,
|
|
460
|
+
Nan,
|
|
461
|
+
Collate,
|
|
462
|
+
IsNull,
|
|
463
|
+
Eq,
|
|
464
|
+
Cmp,
|
|
465
|
+
Not,
|
|
466
|
+
Parity,
|
|
467
|
+
And,
|
|
468
|
+
Or,
|
|
469
|
+
CaseNull,
|
|
470
|
+
TupleNe,
|
|
471
|
+
AnyEq,
|
|
472
|
+
StringCall,
|
|
473
|
+
Regex,
|
|
474
|
+
)
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def _and(items: tuple[SqlExpr, ...]) -> SqlExpr:
|
|
478
|
+
"""One conjunct, or an `And` over them: the plan's only way to combine predicates."""
|
|
479
|
+
return items[0] if len(items) == 1 else And(items)
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def _keyed(reference: SqlExpr, text: bool) -> SqlExpr:
|
|
483
|
+
"""A key column as a code-point comparison: collated when its declared type is text."""
|
|
484
|
+
return Collate(reference) if text else reference
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
#: The declared types an untyped walk may cast a text frontier component back to: the ones whose
|
|
488
|
+
#: text rendering is a faithful key. For each, `x::text::t` is `x` in the same session and two
|
|
489
|
+
#: values render alike exactly when they are equal, so the typed equality is the text comparison's.
|
|
490
|
+
#: `NUMERIC` is absent because it keeps scale (`'1.2300'::numeric = '1.23'::numeric` is true while
|
|
491
|
+
#: their text keys differ) and `DOUBLE_PRECISION` because its text round trip is not exact: under
|
|
492
|
+
#: `extra_float_digits = 0` most values come back changed and near-maximum ones raise
|
|
493
|
+
#: `NumericValueOutOfRange`. Anything not listed keeps the pinned text comparison.
|
|
494
|
+
_EXACT_CASTS: Final[frozenset[PgType]] = frozenset(
|
|
495
|
+
{PgType.BIGINT, PgType.BOOLEAN, PgType.UUID, PgType.DATE, PgType.TIMESTAMPTZ}
|
|
496
|
+
)
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
def _hop_leaving(edge: EdgeType, orientation: Orientation) -> tuple[NodeType, tuple[str, ...]]:
|
|
500
|
+
"""The node a hop leaves and the edge columns that carry its key."""
|
|
501
|
+
if orientation is Orientation.FORWARD:
|
|
502
|
+
return edge.source, edge.source_columns
|
|
503
|
+
return edge.target, edge.target_columns
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
def _hop_landing(edge: EdgeType, orientation: Orientation) -> tuple[NodeType, tuple[str, ...]]:
|
|
507
|
+
"""The node a hop lands on and the edge columns that carry its key."""
|
|
508
|
+
if orientation is Orientation.FORWARD:
|
|
509
|
+
return edge.target, edge.target_columns
|
|
510
|
+
return edge.source, edge.source_columns
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
def _carried_type(edge: EdgeType, column: str, node: NodeType, key: str) -> PgType | None:
|
|
514
|
+
"""The type one edge column's value travels as when it carries one key column of `node`.
|
|
515
|
+
|
|
516
|
+
A column the edge declares itself decides its own type; an undeclared foreign key takes the
|
|
517
|
+
type of the key it points at. `None` when neither declares one.
|
|
518
|
+
"""
|
|
519
|
+
own = declared_pg_type(edge, column)
|
|
520
|
+
return declared_pg_type(node, key) if own is None else own
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def _frontier_type(carried: PgType | None, producer: PgType | None) -> PgType | None:
|
|
524
|
+
"""The type an untyped walk casts a frontier component to on one departing hop, or `None`.
|
|
525
|
+
|
|
526
|
+
The frontier renders a node identity as text — its label plus one component per key column —
|
|
527
|
+
and the hop that produced a component decided its type: its edge's own declaration for the
|
|
528
|
+
column, or the key column an undeclared foreign key points at (`_carried_type`). Casting a
|
|
529
|
+
component back is only exact when the departing column carries the same type its producer did,
|
|
530
|
+
because one value of one type and another type's rendering of it can be different text
|
|
531
|
+
(`'01'` against `1`), and that type is one of `_EXACT_CASTS`.
|
|
532
|
+
|
|
533
|
+
Everything else returns `None`, the pinned text comparison: a component no hop produced, a
|
|
534
|
+
producer that left the type undeclared, two producers that disagree, and a type outside
|
|
535
|
+
`_EXACT_CASTS` — including `TEXT`, whose pinned comparison is already the right one.
|
|
536
|
+
Correctness before an index.
|
|
537
|
+
"""
|
|
538
|
+
if carried is None or carried != producer or carried not in _EXACT_CASTS:
|
|
539
|
+
return None
|
|
540
|
+
return carried
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def _plan_nodes(node: object) -> Iterator[object]:
|
|
544
|
+
"""Every node of one planned tree, pre-order: tuples and dataclass fields, nothing else."""
|
|
545
|
+
yield node
|
|
546
|
+
if isinstance(node, (tuple, list)):
|
|
547
|
+
for item in node:
|
|
548
|
+
yield from _plan_nodes(item)
|
|
549
|
+
elif is_dataclass(node) and not isinstance(node, type):
|
|
550
|
+
for field in fields(node):
|
|
551
|
+
yield from _plan_nodes(getattr(node, field.name))
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
def _referenced_aliases(node: object) -> set[str]:
|
|
555
|
+
"""Every table alias a planned tree reads a column from."""
|
|
556
|
+
return {item.alias for item in _plan_nodes(node) if isinstance(item, ColRef)}
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
def _declared_aliases(node: object) -> set[str]:
|
|
560
|
+
"""Every table alias a planned tree's own `FROM`, joins and row scopes declare."""
|
|
561
|
+
declaring = (Group, Lateral, Join, CrossJoin)
|
|
562
|
+
return {item.alias for item in _plan_nodes(node) if isinstance(item, declaring)}
|