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,794 @@
1
+ """The outer `SELECT`: its projections, its laterals, and every expression it renders.
2
+
3
+ A query with an `OPTIONAL MATCH` cannot use the semi-join shape: a row the optional pattern matches
4
+ nothing for has to survive with its variables NULL, so every row scope becomes one
5
+ `LEFT JOIN LATERAL` in the same `FROM` as the target. A scope whose every element an earlier one
6
+ declared reads no row of its own, and an optional scope nothing outside it names is pruned: it
7
+ cannot change the key set. One target row may meet several rows of a surviving unit, so the keys
8
+ are selected `DISTINCT` unless no required unit survives."""
9
+
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import replace
13
+
14
+ from cypher2sql._ir import (
15
+ BAnd,
16
+ BArray,
17
+ BCmp,
18
+ BCol,
19
+ BConst,
20
+ BExists,
21
+ BExpr,
22
+ BFold,
23
+ BIn,
24
+ BIsNull,
25
+ BNaN,
26
+ BNot,
27
+ BNullWhen,
28
+ BOr,
29
+ Bound,
30
+ BPresent,
31
+ BRecursive,
32
+ BRegex,
33
+ BRel,
34
+ BString,
35
+ BTrail,
36
+ BUntypedRecursive,
37
+ BValue,
38
+ BXor,
39
+ ConstValue,
40
+ Orientation,
41
+ PgType,
42
+ edge_identity,
43
+ edge_key_text,
44
+ edge_side_text,
45
+ )
46
+
47
+ from ._groups import _GroupBuilder
48
+ from ._nodes import (
49
+ _VALUE_EXPRS,
50
+ And,
51
+ AnyEq,
52
+ AnyOf,
53
+ Bool,
54
+ CaseNull,
55
+ Cmp,
56
+ Collate,
57
+ ColRef,
58
+ Conjunct,
59
+ Exists,
60
+ Group,
61
+ IsNull,
62
+ Lateral,
63
+ Nan,
64
+ Not,
65
+ Or,
66
+ Parity,
67
+ Placeholder,
68
+ Projection,
69
+ Recursive,
70
+ Regex,
71
+ Select,
72
+ SqlExpr,
73
+ StringCall,
74
+ TupleNe,
75
+ UntypedWalk,
76
+ Walk,
77
+ WalkIn,
78
+ WalkSource,
79
+ _and,
80
+ _declared_aliases,
81
+ _referenced_aliases,
82
+ )
83
+ from ._rows import _PlanRows
84
+ from ._scopes import (
85
+ _conjuncts,
86
+ _element_set,
87
+ _referenced,
88
+ )
89
+ from ._uniqueness import (
90
+ _identity_pairs,
91
+ _orientations,
92
+ )
93
+ from ._working import (
94
+ _Expansion,
95
+ _Unit,
96
+ _WalkPlan,
97
+ )
98
+
99
+
100
+ def plan(bound: Bound) -> Select:
101
+ """Build the relational plan for a bound query."""
102
+ return _Planner(bound).select()
103
+
104
+
105
+ class _Planner(_PlanRows):
106
+ """One plan of one bound query: alias table, groups and outer predicates."""
107
+
108
+ def _typed_expr(
109
+ self, index: int, recursive: BRecursive, trail: BTrail, *, hoist: bool = False
110
+ ) -> Conjunct | None:
111
+ """One typed walk: its state is one edge row and its trail is the rows already read.
112
+
113
+ The trail seed is the row each earlier occurrence of the same declared edge actually
114
+ binds, whose aliases are visible here: the walk may not read a row the path already read.
115
+ A detached occurrence names its row with its own alias; any other has one orientation (or
116
+ both ends are one pattern node), so the carrying end's row is the seed. Seeding both ends
117
+ of an undirected occurrence would forbid a row the path never read. A walk that lands on
118
+ no hop count at all matches nothing (unless zero hops is allowed).
119
+
120
+ Zero hops are only the identity when both ends are of one node type: two different labels
121
+ are never one row, so that alternative is a comparison of unrelated keys and contributes
122
+ nothing. A walk with no hop left to make after the first is one join, not a recursion:
123
+ it is planned as a plain `EXISTS`, so no recursive term is written for a step that does
124
+ not exist.
125
+
126
+ `hoist` asks for the walk alone, for a `WalkSource`: the zero-hop alternative is then the
127
+ CTE's depth-0 state row (`include_zero`) instead of a key comparison outside the walk.
128
+ """
129
+ edge = recursive.edge_type
130
+ right_type = self._nodes[recursive.right].node_type
131
+ identity = (edge.type, edge.source.label, edge.target.label)
132
+ seed: list[tuple[ColRef, ...]] = []
133
+ seeded: set[tuple[tuple[str, str], ...]] = set()
134
+ for rel in trail.rels:
135
+ if (rel.edge_type.type, rel.edge_type.source.label, rel.edge_type.target.label) != (
136
+ identity
137
+ ):
138
+ continue
139
+ row_element = (
140
+ ("rel", rel.id)
141
+ if self.own_row(rel)
142
+ else self._row_element(rel, _orientations(rel)[0])
143
+ )
144
+ row = tuple(self._ref(row_element, column) for column in edge.key)
145
+ columns = tuple((column.alias, column.column) for column in row)
146
+ if columns not in seeded:
147
+ seeded.add(columns)
148
+ seed.append(row)
149
+ zero = recursive.min_depth == 0 and (
150
+ self._nodes[recursive.left].node_type.label == right_type.label
151
+ )
152
+ items: list[SqlExpr | Exists | Recursive] = []
153
+ if zero and not hoist:
154
+ same = self.same_row(recursive.left, recursive.right)
155
+ if same is None:
156
+ # Zero hops always hold: the zero-length alternative satisfies the expansion.
157
+ return None
158
+ items.append(same)
159
+ depth_min = max(recursive.min_depth, 1)
160
+ if recursive.max_depth >= depth_min and recursive.base:
161
+ walk = Recursive(
162
+ cte=f"reach{index + 1}",
163
+ edge_alias=f"e{index + 1}",
164
+ table=edge.table,
165
+ key=edge.key,
166
+ key_text=edge_key_text(edge),
167
+ source_columns=edge.source_columns,
168
+ target_columns=edge.target_columns,
169
+ source_text=tuple(
170
+ edge_side_text(edge, column, edge.source, key)
171
+ for column, key in zip(edge.source_columns, edge.source.key, strict=True)
172
+ ),
173
+ target_text=tuple(
174
+ edge_side_text(edge, column, edge.target, key)
175
+ for column, key in zip(edge.target_columns, edge.target.key, strict=True)
176
+ ),
177
+ left=self._node_keys(recursive.left),
178
+ right=self._node_keys(recursive.right),
179
+ right_is_source=right_type.label == edge.source.label,
180
+ right_is_target=right_type.label == edge.target.label,
181
+ base=recursive.base,
182
+ steps=recursive.steps,
183
+ seed=tuple(seed),
184
+ depth_min=0 if hoist and zero else depth_min,
185
+ depth_max=recursive.max_depth,
186
+ include_zero=hoist and zero,
187
+ )
188
+ if recursive.steps and recursive.max_depth > 1:
189
+ items.append(walk)
190
+ elif depth_min == 1:
191
+ items.append(self._hop_expr(walk))
192
+ if not items:
193
+ return Bool(ConstValue.FALSE)
194
+ return items[0] if len(items) == 1 else AnyOf(tuple(items))
195
+
196
+ def _untyped_walk(
197
+ self,
198
+ index: int,
199
+ walk: BUntypedRecursive,
200
+ depth_min: int,
201
+ trail: BTrail,
202
+ *,
203
+ include_zero: bool = False,
204
+ ) -> UntypedWalk:
205
+ """The plan of one untyped walk: its hop branches, endpoint identities and trail seed."""
206
+ tags = {edge_identity(hop.edge_type): hop.tag for hop in (*walk.base, *walk.steps)}
207
+ # One counter for base and step hops, so no alias repeats within one statement.
208
+ numbered = tuple(enumerate((*walk.base, *walk.steps), start=1))
209
+ # What produced each frontier component is known only once every branch is counted, so
210
+ # the producer map is built first and every hop's cast decided from it.
211
+ producers = self._frontier_producers(walk)
212
+ base = tuple(
213
+ self._walk_hop(f"e{index + 1}{position}", hop, producers)
214
+ for position, hop in numbered[: len(walk.base)]
215
+ )
216
+ steps = tuple(
217
+ self._walk_hop(f"e{index + 1}{position}", hop, producers)
218
+ for position, hop in numbered[len(walk.base) :]
219
+ )
220
+ seed: list[tuple[int, tuple[ColRef, ...]]] = []
221
+ seeded: set[tuple[int, tuple[tuple[str, str], ...]]] = set()
222
+ for rel in trail.rels:
223
+ tag = tags.get(edge_identity(rel.edge_type))
224
+ if tag is None:
225
+ continue
226
+ row_element = (
227
+ ("rel", rel.id)
228
+ if self.own_row(rel)
229
+ else self._row_element(rel, _orientations(rel)[0])
230
+ )
231
+ row = tuple(self._ref(row_element, column) for column in rel.edge_type.key)
232
+ key = (tag, tuple((column.alias, column.column) for column in row))
233
+ if key not in seeded:
234
+ seeded.add(key)
235
+ seed.append((tag, row))
236
+ return UntypedWalk(
237
+ cte=f"reach{index + 1}",
238
+ step=f"step{index + 1}",
239
+ base=base,
240
+ steps=steps,
241
+ left=self._node_keys(walk.left),
242
+ right=self._node_keys(walk.right),
243
+ left_label=self._nodes[walk.left].node_type.label,
244
+ right_label=self._nodes[walk.right].node_type.label,
245
+ depth_min=0 if include_zero else depth_min,
246
+ depth_max=walk.max_depth,
247
+ seed=tuple(seed),
248
+ include_zero=include_zero,
249
+ )
250
+
251
+ def _chain_branch(self, rel: BRel, orientation: Orientation) -> SqlExpr:
252
+ links = self.links(rel, orientation)
253
+ return _and(tuple(link.equality() for link in links))
254
+
255
+ def _outer_links(self) -> list[SqlExpr]:
256
+ """Edges stored in the target's own row: a predicate, not an `EXISTS`."""
257
+ items: list[SqlExpr] = []
258
+ for rel in self._bound.rels:
259
+ if self._parts(rel):
260
+ continue
261
+ for orientation in _orientations(rel):
262
+ items.extend(link.equality() for link in self.links(rel, orientation))
263
+ return items
264
+
265
+ def _uniqueness(self, first: BRel, second: BRel) -> SqlExpr:
266
+ left = self._keys(first)
267
+ right = self._keys(second)
268
+ if left == right:
269
+ # Both occurrences can only bind the same row: Cypher forbids reusing a
270
+ # relationship, so no row can satisfy them both.
271
+ return Bool(ConstValue.FALSE)
272
+ return TupleNe(left, right)
273
+
274
+ def _untyped_expr(
275
+ self, index: int, walk: BUntypedRecursive, trail: BTrail, *, hoist: bool = False
276
+ ) -> Conjunct | None:
277
+ """One untyped walk, ORed with the zero-hop identity when the bound allows it.
278
+
279
+ The seed is every declared relationship of this path whose edge the walk can read, in the
280
+ trail format the walk appends: a row the path already read is never read again. A walk
281
+ that lands on no hop count at all matches nothing (unless zero hops holds).
282
+
283
+ `hoist` asks for the walk alone, for a `WalkSource`: the zero-hop identity is then the
284
+ CTE's depth-0 state row (`include_zero`), and the endpoint comparison stays outside.
285
+ """
286
+ items: list[SqlExpr | UntypedWalk] = []
287
+ zero = walk.min_depth == 0
288
+ if zero and not hoist:
289
+ same = self.same_row(walk.left, walk.right)
290
+ if same is None:
291
+ return None
292
+ items.append(same)
293
+ depth_min = max(walk.min_depth, 1)
294
+ if walk.max_depth >= depth_min:
295
+ items.append(
296
+ self._untyped_walk(index, walk, depth_min, trail, include_zero=hoist and zero)
297
+ )
298
+ if not items:
299
+ return Bool(ConstValue.FALSE)
300
+ return items[0] if len(items) == 1 else AnyOf(tuple(items))
301
+
302
+ def chain_predicate(self, rels: tuple[BRel, ...]) -> SqlExpr:
303
+ """A path with no element to join: just its equalities, one disjunction per hop."""
304
+ return _and(
305
+ tuple(
306
+ Or(tuple(self._chain_branch(rel, item) for item in _orientations(rel)))
307
+ if len(rel.orientations) > 1
308
+ else self._chain_branch(rel, _orientations(rel)[0])
309
+ for rel in rels
310
+ )
311
+ )
312
+
313
+ def path_uniqueness(self, rels: list[BRel], trail_rels: tuple[BRel, ...]) -> list[SqlExpr]:
314
+ """One path never reads the same edge row twice: an alternative's hops and its trail.
315
+
316
+ Every pair of occurrences that stands for the same declared edge must bind two rows: a
317
+ join table's row compares through its own alias, an edge stored in an end's row through
318
+ that end's alias, and a hop that may traverse either way through a detached row alias of
319
+ its own. A hop is compared with the path's declared and inlined occurrences too, whose
320
+ aliases are visible here; pairs among those are emitted once, by their own group.
321
+ """
322
+ hop_ids = {rel.id for rel in rels}
323
+ pairs: list[tuple[BRel, BRel]] = []
324
+ seen: set[tuple[int, int]] = set()
325
+ for first, second in _identity_pairs([*trail_rels, *rels]):
326
+ if first.id not in hop_ids and second.id not in hop_ids:
327
+ continue
328
+ key = (first.id, second.id)
329
+ if key in seen:
330
+ continue
331
+ seen.add(key)
332
+ pairs.append((first, second))
333
+ return [self._uniqueness(first, second) for first, second in pairs]
334
+
335
+ def trail_uniqueness(self, trails: list[BTrail]) -> list[SqlExpr]:
336
+ """Pairs of non-hop occurrences in one path; both of their rows are visible here.
337
+
338
+ Pairs of two declared occurrences are emitted once, by `uniqueness_in`; an inlined
339
+ inferred chain has no group of its own, so its pairs with a declared occurrence live here.
340
+ """
341
+ return [
342
+ self._uniqueness(first, second)
343
+ for trail in trails
344
+ for first, second in _identity_pairs(trail.rels)
345
+ if not (first.declared and second.declared)
346
+ ]
347
+
348
+ def uniqueness_in(self, rels: list[BRel]) -> list[SqlExpr]:
349
+ """Uniqueness of the occurrences of one declared edge inside one row scope.
350
+
351
+ Pairing within the passed scope lets a `BScope` compare its own two occurrences of one
352
+ edge, which the pattern's pair list cannot see. Cypher's rule is per clause, so a pair of
353
+ two clauses is never compared.
354
+ """
355
+ return [self._uniqueness(first, second) for first, second in self._clause_pairs(rels)]
356
+
357
+ def _outer_uniqueness(self) -> list[SqlExpr]:
358
+ """Pairs of occurrences that are both the target's own row: no group holds them."""
359
+ pairs = [
360
+ (first, second)
361
+ for first, second in self._uniqueness_pairs()
362
+ if not self._parts(first) and not self._parts(second)
363
+ ]
364
+ pairs.extend(
365
+ (first, second)
366
+ for trail in self._bound.trails
367
+ for first, second in _identity_pairs(trail.rels)
368
+ if not (first.declared and second.declared)
369
+ if not self._parts(first) and not self._parts(second)
370
+ )
371
+ return [self._uniqueness(first, second) for first, second in pairs]
372
+
373
+ def inferred_expr(self, expansion: _Expansion) -> Conjunct | None:
374
+ """One `EXISTS` per alternative path, ORed; each references the two endpoints.
375
+
376
+ An empty alternative is the zero-hop case: the two endpoints are the same row, so it
377
+ becomes their key equality, or nothing at all when they are already one pattern node.
378
+ Every non-empty alternative also compares its hops with the trail's other occurrences,
379
+ whose aliases the enclosing scope makes visible here.
380
+ """
381
+ inferred = expansion.relation
382
+ trail_rels = expansion.trail.rels
383
+ branches: list[SqlExpr | Exists] = []
384
+ for path in inferred.alternatives:
385
+ if not path.rels:
386
+ same = self.same_row(inferred.left, inferred.right)
387
+ if same is None:
388
+ # Zero hops always hold: the zero-length alternative satisfies the whole
389
+ # expansion, so longer alternatives add nothing.
390
+ return None
391
+ branches.append(same)
392
+ continue
393
+ uniqueness = self.path_uniqueness(list(path.rels), trail_rels)
394
+ group = _GroupBuilder(
395
+ self,
396
+ [node.id for node in path.nodes],
397
+ list(path.rels),
398
+ outer=(
399
+ self.visible_alias(("node", inferred.left)),
400
+ self.visible_alias(("node", inferred.right)),
401
+ ),
402
+ uniqueness=uniqueness,
403
+ ).build()
404
+ if group is not None:
405
+ branches.append(Exists(group))
406
+ else:
407
+ branches.append(_and((self.chain_predicate(path.rels), *uniqueness)))
408
+ if not branches:
409
+ return Bool(ConstValue.FALSE)
410
+ return branches[0] if len(branches) == 1 else AnyOf(tuple(branches))
411
+
412
+ def recursive_expr(self, plan: _WalkPlan, *, hoist: bool = False) -> Conjunct | None:
413
+ """One `WITH RECURSIVE` walk, ORed with the zero-hop identity when the bound allows it."""
414
+ match plan.walk:
415
+ case BRecursive() as walk:
416
+ return self._typed_expr(plan.number, walk, plan.trail, hoist=hoist)
417
+ case BUntypedRecursive() as walk:
418
+ return self._untyped_expr(plan.number, walk, plan.trail, hoist=hoist)
419
+
420
+ def hoist(self, plan: _WalkPlan, anchor: Group | None) -> WalkIn | None:
421
+ """Lift one walk out of its row scope into a statement-level `WITH RECURSIVE`.
422
+
423
+ The walk qualifies only when its right end is the target and its left end is some other
424
+ pattern node: then the endpoint comparison is the walk's only link to the target, so the
425
+ walk can be computed once and the target matched against its endpoint set. `anchor` is the
426
+ row scope the walk hangs off, without the walk itself; it must read nothing from outside
427
+ its own `FROM` — a derived table cannot correlate — so the aliases it reads, and the ones
428
+ the walk's own start and trail seed read, are all checked against the aliases the anchor
429
+ declares. `None` declines and keeps the correlated plan, which is always correct, only
430
+ slower.
431
+ """
432
+ if anchor is None or anchor.table is None:
433
+ return None
434
+ if plan.walk.right != self._target or plan.walk.left == self._target:
435
+ return None
436
+ declared = _declared_aliases(anchor)
437
+ if not _referenced_aliases(anchor) <= declared:
438
+ return None
439
+ rendered = self.recursive_expr(plan, hoist=True)
440
+ if not isinstance(rendered, (Recursive, UntypedWalk)):
441
+ return None
442
+ if not _referenced_aliases((rendered.left, rendered.seed)) <= declared:
443
+ return None
444
+ source = self._walk_source(plan.number, rendered, anchor)
445
+ if source is None:
446
+ return None
447
+ self.walk_sources.append(source)
448
+ return WalkIn(source)
449
+
450
+ def _walk_source(self, number: int, walk: Walk, anchor: Group) -> WalkSource | None:
451
+ """One walk's CTE: the anchor entry, the walk rebound to it and the columns it exposes.
452
+
453
+ A walk's left end and trail seed are columns of the row scope it hangs off. The anchor
454
+ selects those columns under `k1`, `k2`, … names and the walk reads them through the
455
+ anchor's alias, so the CTE body is the inline walk with its two references renamed.
456
+ `None` declines when a start column is not a column of that scope, which keeps the
457
+ correlated plan instead of writing a reference the anchor entry cannot resolve.
458
+ """
459
+ alias = f"a{number + 1}"
460
+ names: dict[tuple[str, str], str] = {}
461
+ columns: list[Projection] = []
462
+
463
+ def bind(reference: ColRef) -> ColRef:
464
+ known = names.get((reference.alias, reference.column))
465
+ if known is None:
466
+ known = f"k{len(names) + 1}"
467
+ names[(reference.alias, reference.column)] = known
468
+ columns.append(Projection(known, reference))
469
+ return ColRef(alias, known)
470
+
471
+ def left(reference: SqlExpr) -> SqlExpr | None:
472
+ entry = reference.operand if isinstance(reference, Collate) else reference
473
+ if not isinstance(entry, ColRef):
474
+ return None
475
+ bound = bind(entry)
476
+ return Collate(bound) if isinstance(reference, Collate) else bound
477
+
478
+ def lefts(items: tuple[SqlExpr, ...]) -> tuple[SqlExpr, ...] | None:
479
+ bound: list[SqlExpr] = []
480
+ for item in items:
481
+ rendered = left(item)
482
+ if rendered is None:
483
+ return None
484
+ bound.append(rendered)
485
+ return tuple(bound)
486
+
487
+ start = lefts(walk.left)
488
+ if start is None:
489
+ return None
490
+ rebound: Walk
491
+ match walk:
492
+ case Recursive():
493
+ rebound = replace(
494
+ walk,
495
+ left=start,
496
+ seed=tuple(tuple(bind(item) for item in row) for row in walk.seed),
497
+ )
498
+ case UntypedWalk():
499
+ rebound = replace(
500
+ walk,
501
+ left=start,
502
+ seed=tuple((tag, tuple(bind(item) for item in row)) for tag, row in walk.seed),
503
+ )
504
+ return WalkSource(
505
+ cte=walk.cte,
506
+ anchor_cte=f"anchor{number + 1}",
507
+ alias=alias,
508
+ anchor=anchor,
509
+ columns=tuple(columns),
510
+ walk=rebound,
511
+ )
512
+
513
+ def exists(self, body: BExists) -> Exists:
514
+ """One correlated `EXISTS` group for a body bound inside a predicate.
515
+
516
+ The body's own elements are the group's rows; the aliases visible where the predicate is
517
+ written are its correlation. A body with no row of its own (`(n)-[:T]->(m)` between two
518
+ bound nodes) is still a group: `SELECT 1 WHERE …` is an `EXISTS` that reads no table.
519
+ """
520
+ outer = self.visible
521
+ inferred = [
522
+ _Expansion(body.inferred[index], trail)
523
+ for trail in body.trails
524
+ for index in trail.expansions
525
+ ]
526
+ base = self._body_base[body.number]
527
+ recursive = [
528
+ _WalkPlan(base + index, body.recursive[index], trail)
529
+ for trail in body.trails
530
+ for index in trail.recursions
531
+ ]
532
+ group = _GroupBuilder(
533
+ self,
534
+ [node.id for node in body.nodes],
535
+ list(body.rels),
536
+ outer=outer,
537
+ properties=list(body.properties),
538
+ predicates=list(_conjuncts(body.where)),
539
+ inferred=inferred,
540
+ recursive=recursive,
541
+ uniqueness=self.trail_uniqueness(list(body.trails))
542
+ + self.uniqueness_in(list(body.rels)),
543
+ rowless=True,
544
+ ).build()
545
+ if group is None:
546
+ raise AssertionError("internal error: an EXISTS body built no group")
547
+ return Exists(group)
548
+
549
+ def _unit_group(self, unit: _Unit, position: int) -> Group:
550
+ """Render one scope's body with its own elements unprojected and earlier ones projected."""
551
+ saved = self._scope
552
+ self._scope = position
553
+ try:
554
+ outer = frozenset(
555
+ {self.target_alias()} | {self._unit_alias[earlier] for earlier in range(position)}
556
+ )
557
+ group = _GroupBuilder(
558
+ self,
559
+ unit.node_ids,
560
+ unit.rels,
561
+ outer=outer,
562
+ properties=list(unit.properties),
563
+ predicates=list(unit.predicates),
564
+ inferred=unit.inferred,
565
+ recursive=unit.recursive,
566
+ uniqueness=self.trail_uniqueness(unit.trails) + self.uniqueness_in(unit.rels),
567
+ rowless=True,
568
+ hoist=True,
569
+ ).build()
570
+ finally:
571
+ self._scope = saved
572
+ if group is None:
573
+ raise AssertionError("internal error: a rowless lateral scope built no body")
574
+ return group
575
+
576
+ def _group_predicates(self) -> list[Conjunct]:
577
+ items: list[Conjunct] = []
578
+ for members, rels in self._components():
579
+ trails = self._component_trails(members, rels)
580
+ elements = _element_set(members, rels)
581
+ inferred = [
582
+ _Expansion(self._bound.inferred[index], trail)
583
+ for trail in trails
584
+ for index in trail.expansions
585
+ ]
586
+ recursive = [
587
+ _WalkPlan(index, self._bound.recursive[index], trail)
588
+ for trail in trails
589
+ for index in trail.recursions
590
+ ]
591
+ builder = _GroupBuilder(
592
+ self,
593
+ members,
594
+ rels,
595
+ properties=self._group_expressions(self._bound.properties, elements),
596
+ predicates=self._group_expressions(tuple(_conjuncts(self._bound.where)), elements),
597
+ inferred=inferred,
598
+ recursive=recursive,
599
+ uniqueness=self.trail_uniqueness(trails) + self.uniqueness_in(rels),
600
+ hoist=True,
601
+ )
602
+ group = builder.build()
603
+ # A body whose every walk was hoisted is only those walks' anchor: its rows and
604
+ # predicates are what the anchor entries already read, so the membership tests
605
+ # replace it in the outer WHERE and nothing is evaluated twice.
606
+ items.extend(builder.lifted)
607
+ if group is not None and not builder.fully_lifted:
608
+ items.append(Exists(group))
609
+ return items
610
+
611
+ def predicate(self, expr: BExpr) -> Conjunct:
612
+ match expr:
613
+ case BCol(owner=owner, column=column):
614
+ return self._ref(self._element(owner), column)
615
+ case BPresent(index=index):
616
+ return ColRef(self._scope_alias[index], "found")
617
+ case BValue(index=index, pg_type=pg_type):
618
+ return Placeholder(index, pg_type)
619
+ case BArray():
620
+ # The binder only ever puts a list inside `BIn`, whose planner case reads it.
621
+ raise AssertionError("internal error: a bound list reached a predicate position")
622
+ case BConst(value=value):
623
+ return Bool(value)
624
+ case BNaN(pg_type=pg_type):
625
+ return Nan(pg_type)
626
+ case BCmp(op=op, left=left, right=right):
627
+ return Cmp(op, self.collated_operand(left), self.collated_operand(right))
628
+ case BIn(column=column, values=values):
629
+ return AnyEq(
630
+ self.collated_operand(column),
631
+ Placeholder(values.index, values.pg_type, array=True),
632
+ )
633
+ case BString(op=op, column=column, operand=operand):
634
+ return StringCall(op, self.collated_operand(column), self.collated_operand(operand))
635
+ case BRegex(column=column, pattern=pattern):
636
+ return Regex(self.collated_operand(column), self.operand(pattern))
637
+ case BAnd(items=items):
638
+ return And(tuple(self.predicate(item) for item in items))
639
+ case BOr(items=items):
640
+ return Or(tuple(self.predicate(item) for item in items))
641
+ case BXor(items=items):
642
+ return Parity(tuple(self.predicate(item) for item in items))
643
+ case BNot(operand=operand):
644
+ return self.negation(operand)
645
+ case BIsNull(operand=operand, negated=negated):
646
+ return IsNull(self.operand(operand), negated)
647
+ case BFold(guard=guard, negated=negated):
648
+ rendered = self.predicate(guard)
649
+ if negated:
650
+ return Or((Not(rendered), Bool(ConstValue.NULL)))
651
+ return And((rendered, Bool(ConstValue.NULL)))
652
+ case BNullWhen(guard=guard, operand=operand):
653
+ return CaseNull(self.predicate(guard), self.predicate(operand))
654
+ case BExists() as body:
655
+ return self.exists(body)
656
+
657
+ def negation(self, operand: BExpr) -> Conjunct:
658
+ """`NOT operand`, emitting PostgreSQL's `!~` for a negated regex instead of a wrap.
659
+
660
+ Both keep SQL's three-valued negation, so a NULL operand stays NULL.
661
+ """
662
+ if isinstance(operand, BRegex):
663
+ return Regex(
664
+ self.collated_operand(operand.column), self.operand(operand.pattern), negated=True
665
+ )
666
+ return Not(self.predicate(operand))
667
+
668
+ def operand(self, expr: BExpr) -> SqlExpr:
669
+ """One comparison operand; a condition is never a value.
670
+
671
+ The binder refuses `EXISTS` and a pattern predicate in a value position with a
672
+ `CypherSemanticError` (`_condition_not_a_value`), so this narrowing only fails if a
673
+ stage above broke that contract — no query text can reach it.
674
+ """
675
+ rendered = self.predicate(expr)
676
+ if not isinstance(rendered, _VALUE_EXPRS):
677
+ raise AssertionError("internal error: a condition reached a value position")
678
+ return rendered
679
+
680
+ def collated_operand(self, expr: BExpr) -> SqlExpr:
681
+ """A text operand is pinned to code-point order, whatever its collation.
682
+
683
+ Cypher compares, searches and orders strings by code point. PostgreSQL follows the
684
+ operand's collation unless one is written, so a case-insensitive or ICU-nondeterministic
685
+ column could otherwise add, drop or reorder a key. Every text column of `=`, `<>`, `<`,
686
+ `<=`, `>`, `>=`, `IN`, `STARTS WITH`, `ENDS WITH`, `CONTAINS`, `=~` and a text key's order
687
+ operand becomes a `Collate`, so the pin exists in one place. A bound value keeps its bare
688
+ `%s::text` cast: the column's pin decides the comparison. A non-text operand — a number,
689
+ a date, a uuid — has no collation to pin.
690
+ """
691
+ rendered = self.operand(expr)
692
+ if isinstance(expr, BCol) and expr.pg_type is PgType.TEXT:
693
+ return Collate(rendered)
694
+ return rendered
695
+
696
+ def _outer_paths(self) -> list[Conjunct]:
697
+ """Expansions whose whole trail is the target's own row: no group can hold them."""
698
+ items: list[Conjunct] = []
699
+ for trail in self._bound.trails:
700
+ if not self._trail_is_outer(trail):
701
+ continue
702
+ for index in trail.expansions:
703
+ rendered = self.inferred_expr(_Expansion(self._bound.inferred[index], trail))
704
+ if rendered is not None:
705
+ items.append(rendered)
706
+ for index in trail.recursions:
707
+ walk = _WalkPlan(index, self._bound.recursive[index], trail)
708
+ rendered = self.recursive_expr(walk)
709
+ if rendered is not None:
710
+ items.append(rendered)
711
+ return items
712
+
713
+ def _outer_properties(self) -> list[Conjunct]:
714
+ """Pattern property predicates that only the target's own row can decide."""
715
+ return [
716
+ self.predicate(expr)
717
+ for expr in self._bound.properties
718
+ if not self.elements(_referenced(expr))
719
+ ]
720
+
721
+ def _outer_where(self) -> list[Conjunct]:
722
+ """`WHERE` conjuncts that name nothing outside the target's own row."""
723
+ return [
724
+ self.predicate(expr)
725
+ for expr in _conjuncts(self._bound.where)
726
+ if not self.elements(_referenced(expr))
727
+ ]
728
+
729
+ def _lateral_mode(self) -> tuple[tuple[Conjunct, ...], tuple[Lateral, ...]]:
730
+ """Plan every scope as a lateral left join; the outer `WHERE` comes back with them."""
731
+ built = [self._unit_group(unit, position) for position, unit in enumerate(self._units)]
732
+ where: list[Conjunct] = [
733
+ ColRef(unit.alias, "found") for unit in self._units if unit.required
734
+ ]
735
+ self.visible = frozenset({self.target_alias()} | set(self._unit_alias))
736
+ where.extend(self.predicate(expr) for expr in self._bound.properties)
737
+ where.extend(self.predicate(expr) for expr in _conjuncts(self._bound.where))
738
+ where.extend(self._outer_links())
739
+ where.extend(self._outer_paths())
740
+ where.extend(self._outer_uniqueness())
741
+ laterals = tuple(
742
+ Lateral(unit.alias, self._columns(position), group)
743
+ for position, (unit, group) in enumerate(zip(self._units, built, strict=True))
744
+ )
745
+ return tuple(where), laterals
746
+
747
+ def _page(self, value: BValue | None) -> Placeholder | None:
748
+ """One bound `SKIP`/`LIMIT` value as the `Placeholder` the emitter writes."""
749
+ if value is None:
750
+ return None
751
+ rendered = self.predicate(value)
752
+ if not isinstance(rendered, Placeholder):
753
+ raise AssertionError("internal error: a page value is not a placeholder")
754
+ return rendered
755
+
756
+ def select(self) -> Select:
757
+ alias = self.alias(self._target)
758
+ table = self._bound.target.node_type.table
759
+ order = self._order()
760
+ distinct = self._distinct()
761
+ columns = self._projections(order if distinct else ())
762
+ offset = self._page(self._bound.skip)
763
+ limit = self._page(self._bound.limit)
764
+ if self._units:
765
+ where, laterals = self._lateral_mode()
766
+ return Select(
767
+ columns,
768
+ table,
769
+ alias,
770
+ where,
771
+ laterals,
772
+ walks=tuple(self.walk_sources),
773
+ distinct=distinct,
774
+ order=order,
775
+ offset=offset,
776
+ limit=limit,
777
+ )
778
+ where_items: list[Conjunct] = []
779
+ where_items.extend(self._outer_properties())
780
+ where_items.extend(self._outer_where())
781
+ where_items.extend(self._outer_links())
782
+ where_items.extend(self._group_predicates())
783
+ where_items.extend(self._outer_paths())
784
+ where_items.extend(self._outer_uniqueness())
785
+ return Select(
786
+ columns,
787
+ table,
788
+ alias,
789
+ tuple(where_items),
790
+ walks=tuple(self.walk_sources),
791
+ order=order,
792
+ offset=offset,
793
+ limit=limit,
794
+ )