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,633 @@
|
|
|
1
|
+
"""Which declared edges, and which node types, a pattern may use.
|
|
2
|
+
|
|
3
|
+
A typed relationship must name one declared edge; an untyped or undirected one may instead follow
|
|
4
|
+
the shortest declared path between its endpoints, and a node without a label is narrowed by the
|
|
5
|
+
edges around it to a fixpoint. Labels a clause's `WHERE` constrains narrow the candidates of that
|
|
6
|
+
clause. A walk no declared edge chain can satisfy is refused here, before any plan is built."""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import cast
|
|
11
|
+
|
|
12
|
+
from cypher2sql._ast import (
|
|
13
|
+
Direction,
|
|
14
|
+
LabelRef,
|
|
15
|
+
Length,
|
|
16
|
+
Name,
|
|
17
|
+
NodePat,
|
|
18
|
+
Param,
|
|
19
|
+
Path,
|
|
20
|
+
RelPat,
|
|
21
|
+
Selector,
|
|
22
|
+
)
|
|
23
|
+
from cypher2sql._errors import (
|
|
24
|
+
CypherSemanticError,
|
|
25
|
+
CypherSyntaxError,
|
|
26
|
+
LimitExceededError,
|
|
27
|
+
ParameterError,
|
|
28
|
+
Span,
|
|
29
|
+
UnsupportedCypherError,
|
|
30
|
+
_quoted_value,
|
|
31
|
+
bounded_names,
|
|
32
|
+
bounded_text,
|
|
33
|
+
)
|
|
34
|
+
from cypher2sql._infer import _columns
|
|
35
|
+
from cypher2sql._ir import (
|
|
36
|
+
BHop,
|
|
37
|
+
BNode,
|
|
38
|
+
Orientation,
|
|
39
|
+
)
|
|
40
|
+
from cypher2sql._schema import (
|
|
41
|
+
EdgeType,
|
|
42
|
+
NodeType,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
from ._base import (
|
|
46
|
+
_Chain,
|
|
47
|
+
_EdgeResolution,
|
|
48
|
+
_ExpansionResolution,
|
|
49
|
+
_NodeSlot,
|
|
50
|
+
_PathResolution,
|
|
51
|
+
_RecursiveResolution,
|
|
52
|
+
_RelSlot,
|
|
53
|
+
_Resolution,
|
|
54
|
+
_UntypedResolution,
|
|
55
|
+
)
|
|
56
|
+
from ._edges import (
|
|
57
|
+
_connects,
|
|
58
|
+
_endpoint_types,
|
|
59
|
+
_expansion_connects,
|
|
60
|
+
_expansion_ends,
|
|
61
|
+
_expansion_range,
|
|
62
|
+
_expansion_size,
|
|
63
|
+
_labels,
|
|
64
|
+
_landing_label,
|
|
65
|
+
_leaving_label,
|
|
66
|
+
_only,
|
|
67
|
+
_unique_types,
|
|
68
|
+
_untyped_ends,
|
|
69
|
+
_untyped_hops,
|
|
70
|
+
_untyped_levels,
|
|
71
|
+
_untyped_reaches,
|
|
72
|
+
_walk,
|
|
73
|
+
)
|
|
74
|
+
from ._names import _declared_hint, _name_hint
|
|
75
|
+
from ._values import _Values
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class _Patterns(_Values):
|
|
79
|
+
"""Pattern resolution: candidates, shortest paths, narrowing and walk resolution."""
|
|
80
|
+
|
|
81
|
+
def _reuse(self, name: Name, label: Name | None) -> BNode:
|
|
82
|
+
"""The node an earlier clause declared under this name, with its label re-checked."""
|
|
83
|
+
bound = self._variables[name.text]
|
|
84
|
+
if label is not None and label.text != bound.node_type.label:
|
|
85
|
+
raise CypherSemanticError(
|
|
86
|
+
f"variable {bounded_text(name.text)} is already :{bound.node_type.label}",
|
|
87
|
+
query=self._text,
|
|
88
|
+
span=label.span,
|
|
89
|
+
hint=f"use another variable for the :{bounded_text(label.text)} node",
|
|
90
|
+
)
|
|
91
|
+
return bound
|
|
92
|
+
|
|
93
|
+
def _check_length(self, element: RelPat) -> tuple[bool, Length | None]:
|
|
94
|
+
"""Resolve a variable-length bound; return whether its interval is empty.
|
|
95
|
+
|
|
96
|
+
An open-ended `*`/`*a..` is resolved by `Limits.open_path_length` first (raising
|
|
97
|
+
`LimitExceededError` when it is unset, because a path that never stops is not a query);
|
|
98
|
+
truncation at that bound is silent. A lower end past that resolved depth is an empty
|
|
99
|
+
interval, not a match-nothing query: it is refused naming the limit, like any other bound
|
|
100
|
+
past the configured one. Every bound is checked against `max_path_length` before the join
|
|
101
|
+
budget, so the recursive tier is always a bounded walk. Whether the bound names a type is
|
|
102
|
+
not decided here: a typed one is charged against the join budget later, a non-zero untyped
|
|
103
|
+
one is one walk over the declared edge set.
|
|
104
|
+
"""
|
|
105
|
+
length = element.length
|
|
106
|
+
if length is None:
|
|
107
|
+
return False, None
|
|
108
|
+
self._reject_length_properties(element)
|
|
109
|
+
reach = length.max
|
|
110
|
+
if reach is None:
|
|
111
|
+
reach = self._schema.limits.open_path_length
|
|
112
|
+
if reach is None:
|
|
113
|
+
raise LimitExceededError(
|
|
114
|
+
"an open-ended variable-length path needs Limits.open_path_length",
|
|
115
|
+
query=self._text,
|
|
116
|
+
span=length.span,
|
|
117
|
+
hint="set Limits(open_path_length=N) to bound it; N is at most "
|
|
118
|
+
f"max_path_length, {self._schema.limits.max_path_length}",
|
|
119
|
+
)
|
|
120
|
+
if length.min > reach:
|
|
121
|
+
raise LimitExceededError(
|
|
122
|
+
f"variable-length path starts at {length.min} relationships; "
|
|
123
|
+
f"open_path_length is {reach}",
|
|
124
|
+
query=self._text,
|
|
125
|
+
span=length.span,
|
|
126
|
+
hint=f"raise Limits(open_path_length={length.min}) or write a shorter "
|
|
127
|
+
"lower bound",
|
|
128
|
+
)
|
|
129
|
+
path_limit = self._schema.limits.max_path_length
|
|
130
|
+
if reach > path_limit:
|
|
131
|
+
raise LimitExceededError(
|
|
132
|
+
f"variable-length path reaches {reach} relationships; "
|
|
133
|
+
f"max_path_length is {path_limit}",
|
|
134
|
+
query=self._text,
|
|
135
|
+
span=length.span,
|
|
136
|
+
hint=f"raise Limits(max_path_length={reach}) or write a shorter bound",
|
|
137
|
+
)
|
|
138
|
+
bound = Length(length.min, reach, length.span)
|
|
139
|
+
return bound.min > reach, bound
|
|
140
|
+
|
|
141
|
+
def _check_expansions(self, elements: int, paths: tuple[Path, ...], span: Span) -> int:
|
|
142
|
+
"""Bound every join-tier expansion's emitted hops before any alternative is built.
|
|
143
|
+
|
|
144
|
+
The join plan writes one `EXISTS` per length in `min..max`, and a `k`-hop chain is `2k-1`
|
|
145
|
+
elements (k edges and k-1 intermediate nodes; zero hops emit nothing). An expansion
|
|
146
|
+
therefore stands for `sum(2k-1)` over the lengths it allows — every alternative, not just
|
|
147
|
+
the longest — and the join budget is the declared pattern plus that sum. An expansion
|
|
148
|
+
whose own sum is over `max_pattern_size`, and every open-ended one, is compiled by the
|
|
149
|
+
`WITH RECURSIVE` tier instead and is not charged; it is charged only by the depth bound.
|
|
150
|
+
A non-zero untyped bound is one walk and is never charged either: its SQL size is the
|
|
151
|
+
declared edge set, bounded by `max_edge_branches`. Returns the charged total, so the late
|
|
152
|
+
re-check adds only what the untyped relationships' inferred alternatives can still
|
|
153
|
+
contribute. Its span is the bound that pushes the running total over, not the whole `MATCH`.
|
|
154
|
+
"""
|
|
155
|
+
limit = self._schema.limits.max_pattern_size
|
|
156
|
+
contributions: list[tuple[_RelSlot, int]] = []
|
|
157
|
+
for path_index in range(len(paths)):
|
|
158
|
+
for slot in self._rel_slots:
|
|
159
|
+
length = slot.bound
|
|
160
|
+
if slot.constraint or slot.path != path_index or length is None or slot.unsat:
|
|
161
|
+
continue
|
|
162
|
+
if not length.max or slot.type_name is None:
|
|
163
|
+
continue
|
|
164
|
+
size = _expansion_size(length)
|
|
165
|
+
slot.recursive = self._rel_recursive(slot, size)
|
|
166
|
+
if not slot.recursive:
|
|
167
|
+
contributions.append((slot, size))
|
|
168
|
+
total = elements + sum(size for _, size in contributions)
|
|
169
|
+
running = elements
|
|
170
|
+
crossing: tuple[_RelSlot, int] | None = None
|
|
171
|
+
for slot, size in contributions:
|
|
172
|
+
running += size
|
|
173
|
+
if crossing is None and running > limit:
|
|
174
|
+
crossing = (slot, size)
|
|
175
|
+
if crossing is not None:
|
|
176
|
+
slot, size = crossing
|
|
177
|
+
length = cast(Length, slot.bound)
|
|
178
|
+
raise LimitExceededError(
|
|
179
|
+
f"pattern has {total} elements; max_pattern_size is {limit}",
|
|
180
|
+
query=self._text,
|
|
181
|
+
span=length.span,
|
|
182
|
+
hint=f"this bound stands for {size} elements; write a shorter bound, "
|
|
183
|
+
"or raise Limits(max_pattern_size=...)",
|
|
184
|
+
)
|
|
185
|
+
return total
|
|
186
|
+
|
|
187
|
+
def _rel_recursive(self, slot: _RelSlot, size: int) -> bool:
|
|
188
|
+
"""Whether this expansion is above the join tier: open-ended, or its hops exceed K."""
|
|
189
|
+
length = slot.pattern.length
|
|
190
|
+
if length is not None and length.max is None:
|
|
191
|
+
return True
|
|
192
|
+
return size > self._schema.limits.max_pattern_size
|
|
193
|
+
|
|
194
|
+
def _check_reused_label(self, first: Name | None, second: _NodeSlot) -> None:
|
|
195
|
+
label = second.label
|
|
196
|
+
if first is None or label is None:
|
|
197
|
+
return
|
|
198
|
+
if first.text != label.text:
|
|
199
|
+
subject = (
|
|
200
|
+
bounded_text(second.pattern.var.text)
|
|
201
|
+
if second.pattern.var is not None
|
|
202
|
+
else "a node"
|
|
203
|
+
)
|
|
204
|
+
raise CypherSemanticError(
|
|
205
|
+
f"{subject} has more than one label",
|
|
206
|
+
query=self._text,
|
|
207
|
+
span=label.span,
|
|
208
|
+
hint="give each node one label",
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
def _candidate_edges(self, type_name: Name | None) -> tuple[EdgeType, ...]:
|
|
212
|
+
if type_name is None:
|
|
213
|
+
return self._schema.edges
|
|
214
|
+
return tuple(edge for edge in self._schema.edges if edge.type == type_name.text)
|
|
215
|
+
|
|
216
|
+
def _node_label(self, pattern: NodePat) -> Name | None:
|
|
217
|
+
"""Resolve a node's label position to a declared label, once."""
|
|
218
|
+
if not pattern.labels:
|
|
219
|
+
return None
|
|
220
|
+
if len(pattern.labels) > 1:
|
|
221
|
+
first, second = pattern.labels[0], pattern.labels[1]
|
|
222
|
+
subject = bounded_text(pattern.var.text) if pattern.var is not None else "a node"
|
|
223
|
+
raise CypherSemanticError(
|
|
224
|
+
f"{subject} has more than one label",
|
|
225
|
+
query=self._text,
|
|
226
|
+
span=(first.span[0], second.span[1]),
|
|
227
|
+
hint="give each node one label",
|
|
228
|
+
)
|
|
229
|
+
return self._selector(
|
|
230
|
+
pattern.labels[0], "label", tuple(node.label for node in self._schema.nodes)
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
def _rel_type(self, pattern: RelPat) -> Name | None:
|
|
234
|
+
"""Resolve a relationship's type position to a declared type, once."""
|
|
235
|
+
if len(pattern.types) > 1:
|
|
236
|
+
raise UnsupportedCypherError(
|
|
237
|
+
"a relationship with several types is not supported yet",
|
|
238
|
+
query=self._text,
|
|
239
|
+
span=pattern.types[1].span,
|
|
240
|
+
)
|
|
241
|
+
if not pattern.types:
|
|
242
|
+
return None
|
|
243
|
+
return self._selector(
|
|
244
|
+
pattern.types[0],
|
|
245
|
+
"relationship type",
|
|
246
|
+
tuple(edge.type for edge in _unique_types(self._schema.edges)),
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
def _selector(self, ref: LabelRef, kind: str, declared: tuple[str, ...]) -> Name:
|
|
250
|
+
"""A literal name, or one `$param` naming exactly one declared label or type.
|
|
251
|
+
|
|
252
|
+
A selector is compile-time: the value only chooses among names the schema declares, so it
|
|
253
|
+
is never an identifier and never an emitted parameter, and the SQL is the literal's SQL.
|
|
254
|
+
"""
|
|
255
|
+
match ref:
|
|
256
|
+
case Name():
|
|
257
|
+
return ref
|
|
258
|
+
case Selector(param=Param(name=name, span=span)):
|
|
259
|
+
if self._template:
|
|
260
|
+
# A template's interpolations are values; a name position has no channel for
|
|
261
|
+
# one, so a `$name` left in its text cannot select anything.
|
|
262
|
+
raise CypherSyntaxError(
|
|
263
|
+
"a t-string cannot select a label or relationship type",
|
|
264
|
+
query=self._text,
|
|
265
|
+
span=span,
|
|
266
|
+
hint="write the name as text in the template; interpolations are "
|
|
267
|
+
"values, never names",
|
|
268
|
+
)
|
|
269
|
+
source = self._param_value(name, span)
|
|
270
|
+
value = source.value
|
|
271
|
+
plural = f"{kind}s"
|
|
272
|
+
if isinstance(value, (list, tuple)):
|
|
273
|
+
raise UnsupportedCypherError(
|
|
274
|
+
f"parameter {bounded_text(ref.text)} names several {plural}",
|
|
275
|
+
query=self._text,
|
|
276
|
+
span=span,
|
|
277
|
+
hint=f"use one {kind} per pattern element; matching several {plural} "
|
|
278
|
+
"at once is not supported",
|
|
279
|
+
)
|
|
280
|
+
if not isinstance(value, str):
|
|
281
|
+
raise ParameterError(
|
|
282
|
+
f"parameter {bounded_text(ref.text)} must be a declared {kind}, not "
|
|
283
|
+
f"{type(value).__name__}",
|
|
284
|
+
query=self._text,
|
|
285
|
+
span=span,
|
|
286
|
+
hint=_declared_hint(kind, declared),
|
|
287
|
+
)
|
|
288
|
+
if value not in declared:
|
|
289
|
+
raise ParameterError(
|
|
290
|
+
f"parameter {bounded_text(ref.text)} names no declared {kind}: "
|
|
291
|
+
f"{_quoted_value(value)}",
|
|
292
|
+
query=self._text,
|
|
293
|
+
span=span,
|
|
294
|
+
hint=_name_hint(value, kind, declared),
|
|
295
|
+
)
|
|
296
|
+
return Name(value, span)
|
|
297
|
+
|
|
298
|
+
def _infer(self) -> None:
|
|
299
|
+
"""Narrow node types with the declared edges to a fixpoint, then resolve relationships."""
|
|
300
|
+
self._node_candidates = [self._initial_candidates(slot) for slot in self._node_slots]
|
|
301
|
+
self._rel_allowed = [slot.candidates for slot in self._rel_slots]
|
|
302
|
+
for _ in range(self._schema.limits.max_pattern_size):
|
|
303
|
+
if not self._narrow():
|
|
304
|
+
break
|
|
305
|
+
for index, slot in enumerate(self._rel_slots):
|
|
306
|
+
# A constraint slot is only read for narrowing: its own body reports the error, with
|
|
307
|
+
# the span of the predicate that wrote it, once that body is bound.
|
|
308
|
+
if slot.constraint:
|
|
309
|
+
continue
|
|
310
|
+
if slot.type_name is not None and not self._rel_allowed[index]:
|
|
311
|
+
raise self._no_edge(slot, slot.type_name)
|
|
312
|
+
for index, node_slot in enumerate(self._node_slots):
|
|
313
|
+
if node_slot.label is not None or node_slot.bound is not None or node_slot.constraint:
|
|
314
|
+
continue
|
|
315
|
+
candidates = self._node_candidates[index]
|
|
316
|
+
if len(candidates) == 1:
|
|
317
|
+
continue
|
|
318
|
+
subject = (
|
|
319
|
+
bounded_text(node_slot.pattern.var.text)
|
|
320
|
+
if node_slot.pattern.var is not None
|
|
321
|
+
else "the pattern"
|
|
322
|
+
)
|
|
323
|
+
listed = (
|
|
324
|
+
bounded_names((node.label for node in candidates), prefix=":", separator=" or ")
|
|
325
|
+
or "none declared"
|
|
326
|
+
)
|
|
327
|
+
raise CypherSemanticError(
|
|
328
|
+
f"cannot tell which node type {subject} is: {listed}",
|
|
329
|
+
query=self._text,
|
|
330
|
+
span=node_slot.pattern.span,
|
|
331
|
+
hint="add a label",
|
|
332
|
+
)
|
|
333
|
+
self._resolutions = [
|
|
334
|
+
_PathResolution(()) if slot.constraint else self._resolve(slot, index)
|
|
335
|
+
for index, slot in enumerate(self._rel_slots)
|
|
336
|
+
]
|
|
337
|
+
|
|
338
|
+
def _narrow(self) -> bool:
|
|
339
|
+
changed = False
|
|
340
|
+
for index, slot in enumerate(self._rel_slots):
|
|
341
|
+
if slot.unsat or (slot.bound is not None and slot.type_name is None):
|
|
342
|
+
# An untyped bound walks every edge the label graph reaches: no single declared
|
|
343
|
+
# edge must span it, so the edge set stays whole and only node types narrow.
|
|
344
|
+
continue
|
|
345
|
+
length_variants = _expansion_range(slot.bound)
|
|
346
|
+
if length_variants is None:
|
|
347
|
+
narrowed = tuple(
|
|
348
|
+
edge
|
|
349
|
+
for edge in slot.candidates
|
|
350
|
+
if _connects(
|
|
351
|
+
edge,
|
|
352
|
+
self._node_candidates[slot.left],
|
|
353
|
+
self._node_candidates[slot.right],
|
|
354
|
+
slot.pattern.direction,
|
|
355
|
+
)
|
|
356
|
+
)
|
|
357
|
+
else:
|
|
358
|
+
narrowed = tuple(
|
|
359
|
+
edge
|
|
360
|
+
for edge in slot.candidates
|
|
361
|
+
if _expansion_connects(
|
|
362
|
+
edge,
|
|
363
|
+
slot.pattern.direction,
|
|
364
|
+
length_variants,
|
|
365
|
+
self._node_candidates[slot.left],
|
|
366
|
+
self._node_candidates[slot.right],
|
|
367
|
+
)
|
|
368
|
+
)
|
|
369
|
+
if narrowed != self._rel_allowed[index]:
|
|
370
|
+
self._rel_allowed[index] = narrowed
|
|
371
|
+
changed = True
|
|
372
|
+
for index, node_slot in enumerate(self._node_slots):
|
|
373
|
+
if node_slot.label is not None:
|
|
374
|
+
continue
|
|
375
|
+
allowed: list[NodeType] = []
|
|
376
|
+
constrained = False
|
|
377
|
+
for slot_index, relation in enumerate(self._rel_slots):
|
|
378
|
+
if index not in (relation.left, relation.right) or relation.unsat:
|
|
379
|
+
continue
|
|
380
|
+
if relation.bound is not None and relation.type_name is None:
|
|
381
|
+
span = _expansion_range(relation.bound)
|
|
382
|
+
if span is None:
|
|
383
|
+
continue
|
|
384
|
+
starts, ends = _untyped_ends(
|
|
385
|
+
self._schema.edges,
|
|
386
|
+
relation.pattern.direction,
|
|
387
|
+
span,
|
|
388
|
+
self._node_candidates[relation.left],
|
|
389
|
+
self._node_candidates[relation.right],
|
|
390
|
+
)
|
|
391
|
+
if not starts or not ends:
|
|
392
|
+
# No walk fits the bound: the pattern matches nothing, and narrowing a
|
|
393
|
+
# label away here would report a type conflict instead.
|
|
394
|
+
continue
|
|
395
|
+
constrained = True
|
|
396
|
+
if index == relation.left and index == relation.right:
|
|
397
|
+
end_labels = {node.label for node in ends}
|
|
398
|
+
allowed.extend(node for node in starts if node.label in end_labels)
|
|
399
|
+
elif index == relation.left:
|
|
400
|
+
allowed.extend(starts)
|
|
401
|
+
else:
|
|
402
|
+
allowed.extend(ends)
|
|
403
|
+
continue
|
|
404
|
+
if not self._rel_allowed[slot_index]:
|
|
405
|
+
continue
|
|
406
|
+
constrained = True
|
|
407
|
+
length_variants = _expansion_range(relation.bound)
|
|
408
|
+
for edge in self._rel_allowed[slot_index]:
|
|
409
|
+
if length_variants is None:
|
|
410
|
+
allowed.extend(
|
|
411
|
+
_endpoint_types(
|
|
412
|
+
edge, index == relation.left, relation.pattern.direction
|
|
413
|
+
)
|
|
414
|
+
)
|
|
415
|
+
continue
|
|
416
|
+
starts, ends = _expansion_ends(
|
|
417
|
+
edge,
|
|
418
|
+
relation.pattern.direction,
|
|
419
|
+
length_variants,
|
|
420
|
+
self._node_candidates[relation.left],
|
|
421
|
+
self._node_candidates[relation.right],
|
|
422
|
+
)
|
|
423
|
+
if index == relation.left and index == relation.right:
|
|
424
|
+
end_labels = {node.label for node in ends}
|
|
425
|
+
allowed.extend(node for node in starts if node.label in end_labels)
|
|
426
|
+
elif index == relation.left:
|
|
427
|
+
allowed.extend(starts)
|
|
428
|
+
else:
|
|
429
|
+
allowed.extend(ends)
|
|
430
|
+
if not constrained:
|
|
431
|
+
continue
|
|
432
|
+
narrowed_nodes = _only(self._node_candidates[index], allowed)
|
|
433
|
+
if narrowed_nodes != self._node_candidates[index]:
|
|
434
|
+
self._node_candidates[index] = narrowed_nodes
|
|
435
|
+
changed = True
|
|
436
|
+
return changed
|
|
437
|
+
|
|
438
|
+
def _initial_candidates(self, slot: _NodeSlot) -> tuple[NodeType, ...]:
|
|
439
|
+
if slot.bound is not None:
|
|
440
|
+
return (slot.bound.node_type,)
|
|
441
|
+
if slot.label is not None:
|
|
442
|
+
return (self._find_node_type(slot.label),)
|
|
443
|
+
return self._schema.nodes
|
|
444
|
+
|
|
445
|
+
def _resolve(self, slot: _RelSlot, index: int) -> _Resolution:
|
|
446
|
+
if slot.unsat:
|
|
447
|
+
return _PathResolution(())
|
|
448
|
+
allowed = self._rel_allowed[index]
|
|
449
|
+
if slot.bound is not None and slot.type_name is None:
|
|
450
|
+
return self._untyped(slot)
|
|
451
|
+
if len(allowed) > 1:
|
|
452
|
+
subject = (
|
|
453
|
+
bounded_text(slot.pattern.var.text)
|
|
454
|
+
if slot.pattern.var is not None
|
|
455
|
+
else "the relationship"
|
|
456
|
+
)
|
|
457
|
+
listed = bounded_names(
|
|
458
|
+
(edge.type for edge in _unique_types(allowed)), prefix=":", separator=" or "
|
|
459
|
+
)
|
|
460
|
+
raise CypherSemanticError(
|
|
461
|
+
f"cannot tell which relationship type {subject} is: {listed}",
|
|
462
|
+
query=self._text,
|
|
463
|
+
span=slot.pattern.span,
|
|
464
|
+
hint="add a type",
|
|
465
|
+
)
|
|
466
|
+
if len(allowed) == 1:
|
|
467
|
+
edge = allowed[0]
|
|
468
|
+
bound = slot.bound
|
|
469
|
+
if bound is not None:
|
|
470
|
+
if slot.recursive:
|
|
471
|
+
return _RecursiveResolution(edge)
|
|
472
|
+
return _ExpansionResolution(self._expansion_alternatives(edge, bound, slot))
|
|
473
|
+
return _EdgeResolution(edge, self._orientations(edge, slot))
|
|
474
|
+
left = self._node_candidates[slot.left][0]
|
|
475
|
+
right = self._node_candidates[slot.right][0]
|
|
476
|
+
return _PathResolution(self._paths.paths(left, right, slot.pattern))
|
|
477
|
+
|
|
478
|
+
def _expansion_alternatives(
|
|
479
|
+
self, edge: EdgeType, length: Length, slot: _RelSlot
|
|
480
|
+
) -> tuple[_Chain, ...]:
|
|
481
|
+
"""One chain per length whose label walk lands on the resolved right endpoint."""
|
|
482
|
+
left = self._node_candidates[slot.left][0].label
|
|
483
|
+
right = self._node_candidates[slot.right][0].label
|
|
484
|
+
chains: list[_Chain] = []
|
|
485
|
+
for depth in range(length.min, cast(int, length.max) + 1):
|
|
486
|
+
walked = _walk(edge, slot.pattern.direction, left, depth)
|
|
487
|
+
if walked is not None and walked[1] == right:
|
|
488
|
+
chains.append(walked[0])
|
|
489
|
+
return tuple(chains)
|
|
490
|
+
|
|
491
|
+
def _untyped(self, slot: _RelSlot) -> _UntypedResolution:
|
|
492
|
+
"""Every declared edge an untyped walk can read, pruned to the labels it can stand on.
|
|
493
|
+
|
|
494
|
+
The edge set is the schema and the pattern's direction, never the query text. A hop is
|
|
495
|
+
kept only when the label it lands on can still reach the right endpoint before the
|
|
496
|
+
deepest useful depth, and a step only from a label the walk can stand on before its last
|
|
497
|
+
hop, so the emitted union is as small as the label graph allows. `max_edge_branches`
|
|
498
|
+
counts the SELECTs that union would hold, because that is what the SQL size follows.
|
|
499
|
+
"""
|
|
500
|
+
bound = cast(Length, slot.bound)
|
|
501
|
+
left = self._node_candidates[slot.left][0].label
|
|
502
|
+
right = self._node_candidates[slot.right][0].label
|
|
503
|
+
direction = slot.pattern.direction
|
|
504
|
+
high = cast(int, bound.max)
|
|
505
|
+
levels = _untyped_levels(self._schema.edges, direction, left, high)
|
|
506
|
+
deepest = max(
|
|
507
|
+
(depth for depth in range(max(bound.min, 1), high + 1) if right in levels[depth]),
|
|
508
|
+
default=0,
|
|
509
|
+
)
|
|
510
|
+
if deepest == 0:
|
|
511
|
+
return _UntypedResolution((), (), 0)
|
|
512
|
+
expandable: set[str] = set()
|
|
513
|
+
for depth in range(1, deepest):
|
|
514
|
+
expandable |= levels[depth]
|
|
515
|
+
base: list[BHop] = []
|
|
516
|
+
steps: list[BHop] = []
|
|
517
|
+
for tag, edge, orientation in _untyped_hops(self._schema.edges, direction):
|
|
518
|
+
landing = _landing_label(edge, orientation)
|
|
519
|
+
if not _untyped_reaches(self._schema.edges, direction, landing, right, deepest - 1):
|
|
520
|
+
continue
|
|
521
|
+
hop = BHop(tag, edge, orientation)
|
|
522
|
+
leaving = _leaving_label(edge, orientation)
|
|
523
|
+
if leaving == left:
|
|
524
|
+
base.append(hop)
|
|
525
|
+
if deepest > 1 and leaving in expandable:
|
|
526
|
+
steps.append(hop)
|
|
527
|
+
branches = len(base) + len(steps)
|
|
528
|
+
cap = self._schema.limits.max_edge_branches
|
|
529
|
+
if branches > cap:
|
|
530
|
+
raise LimitExceededError(
|
|
531
|
+
f"an untyped variable-length path unions {branches} edge branches; "
|
|
532
|
+
f"max_edge_branches is {cap}",
|
|
533
|
+
query=self._text,
|
|
534
|
+
span=bound.span,
|
|
535
|
+
hint=f"raise Limits(max_edge_branches={branches}), or name a relationship type",
|
|
536
|
+
)
|
|
537
|
+
return _UntypedResolution(tuple(base), tuple(steps), deepest)
|
|
538
|
+
|
|
539
|
+
def _orientations(self, edge: EdgeType, slot: _RelSlot) -> frozenset[Orientation]:
|
|
540
|
+
left = self._node_candidates[slot.left][0].label
|
|
541
|
+
right = self._node_candidates[slot.right][0].label
|
|
542
|
+
forward = edge.source.label == left and edge.target.label == right
|
|
543
|
+
backward = edge.source.label == right and edge.target.label == left
|
|
544
|
+
match slot.pattern.direction:
|
|
545
|
+
case Direction.OUT:
|
|
546
|
+
return frozenset({Orientation.FORWARD})
|
|
547
|
+
case Direction.IN:
|
|
548
|
+
return frozenset({Orientation.BACKWARD})
|
|
549
|
+
case _:
|
|
550
|
+
found: set[Orientation] = set()
|
|
551
|
+
if forward:
|
|
552
|
+
found.add(Orientation.FORWARD)
|
|
553
|
+
if backward:
|
|
554
|
+
found.add(Orientation.BACKWARD)
|
|
555
|
+
return frozenset(found)
|
|
556
|
+
|
|
557
|
+
def _no_edge(self, slot: _RelSlot, wanted: Name) -> CypherSemanticError:
|
|
558
|
+
patterns = self._node_slots
|
|
559
|
+
left_label = _labels(self._node_candidates[slot.left], patterns[slot.left])
|
|
560
|
+
right_label = _labels(self._node_candidates[slot.right], patterns[slot.right])
|
|
561
|
+
declared = tuple(edge for edge in self._schema.edges if edge.type == wanted.text)
|
|
562
|
+
if not declared:
|
|
563
|
+
types = _unique_types(self._schema.edges)
|
|
564
|
+
return CypherSemanticError(
|
|
565
|
+
f"unknown relationship :{bounded_text(wanted.text)}",
|
|
566
|
+
query=self._text,
|
|
567
|
+
span=wanted.span,
|
|
568
|
+
hint=_name_hint(
|
|
569
|
+
wanted.text,
|
|
570
|
+
"relationship type",
|
|
571
|
+
tuple(edge.type for edge in types),
|
|
572
|
+
),
|
|
573
|
+
)
|
|
574
|
+
hint = "; ".join(
|
|
575
|
+
f":{edge.source.label} joins :{edge.target.label} on {_columns(edge, edge.source)}"
|
|
576
|
+
for edge in declared
|
|
577
|
+
)
|
|
578
|
+
return CypherSemanticError(
|
|
579
|
+
f"relationship :{bounded_text(wanted.text)} does not connect "
|
|
580
|
+
f"{left_label} and {right_label}",
|
|
581
|
+
query=self._text,
|
|
582
|
+
span=slot.pattern.span,
|
|
583
|
+
hint=hint,
|
|
584
|
+
)
|
|
585
|
+
|
|
586
|
+
def _unify_zero_node(
|
|
587
|
+
self,
|
|
588
|
+
key: tuple[int, int],
|
|
589
|
+
left_key: tuple[int, int],
|
|
590
|
+
element: NodePat,
|
|
591
|
+
variables: dict[str, int],
|
|
592
|
+
) -> None:
|
|
593
|
+
"""`*0..0` between two node patterns: the right one is the left node's occurrence."""
|
|
594
|
+
first = self._node_slot_by_key[left_key]
|
|
595
|
+
slot = self._node_slots[first]
|
|
596
|
+
label = self._node_label(element)
|
|
597
|
+
if label is not None:
|
|
598
|
+
if slot.label is not None and slot.label.text != label.text:
|
|
599
|
+
raise CypherSemanticError(
|
|
600
|
+
"a zero-length path makes both ends one node, but "
|
|
601
|
+
f":{bounded_text(slot.label.text)} and :{bounded_text(label.text)} are "
|
|
602
|
+
"different node types",
|
|
603
|
+
query=self._text,
|
|
604
|
+
span=label.span,
|
|
605
|
+
hint="give both ends the same label, or use a bound of at least one hop",
|
|
606
|
+
)
|
|
607
|
+
if slot.label is None:
|
|
608
|
+
slot.label = label
|
|
609
|
+
self._node_slot_by_key[key] = first
|
|
610
|
+
if element.var is not None:
|
|
611
|
+
bound = variables.get(element.var.text)
|
|
612
|
+
if bound is not None and bound != first:
|
|
613
|
+
raise UnsupportedCypherError(
|
|
614
|
+
"a zero-length relationship cannot join a variable already bound elsewhere",
|
|
615
|
+
query=self._text,
|
|
616
|
+
span=element.var.span,
|
|
617
|
+
hint="write the same node position on both sides",
|
|
618
|
+
)
|
|
619
|
+
variables[element.var.text] = first
|
|
620
|
+
|
|
621
|
+
def _zero_relationship(self, element: RelPat) -> None:
|
|
622
|
+
"""A `*0..0` relationship reads no row; a written type must still be declared."""
|
|
623
|
+
self._reject_length_properties(element)
|
|
624
|
+
self._rel_type(element)
|
|
625
|
+
|
|
626
|
+
def _reject_length_properties(self, element: RelPat) -> None:
|
|
627
|
+
if element.props:
|
|
628
|
+
raise UnsupportedCypherError(
|
|
629
|
+
"a property map on a variable-length relationship is not supported yet",
|
|
630
|
+
query=self._text,
|
|
631
|
+
span=element.span,
|
|
632
|
+
hint="write one relationship per hop, or filter the nodes at either end",
|
|
633
|
+
)
|