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,701 @@
|
|
|
1
|
+
"""One `MATCH` path becomes bound IR: nodes, relationships, trails and their properties.
|
|
2
|
+
|
|
3
|
+
The slots the resolver filled are laid out into `BNode`/`BRel`/`BPath` forms with their inline
|
|
4
|
+
property predicates, uniqueness trails and inferred expansions; a subquery body is built into its
|
|
5
|
+
own body with the enclosing names visible to it. Nothing here writes SQL or names an alias."""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import cast
|
|
10
|
+
|
|
11
|
+
from cypher2sql._ast import (
|
|
12
|
+
And,
|
|
13
|
+
ExistsSubquery,
|
|
14
|
+
Expr,
|
|
15
|
+
Length,
|
|
16
|
+
Name,
|
|
17
|
+
NodePat,
|
|
18
|
+
Path,
|
|
19
|
+
PatternPredicate,
|
|
20
|
+
RelPat,
|
|
21
|
+
Where,
|
|
22
|
+
)
|
|
23
|
+
from cypher2sql._errors import (
|
|
24
|
+
CypherSemanticError,
|
|
25
|
+
LimitExceededError,
|
|
26
|
+
Span,
|
|
27
|
+
UnsupportedCypherError,
|
|
28
|
+
_limit_hint,
|
|
29
|
+
bounded_text,
|
|
30
|
+
)
|
|
31
|
+
from cypher2sql._ir import (
|
|
32
|
+
BExpr,
|
|
33
|
+
BInferred,
|
|
34
|
+
BNode,
|
|
35
|
+
BNodeRef,
|
|
36
|
+
BPath,
|
|
37
|
+
BRecursive,
|
|
38
|
+
BRel,
|
|
39
|
+
BTrail,
|
|
40
|
+
BUntypedRecursive,
|
|
41
|
+
Orientation,
|
|
42
|
+
carrier,
|
|
43
|
+
edge_identity,
|
|
44
|
+
walk_identities,
|
|
45
|
+
)
|
|
46
|
+
from cypher2sql._schema import (
|
|
47
|
+
EdgeType,
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
from ._base import (
|
|
51
|
+
_PATTERN_VARIABLE_HINT,
|
|
52
|
+
_Chain,
|
|
53
|
+
_EdgeResolution,
|
|
54
|
+
_ExpansionResolution,
|
|
55
|
+
_NodeSlot,
|
|
56
|
+
_Parts,
|
|
57
|
+
_PathResolution,
|
|
58
|
+
_RecursiveResolution,
|
|
59
|
+
_RelSlot,
|
|
60
|
+
_UntypedResolution,
|
|
61
|
+
)
|
|
62
|
+
from ._edges import _as_chain, _deepest, _hop, _zero_left_key
|
|
63
|
+
from ._patterns import _Patterns
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _constraint_groups(expr: Expr) -> tuple[tuple[Path, ...], ...]:
|
|
67
|
+
"""The pattern groups a `WHERE` contributes to its clause's type inference.
|
|
68
|
+
|
|
69
|
+
Only a pattern in *positive* conjunctive position constrains anything: `(n)-[:T]->()` says
|
|
70
|
+
`n` can be `:T`'s source, while `NOT (n)-[:T]->()` and `a OR b` say nothing (a node of
|
|
71
|
+
another label simply satisfies the negation). Groups are flattened into the clause's slot
|
|
72
|
+
machine, never built, so they only narrow labels and are charged by their own bodies.
|
|
73
|
+
"""
|
|
74
|
+
match expr:
|
|
75
|
+
case And(items=items):
|
|
76
|
+
return tuple(group for item in items for group in _constraint_groups(item))
|
|
77
|
+
case PatternPredicate(path=path):
|
|
78
|
+
return ((path,),)
|
|
79
|
+
case ExistsSubquery(clauses=clauses):
|
|
80
|
+
body: tuple[Path, ...] = tuple(path for clause in clauses for path in clause.paths)
|
|
81
|
+
nested = tuple(
|
|
82
|
+
group
|
|
83
|
+
for clause in clauses
|
|
84
|
+
if clause.where is not None
|
|
85
|
+
for group in _constraint_groups(clause.where.expr)
|
|
86
|
+
)
|
|
87
|
+
return (body, *nested)
|
|
88
|
+
case _:
|
|
89
|
+
return ()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class _Build(_Patterns):
|
|
93
|
+
"""Building bound IR out of resolved pattern slots."""
|
|
94
|
+
|
|
95
|
+
def _pattern(self, paths: tuple[Path, ...], where: Where | None, span: Span) -> _Parts:
|
|
96
|
+
"""Flatten, resolve and build one clause; the parts, names, trails and satisfiability.
|
|
97
|
+
|
|
98
|
+
The `WHERE`'s positive pattern predicates and `EXISTS` bodies are flattened *first*, as
|
|
99
|
+
constraint-only slots: an unlabeled node in `MATCH` is narrowed by the pattern that
|
|
100
|
+
filters it, exactly as a JOIN would. They are never built here, so they are charged when
|
|
101
|
+
their own body is bound — once, against the same `max_pattern_size`.
|
|
102
|
+
"""
|
|
103
|
+
elements = sum(len(path.elements) for path in paths)
|
|
104
|
+
limit = self._schema.limits.max_pattern_size
|
|
105
|
+
self._used += elements
|
|
106
|
+
if self._used > limit:
|
|
107
|
+
raise LimitExceededError(
|
|
108
|
+
f"pattern has {self._used} elements; max_pattern_size is {limit}",
|
|
109
|
+
query=self._text,
|
|
110
|
+
span=span,
|
|
111
|
+
hint=_limit_hint("max_pattern_size", "write a shorter pattern"),
|
|
112
|
+
)
|
|
113
|
+
constraints = () if where is None else _constraint_groups(where.expr)
|
|
114
|
+
self._flatten(paths, constraints)
|
|
115
|
+
charged = self._check_expansions(self._used, paths, span)
|
|
116
|
+
self._infer()
|
|
117
|
+
return self._build(paths, span, limit, charged)
|
|
118
|
+
|
|
119
|
+
def _flatten(
|
|
120
|
+
self, paths: tuple[Path, ...], constraints: tuple[tuple[Path, ...], ...] = ()
|
|
121
|
+
) -> None:
|
|
122
|
+
"""Turn the paths into node and relationship slots, reusing a variable's slot.
|
|
123
|
+
|
|
124
|
+
Every label and type position is resolved here, before inference, so a `$param` selector
|
|
125
|
+
is already the declared name the rest of the binder reasons about. A relationship whose
|
|
126
|
+
length is exactly `*0..0` adds no slot: its right node *is* its left node. A variable a
|
|
127
|
+
previous clause declared names the node it already names: the pattern element constrains
|
|
128
|
+
that node (one static label, so a different label is a semantic error), it does not add a
|
|
129
|
+
second one.
|
|
130
|
+
|
|
131
|
+
Each constraint group is one predicate's pattern (or one `EXISTS` body) and gets its own
|
|
132
|
+
copy of the names: a variable it declares is local to it, so two subqueries may both use
|
|
133
|
+
`m` without meeting. A name it only *reuses* is the outer one, which is what correlates.
|
|
134
|
+
"""
|
|
135
|
+
variables: dict[str, int] = {}
|
|
136
|
+
self._flatten_paths(paths, 0, variables, constraint=False)
|
|
137
|
+
first = len(paths)
|
|
138
|
+
for group in constraints:
|
|
139
|
+
self._flatten_paths(group, first, dict(variables), constraint=True)
|
|
140
|
+
first += len(group)
|
|
141
|
+
|
|
142
|
+
def _flatten_paths(
|
|
143
|
+
self,
|
|
144
|
+
paths: tuple[Path, ...],
|
|
145
|
+
first_path: int,
|
|
146
|
+
variables: dict[str, int],
|
|
147
|
+
*,
|
|
148
|
+
constraint: bool,
|
|
149
|
+
) -> None:
|
|
150
|
+
"""Flatten one group of paths, starting at pattern position `first_path`."""
|
|
151
|
+
zero_relationships: set[tuple[int, int]] = set()
|
|
152
|
+
for offset, path in enumerate(paths):
|
|
153
|
+
path_index = first_path + offset
|
|
154
|
+
for index, element in enumerate(path.elements):
|
|
155
|
+
if not isinstance(element, NodePat):
|
|
156
|
+
continue
|
|
157
|
+
key = (path_index, index)
|
|
158
|
+
left_key = _zero_left_key(path.elements, path_index, index)
|
|
159
|
+
if left_key is not None:
|
|
160
|
+
zero_relationships.add((path_index, index - 1))
|
|
161
|
+
self._unify_zero_node(key, left_key, element, variables)
|
|
162
|
+
continue
|
|
163
|
+
reused = element.var.text if element.var is not None else None
|
|
164
|
+
slot = _NodeSlot(element, self._node_label(element), constraint)
|
|
165
|
+
if reused is not None and reused in variables:
|
|
166
|
+
first = variables[reused]
|
|
167
|
+
self._check_reused_label(self._node_slots[first].label, slot)
|
|
168
|
+
elif element.var is not None and reused in self._variables:
|
|
169
|
+
slot.bound = self._reuse(element.var, slot.label)
|
|
170
|
+
group = self._optional_of.get(element.var.text)
|
|
171
|
+
if group is not None and self._optional_group is None:
|
|
172
|
+
# A mandatory pattern element naming a variable an earlier OPTIONAL
|
|
173
|
+
# MATCH may leave unbound requires it to be present: a bare `(b)` is a
|
|
174
|
+
# node pattern, and NULL is not a node. An optional clause naming it
|
|
175
|
+
# does not: its expansion simply matches nothing for a null variable.
|
|
176
|
+
self._present_groups.add(group)
|
|
177
|
+
first = len(self._node_slots)
|
|
178
|
+
self._node_slots.append(slot)
|
|
179
|
+
variables[element.var.text] = first
|
|
180
|
+
else:
|
|
181
|
+
if reused is not None and self._refuse_new and not constraint:
|
|
182
|
+
raise self._unknown_variable(
|
|
183
|
+
reused,
|
|
184
|
+
element.var.span if element.var else element.span,
|
|
185
|
+
_PATTERN_VARIABLE_HINT,
|
|
186
|
+
)
|
|
187
|
+
first = len(self._node_slots)
|
|
188
|
+
self._node_slots.append(slot)
|
|
189
|
+
if reused is not None:
|
|
190
|
+
variables[reused] = first
|
|
191
|
+
self._node_slot_by_key[key] = first
|
|
192
|
+
relation_variables: set[str] = set()
|
|
193
|
+
for offset, path in enumerate(paths):
|
|
194
|
+
path_index = first_path + offset
|
|
195
|
+
for index, element in enumerate(path.elements):
|
|
196
|
+
if not isinstance(element, RelPat):
|
|
197
|
+
continue
|
|
198
|
+
if element.var is not None:
|
|
199
|
+
# A name an earlier clause gave a relationship would mean that same row;
|
|
200
|
+
# binding it afresh would silently drop the equality, so it is refused too.
|
|
201
|
+
if element.var.text in self._rel_vars:
|
|
202
|
+
bound_in = "an earlier clause"
|
|
203
|
+
elif element.var.text in relation_variables:
|
|
204
|
+
bound_in = "this clause"
|
|
205
|
+
else:
|
|
206
|
+
bound_in = None
|
|
207
|
+
if bound_in is not None and not constraint:
|
|
208
|
+
raise UnsupportedCypherError(
|
|
209
|
+
f"relationship variable {bounded_text(element.var.text)} is already "
|
|
210
|
+
f"bound in {bound_in}",
|
|
211
|
+
query=self._text,
|
|
212
|
+
span=element.var.span,
|
|
213
|
+
hint="give the second occurrence a new variable — cypher2sql does not "
|
|
214
|
+
"compile the equality a reused relationship variable implies",
|
|
215
|
+
)
|
|
216
|
+
if bound_in is None and self._refuse_new and not constraint:
|
|
217
|
+
raise self._unknown_variable(
|
|
218
|
+
element.var.text, element.var.span, _PATTERN_VARIABLE_HINT
|
|
219
|
+
)
|
|
220
|
+
relation_variables.add(element.var.text)
|
|
221
|
+
if (path_index, index) in zero_relationships:
|
|
222
|
+
self._zero_relationship(element)
|
|
223
|
+
continue
|
|
224
|
+
type_name = self._rel_type(element)
|
|
225
|
+
unsat, bound = self._check_length(element)
|
|
226
|
+
self._rel_slot_by_key[(path_index, index)] = len(self._rel_slots)
|
|
227
|
+
self._rel_slots.append(
|
|
228
|
+
_RelSlot(
|
|
229
|
+
element,
|
|
230
|
+
type_name,
|
|
231
|
+
path_index,
|
|
232
|
+
self._node_slot_by_key[(path_index, index - 1)],
|
|
233
|
+
self._node_slot_by_key[(path_index, index + 1)],
|
|
234
|
+
self._candidate_edges(type_name),
|
|
235
|
+
unsat,
|
|
236
|
+
bound,
|
|
237
|
+
constraint=constraint,
|
|
238
|
+
)
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
def _build(self, paths: tuple[Path, ...], span: Span, limit: int, charged: int) -> _Parts:
|
|
242
|
+
# Constraint-only slots are a predicate's own pattern, bound later by `_exists_body`;
|
|
243
|
+
# their resolution is an empty `_PathResolution` and says nothing about this clause's
|
|
244
|
+
# paths. Counting them would turn one inline inferred path into a row-nested `EXISTS`
|
|
245
|
+
# just because an unrelated pattern predicate is written beside it.
|
|
246
|
+
self._inline = all(
|
|
247
|
+
slot.constraint
|
|
248
|
+
or not isinstance(resolution, _PathResolution)
|
|
249
|
+
or len(resolution.alternatives) == 1
|
|
250
|
+
for slot, resolution in zip(self._rel_slots, self._resolutions, strict=True)
|
|
251
|
+
)
|
|
252
|
+
nodes: list[BNode] = []
|
|
253
|
+
rels: list[BRel] = []
|
|
254
|
+
inferred: list[BInferred] = []
|
|
255
|
+
recursive: list[BRecursive | BUntypedRecursive] = []
|
|
256
|
+
trails: list[BTrail] = []
|
|
257
|
+
properties: list[BExpr] = []
|
|
258
|
+
built: dict[int, BNode] = {}
|
|
259
|
+
reserved: dict[tuple[int, int], int] = {}
|
|
260
|
+
next_node = self._next_node
|
|
261
|
+
next_rel = self._next_rel
|
|
262
|
+
for path_index, path in enumerate(paths):
|
|
263
|
+
trail_rels: list[BRel] = []
|
|
264
|
+
trail_expansions: list[int] = []
|
|
265
|
+
trail_recursions: list[int] = []
|
|
266
|
+
for index, element in enumerate(path.elements):
|
|
267
|
+
match element:
|
|
268
|
+
case NodePat():
|
|
269
|
+
slot = self._node_slot_by_key[(path_index, index)]
|
|
270
|
+
node = built.get(slot)
|
|
271
|
+
if node is None:
|
|
272
|
+
bound = self._node_slots[slot].bound
|
|
273
|
+
if bound is not None:
|
|
274
|
+
# Declared by an earlier clause: the element names that node.
|
|
275
|
+
node = bound
|
|
276
|
+
else:
|
|
277
|
+
node_id = reserved.pop((path_index, index), next_node)
|
|
278
|
+
node = BNode(node_id, self._node_candidates[slot][0])
|
|
279
|
+
next_node = max(next_node, node_id + 1)
|
|
280
|
+
nodes.append(node)
|
|
281
|
+
built[slot] = node
|
|
282
|
+
properties.extend(self._node_properties(node, element))
|
|
283
|
+
if element.var is not None:
|
|
284
|
+
self._declare(element.var, element.var.text in self._rel_vars)
|
|
285
|
+
self._variables[element.var.text] = node
|
|
286
|
+
case RelPat():
|
|
287
|
+
slot_index = self._rel_slot_by_key.get((path_index, index))
|
|
288
|
+
if slot_index is None:
|
|
289
|
+
# `*0..0`: the right node is already the left node, no row read.
|
|
290
|
+
if element.var is not None:
|
|
291
|
+
self._declare(element.var, element.var.text in self._variables)
|
|
292
|
+
self._rel_vars[element.var.text] = (None, element)
|
|
293
|
+
continue
|
|
294
|
+
rels_before, inferred_before = len(rels), len(inferred)
|
|
295
|
+
recursive_before = len(recursive)
|
|
296
|
+
next_node, next_rel = self._relationship(
|
|
297
|
+
path_index,
|
|
298
|
+
index,
|
|
299
|
+
built,
|
|
300
|
+
reserved,
|
|
301
|
+
nodes,
|
|
302
|
+
rels,
|
|
303
|
+
inferred,
|
|
304
|
+
recursive,
|
|
305
|
+
properties,
|
|
306
|
+
next_node,
|
|
307
|
+
next_rel,
|
|
308
|
+
)
|
|
309
|
+
trail_rels.extend(rels[rels_before:])
|
|
310
|
+
for created_index in range(inferred_before, len(inferred)):
|
|
311
|
+
trail_expansions.append(created_index)
|
|
312
|
+
self._inferred_slot[created_index] = slot_index
|
|
313
|
+
for created_index in range(recursive_before, len(recursive)):
|
|
314
|
+
trail_recursions.append(created_index)
|
|
315
|
+
self._recursive_slot[created_index] = slot_index
|
|
316
|
+
if element.var is not None:
|
|
317
|
+
self._declare(element.var, element.var.text in self._variables)
|
|
318
|
+
resolution = self._resolutions[slot_index]
|
|
319
|
+
created = rels[-1] if isinstance(resolution, _EdgeResolution) else None
|
|
320
|
+
self._rel_vars[element.var.text] = (created, element)
|
|
321
|
+
trails.append(
|
|
322
|
+
BTrail(
|
|
323
|
+
tuple(trail_rels),
|
|
324
|
+
tuple(trail_expansions),
|
|
325
|
+
tuple(trail_recursions),
|
|
326
|
+
self._clause,
|
|
327
|
+
)
|
|
328
|
+
)
|
|
329
|
+
self._next_node = next_node
|
|
330
|
+
self._next_rel = next_rel
|
|
331
|
+
self._reject_shared_inferred_rows(trails, inferred, recursive)
|
|
332
|
+
# Expansions were charged exactly by `_check_expansions`; what can still grow here is an
|
|
333
|
+
# untyped relationship's inferred alternatives, each emitting its own `EXISTS`.
|
|
334
|
+
total = charged + sum(
|
|
335
|
+
len(alternative.nodes) + len(alternative.rels)
|
|
336
|
+
for index, relation in enumerate(inferred)
|
|
337
|
+
if not self._expanding(index)
|
|
338
|
+
for alternative in relation.alternatives
|
|
339
|
+
)
|
|
340
|
+
if total > limit:
|
|
341
|
+
raise LimitExceededError(
|
|
342
|
+
f"pattern has {total} elements; max_pattern_size is {limit}",
|
|
343
|
+
query=self._text,
|
|
344
|
+
span=span,
|
|
345
|
+
hint=_limit_hint("max_pattern_size", "write a shorter pattern"),
|
|
346
|
+
)
|
|
347
|
+
self._used = total
|
|
348
|
+
nodes.sort(key=lambda node: node.id)
|
|
349
|
+
return _Parts(
|
|
350
|
+
tuple(nodes),
|
|
351
|
+
tuple(rels),
|
|
352
|
+
tuple(inferred),
|
|
353
|
+
tuple(recursive),
|
|
354
|
+
tuple(trails),
|
|
355
|
+
tuple(properties),
|
|
356
|
+
any(slot.unsat for slot in self._rel_slots),
|
|
357
|
+
)
|
|
358
|
+
|
|
359
|
+
def _reject_shared_inferred_rows(
|
|
360
|
+
self,
|
|
361
|
+
trails: list[BTrail],
|
|
362
|
+
inferred: list[BInferred],
|
|
363
|
+
recursive: list[BRecursive | BUntypedRecursive],
|
|
364
|
+
) -> None:
|
|
365
|
+
"""Refuse two occurrences in one path whose rows one check cannot compare.
|
|
366
|
+
|
|
367
|
+
Every inferred occurrence is its own `EXISTS` (a join expansion) or its own
|
|
368
|
+
`WITH RECURSIVE` walk, so their hop rows cannot be compared: two of them could both read
|
|
369
|
+
the same row and return it. An untyped walk reads every edge it can stand on, so it shares
|
|
370
|
+
a row stream with any other occurrence that reads one of those edges. A trail whose
|
|
371
|
+
occurrences all fit one row stream would need one walk over the whole path, which is not
|
|
372
|
+
built; the pattern is refused rather than compiled with a missing uniqueness check.
|
|
373
|
+
"""
|
|
374
|
+
for trail in trails:
|
|
375
|
+
occurrences: list[tuple[int, tuple[tuple[str, str, str], ...], str]] = []
|
|
376
|
+
for index in trail.expansions:
|
|
377
|
+
occurrences.append(
|
|
378
|
+
(
|
|
379
|
+
self._inferred_slot[index],
|
|
380
|
+
tuple(
|
|
381
|
+
dict.fromkeys(
|
|
382
|
+
edge_identity(rel.edge_type)
|
|
383
|
+
for path in inferred[index].alternatives
|
|
384
|
+
for rel in path.rels
|
|
385
|
+
)
|
|
386
|
+
),
|
|
387
|
+
"expansion" if self._expanding(index) else "inferred",
|
|
388
|
+
)
|
|
389
|
+
)
|
|
390
|
+
for index in trail.recursions:
|
|
391
|
+
walk = recursive[index]
|
|
392
|
+
occurrences.append(
|
|
393
|
+
(
|
|
394
|
+
self._recursive_slot[index],
|
|
395
|
+
walk_identities(walk),
|
|
396
|
+
"untyped" if isinstance(walk, BUntypedRecursive) else "recursive",
|
|
397
|
+
)
|
|
398
|
+
)
|
|
399
|
+
for position, (first, left, first_kind) in enumerate(occurrences):
|
|
400
|
+
for second, right, second_kind in occurrences[position + 1 :]:
|
|
401
|
+
shared = set(left) & set(right)
|
|
402
|
+
if not shared:
|
|
403
|
+
continue
|
|
404
|
+
# Written order, never set order: the same query names the same type.
|
|
405
|
+
name = next(identity[0] for identity in left if identity in shared)
|
|
406
|
+
walkable = ("expansion", "recursive")
|
|
407
|
+
if "untyped" in (first_kind, second_kind):
|
|
408
|
+
if first_kind == second_kind:
|
|
409
|
+
what = "two untyped variable-length relationships"
|
|
410
|
+
else:
|
|
411
|
+
what = (
|
|
412
|
+
"an untyped variable-length relationship and another "
|
|
413
|
+
f"[:{name}] relationship"
|
|
414
|
+
)
|
|
415
|
+
culprit = second
|
|
416
|
+
hint = (
|
|
417
|
+
"use one variable-length relationship per path; the two walks "
|
|
418
|
+
"cannot share one uniqueness check"
|
|
419
|
+
)
|
|
420
|
+
elif first_kind in walkable and second_kind in walkable:
|
|
421
|
+
what = f"two variable-length [:{name}] relationships"
|
|
422
|
+
culprit = second
|
|
423
|
+
hint = (
|
|
424
|
+
"use one variable-length relationship per path; the two walks "
|
|
425
|
+
"cannot share one uniqueness check"
|
|
426
|
+
)
|
|
427
|
+
elif first_kind in walkable or second_kind in walkable:
|
|
428
|
+
what = (
|
|
429
|
+
f"a variable-length [:{name}] relationship and another inferred "
|
|
430
|
+
f"[:{name}] path"
|
|
431
|
+
)
|
|
432
|
+
culprit = first if first_kind in walkable else second
|
|
433
|
+
hint = (
|
|
434
|
+
"use one variable-length relationship per path; the two walks "
|
|
435
|
+
"cannot share one uniqueness check"
|
|
436
|
+
)
|
|
437
|
+
else:
|
|
438
|
+
what = f"two inferred [:{name}] relationships"
|
|
439
|
+
culprit = second
|
|
440
|
+
hint = (
|
|
441
|
+
"use one inferred relationship per path; the two paths "
|
|
442
|
+
"cannot share one uniqueness check"
|
|
443
|
+
)
|
|
444
|
+
slot = self._rel_slots[culprit]
|
|
445
|
+
length = slot.bound
|
|
446
|
+
raise UnsupportedCypherError(
|
|
447
|
+
f"a path with {what} is not supported yet",
|
|
448
|
+
query=self._text,
|
|
449
|
+
span=length.span if length is not None else slot.pattern.span,
|
|
450
|
+
hint=hint,
|
|
451
|
+
)
|
|
452
|
+
|
|
453
|
+
def _expanding(self, index: int) -> bool:
|
|
454
|
+
"""Whether these inferred alternatives are the lengths of a `[*a..b]`."""
|
|
455
|
+
return self._rel_slots[self._inferred_slot[index]].pattern.length is not None
|
|
456
|
+
|
|
457
|
+
def _declare(self, name: Name, clash: bool) -> None:
|
|
458
|
+
"""A node may be named twice in one pattern; a node and a relationship may not share."""
|
|
459
|
+
if clash:
|
|
460
|
+
raise CypherSemanticError(
|
|
461
|
+
f"variable {bounded_text(name.text)} is already declared",
|
|
462
|
+
query=self._text,
|
|
463
|
+
span=name.span,
|
|
464
|
+
hint="give each node and relationship its own name",
|
|
465
|
+
)
|
|
466
|
+
# A name a WITH dropped can be declared again by a later clause; from then on it is not
|
|
467
|
+
# a dropped name any more, so a later unknown reference gets the ordinary hint.
|
|
468
|
+
self._dropped.discard(name.text)
|
|
469
|
+
|
|
470
|
+
# Long parameter list: one relationship step threads the whole build state.
|
|
471
|
+
def _relationship(
|
|
472
|
+
self,
|
|
473
|
+
path_index: int,
|
|
474
|
+
index: int,
|
|
475
|
+
built: dict[int, BNode],
|
|
476
|
+
reserved: dict[tuple[int, int], int],
|
|
477
|
+
nodes: list[BNode],
|
|
478
|
+
rels: list[BRel],
|
|
479
|
+
inferred: list[BInferred],
|
|
480
|
+
recursive: list[BRecursive | BUntypedRecursive],
|
|
481
|
+
properties: list[BExpr],
|
|
482
|
+
next_node: int,
|
|
483
|
+
next_rel: int,
|
|
484
|
+
) -> tuple[int, int]:
|
|
485
|
+
"""Build the nodes and edges one relationship element stands for."""
|
|
486
|
+
slot_index = self._rel_slot_by_key[(path_index, index)]
|
|
487
|
+
slot = self._rel_slots[slot_index]
|
|
488
|
+
right_slot = self._node_slot_by_key[(path_index, index + 1)]
|
|
489
|
+
right_key = (path_index, index + 1)
|
|
490
|
+
previous = built[self._node_slot_by_key[(path_index, index - 1)]]
|
|
491
|
+
known = self._node_slots[right_slot].bound
|
|
492
|
+
# A node declared by an earlier clause is already known: an element naming it must not
|
|
493
|
+
# reserve a fresh position, which would give the relationship an id no node has.
|
|
494
|
+
right_id = (
|
|
495
|
+
built[right_slot].id
|
|
496
|
+
if right_slot in built
|
|
497
|
+
else (known.id if known is not None else None)
|
|
498
|
+
)
|
|
499
|
+
if slot.unsat:
|
|
500
|
+
# An empty interval matches nothing: reserve the right node so later elements keep
|
|
501
|
+
# their pattern positions; `bind` turns the whole query into `WHERE FALSE`.
|
|
502
|
+
if right_id is None:
|
|
503
|
+
reserved[right_key] = next_node
|
|
504
|
+
next_node += 1
|
|
505
|
+
return next_node, next_rel
|
|
506
|
+
resolution = self._resolutions[slot_index]
|
|
507
|
+
pattern = slot.pattern
|
|
508
|
+
match resolution:
|
|
509
|
+
case _EdgeResolution(edge=edge, orientations=orientations):
|
|
510
|
+
if right_id is None:
|
|
511
|
+
right_id = next_node
|
|
512
|
+
reserved[right_key] = right_id
|
|
513
|
+
next_node += 1
|
|
514
|
+
rel = BRel(next_rel, edge, previous.id, right_id, orientations, carrier(edge))
|
|
515
|
+
next_rel += 1
|
|
516
|
+
rels.append(rel)
|
|
517
|
+
properties.extend(self._rel_properties(rel, pattern))
|
|
518
|
+
case _PathResolution(alternatives=alternatives):
|
|
519
|
+
if pattern.props:
|
|
520
|
+
raise UnsupportedCypherError(
|
|
521
|
+
"a property map on an inferred path is not supported yet",
|
|
522
|
+
query=self._text,
|
|
523
|
+
span=pattern.span,
|
|
524
|
+
)
|
|
525
|
+
if not self._inline:
|
|
526
|
+
if right_id is None:
|
|
527
|
+
right_id = next_node
|
|
528
|
+
reserved[right_key] = right_id
|
|
529
|
+
next_node += 1
|
|
530
|
+
paths: list[BPath] = []
|
|
531
|
+
for steps in alternatives:
|
|
532
|
+
ids = list(range(next_node, next_node + len(steps) - 1))
|
|
533
|
+
next_node += len(steps) - 1
|
|
534
|
+
paths.append(
|
|
535
|
+
self._chain([previous.id, *ids, right_id], _as_chain(steps), next_rel)
|
|
536
|
+
)
|
|
537
|
+
next_rel += len(steps)
|
|
538
|
+
inferred.append(BInferred(previous.id, right_id, tuple(paths)))
|
|
539
|
+
else:
|
|
540
|
+
steps = alternatives[0]
|
|
541
|
+
ids = list(range(next_node, next_node + len(steps) - 1))
|
|
542
|
+
next_node += len(steps) - 1
|
|
543
|
+
if right_id is None:
|
|
544
|
+
right_id = next_node
|
|
545
|
+
reserved[right_key] = right_id
|
|
546
|
+
next_node += 1
|
|
547
|
+
built_path = self._chain(
|
|
548
|
+
[previous.id, *ids, right_id], _as_chain(steps), next_rel
|
|
549
|
+
)
|
|
550
|
+
next_rel += len(steps)
|
|
551
|
+
nodes.extend(built_path.nodes)
|
|
552
|
+
rels.extend(built_path.rels)
|
|
553
|
+
case _ExpansionResolution(alternatives=chains):
|
|
554
|
+
if right_id is None:
|
|
555
|
+
right_id = next_node
|
|
556
|
+
reserved[right_key] = right_id
|
|
557
|
+
next_node += 1
|
|
558
|
+
paths = []
|
|
559
|
+
for chain in chains:
|
|
560
|
+
ids = list(range(next_node, next_node + len(chain) - 1))
|
|
561
|
+
next_node += max(len(chain) - 1, 0)
|
|
562
|
+
paths.append(self._chain([previous.id, *ids, right_id], chain, next_rel))
|
|
563
|
+
next_rel += len(chain)
|
|
564
|
+
inferred.append(BInferred(previous.id, right_id, tuple(paths)))
|
|
565
|
+
case _RecursiveResolution(edge=edge):
|
|
566
|
+
if right_id is None:
|
|
567
|
+
right_id = next_node
|
|
568
|
+
reserved[right_key] = right_id
|
|
569
|
+
next_node += 1
|
|
570
|
+
recursive.append(self._recursive(edge, slot, previous.id, right_id))
|
|
571
|
+
case _UntypedResolution(base=base, steps=steps, max_depth=max_depth):
|
|
572
|
+
if right_id is None:
|
|
573
|
+
right_id = next_node
|
|
574
|
+
reserved[right_key] = right_id
|
|
575
|
+
next_node += 1
|
|
576
|
+
bound = cast(Length, slot.bound)
|
|
577
|
+
# Zero hops make both ends the same node. Two different labels can never be one
|
|
578
|
+
# node, so a `*0..b` that starts at zero must not OR the key equality in; the
|
|
579
|
+
# exact `*0..0` case already unified both ends (or refused differing labels).
|
|
580
|
+
left_label = self._node_candidates[slot.left][0].label
|
|
581
|
+
right_label = self._node_candidates[slot.right][0].label
|
|
582
|
+
min_depth = 1 if bound.min == 0 and left_label != right_label else bound.min
|
|
583
|
+
recursive.append(
|
|
584
|
+
BUntypedRecursive(previous.id, right_id, min_depth, max_depth, base, steps)
|
|
585
|
+
)
|
|
586
|
+
return next_node, next_rel
|
|
587
|
+
|
|
588
|
+
def _recursive(self, edge: EdgeType, slot: _RelSlot, left: int, right: int) -> BRecursive:
|
|
589
|
+
"""Shape one `WITH RECURSIVE` walk: its hop branches and its deepest useful depth.
|
|
590
|
+
|
|
591
|
+
The first hop leaves the left node in an orientation its label allows; a later hop leaves
|
|
592
|
+
the node the previous row arrived at, which may be either end of that row. Both come from
|
|
593
|
+
`_hop`, the same one-hop rule the join tier walks, so the two tiers cannot drift. A walk of
|
|
594
|
+
one declared edge alternates the two endpoint labels (or stays on a self-labelled one), so
|
|
595
|
+
`_deepest` finds the deepest hop count that lands on the right endpoint by label parity,
|
|
596
|
+
never by walking every length in the bound.
|
|
597
|
+
"""
|
|
598
|
+
bound = cast(Length, slot.bound)
|
|
599
|
+
left_label = self._node_candidates[slot.left][0].label
|
|
600
|
+
right_label = self._node_candidates[slot.right][0].label
|
|
601
|
+
direction = slot.pattern.direction
|
|
602
|
+
first = _hop(edge, direction, left_label)
|
|
603
|
+
base = (
|
|
604
|
+
()
|
|
605
|
+
if first is None
|
|
606
|
+
else tuple(
|
|
607
|
+
orientation
|
|
608
|
+
for orientation in (Orientation.FORWARD, Orientation.BACKWARD)
|
|
609
|
+
if orientation in first[1]
|
|
610
|
+
)
|
|
611
|
+
)
|
|
612
|
+
steps: list[tuple[bool, Orientation]] = []
|
|
613
|
+
for at_target in (False, True):
|
|
614
|
+
current = edge.target.label if at_target else edge.source.label
|
|
615
|
+
hop = _hop(edge, direction, current)
|
|
616
|
+
if hop is None:
|
|
617
|
+
continue
|
|
618
|
+
steps.extend(
|
|
619
|
+
(at_target, orientation)
|
|
620
|
+
for orientation in (Orientation.FORWARD, Orientation.BACKWARD)
|
|
621
|
+
if orientation in hop[1]
|
|
622
|
+
)
|
|
623
|
+
deepest = _deepest(
|
|
624
|
+
edge, direction, left_label, right_label, bound.min, cast(int, bound.max)
|
|
625
|
+
)
|
|
626
|
+
return BRecursive(
|
|
627
|
+
left,
|
|
628
|
+
right,
|
|
629
|
+
edge,
|
|
630
|
+
bound.min,
|
|
631
|
+
deepest,
|
|
632
|
+
base,
|
|
633
|
+
tuple(steps),
|
|
634
|
+
)
|
|
635
|
+
|
|
636
|
+
def _chain(self, chain: list[int], steps: _Chain, first: int) -> BPath:
|
|
637
|
+
"""Build the intermediate nodes and edges of one path; `chain` ends at the right node."""
|
|
638
|
+
intermediate: list[BNode] = []
|
|
639
|
+
rels: list[BRel] = []
|
|
640
|
+
for step_index, (edge, orientations) in enumerate(steps):
|
|
641
|
+
node_id = chain[step_index + 1]
|
|
642
|
+
if step_index < len(steps) - 1:
|
|
643
|
+
edge_end = edge.target if Orientation.FORWARD in orientations else edge.source
|
|
644
|
+
intermediate.append(BNode(node_id, edge_end))
|
|
645
|
+
rels.append(
|
|
646
|
+
BRel(
|
|
647
|
+
first + step_index,
|
|
648
|
+
edge,
|
|
649
|
+
chain[step_index],
|
|
650
|
+
node_id,
|
|
651
|
+
orientations,
|
|
652
|
+
carrier(edge),
|
|
653
|
+
declared=False,
|
|
654
|
+
)
|
|
655
|
+
)
|
|
656
|
+
return BPath(tuple(intermediate), tuple(rels))
|
|
657
|
+
|
|
658
|
+
def _node_properties(self, node: BNode, pattern: NodePat) -> list[BExpr]:
|
|
659
|
+
predicates: list[BExpr] = []
|
|
660
|
+
seen: set[str] = set()
|
|
661
|
+
for entry in pattern.props:
|
|
662
|
+
key = entry.key.text
|
|
663
|
+
if key in seen:
|
|
664
|
+
raise CypherSemanticError(
|
|
665
|
+
f"duplicate property {bounded_text(key)}", query=self._text, span=entry.key.span
|
|
666
|
+
)
|
|
667
|
+
seen.add(key)
|
|
668
|
+
column = node.node_type.properties.get(key)
|
|
669
|
+
if column is None:
|
|
670
|
+
raise CypherSemanticError(
|
|
671
|
+
f"unknown property {bounded_text(key)} on :{node.node_type.label}",
|
|
672
|
+
query=self._text,
|
|
673
|
+
span=entry.key.span,
|
|
674
|
+
hint=self._property_hint(node.node_type, key),
|
|
675
|
+
)
|
|
676
|
+
predicates.append(self._mapped_value(BNodeRef(node.id), column, entry.value))
|
|
677
|
+
return predicates
|
|
678
|
+
|
|
679
|
+
def _rel_properties(self, rel: BRel, pattern: RelPat) -> list[BExpr]:
|
|
680
|
+
if not pattern.props:
|
|
681
|
+
return []
|
|
682
|
+
owner = self._rel_owner(rel, pattern)
|
|
683
|
+
predicates: list[BExpr] = []
|
|
684
|
+
seen: set[str] = set()
|
|
685
|
+
for entry in pattern.props:
|
|
686
|
+
key = entry.key.text
|
|
687
|
+
if key in seen:
|
|
688
|
+
raise CypherSemanticError(
|
|
689
|
+
f"duplicate property {bounded_text(key)}", query=self._text, span=entry.key.span
|
|
690
|
+
)
|
|
691
|
+
seen.add(key)
|
|
692
|
+
column = rel.edge_type.properties.get(key)
|
|
693
|
+
if column is None:
|
|
694
|
+
raise CypherSemanticError(
|
|
695
|
+
f"unknown property {bounded_text(key)} on :{rel.edge_type.type}",
|
|
696
|
+
query=self._text,
|
|
697
|
+
span=entry.key.span,
|
|
698
|
+
hint=self._rel_property_hint(rel.edge_type, key),
|
|
699
|
+
)
|
|
700
|
+
predicates.append(self._mapped_value(owner, column, entry.value))
|
|
701
|
+
return predicates
|