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,622 @@
|
|
|
1
|
+
"""Walk rendering: each recursive CTE, its endpoint membership and the `EXISTS` around it.
|
|
2
|
+
|
|
3
|
+
A walk's state, endpoint identity and trail are text pinned to code points, so two different
|
|
4
|
+
rows never compare equal. A hoisted walk's entries are written before the `SELECT`; a correlated
|
|
5
|
+
one is a single `EXISTS` over its own `WITH RECURSIVE` entry and the key check against it.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Iterable
|
|
11
|
+
|
|
12
|
+
from cypher2sql._ir import Orientation, PgType
|
|
13
|
+
from cypher2sql._plan import (
|
|
14
|
+
Collate,
|
|
15
|
+
Recursive,
|
|
16
|
+
SqlExpr,
|
|
17
|
+
UntypedWalk,
|
|
18
|
+
Walk,
|
|
19
|
+
WalkHop,
|
|
20
|
+
WalkIn,
|
|
21
|
+
WalkSource,
|
|
22
|
+
)
|
|
23
|
+
from cypher2sql._schema import quote_ident
|
|
24
|
+
|
|
25
|
+
from ._core import (
|
|
26
|
+
_PIN,
|
|
27
|
+
_all,
|
|
28
|
+
_any,
|
|
29
|
+
_array_text,
|
|
30
|
+
_arrival,
|
|
31
|
+
_code_point,
|
|
32
|
+
_Emitter,
|
|
33
|
+
_ends,
|
|
34
|
+
_pinned,
|
|
35
|
+
_row,
|
|
36
|
+
_single_orientation,
|
|
37
|
+
_text_literal,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class _WalkEmitter(_Emitter):
|
|
42
|
+
"""The emitter core plus every walk's CTE and the check that reads it."""
|
|
43
|
+
|
|
44
|
+
def walk_conjunct(self, expr: WalkIn | Recursive | UntypedWalk, indent: int) -> str:
|
|
45
|
+
"""Dispatch one walk conjunct to the renderer that owns its block shape."""
|
|
46
|
+
match expr:
|
|
47
|
+
case WalkIn():
|
|
48
|
+
return self.walk_in(expr, indent)
|
|
49
|
+
case Recursive():
|
|
50
|
+
return self.recursive(expr, indent)
|
|
51
|
+
return self.untyped(expr, indent)
|
|
52
|
+
|
|
53
|
+
def walk_sources(self, sources: tuple[WalkSource, ...]) -> list[str]:
|
|
54
|
+
"""Every hoisted walk's `WITH RECURSIVE` entries: its anchor, then the walk itself."""
|
|
55
|
+
entries: list[str] = []
|
|
56
|
+
for source in sources:
|
|
57
|
+
entries.append(self.anchor_definition(source, 0))
|
|
58
|
+
entries.append(self.walk_definition(source.walk, 0, materialized=True, anchor=source))
|
|
59
|
+
return entries
|
|
60
|
+
|
|
61
|
+
def anchor_definition(self, source: WalkSource, indent: int) -> str:
|
|
62
|
+
"""`anchor1 AS NOT MATERIALIZED (…)`: the columns one hoisted walk reads, once.
|
|
63
|
+
|
|
64
|
+
The entry is a derived table of the walk's own row scope, so it may not correlate; the
|
|
65
|
+
walk's left end and trail seed arrive as the `k1`, `k2`, … columns it projects. It is
|
|
66
|
+
referenced from the CTE's base terms only, so PostgreSQL inlines it there.
|
|
67
|
+
"""
|
|
68
|
+
projection = ", ".join(
|
|
69
|
+
f"{self.expression(item.expr, indent + 2)} AS {quote_ident(item.name)}"
|
|
70
|
+
for item in source.columns
|
|
71
|
+
)
|
|
72
|
+
pad = " " * indent
|
|
73
|
+
lines = [f"{source.anchor_cte} AS NOT MATERIALIZED ("]
|
|
74
|
+
lines.extend(self.group_body(source.anchor, indent + 2, projection))
|
|
75
|
+
lines.append(f"{pad})")
|
|
76
|
+
return "\n".join(lines)
|
|
77
|
+
|
|
78
|
+
def walk_definition(
|
|
79
|
+
self, walk: Walk, indent: int, *, materialized: bool, anchor: WalkSource | None
|
|
80
|
+
) -> str:
|
|
81
|
+
"""`reach1 (…) AS MATERIALIZED (…)`: one walk's CTE, over its anchor entry if hoisted."""
|
|
82
|
+
match walk:
|
|
83
|
+
case Recursive():
|
|
84
|
+
return self._recursive_definition(walk, indent, materialized, anchor)
|
|
85
|
+
case UntypedWalk():
|
|
86
|
+
return self._untyped_definition(walk, indent, materialized, anchor)
|
|
87
|
+
|
|
88
|
+
def walk_in(self, node: WalkIn, indent: int) -> str:
|
|
89
|
+
"""The target's membership in a hoisted walk's endpoint set: one semi-join, no walk.
|
|
90
|
+
|
|
91
|
+
The CTE is a statement-level entry, so this subquery only reads the endpoint set it
|
|
92
|
+
already holds; it never re-runs the walk for another candidate row.
|
|
93
|
+
"""
|
|
94
|
+
return self._exists_walk(None, self._consumer(node.source.walk, indent + 2), indent)
|
|
95
|
+
|
|
96
|
+
def _consumer(self, walk: Walk, indent: int) -> list[str]:
|
|
97
|
+
"""`SELECT 1 FROM <cte> WHERE depth BETWEEN … AND <arrival>`, indented for its place."""
|
|
98
|
+
pad = " " * indent
|
|
99
|
+
inner = " " * (indent + 2)
|
|
100
|
+
cte = walk.cte
|
|
101
|
+
match walk:
|
|
102
|
+
case Recursive():
|
|
103
|
+
sources = _ends(walk.source_columns, "src")
|
|
104
|
+
targets = _ends(walk.target_columns, "dst")
|
|
105
|
+
arrival = self._recursive_end(walk, sources, targets, _single_orientation(walk))
|
|
106
|
+
case UntypedWalk():
|
|
107
|
+
arrival = f"{cte}.current = {self._node_key(walk.right_label, walk.right)}"
|
|
108
|
+
return [
|
|
109
|
+
f"{pad}SELECT 1",
|
|
110
|
+
f"{pad}FROM {cte}",
|
|
111
|
+
f"{pad}WHERE {cte}.depth BETWEEN {walk.depth_min} AND {walk.depth_max}",
|
|
112
|
+
f"{inner}AND {arrival}",
|
|
113
|
+
]
|
|
114
|
+
|
|
115
|
+
def _exists_walk(self, definition: str | None, consumer: list[str], indent: int) -> str:
|
|
116
|
+
"""`EXISTS (…)` around one walk: its optional CTE entry, then the endpoint consumer.
|
|
117
|
+
|
|
118
|
+
A correlated walk writes its `WITH RECURSIVE` entry first; a hoisted walk's CTE is
|
|
119
|
+
statement-level, so `definition` is `None` and only the consumer lines are indented.
|
|
120
|
+
"""
|
|
121
|
+
lines = ["EXISTS ("]
|
|
122
|
+
if definition is not None:
|
|
123
|
+
first, *rest = definition.split("\n")
|
|
124
|
+
lines.append(f"{' ' * (indent + 2)}WITH RECURSIVE {first}")
|
|
125
|
+
lines.extend(rest)
|
|
126
|
+
lines.extend(consumer)
|
|
127
|
+
lines.append(" " * indent + ")")
|
|
128
|
+
return "\n".join(lines)
|
|
129
|
+
|
|
130
|
+
def recursive(self, recursive: Recursive, indent: int) -> str:
|
|
131
|
+
"""One correlated `WITH RECURSIVE` walk: base hop, recursive hop, then the key check.
|
|
132
|
+
|
|
133
|
+
A walk that may only traverse its edge one way needs no arrival state: its hops always
|
|
134
|
+
land on the same end, so `at_target` is dropped and the step has one join condition.
|
|
135
|
+
"""
|
|
136
|
+
body = indent + 2
|
|
137
|
+
definition = self.walk_definition(recursive, body, materialized=False, anchor=None)
|
|
138
|
+
return self._exists_walk(definition, self._consumer(recursive, body), indent)
|
|
139
|
+
|
|
140
|
+
def _recursive_definition(
|
|
141
|
+
self,
|
|
142
|
+
recursive: Recursive,
|
|
143
|
+
indent: int,
|
|
144
|
+
materialized: bool,
|
|
145
|
+
anchor: WalkSource | None,
|
|
146
|
+
) -> str:
|
|
147
|
+
"""The CTE of one typed walk: its state, its base hop, its step and its trail."""
|
|
148
|
+
pad = " " * indent
|
|
149
|
+
inner = " " * (indent + 2)
|
|
150
|
+
edge = recursive.edge_alias
|
|
151
|
+
sources = _ends(recursive.source_columns, "src")
|
|
152
|
+
targets = _ends(recursive.target_columns, "dst")
|
|
153
|
+
plain = _single_orientation(recursive)
|
|
154
|
+
state = ["depth", *sources, *targets]
|
|
155
|
+
if plain is None:
|
|
156
|
+
state.append("at_target")
|
|
157
|
+
state.append("trail")
|
|
158
|
+
key_row = self._trail_row(
|
|
159
|
+
[self._edge_column(edge, column) for column in recursive.key], recursive.key_text
|
|
160
|
+
)
|
|
161
|
+
before = [
|
|
162
|
+
self._trail_row([self.column(column) for column in row], recursive.key_text)
|
|
163
|
+
for row in recursive.seed
|
|
164
|
+
]
|
|
165
|
+
lines = [
|
|
166
|
+
f"{recursive.cte} ({', '.join(state)}) AS {'MATERIALIZED ' if materialized else ''}("
|
|
167
|
+
]
|
|
168
|
+
if recursive.include_zero:
|
|
169
|
+
lines.extend(
|
|
170
|
+
f"{inner}{line}" for line in self._recursive_zero(recursive, anchor, plain is None)
|
|
171
|
+
)
|
|
172
|
+
lines.append(f"{inner}UNION ALL")
|
|
173
|
+
lines.extend(
|
|
174
|
+
f"{inner}{line}"
|
|
175
|
+
for line in self._recursive_base(recursive, key_row, before, plain is None, anchor)
|
|
176
|
+
)
|
|
177
|
+
lines.append(f"{inner}UNION ALL")
|
|
178
|
+
lines.extend(
|
|
179
|
+
f"{inner}{line}"
|
|
180
|
+
for line in self._recursive_step(recursive, sources, targets, key_row, plain)
|
|
181
|
+
)
|
|
182
|
+
lines.append(f"{pad})")
|
|
183
|
+
return "\n".join(lines)
|
|
184
|
+
|
|
185
|
+
def _recursive_zero(
|
|
186
|
+
self, recursive: Recursive, anchor: WalkSource | None, with_state: bool
|
|
187
|
+
) -> list[str]:
|
|
188
|
+
"""The depth-0 state row: the left node itself, no edge read, an empty trail.
|
|
189
|
+
|
|
190
|
+
The zero-hop alternative is then one more row of the endpoint set instead of a key
|
|
191
|
+
comparison outside the walk. `right_is_target` says which end the walk arrived at, so the
|
|
192
|
+
row's arrival end is the one the target's label names. Both ends hold the left node's key,
|
|
193
|
+
each pinned with the same flag its end's edge column carries, so no branch of the
|
|
194
|
+
`UNION ALL` leaves PostgreSQL to resolve a collation mismatch.
|
|
195
|
+
"""
|
|
196
|
+
if anchor is None:
|
|
197
|
+
raise AssertionError("internal error: a zero hop outside a hoisted walk")
|
|
198
|
+
values = ["0", *self._zero_columns(recursive)]
|
|
199
|
+
if with_state:
|
|
200
|
+
values.append("TRUE" if recursive.right_is_target else "FALSE")
|
|
201
|
+
values.append("ARRAY[]::record[]")
|
|
202
|
+
return [
|
|
203
|
+
f"SELECT {', '.join(values)}",
|
|
204
|
+
f"FROM {anchor.anchor_cte} AS {anchor.alias}",
|
|
205
|
+
]
|
|
206
|
+
|
|
207
|
+
def _zero_columns(self, recursive: Recursive) -> list[str]:
|
|
208
|
+
"""The depth-0 state's two ends: the left node's keys, pinned exactly as the base is.
|
|
209
|
+
|
|
210
|
+
The left node stands in both the source and the target end at depth zero, so each end's
|
|
211
|
+
copy takes that end's text flag from `_state_pins` — the same flags, in the same order,
|
|
212
|
+
the base and step branches pin their edge columns with. A key column the schema does not
|
|
213
|
+
declare as text would otherwise reach the union bare while the edge column beside it is
|
|
214
|
+
pinned, and only PostgreSQL's collation-resolution rule would keep the two comparable.
|
|
215
|
+
"""
|
|
216
|
+
pins = self._state_pins(recursive)
|
|
217
|
+
split = len(recursive.source_text)
|
|
218
|
+
return [
|
|
219
|
+
_pinned(self._unpinned(recursive.left[index]), pin)
|
|
220
|
+
for texts in (pins[:split], pins[split:])
|
|
221
|
+
for index, pin in enumerate(texts)
|
|
222
|
+
]
|
|
223
|
+
|
|
224
|
+
def _state_pins(self, recursive: Recursive) -> tuple[bool, ...]:
|
|
225
|
+
"""The state's text flags in column order: the source end, then the target end."""
|
|
226
|
+
return (*recursive.source_text, *recursive.target_text)
|
|
227
|
+
|
|
228
|
+
def _state_columns(self, recursive: Recursive, edge: str) -> list[str]:
|
|
229
|
+
"""The state's key columns: the edge row's two ends, text keys pinned to code points.
|
|
230
|
+
|
|
231
|
+
The depth-0 row projects the anchor's key columns through the same pins (`_state_pins`,
|
|
232
|
+
used by `_zero_columns`), so every branch of the `UNION ALL` carries one collation.
|
|
233
|
+
Without it a nondeterministic column collation on the table rejects the mix; with it the
|
|
234
|
+
state compares code points like every join that reads it.
|
|
235
|
+
"""
|
|
236
|
+
columns = (*recursive.source_columns, *recursive.target_columns)
|
|
237
|
+
return [
|
|
238
|
+
_pinned(self._edge_column(edge, column), pin)
|
|
239
|
+
for column, pin in zip(columns, self._state_pins(recursive), strict=True)
|
|
240
|
+
]
|
|
241
|
+
|
|
242
|
+
def _unpinned(self, expr: SqlExpr) -> str:
|
|
243
|
+
"""One expression without the `Collate` it already carries: the state pin comes after."""
|
|
244
|
+
return self.expression(expr.operand if isinstance(expr, Collate) else expr, 0)
|
|
245
|
+
|
|
246
|
+
def _recursive_base(
|
|
247
|
+
self,
|
|
248
|
+
recursive: Recursive,
|
|
249
|
+
key_row: str,
|
|
250
|
+
before: list[str],
|
|
251
|
+
with_state: bool,
|
|
252
|
+
anchor: WalkSource | None,
|
|
253
|
+
) -> list[str]:
|
|
254
|
+
"""The non-recursive term: the left node's key joins one edge row per orientation."""
|
|
255
|
+
edge = recursive.edge_alias
|
|
256
|
+
conditions: list[str] = []
|
|
257
|
+
forwards: list[str] = []
|
|
258
|
+
for orientation in recursive.base:
|
|
259
|
+
forward = orientation is Orientation.FORWARD
|
|
260
|
+
end = recursive.source_columns if forward else recursive.target_columns
|
|
261
|
+
text = recursive.source_text if forward else recursive.target_text
|
|
262
|
+
condition = _all(
|
|
263
|
+
[
|
|
264
|
+
f"{_pinned(self._edge_column(edge, column), pinned)} = "
|
|
265
|
+
f"{self.expression(recursive.left[index], 0)}"
|
|
266
|
+
for index, (column, pinned) in enumerate(zip(end, text, strict=True))
|
|
267
|
+
]
|
|
268
|
+
)
|
|
269
|
+
conditions.append(condition)
|
|
270
|
+
if forward:
|
|
271
|
+
forwards.append(condition)
|
|
272
|
+
values = ["1", *self._state_columns(recursive, edge)]
|
|
273
|
+
if with_state:
|
|
274
|
+
values.append(_arrival(recursive.base, forwards))
|
|
275
|
+
values.append(f"ARRAY[{', '.join([key_row, *before])}]")
|
|
276
|
+
lines = [f"SELECT {', '.join(values)}", f"FROM {quote_ident(recursive.table)} AS {edge}"]
|
|
277
|
+
if anchor is not None:
|
|
278
|
+
lines.append(f"CROSS JOIN {anchor.anchor_cte} AS {anchor.alias}")
|
|
279
|
+
lines.append(f"WHERE {_any(conditions)}")
|
|
280
|
+
if before:
|
|
281
|
+
lines.append(f" AND NOT ({key_row} = ANY (ARRAY[{', '.join(before)}]))")
|
|
282
|
+
return lines
|
|
283
|
+
|
|
284
|
+
def _recursive_step(
|
|
285
|
+
self,
|
|
286
|
+
recursive: Recursive,
|
|
287
|
+
sources: tuple[str, ...],
|
|
288
|
+
targets: tuple[str, ...],
|
|
289
|
+
key_row: str,
|
|
290
|
+
plain: Orientation | None,
|
|
291
|
+
) -> list[str]:
|
|
292
|
+
"""The recursive term: leave the arrived node, never re-reading a trail row."""
|
|
293
|
+
cte = recursive.cte
|
|
294
|
+
edge = recursive.edge_alias
|
|
295
|
+
values = [f"{cte}.depth + 1", *self._state_columns(recursive, edge)]
|
|
296
|
+
if plain is None:
|
|
297
|
+
disjuncts: list[str] = []
|
|
298
|
+
forwards: list[str] = []
|
|
299
|
+
for at_target, orientation in recursive.steps:
|
|
300
|
+
current = targets if at_target else sources
|
|
301
|
+
forward = orientation is Orientation.FORWARD
|
|
302
|
+
end = recursive.source_columns if forward else recursive.target_columns
|
|
303
|
+
parts = [f"{cte}.at_target" if at_target else f"NOT {cte}.at_target"]
|
|
304
|
+
parts.extend(
|
|
305
|
+
self._state_join(recursive, cte, edge, end, current, forward, at_target)
|
|
306
|
+
)
|
|
307
|
+
disjunct = _all(parts)
|
|
308
|
+
disjuncts.append(disjunct)
|
|
309
|
+
if forward:
|
|
310
|
+
forwards.append(disjunct)
|
|
311
|
+
values.append(
|
|
312
|
+
_arrival(tuple(orientation for _, orientation in recursive.steps), forwards)
|
|
313
|
+
)
|
|
314
|
+
condition = _any(disjuncts)
|
|
315
|
+
else:
|
|
316
|
+
forward = plain is Orientation.FORWARD
|
|
317
|
+
current = targets if forward else sources
|
|
318
|
+
end = recursive.source_columns if forward else recursive.target_columns
|
|
319
|
+
condition = _all(self._state_join(recursive, cte, edge, end, current, forward, forward))
|
|
320
|
+
values.append(f"{cte}.trail || {key_row}")
|
|
321
|
+
return [
|
|
322
|
+
f"SELECT {', '.join(values)}",
|
|
323
|
+
f"FROM {cte}",
|
|
324
|
+
f"JOIN {quote_ident(recursive.table)} AS {edge} ON {condition}",
|
|
325
|
+
f"WHERE {cte}.depth < {recursive.depth_max}",
|
|
326
|
+
f" AND NOT ({key_row} = ANY ({cte}.trail))",
|
|
327
|
+
]
|
|
328
|
+
|
|
329
|
+
def _trail_row(self, columns: Iterable[str], text: tuple[bool, ...]) -> str:
|
|
330
|
+
"""One trail identity as `ROW(…)`, every declared-text key column pinned to code points.
|
|
331
|
+
|
|
332
|
+
The trail decides which edge rows a walk may still read, so two different rows must never
|
|
333
|
+
compare equal: a case-insensitive or nondeterministic collation could otherwise hide a
|
|
334
|
+
legitimate row from a multi-hop walk. Each key column whose declared type is text is
|
|
335
|
+
emitted `(<col> COLLATE "C")` — in the base seed, in the recursive step and in the
|
|
336
|
+
`NOT (… = ANY (trail))` comparison alike. A column with no declared text type keeps its
|
|
337
|
+
own collation and is written bare.
|
|
338
|
+
"""
|
|
339
|
+
return _row(
|
|
340
|
+
f"({column}{_PIN})" if pinned else column
|
|
341
|
+
for column, pinned in zip(columns, text, strict=True)
|
|
342
|
+
)
|
|
343
|
+
|
|
344
|
+
def _state_join(
|
|
345
|
+
self,
|
|
346
|
+
recursive: Recursive,
|
|
347
|
+
cte: str,
|
|
348
|
+
edge: str,
|
|
349
|
+
end: tuple[str, ...],
|
|
350
|
+
state: tuple[str, ...],
|
|
351
|
+
forward: bool,
|
|
352
|
+
at_target: bool,
|
|
353
|
+
) -> list[str]:
|
|
354
|
+
"""One hop's join: the new edge row's end is the state row's arrival identity.
|
|
355
|
+
|
|
356
|
+
Both sides of every text column are pinned to code points, so a nondeterministic column
|
|
357
|
+
collation cannot let a walk step between two different keys that compare equal.
|
|
358
|
+
"""
|
|
359
|
+
end_text = recursive.source_text if forward else recursive.target_text
|
|
360
|
+
state_text = recursive.target_text if at_target else recursive.source_text
|
|
361
|
+
return [
|
|
362
|
+
f"{_pinned(self._edge_column(edge, column), text)} = "
|
|
363
|
+
f"{_pinned(f'{cte}.{state[index]}', state_pinned)}"
|
|
364
|
+
for index, (column, text, state_pinned) in enumerate(
|
|
365
|
+
zip(end, end_text, state_text, strict=True)
|
|
366
|
+
)
|
|
367
|
+
]
|
|
368
|
+
|
|
369
|
+
def _recursive_end(
|
|
370
|
+
self,
|
|
371
|
+
recursive: Recursive,
|
|
372
|
+
sources: tuple[str, ...],
|
|
373
|
+
targets: tuple[str, ...],
|
|
374
|
+
plain: Orientation | None,
|
|
375
|
+
) -> str:
|
|
376
|
+
"""The walk reached the right pattern node at its last hop, in the right direction."""
|
|
377
|
+
cte = recursive.cte
|
|
378
|
+
right = [self.expression(column, 0) for column in recursive.right]
|
|
379
|
+
|
|
380
|
+
def arrival(state: tuple[str, ...], text: tuple[bool, ...]) -> list[str]:
|
|
381
|
+
return [
|
|
382
|
+
f"{_pinned(f'{cte}.{state[index]}', pinned)} = {right[index]}"
|
|
383
|
+
for index, pinned in enumerate(text)
|
|
384
|
+
]
|
|
385
|
+
|
|
386
|
+
if plain is not None:
|
|
387
|
+
forward = plain is Orientation.FORWARD
|
|
388
|
+
return _all(
|
|
389
|
+
arrival(
|
|
390
|
+
targets if forward else sources,
|
|
391
|
+
recursive.target_text if forward else recursive.source_text,
|
|
392
|
+
)
|
|
393
|
+
)
|
|
394
|
+
sides: list[str] = []
|
|
395
|
+
if recursive.right_is_target:
|
|
396
|
+
sides.append(_all([f"{cte}.at_target", *arrival(targets, recursive.target_text)]))
|
|
397
|
+
if recursive.right_is_source:
|
|
398
|
+
sides.append(_all([f"NOT {cte}.at_target", *arrival(sources, recursive.source_text)]))
|
|
399
|
+
return _any(sides)
|
|
400
|
+
|
|
401
|
+
def _edge_column(self, alias: str, column: str) -> str:
|
|
402
|
+
return f"{alias}.{quote_ident(column)}"
|
|
403
|
+
|
|
404
|
+
# ---------------------------------------------------------------- untyped walks
|
|
405
|
+
|
|
406
|
+
def untyped(self, walk: UntypedWalk, indent: int) -> str:
|
|
407
|
+
"""One correlated untyped `WITH RECURSIVE` walk: its first hops, then one per step."""
|
|
408
|
+
body = indent + 2
|
|
409
|
+
definition = self._untyped_definition(walk, body, materialized=False, anchor=None)
|
|
410
|
+
return self._exists_walk(definition, self._consumer(walk, body), indent)
|
|
411
|
+
|
|
412
|
+
def _untyped_definition(
|
|
413
|
+
self,
|
|
414
|
+
walk: UntypedWalk,
|
|
415
|
+
indent: int,
|
|
416
|
+
materialized: bool,
|
|
417
|
+
anchor: WalkSource | None,
|
|
418
|
+
) -> str:
|
|
419
|
+
"""The CTE of one untyped walk: every first hop, one branch per later hop.
|
|
420
|
+
|
|
421
|
+
The walk's state, its endpoint keys and a trail entry are all text values pinned to code
|
|
422
|
+
points — a state and an endpoint carry `ARRAY[label, key columns...]`, a trail entry its
|
|
423
|
+
`tag:key` identity, and each is `COLLATE "C"` — so every identity comparison runs by code
|
|
424
|
+
point whatever the columns' collations. PostgreSQL allows the recursive term to reference
|
|
425
|
+
the CTE from a lateral subquery in its `FROM`, so the step branches union inside one
|
|
426
|
+
lateral entry (see `_walk_step`) instead of at the top level of the recursive term.
|
|
427
|
+
"""
|
|
428
|
+
pad = " " * indent
|
|
429
|
+
inner = " " * (indent + 2)
|
|
430
|
+
chunks: list[list[str]] = []
|
|
431
|
+
if walk.include_zero:
|
|
432
|
+
chunks.append(self._untyped_zero(walk, anchor))
|
|
433
|
+
chunks.extend(self._walk_base(walk, hop, anchor) for hop in walk.base)
|
|
434
|
+
if walk.steps:
|
|
435
|
+
chunks.append(self._walk_step(walk))
|
|
436
|
+
block: list[str] = []
|
|
437
|
+
for chunk in chunks:
|
|
438
|
+
if block:
|
|
439
|
+
block.append("UNION ALL")
|
|
440
|
+
block.extend(chunk)
|
|
441
|
+
lines = [
|
|
442
|
+
f"{walk.cte} (current, depth, trail) AS {'MATERIALIZED ' if materialized else ''}("
|
|
443
|
+
]
|
|
444
|
+
lines.extend(f"{inner}{line}" for line in block)
|
|
445
|
+
lines.append(f"{pad})")
|
|
446
|
+
return "\n".join(lines)
|
|
447
|
+
|
|
448
|
+
def _untyped_zero(self, walk: UntypedWalk, anchor: WalkSource | None) -> list[str]:
|
|
449
|
+
"""The depth-0 state row: the left node's identity, no hop, an empty trail."""
|
|
450
|
+
if anchor is None:
|
|
451
|
+
raise AssertionError("internal error: a zero hop outside a hoisted walk")
|
|
452
|
+
return [
|
|
453
|
+
f"SELECT {self._node_key(walk.left_label, walk.left)}, 0, ARRAY[]::text[]",
|
|
454
|
+
f"FROM {anchor.anchor_cte} AS {anchor.alias}",
|
|
455
|
+
]
|
|
456
|
+
|
|
457
|
+
def _walk_base(self, walk: UntypedWalk, hop: WalkHop, anchor: WalkSource | None) -> list[str]:
|
|
458
|
+
"""The non-recursive term: one declared edge row leaving the left node, at depth one."""
|
|
459
|
+
alias = hop.alias
|
|
460
|
+
equality = " AND ".join(
|
|
461
|
+
f"{_pinned(self._edge_column(alias, column), pinned)} = {self.expression(left, 0)}"
|
|
462
|
+
for column, left, pinned in zip(hop.from_columns, walk.left, hop.from_text, strict=True)
|
|
463
|
+
)
|
|
464
|
+
values = [
|
|
465
|
+
self._hop_key(hop, hop.to_label, hop.to_columns),
|
|
466
|
+
"1",
|
|
467
|
+
self._trail_seed(walk, hop),
|
|
468
|
+
]
|
|
469
|
+
lines = ["SELECT " + ", ".join(values), f"FROM {quote_ident(hop.table)} AS {alias}"]
|
|
470
|
+
if anchor is not None:
|
|
471
|
+
lines.append(f"CROSS JOIN {anchor.anchor_cte} AS {anchor.alias}")
|
|
472
|
+
lines.append(f"WHERE {self._arrived(hop, equality)}")
|
|
473
|
+
seed = self._seed_array(walk)
|
|
474
|
+
if seed is not None:
|
|
475
|
+
lines.append(f" AND NOT ({self._trail(hop)} = ANY ({seed}))")
|
|
476
|
+
return lines
|
|
477
|
+
|
|
478
|
+
def _arrived(self, hop: WalkHop, equality: str | None = None) -> str:
|
|
479
|
+
"""The hop arrives at a real node; a row with a NULL key column names no node.
|
|
480
|
+
|
|
481
|
+
A NULL foreign key is the absence of a relationship, and the key columns of a real node
|
|
482
|
+
are never NULL, so no walk may stand on one. The leaving side needs no check: every state
|
|
483
|
+
was produced by this same rule, so its key columns are non-NULL. When the edge row lives
|
|
484
|
+
in the landing node's own table and the landing columns are that table's key columns, the
|
|
485
|
+
check is provably true, so it is not emitted. An empty string means no condition at all.
|
|
486
|
+
"""
|
|
487
|
+
conditions = [] if equality is None else [equality]
|
|
488
|
+
conditions.extend(
|
|
489
|
+
f"{self._edge_column(hop.alias, column)} IS NOT NULL"
|
|
490
|
+
for column in hop.to_columns
|
|
491
|
+
if not (hop.table == hop.landing_table and column in hop.landing_key)
|
|
492
|
+
)
|
|
493
|
+
return _all(conditions) if conditions else ""
|
|
494
|
+
|
|
495
|
+
def _walk_step(self, walk: UntypedWalk) -> list[str]:
|
|
496
|
+
"""The recursive term: leave the current node, never reading a row the trail holds.
|
|
497
|
+
|
|
498
|
+
One lateral entry holds a branch per hop, and the frontier row drives each branch: the
|
|
499
|
+
branch compares its edge table's own key columns with the frontier's key components (see
|
|
500
|
+
`_frontier_join`) instead of matching a rendered cursor, so the recursion reads an index
|
|
501
|
+
from the small frontier rather than scanning and sorting every edge row. The label guard
|
|
502
|
+
comes first in each branch and is pinned to code points by construction, so a branch whose
|
|
503
|
+
leaving label is not the current node's is skipped before its table is touched whatever
|
|
504
|
+
the database's collation is. Every branch reads the one frontier row the lateral is
|
|
505
|
+
correlated with, so the recursive term still holds a single reference to the walk's own
|
|
506
|
+
states and stays one `WITH RECURSIVE` entry.
|
|
507
|
+
"""
|
|
508
|
+
cte = walk.cte
|
|
509
|
+
step = walk.step
|
|
510
|
+
frontier = f"{cte}.current"
|
|
511
|
+
branches: list[str] = []
|
|
512
|
+
for hop in walk.steps:
|
|
513
|
+
if branches:
|
|
514
|
+
branches.append(" UNION ALL")
|
|
515
|
+
branches.append(
|
|
516
|
+
f" SELECT {self._hop_key(hop, hop.to_label, hop.to_columns)} AS next_key, "
|
|
517
|
+
f"{self._trail(hop)} AS identity"
|
|
518
|
+
)
|
|
519
|
+
branches.append(f" FROM {quote_ident(hop.table)} AS {hop.alias}")
|
|
520
|
+
conditions = [
|
|
521
|
+
f"{_pinned(f'({frontier}::text[])[1]', True)} = {_text_literal(hop.from_label)}",
|
|
522
|
+
*self._frontier_join(hop, frontier),
|
|
523
|
+
]
|
|
524
|
+
arrived = self._arrived(hop)
|
|
525
|
+
if arrived:
|
|
526
|
+
conditions.append(arrived)
|
|
527
|
+
branches.append(f" WHERE {conditions[0]}")
|
|
528
|
+
branches.extend(f" AND {condition}" for condition in conditions[1:])
|
|
529
|
+
return [
|
|
530
|
+
f"SELECT {step}.next_key, {cte}.depth + 1, {cte}.trail || {step}.identity",
|
|
531
|
+
f"FROM {cte}",
|
|
532
|
+
"CROSS JOIN LATERAL (",
|
|
533
|
+
*branches,
|
|
534
|
+
f") AS {step}",
|
|
535
|
+
f"WHERE {cte}.depth < {walk.depth_max}",
|
|
536
|
+
f" AND NOT ({step}.identity = ANY ({cte}.trail))",
|
|
537
|
+
]
|
|
538
|
+
|
|
539
|
+
def _frontier_join(self, hop: WalkHop, frontier: str) -> list[str]:
|
|
540
|
+
"""One hop's key join: the edge row's leaving end is the frontier node's key.
|
|
541
|
+
|
|
542
|
+
The frontier carries one text component per key column, after its label: `[label, k1, …]`.
|
|
543
|
+
A typed branch compares the edge column with the frontier component cast to the type that
|
|
544
|
+
produced it — the cast is on the frontier value, so an index on the edge table's own key
|
|
545
|
+
columns can serve the recursive term. A branch whose producer cannot prove such a type
|
|
546
|
+
compares as pinned text instead, which must cast the edge column to text and knowingly
|
|
547
|
+
gives that index up (see `_frontier_key`): correctness before speed.
|
|
548
|
+
"""
|
|
549
|
+
return [
|
|
550
|
+
self._frontier_key(hop, column, text, kind, index + 2, frontier)
|
|
551
|
+
for index, (column, text, kind) in enumerate(
|
|
552
|
+
zip(hop.from_columns, hop.from_text, hop.from_types, strict=True)
|
|
553
|
+
)
|
|
554
|
+
]
|
|
555
|
+
|
|
556
|
+
def _frontier_key(
|
|
557
|
+
self,
|
|
558
|
+
hop: WalkHop,
|
|
559
|
+
column: str,
|
|
560
|
+
text: bool,
|
|
561
|
+
kind: PgType | None,
|
|
562
|
+
position: int,
|
|
563
|
+
frontier: str,
|
|
564
|
+
) -> str:
|
|
565
|
+
"""One frontier component against one edge column: typed when the cast is exact.
|
|
566
|
+
|
|
567
|
+
The component is the frontier's text rendering of a node key. A typed branch casts the
|
|
568
|
+
*frontier* value and leaves the edge column bare. Otherwise the comparison is pinned code
|
|
569
|
+
points: a text column keeps its own type, and a column the plan could not reconcile with
|
|
570
|
+
the type that produced the component (`kind` is `None`, see `_frontier_type`) must be cast
|
|
571
|
+
to text instead, which matches what the rendered cursor compared before.
|
|
572
|
+
"""
|
|
573
|
+
edge = self._edge_column(hop.alias, column)
|
|
574
|
+
if kind is not None and not text:
|
|
575
|
+
return f"{edge} = ({frontier}::text[])[{position}]::{kind.value}"
|
|
576
|
+
component = _pinned(f"({frontier}::text[])[{position}]", True)
|
|
577
|
+
if text:
|
|
578
|
+
return f"{_pinned(edge, True)} = {component}"
|
|
579
|
+
return f"(({edge})::text{_PIN}) = {component}"
|
|
580
|
+
|
|
581
|
+
def _hop_key(self, hop: WalkHop, label: str, columns: tuple[str, ...]) -> str:
|
|
582
|
+
"""One end of a hop as a comparable code-point text value: its label and key columns."""
|
|
583
|
+
fields = [_text_literal(label)]
|
|
584
|
+
fields.extend(f"{self._edge_column(hop.alias, column)}::text" for column in columns)
|
|
585
|
+
return _code_point(_array_text(fields))
|
|
586
|
+
|
|
587
|
+
def _node_key(self, label: str, columns: tuple[SqlExpr, ...]) -> str:
|
|
588
|
+
"""A pattern node's identity as the same pinned text value a walk's state carries."""
|
|
589
|
+
return _code_point(
|
|
590
|
+
_array_text(
|
|
591
|
+
[_text_literal(label), *(f"({self.expression(c, 0)})::text" for c in columns)]
|
|
592
|
+
)
|
|
593
|
+
)
|
|
594
|
+
|
|
595
|
+
def _trail(self, hop: WalkHop) -> str:
|
|
596
|
+
"""One edge row's identity in the trail: the declared edge's tag and the row's key."""
|
|
597
|
+
fields = [f"{self._edge_column(hop.alias, column)}::text" for column in hop.key]
|
|
598
|
+
return _code_point(f"{_text_literal(f'{hop.tag}:')} || {_array_text(fields)}")
|
|
599
|
+
|
|
600
|
+
def _trail_seed(self, walk: UntypedWalk, hop: WalkHop) -> str:
|
|
601
|
+
"""The trail column's initial value: this row's identity plus every seeded row's.
|
|
602
|
+
|
|
603
|
+
Mirroring the typed walk, the first hop starts with the rows the path's declared
|
|
604
|
+
relationships already read, so a later hop can never read one of them again.
|
|
605
|
+
"""
|
|
606
|
+
entries = [self._trail(hop), *self._seed_entries(walk)]
|
|
607
|
+
return "ARRAY[" + ", ".join(entries) + "]"
|
|
608
|
+
|
|
609
|
+
def _seed_array(self, walk: UntypedWalk) -> str | None:
|
|
610
|
+
"""The rows the path's declared relationships already read, as a trail array."""
|
|
611
|
+
entries = self._seed_entries(walk)
|
|
612
|
+
return "ARRAY[" + ", ".join(entries) + "]" if entries else None
|
|
613
|
+
|
|
614
|
+
def _seed_entries(self, walk: UntypedWalk) -> list[str]:
|
|
615
|
+
"""One pinned trail entry per row a declared relationship of this path actually binds."""
|
|
616
|
+
return [
|
|
617
|
+
_code_point(
|
|
618
|
+
f"{_text_literal(f'{tag}:')} || "
|
|
619
|
+
f"{_array_text([f'{self.column(c)}::text' for c in row])}"
|
|
620
|
+
)
|
|
621
|
+
for tag, row in walk.seed
|
|
622
|
+
]
|