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.
@@ -0,0 +1,803 @@
1
+ """The plan's rows: aliases, elements, uniqueness and the projections the query asks for.
2
+
3
+ Every alias comes from a pattern position, never from query text: `n<i>` is the i-th node, `r<i>`
4
+ the i-th edge that needs a row of its own. An edge stored in an end's own table is that row, so it
5
+ reuses the end's alias — except when the row depends on the orientation and uniqueness must name
6
+ it. Uniqueness compares two rows, so it is decided where both aliases are in scope.
7
+
8
+ This module starts the planner: `_planner._Planner` subclasses this class, so the outer `SELECT`
9
+ and every expression it renders see the same alias table and row scopes without re-deriving
10
+ either."""
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections.abc import Iterable, Mapping
15
+
16
+ from cypher2sql._ir import (
17
+ BExpr,
18
+ BHop,
19
+ BInferred,
20
+ BNodeRef,
21
+ Bound,
22
+ BOwner,
23
+ BRel,
24
+ BRelRef,
25
+ BScope,
26
+ BTrail,
27
+ BUntypedRecursive,
28
+ Carrier,
29
+ ConstValue,
30
+ Orientation,
31
+ PgType,
32
+ declared_pg_type,
33
+ edge_side_text,
34
+ text_key,
35
+ )
36
+ from cypher2sql._schema import EdgeType, NodeType
37
+
38
+ from ._nodes import (
39
+ _MAX_IDENT,
40
+ And,
41
+ Bool,
42
+ ColRef,
43
+ Conjunct,
44
+ Eq,
45
+ Exists,
46
+ Group,
47
+ Or,
48
+ OrderColumn,
49
+ Projection,
50
+ Recursive,
51
+ SqlExpr,
52
+ TupleNe,
53
+ WalkHop,
54
+ WalkSource,
55
+ _carried_type,
56
+ _frontier_type,
57
+ _hop_landing,
58
+ _hop_leaving,
59
+ _keyed,
60
+ )
61
+ from ._scopes import (
62
+ _absent_groups,
63
+ _collect_bodies,
64
+ _conjuncts,
65
+ _element_set,
66
+ _optional_references,
67
+ _referenced,
68
+ _scope_elements,
69
+ )
70
+ from ._uniqueness import (
71
+ _detached_rows,
72
+ _identity_pairs,
73
+ _orientations,
74
+ )
75
+ from ._working import (
76
+ _Element,
77
+ _Expansion,
78
+ _Link,
79
+ _Unit,
80
+ _WalkPlan,
81
+ )
82
+
83
+
84
+ class _PlanRows:
85
+ """Aliases, elements, uniqueness and the outer select-list; one plan of one query."""
86
+
87
+ def __init__(self, bound: Bound) -> None:
88
+ self._bound = bound
89
+ self._target = bound.target.id
90
+ self._nodes = {node.id: node for node in bound.nodes}
91
+ self._rels = {rel.id: rel for rel in bound.rels}
92
+ self._register(bound.inferred)
93
+ self._scope_of = {
94
+ element: scope.index for scope in bound.scopes for element in _scope_elements(scope)
95
+ }
96
+ self._scopes = self._live_scopes()
97
+ for scope in self._scopes:
98
+ for node in scope.nodes:
99
+ self._nodes[node.id] = node
100
+ for rel in scope.rels:
101
+ self._rels[rel.id] = rel
102
+ self._register(scope.inferred)
103
+ # Relationship uniqueness holds within one `MATCH` clause, across its paths.
104
+ self._rel_clause = {
105
+ rel.id: trail.clause
106
+ for trails in (bound.trails, *(scope.trails for scope in self._scopes))
107
+ for trail in trails
108
+ for rel in trail.rels
109
+ }
110
+ # Subquery bodies are their own pattern elements: register them before any alias is
111
+ # named, so their nodes and rows get their own `n<i>`/`r<i>` exactly like the pattern's.
112
+ self._bodies = _collect_bodies(
113
+ (
114
+ (*bound.properties, bound.where),
115
+ *((*scope.properties, scope.where) for scope in self._scopes),
116
+ )
117
+ )
118
+ for body in self._bodies:
119
+ for node in body.nodes:
120
+ self._nodes[node.id] = node
121
+ for rel in body.rels:
122
+ self._rels[rel.id] = rel
123
+ self._register(body.inferred)
124
+ self._rel_clause.update(
125
+ {rel.id: trail.clause for trail in body.trails for rel in trail.rels}
126
+ )
127
+ self._detached = _detached_rows(
128
+ [(bound.rels, bound.trails, bound.inferred, bound.recursive)]
129
+ + [
130
+ (scope.rels, scope.trails, scope.inferred, scope.recursive)
131
+ for scope in self._scopes
132
+ ]
133
+ + [(body.rels, body.trails, body.inferred, body.recursive) for body in self._bodies]
134
+ )
135
+ # A body's walks continue the query's numbering, so no `reach<i>` names two walks.
136
+ base = len(bound.recursive) + sum(len(scope.recursive) for scope in self._scopes)
137
+ self._body_base: dict[int, int] = {}
138
+ for body in self._bodies:
139
+ self._body_base[body.number] = base
140
+ base += len(body.recursive)
141
+ # The aliases visible where the expression being rendered sits: the outer `WHERE` sees the
142
+ # target (and, after the laterals are planned, every scope's alias), a group body sees its
143
+ # own rows and whatever encloses it.
144
+ self.visible: frozenset[str] = frozenset({self.target_alias()})
145
+ self._rel_alias: dict[int, str] = {}
146
+ index = 0
147
+ for rel in self._rels.values():
148
+ if self.own_row(rel):
149
+ index += 1
150
+ self._rel_alias[rel.id] = f"r{index}"
151
+ # The lateral plan: every element belongs to one row scope (`_unit_owner`), which is a
152
+ # `LEFT JOIN LATERAL` exposing the columns a later scope or the outer `WHERE` names.
153
+ self._unit_owner: dict[_Element, int] = {}
154
+ self._unit_alias: list[str] = []
155
+ self._projected: list[dict[tuple[_Element, str], str]] = []
156
+ self._scope_alias: dict[int, str] = {}
157
+ self._scope: int | None = None
158
+ self._units: list[_Unit] = []
159
+ # The statement's hoisted walks: recursive CTEs outside every row scope, so each is
160
+ # evaluated once per query instead of once per candidate target row.
161
+ self.walk_sources: list[WalkSource] = []
162
+ if self._scopes:
163
+ self._units = self._unit_list()
164
+ self._scope_alias = {
165
+ unit.scope: unit.alias for unit in self._units if unit.scope is not None
166
+ }
167
+
168
+ def _register(self, inferred: tuple[BInferred, ...]) -> None:
169
+ """Make every hop of every alternative path findable by its node or relationship id."""
170
+ for relation in inferred:
171
+ for path in relation.alternatives:
172
+ for node in path.nodes:
173
+ self._nodes[node.id] = node
174
+ for rel in path.rels:
175
+ self._rels[rel.id] = rel
176
+
177
+ def _live_scopes(self) -> tuple[BScope, ...]:
178
+ """The scopes whose result is observable; the rest are pruned before planning.
179
+
180
+ A required scope always is: it filters rows. An optional one is when an outer predicate
181
+ reads one of its elements or its presence, or when a live scope's pattern or predicate
182
+ does. An optional scope nothing reads can neither filter nor project, so planning it would
183
+ only add a lateral join and a `DISTINCT`.
184
+ """
185
+ scope_of = self._scope_of
186
+
187
+ def named(expressions: Iterable[BExpr]) -> set[int]:
188
+ scopes: set[int] = set()
189
+ for expr in expressions:
190
+ scopes |= _optional_references(expr)
191
+ scopes |= {
192
+ scope_of[element]
193
+ for owner in _referenced(expr)
194
+ if (element := self._element(owner)) in scope_of
195
+ }
196
+ return scopes
197
+
198
+ def pattern(scope: BScope) -> set[int]:
199
+ """The scopes one scope's pattern hangs off, its own excluded."""
200
+ elements: set[_Element] = set()
201
+ for rel in scope.rels:
202
+ elements |= {("node", rel.left), ("node", rel.right)}
203
+ for inferred in scope.inferred:
204
+ elements |= {("node", inferred.left), ("node", inferred.right)}
205
+ for walk in scope.recursive:
206
+ elements |= {("node", walk.left), ("node", walk.right)}
207
+ return {scope_of[element] for element in elements if element in scope_of} - {
208
+ scope.index
209
+ }
210
+
211
+ live = named((*self._bound.properties, *_conjuncts(self._bound.where)))
212
+ live |= {scope.index for scope in self._bound.scopes if not scope.optional}
213
+ changed = True
214
+ while changed:
215
+ changed = False
216
+ for scope in self._bound.scopes:
217
+ if scope.index not in live:
218
+ continue
219
+ found = named((*scope.properties, *_conjuncts(scope.where))) | pattern(scope)
220
+ if not found <= live:
221
+ live |= found
222
+ changed = True
223
+ return tuple(scope for scope in self._bound.scopes if scope.index in live)
224
+
225
+ def _distinct(self) -> bool:
226
+ """Whether a surviving unit can turn one target row into several.
227
+
228
+ A required unit is a lateral join that may match many rows per target, so it always can;
229
+ an optional scope can too unless the outer `WHERE` pins it to its null row (`o IS NULL`),
230
+ which contributes at most that one row. Keys are a set, so `DISTINCT` whenever a unit
231
+ might multiply rows is always correct, only slower.
232
+ """
233
+ if any(unit.required for unit in self._units):
234
+ return True
235
+ absent = _absent_groups(self._bound.where)
236
+ return any(scope.index not in absent for scope in self._scopes)
237
+
238
+ def _element(self, owner: BOwner) -> _Element:
239
+ match owner:
240
+ case BNodeRef(id=node_id):
241
+ return ("node", node_id)
242
+ case BRelRef(id=rel_id):
243
+ return ("rel", rel_id)
244
+
245
+ def own_row(self, rel: BRel) -> bool:
246
+ """Whether `rel` is planned as a row of its own, under an `r<i>` alias."""
247
+ return rel.carrier is Carrier.OWN or rel.id in self._detached
248
+
249
+ def _parts(self, rel: BRel) -> list[_Element]:
250
+ """The group elements `rel` needs: its non-target ends and its own row, if any."""
251
+ parts: list[_Element] = [
252
+ ("node", end) for end in dict.fromkeys((rel.left, rel.right)) if end != self._target
253
+ ]
254
+ if self.own_row(rel):
255
+ parts.append(("rel", rel.id))
256
+ return parts
257
+
258
+ def _row_element(self, rel: BRel, orientation: Orientation) -> _Element:
259
+ """The row that carries one orientation of `rel`: its own row, or one end's."""
260
+ if self.own_row(rel):
261
+ return ("rel", rel.id)
262
+ if rel.carrier is Carrier.SOURCE:
263
+ return ("node", rel.left if orientation is Orientation.FORWARD else rel.right)
264
+ return ("node", rel.right if orientation is Orientation.FORWARD else rel.left)
265
+
266
+ def element_alias(self, element: tuple[str, int]) -> str:
267
+ kind, identifier = element
268
+ return self.alias(identifier) if kind == "node" else self._rel_alias[identifier]
269
+
270
+ def element_table(self, element: tuple[str, int]) -> tuple[str, str]:
271
+ kind, identifier = element
272
+ if kind == "node":
273
+ return self._nodes[identifier].node_type.table, self.alias(identifier)
274
+ return self._rels[identifier].edge_type.table, self._rel_alias[identifier]
275
+
276
+ def target_alias(self) -> str:
277
+ return self.alias(self._target)
278
+
279
+ def alias(self, node_id: int) -> str:
280
+ """The deterministic alias of the node at this pattern position: `n1`, `n2`, ..."""
281
+ return f"n{node_id + 1}"
282
+
283
+ def _clause_pairs(self, rels: Iterable[BRel]) -> list[tuple[BRel, BRel]]:
284
+ """Declared occurrences of one edge in one `MATCH` clause; other clauses may share rows."""
285
+ return [
286
+ (first, second)
287
+ for first, second in _identity_pairs(rel for rel in rels if rel.declared)
288
+ if self._rel_clause.get(first.id) == self._rel_clause.get(second.id)
289
+ ]
290
+
291
+ def _component_trails(self, members: list[int], rels: list[BRel]) -> list[BTrail]:
292
+ """The trails that meet in one group: a declared rel or an expansion endpoint is in it."""
293
+ rel_ids = {rel.id for rel in rels}
294
+ member_ids = set(members)
295
+ return [
296
+ trail
297
+ for trail in self._bound.trails
298
+ if any(rel.id in rel_ids for rel in trail.rels)
299
+ or any(
300
+ end in member_ids
301
+ for index in trail.expansions
302
+ for end in (
303
+ self._bound.inferred[index].left,
304
+ self._bound.inferred[index].right,
305
+ )
306
+ )
307
+ or any(
308
+ end in member_ids
309
+ for index in trail.recursions
310
+ for end in (
311
+ self._bound.recursive[index].left,
312
+ self._bound.recursive[index].right,
313
+ )
314
+ )
315
+ ]
316
+
317
+ def _group_expressions(
318
+ self, expressions: tuple[BExpr, ...], elements: set[_Element]
319
+ ) -> list[BExpr]:
320
+ """Expressions that only this group's aliases decide, in their written order."""
321
+ return [
322
+ expr
323
+ for expr in expressions
324
+ if (named := self.elements(_referenced(expr))) and named <= elements
325
+ ]
326
+
327
+ def _uniqueness_pairs(self) -> list[tuple[BRel, BRel]]:
328
+ """Pairs of declared occurrences that stand for the same edge: none may share a row."""
329
+ return self._clause_pairs(self._bound.rels)
330
+
331
+ def _keys(self, rel: BRel) -> tuple[SqlExpr, ...]:
332
+ """The columns identifying the row one occurrence binds.
333
+
334
+ A text column is a `Collate` operand, so row uniqueness compares code points even when
335
+ the column's collation is nondeterministic (where two distinct keys could otherwise
336
+ compare equal and make a legal query drop rows).
337
+ """
338
+ edge = rel.edge_type
339
+ if rel.carrier is Carrier.OWN:
340
+ element: _Element = ("rel", rel.id)
341
+ return tuple(self._key_ref(element, edge, column) for column in edge.key)
342
+ node_type = edge.target if rel.carrier is Carrier.TARGET else edge.source
343
+ if rel.id in self._detached:
344
+ element = ("rel", rel.id)
345
+ else:
346
+ # One orientation, or both ends are one node: the row alias cannot vary.
347
+ element = self._row_element(rel, _orientations(rel)[0])
348
+ return tuple(self._key_ref(element, node_type, column) for column in node_type.key)
349
+
350
+ def _key_ref(self, element: _Element, owner: NodeType | EdgeType, column: str) -> SqlExpr:
351
+ """One key column, collated when its declared type is text."""
352
+ return _keyed(self._ref(element, column), text_key(owner, column))
353
+
354
+ def _node_keys(self, node_id: int) -> tuple[SqlExpr, ...]:
355
+ """The key columns of the pattern node at this position, as this scope reads them.
356
+
357
+ A text key column is a `Collate` operand, exactly like a trail key, so a walk's endpoint
358
+ identity and its hop joins compare code points even when the column's collation is
359
+ nondeterministic.
360
+ """
361
+ node_type = self._nodes[node_id].node_type
362
+ return tuple(
363
+ _keyed(self._ref(("node", node_id), column), text_key(node_type, column))
364
+ for column in node_type.key
365
+ )
366
+
367
+ def _order(self) -> tuple[OrderColumn, ...]:
368
+ """The target's key columns in key order, all ascending or all descending.
369
+
370
+ The order is the key's, not the pattern's or the query's: `ORDER BY o` sorts by every key
371
+ column in key order, which is also what makes a composite key's result deterministic. A
372
+ text key reuses the `Collate` node a string comparison emits.
373
+ """
374
+ order = self._bound.order
375
+ if order is None:
376
+ return ()
377
+ columns: list[OrderColumn] = []
378
+ for key in order.keys:
379
+ operand = _keyed(self._ref(("node", self._target), key.column), key.text)
380
+ columns.append(OrderColumn(operand, order.descending))
381
+ return tuple(columns)
382
+
383
+ def _projections(self, order: tuple[OrderColumn, ...]) -> tuple[Projection, ...]:
384
+ """The target's key columns, as the order operands when `DISTINCT` needs them there.
385
+
386
+ PostgreSQL requires every `SELECT DISTINCT` order expression to appear in the select
387
+ list, and a collated operand is a different expression from the bare column. Projecting
388
+ the very operand the `ORDER BY` uses makes the two identical; with no `DISTINCT`, the
389
+ select list stays the bare key columns.
390
+ """
391
+ keys = self._bound.target.node_type.key
392
+ if order:
393
+ return tuple(
394
+ Projection(column, item.operand) for item, column in zip(order, keys, strict=True)
395
+ )
396
+ return tuple(
397
+ Projection(column, self._ref(("node", self._target), column)) for column in keys
398
+ )
399
+
400
+ def links(self, rel: BRel, orientation: Orientation) -> tuple[_Link, ...]:
401
+ """The equalities that make `rel` hold in one orientation, row side first.
402
+
403
+ Each side of a link says whether it is text: the edge row's column when the edge declares
404
+ it as a text property or carries a foreign key to a text node key, and the pattern node's
405
+ key column when it is declared text. A text side is pinned to code points, so neither the
406
+ column's collation nor a nondeterministic one can make two different keys look equal.
407
+ """
408
+ edge = rel.edge_type
409
+ row = self._row_element(rel, orientation)
410
+ if orientation is Orientation.FORWARD:
411
+ source, target = rel.left, rel.right
412
+ else:
413
+ source, target = rel.right, rel.left
414
+ # A row of its own links both ends; an end's row is that end, so only the other links.
415
+ carrier = Carrier.OWN if self.own_row(rel) else rel.carrier
416
+ links: list[_Link] = []
417
+ if carrier is not Carrier.SOURCE:
418
+ for column, key in zip(edge.source_columns, edge.source.key, strict=True):
419
+ links.append(
420
+ _Link(
421
+ rel.id,
422
+ orientation,
423
+ len(links),
424
+ self._ref(row, column),
425
+ self._ref(("node", source), key),
426
+ row_text=edge_side_text(edge, column, edge.source, key),
427
+ key_text=text_key(edge.source, key),
428
+ )
429
+ )
430
+ if carrier is not Carrier.TARGET:
431
+ for column, key in zip(edge.target_columns, edge.target.key, strict=True):
432
+ links.append(
433
+ _Link(
434
+ rel.id,
435
+ orientation,
436
+ len(links),
437
+ self._ref(row, column),
438
+ self._ref(("node", target), key),
439
+ row_text=edge_side_text(edge, column, edge.target, key),
440
+ key_text=text_key(edge.target, key),
441
+ )
442
+ )
443
+ return tuple(links)
444
+
445
+ def same_row(self, left: int, right: int) -> SqlExpr | None:
446
+ """`left` and `right` are the same node row; `None` when that is already true.
447
+
448
+ A text key column is collated on both sides, so a nondeterministic column collation
449
+ cannot make two different keys look equal and turn a legal zero-hop pattern into an
450
+ unsatisfiable one.
451
+ """
452
+ if left == right:
453
+ return None
454
+ node_type = self._nodes[left].node_type
455
+ pairs = tuple(
456
+ Eq(
457
+ self._key_ref(("node", left), node_type, column),
458
+ self._key_ref(("node", right), node_type, column),
459
+ )
460
+ for column in node_type.key
461
+ )
462
+ return pairs[0] if len(pairs) == 1 else And(pairs)
463
+
464
+ def _columns(self, position: int) -> tuple[Projection, ...]:
465
+ """What one lateral group exposes: its presence, then every column named outside it."""
466
+ columns = [Projection("found", Bool(ConstValue.TRUE))]
467
+ columns.extend(
468
+ Projection(name, ColRef(self.element_alias(element), column))
469
+ for (element, column), name in self._projected[position].items()
470
+ )
471
+ return tuple(columns)
472
+
473
+ def _components(self) -> list[tuple[list[int], list[BRel]]]:
474
+ """Elements linked other than through the target: each group's nodes and edges.
475
+
476
+ Both occurrences of a uniqueness pair join one group, so the comparison sees both rows,
477
+ and a `WHERE` conjunct naming two elements joins their groups for the same reason; an
478
+ edge with no element of its own (it is the target's row) stays in the outer `WHERE`.
479
+ """
480
+ parent: dict[_Element, _Element] = {
481
+ ("node", node.id): ("node", node.id)
482
+ for node in self._bound.nodes
483
+ if node.id != self._target
484
+ }
485
+ for rel in self._bound.rels:
486
+ if self.own_row(rel):
487
+ parent[("rel", rel.id)] = ("rel", rel.id)
488
+
489
+ def find(element: _Element) -> _Element:
490
+ while parent[element] != element:
491
+ parent[element] = parent[parent[element]]
492
+ element = parent[element]
493
+ return element
494
+
495
+ def union(elements: list[_Element]) -> None:
496
+ for element in elements[1:]:
497
+ first, second = find(elements[0]), find(element)
498
+ if first != second:
499
+ parent[max(first, second)] = min(first, second)
500
+
501
+ def union_known(elements: set[_Element]) -> None:
502
+ known = sorted(element for element in elements if element in parent)
503
+ if len(known) > 1:
504
+ union(known)
505
+
506
+ for rel in self._bound.rels:
507
+ union_known(set(self._parts(rel)))
508
+ for trail in self._bound.trails:
509
+ # One path's declared rows and both endpoints of its expansions/walks share a group:
510
+ # uniqueness compares the declared row with the walk's hops, and a walk seeds itself
511
+ # from those rows, so naming any of them from another group would be out of scope.
512
+ elements = [part for rel in trail.rels for part in self._parts(rel)]
513
+ for index in trail.expansions:
514
+ inferred = self._bound.inferred[index]
515
+ elements.extend(
516
+ ("node", end) for end in (inferred.left, inferred.right) if end != self._target
517
+ )
518
+ for index in trail.recursions:
519
+ recursive = self._bound.recursive[index]
520
+ elements.extend(
521
+ ("node", end)
522
+ for end in (recursive.left, recursive.right)
523
+ if end != self._target
524
+ )
525
+ union_known(set(elements))
526
+ for first, second in self._uniqueness_pairs():
527
+ union_known({*self._parts(first), *self._parts(second)})
528
+ for expr in _conjuncts(self._bound.where):
529
+ union_known(self.elements(_referenced(expr)))
530
+ groups: dict[_Element, list[_Element]] = {}
531
+ for element in sorted(parent):
532
+ groups.setdefault(find(element), []).append(element)
533
+ components: list[tuple[list[int], list[BRel]]] = []
534
+ for _, elements in sorted(groups.items()):
535
+ members = [identifier for kind, identifier in elements if kind == "node"]
536
+ rels = [
537
+ rel
538
+ for rel in self._bound.rels
539
+ if any(part in elements for part in self._parts(rel))
540
+ ]
541
+ components.append((members, rels))
542
+ return components
543
+
544
+ def _project(self, owner: int, element: _Element, column: str) -> str:
545
+ """The name one lateral group gives a column, recorded the first time a scope names it.
546
+
547
+ `<alias>:<column>` reads well and cannot repeat: aliases are `n<i>`/`r<i>`, so the first
548
+ `:` ends the alias. A name over PostgreSQL's 63-byte limit would be truncated, maybe into
549
+ another one, so it becomes `<alias>#<k>` instead, which has no `:` at all and so can never
550
+ equal a column's name (whatever that column is called); `k` grows with every name the
551
+ group exposes, so two shortened names never meet either.
552
+ """
553
+ known = self._projected[owner]
554
+ name = known.get((element, column))
555
+ if name is None:
556
+ alias = self.element_alias(element)
557
+ name = f"{alias}:{column}"
558
+ if len(name.encode("utf-8")) > _MAX_IDENT:
559
+ name = f"{alias}#{len(known) + 1}"
560
+ known[(element, column)] = name
561
+ return name
562
+
563
+ def _trail_is_outer(self, trail: BTrail) -> bool:
564
+ """Whether every occurrence in this trail is the target's own row (so no group holds it)."""
565
+ if any(self._parts(rel) for rel in trail.rels):
566
+ return False
567
+ if not all(
568
+ inferred.left == self._target and inferred.right == self._target
569
+ for inferred in (self._bound.inferred[index] for index in trail.expansions)
570
+ ):
571
+ return False
572
+ return all(
573
+ recursive.left == self._target and recursive.right == self._target
574
+ for recursive in (self._bound.recursive[index] for index in trail.recursions)
575
+ )
576
+
577
+ def visible_alias(self, element: _Element) -> str:
578
+ """The alias the current scope reads one element's columns through, projecting nothing."""
579
+ owner = self._unit_owner.get(element)
580
+ if owner is None or owner == self._scope:
581
+ return self.element_alias(element)
582
+ return self._unit_alias[owner]
583
+
584
+ def _ref(self, element: _Element, column: str) -> ColRef:
585
+ """A column of one element, as the current scope can read it.
586
+
587
+ Inside the element's own scope it is the table's alias; from another scope it is the
588
+ lateral group's projected column, which is NULL when that group matched nothing.
589
+ """
590
+ owner = self._unit_owner.get(element)
591
+ if owner is None or owner == self._scope:
592
+ return ColRef(self.element_alias(element), column)
593
+ return ColRef(self._unit_alias[owner], self._project(owner, element, column))
594
+
595
+ def _unit_list(self) -> list[_Unit]:
596
+ """Every row scope, in the order a later one may name the columns an earlier one exposes.
597
+
598
+ The pattern's components come first: they name only the target and themselves. Then each
599
+ live `BScope`, in clause order: a clause can only name what earlier clauses declared, so
600
+ that order already puts every scope after the ones it reads, and `o<i>` follows it.
601
+ """
602
+ units: list[_Unit] = []
603
+ for members, rels in self._components():
604
+ trails = self._component_trails(members, rels)
605
+ units.append(
606
+ _Unit(
607
+ "",
608
+ None,
609
+ True,
610
+ members,
611
+ rels,
612
+ [
613
+ _Expansion(self._bound.inferred[index], trail)
614
+ for trail in trails
615
+ for index in trail.expansions
616
+ ],
617
+ [
618
+ _WalkPlan(index, self._bound.recursive[index], trail)
619
+ for trail in trails
620
+ for index in trail.recursions
621
+ ],
622
+ trails,
623
+ (),
624
+ (),
625
+ )
626
+ )
627
+ number = len(self._bound.recursive)
628
+ for scope in self._scopes:
629
+ units.append(
630
+ _Unit(
631
+ "",
632
+ scope.index,
633
+ not scope.optional,
634
+ [node.id for node in scope.nodes if node.id != self._target],
635
+ list(scope.rels),
636
+ [
637
+ _Expansion(scope.inferred[index], trail)
638
+ for trail in scope.trails
639
+ for index in trail.expansions
640
+ ],
641
+ [
642
+ _WalkPlan(number + index, scope.recursive[index], trail)
643
+ for trail in scope.trails
644
+ for index in trail.recursions
645
+ ],
646
+ list(scope.trails),
647
+ scope.properties,
648
+ tuple(_conjuncts(scope.where)),
649
+ )
650
+ )
651
+ number += len(scope.recursive)
652
+ self._unit_alias = [f"o{position + 1}" for position in range(len(units))]
653
+ self._projected = [{} for _ in units]
654
+ for position, unit in enumerate(units):
655
+ unit.alias = self._unit_alias[position]
656
+ for element in _element_set(unit.node_ids, unit.rels):
657
+ self._unit_owner[element] = position
658
+ return units
659
+
660
+ def _hop_expr(self, walk: Recursive) -> Exists:
661
+ """The one hop a walk can make when nothing leaves the end it arrives at.
662
+
663
+ A directed edge between two labels is walkable once, and a bound that stops at the first
664
+ hop reads no second row: the walk is one join over one edge row, so it is a plain
665
+ `EXISTS` with no `WITH RECURSIVE` and no step whose join could compare keys of different
666
+ ends. Each orientation links the end it leaves to the left node and the end it lands on to
667
+ the right one, and the row is still excluded when the path already read it: both sides of
668
+ that comparison are text keys pinned to code points, so a nondeterministic column
669
+ collation cannot make two different rows look like one.
670
+ """
671
+ alias = walk.edge_alias
672
+ alternatives: list[tuple[SqlExpr, ...]] = []
673
+ for orientation in walk.base:
674
+ forward = orientation is Orientation.FORWARD
675
+ leaving = walk.source_columns if forward else walk.target_columns
676
+ leaving_text = walk.source_text if forward else walk.target_text
677
+ landing = walk.target_columns if forward else walk.source_columns
678
+ landing_text = walk.target_text if forward else walk.source_text
679
+ links = [
680
+ Eq(_keyed(ColRef(alias, column), pinned), key)
681
+ for column, pinned, key in zip(leaving, leaving_text, walk.left, strict=True)
682
+ ]
683
+ links.extend(
684
+ Eq(_keyed(ColRef(alias, column), pinned), key)
685
+ for column, pinned, key in zip(landing, landing_text, walk.right, strict=True)
686
+ )
687
+ alternatives.append(tuple(links))
688
+ row = tuple(
689
+ _keyed(ColRef(alias, column), text)
690
+ for column, text in zip(walk.key, walk.key_text, strict=True)
691
+ )
692
+ where: tuple[Conjunct, ...] = (
693
+ *(
694
+ alternatives[0]
695
+ if len(alternatives) == 1
696
+ else (Or(tuple(And(links) for links in alternatives)),)
697
+ ),
698
+ *(
699
+ TupleNe(
700
+ row,
701
+ tuple(
702
+ _keyed(column, text)
703
+ for column, text in zip(earlier, walk.key_text, strict=True)
704
+ ),
705
+ )
706
+ for earlier in walk.seed
707
+ ),
708
+ )
709
+ return Exists(Group(walk.table, alias, (), where))
710
+
711
+ def _frontier_producers(self, walk: BUntypedRecursive) -> dict[tuple[str, str], PgType]:
712
+ """The one type every frontier component can have been produced with, by identity.
713
+
714
+ A component is a node identity: its label plus one text component per key column, each the
715
+ rendering of the column the hop that landed there carried. That type is `_carried_type` of
716
+ the hop's landing column, over every hop that can land on the label; a hop departing from
717
+ the walk's left node also lets the hoisted depth-0 row stand in the frontier, and that row
718
+ renders the left node's own declared key type. A position no hop produced, one a hop left
719
+ undeclared, or one two hops disagree about has no single type and is absent here: the
720
+ departing hop keeps its pinned text comparison there.
721
+ """
722
+ left = self._nodes[walk.left].node_type
723
+ producers: dict[tuple[str, str], PgType | None] = {}
724
+
725
+ def produced(position: tuple[str, str], kind: PgType | None) -> None:
726
+ """One more hop's type for a position: two kinds, or an undeclared one, prove none."""
727
+ if position in producers and producers[position] != kind:
728
+ producers[position] = None
729
+ else:
730
+ producers[position] = kind
731
+
732
+ for hop in (*walk.base, *walk.steps):
733
+ leaving, _ = _hop_leaving(hop.edge_type, hop.orientation)
734
+ landing, columns = _hop_landing(hop.edge_type, hop.orientation)
735
+ for column, key in zip(columns, landing.key, strict=True):
736
+ produced(
737
+ (landing.label, key),
738
+ _carried_type(hop.edge_type, column, landing, key),
739
+ )
740
+ if leaving.label == left.label:
741
+ for key in left.key:
742
+ produced((left.label, key), declared_pg_type(left, key))
743
+ return {position: kind for position, kind in producers.items() if kind is not None}
744
+
745
+ def _walk_hop(
746
+ self, alias: str, hop: BHop, producers: Mapping[tuple[str, str], PgType]
747
+ ) -> WalkHop:
748
+ """One declared edge as the plan reads it: both ends, its row key and its trail tag.
749
+
750
+ Each end's columns say whether they compare as text, from the edge's own property
751
+ declarations or from the node key an undeclared foreign key points at, so the emitter
752
+ pins exactly the hop joins that need it. `from_types` casts a component back only when
753
+ `producers` names exactly one type for it and the departing column carries that same type
754
+ (see `_frontier_type`); the producer type itself is resolved once by `_frontier_producers`.
755
+ """
756
+ edge = hop.edge_type
757
+ leaving, from_columns = _hop_leaving(edge, hop.orientation)
758
+ landing, to_columns = _hop_landing(edge, hop.orientation)
759
+ return WalkHop(
760
+ alias=alias,
761
+ table=edge.table,
762
+ from_label=leaving.label,
763
+ from_columns=from_columns,
764
+ from_text=tuple(
765
+ edge_side_text(edge, column, leaving, key)
766
+ for column, key in zip(from_columns, leaving.key, strict=True)
767
+ ),
768
+ from_types=tuple(
769
+ _frontier_type(
770
+ _carried_type(edge, column, leaving, key),
771
+ producers.get((leaving.label, key)),
772
+ )
773
+ for column, key in zip(from_columns, leaving.key, strict=True)
774
+ ),
775
+ to_label=landing.label,
776
+ to_columns=to_columns,
777
+ to_text=tuple(
778
+ edge_side_text(edge, column, landing, key)
779
+ for column, key in zip(to_columns, landing.key, strict=True)
780
+ ),
781
+ landing_table=landing.table,
782
+ landing_key=landing.key,
783
+ key=edge.key,
784
+ tag=hop.tag,
785
+ )
786
+
787
+ def elements(self, owners: set[BOwner]) -> set[_Element]:
788
+ """The elements of a mandatory group a set of column owners names.
789
+
790
+ The target is the outer `FROM` and a lateral scope's element is read through its exposed
791
+ columns, so neither is an element a group can decide on its own: a predicate naming one
792
+ stays in the outer `WHERE`.
793
+ """
794
+ elements: set[_Element] = set()
795
+ for owner in owners:
796
+ match owner:
797
+ case BNodeRef(id=node_id):
798
+ if node_id != self._target and ("node", node_id) not in self._unit_owner:
799
+ elements.add(("node", node_id))
800
+ case BRelRef(id=rel_id):
801
+ if ("rel", rel_id) not in self._unit_owner:
802
+ elements.add(("rel", rel_id))
803
+ return elements