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,143 @@
1
+ """IR → relational plan: aliases, `EXISTS` groups, join order and predicate placement.
2
+
3
+ The target's table is the only element in the outer `FROM`; every other connected piece is one
4
+ `EXISTS` group (a semi-join), so the output is the target's keys and nothing else. Inside a group
5
+ the first non-target element is the `FROM`, then every linked element is joined greedily, `ON` the
6
+ link to what is already there; links to the outer alias become `WHERE` conjuncts, then inline
7
+ property predicates in pattern order, then the `WHERE` conjuncts that touch the group.
8
+
9
+ A `WHERE` conjunct that names elements of two groups is the link between them: they are merged
10
+ into one group so the comparison sees both aliases; a conjunct naming only the target stays in the
11
+ outer `WHERE`, before every `EXISTS`.
12
+
13
+ Aliases come from pattern positions, never query text: `n<i>` is the i-th node, `r<i>` the i-th
14
+ edge that needs a row of its own (a join table). An edge stored in an end's own table is that
15
+ row, so it reuses the end's alias, except when that row depends on the orientation (an undirected
16
+ foreign-key edge between two different nodes) and uniqueness must name it: then the row gets an
17
+ `r<i>` alias of its own, pinned to the end by its key, so `(r1 keys) <> (r2 keys)` compares the
18
+ rows the occurrences actually use.
19
+
20
+ Uniqueness compares two rows, so it is evaluated exactly once, where both aliases are in scope:
21
+ the two occurrences' elements share one group, and a pair whose rows are both the target's own
22
+ row is an outer conjunct. It holds between the occurrences of one `MATCH` clause only (Cypher lets
23
+ a later clause bind a relationship an earlier one bound), so each pair is of one clause.
24
+
25
+ Within a path, no occurrence in one trail (`_ir.BTrail`) may bind a row another occurrence of the
26
+ same declared edge binds. The declared occurrences are compared in their
27
+ group; an expansion's hop is compared against the path's declared occurrences inside each
28
+ alternative's `EXISTS`, because those outer aliases are visible there. A walk's declared rows and
29
+ both endpoints share one group, so every alias it names is in scope. A recursive walk seeds its
30
+ trail with the row each such occurrence actually binds: the occurrence's own detached alias when
31
+ uniqueness gave it one, else its single carrying end's row. Seeding both ends of an undirected edge
32
+ would forbid a row the path never read. A walk only ever goes as deep as a hop leaves the node it
33
+ arrived at: a directed edge between two labels is walkable once, and a bound that stops at the
34
+ first hop reads no second row, so such a walk is planned as that one join and no recursive term
35
+ is written for a step that does not exist. Two expansions of one edge type in one path
36
+ cannot share one scope in either tier, so the binder refuses them.
37
+
38
+ A bounded variable-length relationship is a `BInferred` whose alternatives are its lengths: each
39
+ non-empty alternative is an `EXISTS` over that many joins, an empty one is the zero-hop equality
40
+ of the two endpoints, and the alternatives are ORed.
41
+
42
+ A walk whose right end is the target is hoisted out of every row scope: one materialized
43
+ `WITH RECURSIVE` entry computes its endpoint set once for the statement, and the target's `WHERE`
44
+ asks whether its key is in that set. The walk's own anchor — its left end and the edge rows its
45
+ trail already read — becomes one non-recursive entry selecting just those columns, so the walk is
46
+ evaluated once per query instead of once per candidate target. A walk anchored *at* the target, or
47
+ inside a subquery that correlates with something the anchor cannot reproduce, keeps the inline
48
+ correlated form, which is always correct.
49
+
50
+ A query with an `OPTIONAL MATCH` cannot use that semi-join shape: a row the optional pattern
51
+ matches nothing for has to survive, with its variables NULL. So every row scope becomes one
52
+ `LEFT JOIN LATERAL` in the same `FROM` as the target: first the components of the pattern every
53
+ row has, then each `_ir.BScope` in clause order. A clause can only name what earlier clauses
54
+ declared, so that order puts every scope after the ones it reads; a scope reads an earlier one's
55
+ element through the columns it exposes, and renders all of its own relationships, expansions and
56
+ walks itself — nothing of a scope is ever left for another to pick up. A required scope's (and a
57
+ component's) `found` column is required in the outer `WHERE`, which keeps its semi-join meaning;
58
+ an optional scope adds no requirement, and its columns are NULL when it matched nothing. A later
59
+ clause that names an optional variable requires that scope to be present. A scope whose every
60
+ element an earlier one declared reads no row of its own: its body has no `FROM`. An optional
61
+ scope nothing outside it names is pruned before planning: it cannot change the key set, so it
62
+ adds neither a join nor `DISTINCT`. One target row may meet several rows of a surviving unit, so
63
+ the keys are selected `DISTINCT` unless no required unit survives and every optional one is
64
+ pinned to its null row.
65
+ """
66
+
67
+ from __future__ import annotations
68
+
69
+ from ._nodes import (
70
+ And,
71
+ AnyEq,
72
+ AnyOf,
73
+ Bool,
74
+ CaseNull,
75
+ Cmp,
76
+ Collate,
77
+ ColRef,
78
+ Conjunct,
79
+ CrossJoin,
80
+ Eq,
81
+ Exists,
82
+ Group,
83
+ IsNull,
84
+ Join,
85
+ Lateral,
86
+ Nan,
87
+ Not,
88
+ Or,
89
+ OrderColumn,
90
+ Parity,
91
+ Placeholder,
92
+ Projection,
93
+ Recursive,
94
+ Regex,
95
+ Select,
96
+ SqlExpr,
97
+ StringCall,
98
+ TupleNe,
99
+ UntypedWalk,
100
+ Walk,
101
+ WalkHop,
102
+ WalkIn,
103
+ WalkSource,
104
+ )
105
+ from ._planner import plan
106
+
107
+ __all__ = [
108
+ "And",
109
+ "AnyEq",
110
+ "AnyOf",
111
+ "Bool",
112
+ "CaseNull",
113
+ "Cmp",
114
+ "ColRef",
115
+ "Collate",
116
+ "Conjunct",
117
+ "CrossJoin",
118
+ "Eq",
119
+ "Exists",
120
+ "Group",
121
+ "IsNull",
122
+ "Join",
123
+ "Lateral",
124
+ "Nan",
125
+ "Not",
126
+ "Or",
127
+ "OrderColumn",
128
+ "Parity",
129
+ "Placeholder",
130
+ "Projection",
131
+ "Recursive",
132
+ "Regex",
133
+ "Select",
134
+ "SqlExpr",
135
+ "StringCall",
136
+ "TupleNe",
137
+ "UntypedWalk",
138
+ "Walk",
139
+ "WalkHop",
140
+ "WalkIn",
141
+ "WalkSource",
142
+ "plan",
143
+ ]
@@ -0,0 +1,282 @@
1
+ """One `EXISTS` group: the `FROM`, the greedy joins and the conjuncts left for its `WHERE`.
2
+
3
+ A group starts from the element that is not the target, then joins every element linked to what is
4
+ already there, `ON` the link; a link to an enclosing alias becomes a `WHERE` conjunct instead, and
5
+ the group's own property predicates follow in pattern order. A group the target alone cannot reach
6
+ is built against the target's alias and rendered as one `EXISTS` per outer row."""
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Iterable
11
+ from typing import TYPE_CHECKING
12
+
13
+ from cypher2sql._ir import (
14
+ BExpr,
15
+ BRel,
16
+ Orientation,
17
+ )
18
+
19
+ from ._nodes import (
20
+ Conjunct,
21
+ CrossJoin,
22
+ Group,
23
+ Join,
24
+ Or,
25
+ SqlExpr,
26
+ WalkIn,
27
+ _and,
28
+ )
29
+ from ._uniqueness import _orientations
30
+ from ._working import (
31
+ _Element,
32
+ _Expansion,
33
+ _Link,
34
+ _WalkPlan,
35
+ )
36
+
37
+ if TYPE_CHECKING:
38
+ from ._planner import _Planner
39
+
40
+
41
+ class _GroupBuilder:
42
+ """One `EXISTS` body under construction: what is joined, and what is left to `WHERE`."""
43
+
44
+ def __init__(
45
+ self,
46
+ planner: _Planner,
47
+ node_ids: list[int],
48
+ rels: list[BRel],
49
+ outer: Iterable[str] | None = None,
50
+ properties: list[BExpr] | None = None,
51
+ predicates: list[BExpr] | None = None,
52
+ inferred: list[_Expansion] | None = None,
53
+ recursive: list[_WalkPlan] | None = None,
54
+ uniqueness: list[SqlExpr] | None = None,
55
+ rowless: bool = False,
56
+ hoist: bool = False,
57
+ ) -> None:
58
+ self._planner = planner
59
+ self._node_ids = sorted(node_ids)
60
+ self._rels = sorted(rels, key=lambda rel: rel.id)
61
+ self._properties = properties or []
62
+ self._predicates = predicates or []
63
+ self._inferred = inferred or []
64
+ self._recursive = recursive or []
65
+ self._uniqueness = uniqueness or []
66
+ self._rowless = rowless
67
+ self._hoist = hoist
68
+ # The walks this body asked the planner to lift: they need no row scope of their own.
69
+ self.lifted: list[WalkIn] = []
70
+ self._outer = frozenset(outer) if outer is not None else frozenset({planner.target_alias()})
71
+ self._present: set[tuple[str, int]] = set()
72
+ self._aliases: set[str] = set()
73
+ self._table: str | None = None
74
+ self._alias = ""
75
+ self._joins: list[Join | CrossJoin] = []
76
+ self._where: list[Conjunct] = []
77
+ self._emitted: set[tuple[int, Orientation, int]] = set()
78
+ self._whole: set[int] = set()
79
+
80
+ def build(self) -> Group | None:
81
+ """The body; `None` when it has no row to read, unless built `rowless`.
82
+
83
+ A rowless body (a lateral scope whose every element an earlier scope declared, or whose
84
+ relationships are all stored in those rows) has no `FROM`: `SELECT … WHERE …` decides it
85
+ from the columns already in scope.
86
+ """
87
+ if self._node_ids:
88
+ self._start(("node", self._node_ids[0]))
89
+ else:
90
+ first = next((rel for rel in self._rels if self._planner.own_row(rel)), None)
91
+ if first is not None:
92
+ self._start(("rel", first.id))
93
+ elif not self._rowless:
94
+ return None
95
+ for rel in self._rels:
96
+ self._consider(rel)
97
+ for node_id in self._node_ids:
98
+ if ("node", node_id) not in self._present:
99
+ self._cross(("node", node_id))
100
+ self._leftovers()
101
+ # The body's own rows are joined now, so its predicates — and the subqueries they hold —
102
+ # see them as well as everything that encloses the body.
103
+ saved = self._planner.visible
104
+ self._planner.visible = frozenset(self._aliases | self._outer)
105
+ try:
106
+ self._where.extend(self._planner.predicate(expr) for expr in self._properties)
107
+ self._where.extend(self._planner.predicate(expr) for expr in self._predicates)
108
+ finally:
109
+ self._planner.visible = saved
110
+ for expansion in self._inferred:
111
+ self._check_visible(expansion.relation.left, expansion.relation.right)
112
+ rendered = self._planner.inferred_expr(expansion)
113
+ if rendered is not None:
114
+ self._where.append(rendered)
115
+ # The anchor a hoisted walk reads: this body as it stands, uniqueness included, but
116
+ # without any walk (a walk asks the planner to lift it with this scope as its anchor).
117
+ anchor = Group(
118
+ self._table, self._alias, tuple(self._joins), (*self._where, *self._uniqueness)
119
+ )
120
+ lifted_here: list[WalkIn] = []
121
+ for plan in self._recursive:
122
+ self._check_visible(plan.walk.left, plan.walk.right)
123
+ lifted = self._planner.hoist(plan, anchor) if self._hoist else None
124
+ if lifted is not None:
125
+ lifted_here.append(lifted)
126
+ self._where.append(lifted)
127
+ continue
128
+ rendered = self._planner.recursive_expr(plan)
129
+ if rendered is not None:
130
+ self._where.append(rendered)
131
+ # A body whose every walk was lifted is only those walks' anchor: the membership tests go
132
+ # to the statement's `WHERE` and this body is dropped. A body that keeps another walk has
133
+ # its lifted walk already inside its own `WHERE`, so testing it outside too would repeat it.
134
+ if lifted_here and len(lifted_here) == len(self._recursive):
135
+ self.lifted.extend(lifted_here)
136
+ self._where.extend(self._uniqueness)
137
+ return Group(self._table, self._alias, tuple(self._joins), tuple(self._where))
138
+
139
+ @property
140
+ def fully_lifted(self) -> bool:
141
+ """Whether every walk this body owns was hoisted, so the body is only their anchor."""
142
+ return bool(self._recursive) and len(self.lifted) == len(self._recursive)
143
+
144
+ def _check_visible(self, left: int, right: int) -> None:
145
+ """Both endpoints of an expansion or walk this group renders must be readable here.
146
+
147
+ The group's own rows, the target and every earlier lateral scope are; the planner hands a
148
+ walk only to the group that owns it, so anything else is a planning bug. It is raised,
149
+ never skipped: a skipped walk would silently drop a required pattern and leak rows.
150
+ """
151
+ scope = self._aliases | self._outer
152
+ for node_id in (left, right):
153
+ if self._planner.visible_alias(("node", node_id)) not in scope:
154
+ raise AssertionError(
155
+ f"internal error: a variable-length path reads n{node_id + 1} "
156
+ "outside the group that renders it"
157
+ )
158
+
159
+ # ---------------------------------------------------------------- joining
160
+
161
+ def _start(self, element: _Element) -> None:
162
+ self._table, self._alias = self._planner.element_table(element)
163
+ self._present.add(element)
164
+ self._aliases.add(self._alias)
165
+
166
+ def _cross(self, element: tuple[str, int]) -> None:
167
+ table, alias = self._planner.element_table(element)
168
+ self._joins.append(CrossJoin(table, alias))
169
+ self._present.add(element)
170
+ self._aliases.add(alias)
171
+
172
+ def _consider(self, rel: BRel) -> None:
173
+ orientations = _orientations(rel)
174
+ own = self._planner.own_row(rel)
175
+ if own and len(orientations) > 1:
176
+ for node_id in self._endpoints(rel):
177
+ self._join_node(node_id, rel)
178
+ self._join_rel(rel)
179
+ return
180
+ if own:
181
+ self._join_rel(rel)
182
+ for node_id in self._endpoints(rel):
183
+ self._join_node(node_id, rel)
184
+
185
+ def _join_rel(self, rel: BRel) -> None:
186
+ element = ("rel", rel.id)
187
+ if element in self._present:
188
+ return
189
+ condition = self._condition(rel, self._planner.element_alias(element))
190
+ if condition is None:
191
+ self._cross(element)
192
+ return
193
+ table, alias = self._planner.element_table(element)
194
+ self._joins.append(Join(table, alias, condition))
195
+ self._present.add(element)
196
+ self._aliases.add(alias)
197
+
198
+ def _join_node(self, node_id: int, rel: BRel) -> None:
199
+ element = ("node", node_id)
200
+ if node_id not in self._node_ids or element in self._present:
201
+ return
202
+ condition = self._condition(rel, self._planner.alias(node_id))
203
+ if condition is None:
204
+ self._cross(element)
205
+ return
206
+ table, alias = self._planner.element_table(element)
207
+ self._joins.append(Join(table, alias, condition))
208
+ self._present.add(element)
209
+ self._aliases.add(alias)
210
+
211
+ def _endpoints(self, rel: BRel) -> list[int]:
212
+ ordered: list[int] = []
213
+ for orientation in _orientations(rel):
214
+ source, target = (
215
+ (rel.left, rel.right)
216
+ if orientation is Orientation.FORWARD
217
+ else (rel.right, rel.left)
218
+ )
219
+ for node_id in (source, target):
220
+ if node_id not in ordered:
221
+ ordered.append(node_id)
222
+ return ordered
223
+
224
+ def _condition(self, rel: BRel, alias: str) -> SqlExpr | None:
225
+ orientations = _orientations(rel)
226
+ if len(orientations) > 1:
227
+ links = tuple(
228
+ link
229
+ for orientation in orientations
230
+ for link in self._planner.links(rel, orientation)
231
+ )
232
+ scope = self._aliases | self._outer
233
+ if any(self._other(link, alias) not in scope for link in links):
234
+ # An endpoint alias is not joined yet: leave the OR to the group's WHERE.
235
+ return None
236
+ branches = tuple(self._all(rel, orientation) for orientation in orientations)
237
+ self._whole.add(rel.id)
238
+ return Or(branches)
239
+ links = self._planner.links(rel, orientations[0])
240
+ candidates = [
241
+ link
242
+ for link in links
243
+ if alias in (link.row.alias, link.key.alias)
244
+ and (link.rel, link.orientation, link.index) not in self._emitted
245
+ ]
246
+ inside = [link for link in candidates if self._other(link, alias) in self._aliases]
247
+ chosen = inside or [link for link in candidates if self._other(link, alias) in self._outer]
248
+ if not chosen:
249
+ return None
250
+ for link in chosen:
251
+ self._emitted.add((link.rel, link.orientation, link.index))
252
+ return _and(tuple(self._join_eq(link, alias) for link in chosen))
253
+
254
+ def _join_eq(self, link: _Link, alias: str) -> SqlExpr:
255
+ """New alias on the left of `ON`, as in the tutorial."""
256
+ if link.key.alias == alias:
257
+ return link.reversed()
258
+ return link.equality()
259
+
260
+ def _all(self, rel: BRel, orientation: Orientation) -> SqlExpr:
261
+ links = self._planner.links(rel, orientation)
262
+ for link in links:
263
+ self._emitted.add((link.rel, link.orientation, link.index))
264
+ return _and(tuple(link.equality() for link in links))
265
+
266
+ def _other(self, link: _Link, alias: str) -> str:
267
+ return link.key.alias if link.row.alias == alias else link.row.alias
268
+
269
+ # ---------------------------------------------------------------- leftovers
270
+
271
+ def _leftovers(self) -> None:
272
+ for rel in self._rels:
273
+ if rel.id in self._whole:
274
+ continue
275
+ orientations = _orientations(rel)
276
+ if len(orientations) > 1:
277
+ # One undirected edge between two ends is (forward) OR (backward).
278
+ self._where.append(Or(tuple(self._all(rel, item) for item in orientations)))
279
+ continue
280
+ for link in self._planner.links(rel, orientations[0]):
281
+ if (link.rel, link.orientation, link.index) not in self._emitted:
282
+ self._where.append(link.equality())