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
cypher2sql/_errors.py
ADDED
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
"""The public exception hierarchy and the caret-formatted query error message.
|
|
2
|
+
|
|
3
|
+
`str(QueryError)` is the format documented in `docs/api.md` → Errors: the reason with its
|
|
4
|
+
position, the offending query line (at most 120 characters) with carets under the span, then the
|
|
5
|
+
hint. It never contains a value: values are not part of a `QueryError`. A query-supplied name is
|
|
6
|
+
echoed cut to the 63-byte suggestion budget, so a caller-sized name cannot make a caller-sized
|
|
7
|
+
message; declared names are escaped and shown within the same hint budget (a long list is cut with
|
|
8
|
+
`…`). The query line is escaped before it is windowed, so a control byte in the query cannot reach
|
|
9
|
+
a terminal and the carets stay under the token.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from collections.abc import Callable, Iterable
|
|
15
|
+
|
|
16
|
+
type Span = tuple[int, int]
|
|
17
|
+
|
|
18
|
+
_QUERY_LINE_LIMIT = 120
|
|
19
|
+
_LEADING_CONTEXT = 24
|
|
20
|
+
_ELLIPSIS = "\u2026"
|
|
21
|
+
_MAX_SUGGESTION_BYTES = 63
|
|
22
|
+
#: The whole `str(SchemaError)`, so no declaration can make a message caller-sized.
|
|
23
|
+
_MAX_SCHEMA_MESSAGE_BYTES = 200
|
|
24
|
+
_MAX_DISTANCE = 3
|
|
25
|
+
_CONTROL_ESCAPES = {"\n": "\\n", "\r": "\\r", "\t": "\\t"}
|
|
26
|
+
# Line separators and bidi controls can forge a message line or reorder what follows, so they
|
|
27
|
+
# are escaped like the C0/C1 controls instead of being printed.
|
|
28
|
+
_UNSAFE_CODE_POINTS = frozenset({0x2028, 0x2029})
|
|
29
|
+
_UNSAFE_RANGES = ((0x202A, 0x202E), (0x2066, 0x2069))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Cypher2SQLError(Exception):
|
|
33
|
+
"""Base of every error cypher2sql raises on purpose."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class SchemaError(Cypher2SQLError):
|
|
37
|
+
"""`Schema(...)` rejected a declaration, or a declaration rejected itself."""
|
|
38
|
+
|
|
39
|
+
def __init__(self, message: str) -> None:
|
|
40
|
+
# One escaped line within the documented whole-message budget: a declared name can make
|
|
41
|
+
# the message name itself, never decide its length or forge a second line.
|
|
42
|
+
super().__init__(bounded_text(message, budget=_MAX_SCHEMA_MESSAGE_BYTES))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class QueryError(Cypher2SQLError):
|
|
46
|
+
"""`to_sql(...)` rejected a query; names where in the Cypher text the problem is."""
|
|
47
|
+
|
|
48
|
+
__slots__ = (
|
|
49
|
+
"_caret_length",
|
|
50
|
+
"_caret_offset",
|
|
51
|
+
"_line_text",
|
|
52
|
+
"column",
|
|
53
|
+
"hint",
|
|
54
|
+
"line",
|
|
55
|
+
"reason",
|
|
56
|
+
"span",
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
reason: str
|
|
60
|
+
line: int
|
|
61
|
+
column: int
|
|
62
|
+
span: tuple[int, int]
|
|
63
|
+
hint: str | None
|
|
64
|
+
|
|
65
|
+
def __init__(
|
|
66
|
+
self,
|
|
67
|
+
reason: str,
|
|
68
|
+
*,
|
|
69
|
+
query: str = "",
|
|
70
|
+
span: tuple[int, int] = (0, 0),
|
|
71
|
+
hint: str | None = None,
|
|
72
|
+
) -> None:
|
|
73
|
+
start = max(span[0], 0)
|
|
74
|
+
end = max(span[1], start)
|
|
75
|
+
self.reason = _one_line(reason)
|
|
76
|
+
super().__init__(self.reason)
|
|
77
|
+
self.span = (start, end)
|
|
78
|
+
self.hint = None if hint is None else _one_line(hint)
|
|
79
|
+
self.line, self.column = _position(query, start)
|
|
80
|
+
self._line_text, self._caret_offset, self._caret_length = _pointer(query, start, end)
|
|
81
|
+
|
|
82
|
+
def __str__(self) -> str:
|
|
83
|
+
heading = f"{self.reason} (line {self.line}, column {self.column})"
|
|
84
|
+
if self._line_text is None:
|
|
85
|
+
parts = [heading]
|
|
86
|
+
else:
|
|
87
|
+
carets = " " * self._caret_offset + "^" * self._caret_length
|
|
88
|
+
parts = [heading, f" {self._line_text}", f" {carets}"]
|
|
89
|
+
if self.hint is not None:
|
|
90
|
+
parts.append(f"hint: {self.hint}")
|
|
91
|
+
return "\n".join(parts)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class CypherSyntaxError(QueryError):
|
|
95
|
+
"""The text is not valid Cypher."""
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class CypherSemanticError(QueryError):
|
|
99
|
+
"""Unknown label, type, property or variable; ambiguity; misuse."""
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class UnsupportedCypherError(QueryError):
|
|
103
|
+
"""Valid Cypher that cypher2sql does not compile (writes, ...)."""
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class ParameterError(QueryError):
|
|
107
|
+
"""A `$param` is missing, of an unsupported type, or misfits its declared property."""
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class LimitExceededError(QueryError):
|
|
111
|
+
"""A `Limits` field was exceeded."""
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _limit_hint(name: str, action: str) -> str:
|
|
115
|
+
"""The one-line fix for an exceeded `Limits` field: raise it, or write less.
|
|
116
|
+
|
|
117
|
+
`name` and `action` are static at every call site, so the query text can never choose a hint's
|
|
118
|
+
content or length. The value is left out: the reason already names it, and a hint points at
|
|
119
|
+
the declaration to change instead of repeating a number.
|
|
120
|
+
"""
|
|
121
|
+
return f"raise Limits({name}=...) or {action}"
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _position(query: str, start: int) -> tuple[int, int]:
|
|
125
|
+
"""The 1-based line and column of a 0-based offset."""
|
|
126
|
+
offset = min(start, len(query))
|
|
127
|
+
line_start = query.rfind("\n", 0, offset) + 1
|
|
128
|
+
return query.count("\n", 0, line_start) + 1, offset - line_start + 1
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _pointer(query: str, start: int, end: int) -> tuple[str | None, int, int]:
|
|
132
|
+
"""The offending line windowed to 120 characters, escaped, and the span's caret there.
|
|
133
|
+
|
|
134
|
+
Every character of the line becomes one escaped cell before windowing, so a control byte or
|
|
135
|
+
bidi override never reaches a terminal, a cut never splits an escape, and the caret offset is
|
|
136
|
+
measured in the escaped text — it stays under the token however long its escape is.
|
|
137
|
+
"""
|
|
138
|
+
if not query:
|
|
139
|
+
return None, 0, 0
|
|
140
|
+
offset = min(start, len(query))
|
|
141
|
+
line_start = query.rfind("\n", 0, offset) + 1
|
|
142
|
+
line_end = query.find("\n", line_start)
|
|
143
|
+
if line_end == -1:
|
|
144
|
+
line_end = len(query)
|
|
145
|
+
caret_start = offset - line_start
|
|
146
|
+
caret_end = min(max(end, offset + 1), line_end) - line_start
|
|
147
|
+
cells = [_escape_char(char) for char in query[line_start:line_end]]
|
|
148
|
+
line, offset, length = _window(cells, caret_start, caret_end)
|
|
149
|
+
return line, offset, max(length, 1)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _fill(cells: list[str], begin: int, budget: int) -> tuple[int, int]:
|
|
153
|
+
"""The index after the last cell that fits from `begin` (the caller's `stop`), and its width."""
|
|
154
|
+
stop = begin
|
|
155
|
+
width = 0
|
|
156
|
+
while stop < len(cells) and width + len(cells[stop]) <= budget:
|
|
157
|
+
width += len(cells[stop])
|
|
158
|
+
stop += 1
|
|
159
|
+
return stop, width
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _window(cells: list[str], start: int, end: int) -> tuple[str, int, int]:
|
|
163
|
+
"""Cut the escaped cells around the span; return the shown line and the span inside it.
|
|
164
|
+
|
|
165
|
+
One cell is one source character escaped, so the shown line stays at most
|
|
166
|
+
`_QUERY_LINE_LIMIT` characters and a cut never splits an escape sequence. Leading context is
|
|
167
|
+
dropped rather than the token when a run of long escapes would otherwise push the span out.
|
|
168
|
+
"""
|
|
169
|
+
if sum(map(len, cells)) <= _QUERY_LINE_LIMIT:
|
|
170
|
+
return "".join(cells), sum(map(len, cells[:start])), sum(map(len, cells[start:end]))
|
|
171
|
+
begin = max(0, start - _LEADING_CONTEXT)
|
|
172
|
+
lead = int(begin > 0)
|
|
173
|
+
stop, width = _fill(cells, begin, _QUERY_LINE_LIMIT - lead)
|
|
174
|
+
if stop <= start and start < len(cells):
|
|
175
|
+
begin, lead = start, int(start > 0)
|
|
176
|
+
stop, width = _fill(cells, begin, _QUERY_LINE_LIMIT - lead)
|
|
177
|
+
trailing = stop < len(cells)
|
|
178
|
+
while trailing and width + 1 > _QUERY_LINE_LIMIT - lead and stop > start + 1:
|
|
179
|
+
stop -= 1
|
|
180
|
+
width -= len(cells[stop])
|
|
181
|
+
shown = f"{_ELLIPSIS if lead else ''}{''.join(cells[begin:stop])}"
|
|
182
|
+
if trailing:
|
|
183
|
+
shown = f"{shown}{_ELLIPSIS}"
|
|
184
|
+
offset = lead + sum(map(len, cells[begin:start]))
|
|
185
|
+
length = sum(map(len, cells[start : min(end, stop)]))
|
|
186
|
+
return shown, offset, length
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _escape_char(char: str) -> str:
|
|
190
|
+
"""One character as printable ASCII-safe text, so it cannot break or reorder a message."""
|
|
191
|
+
code = ord(char)
|
|
192
|
+
if char in _CONTROL_ESCAPES:
|
|
193
|
+
return _CONTROL_ESCAPES[char]
|
|
194
|
+
if code <= 0x1F or 0x7F <= code <= 0x9F:
|
|
195
|
+
return f"\\x{code:02x}"
|
|
196
|
+
if code in _UNSAFE_CODE_POINTS or any(low <= code <= high for low, high in _UNSAFE_RANGES):
|
|
197
|
+
return f"\\u{code:04x}"
|
|
198
|
+
if 0xD800 <= code <= 0xDFFF:
|
|
199
|
+
return f"\\u{code:04x}"
|
|
200
|
+
return char
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _one_line(text: str) -> str:
|
|
204
|
+
"""Escape controls, separators, bidi controls and lone surrogates in a message."""
|
|
205
|
+
return "".join(_escape_char(char) for char in text)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def bounded_text(text: str, *, budget: int = _MAX_SUGGESTION_BYTES) -> str:
|
|
209
|
+
"""A query-supplied value, escaped and cut to a UTF-8 byte budget.
|
|
210
|
+
|
|
211
|
+
The echo is marked with an ellipsis, so a rejected label/type selector can name itself in a
|
|
212
|
+
message without letting a caller-sized value decide the message's length.
|
|
213
|
+
"""
|
|
214
|
+
return _bounded_echo(text, budget=budget, escape=_escape_char)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _bounded_echo(text: str, *, budget: int, escape: Callable[[str], str]) -> str:
|
|
218
|
+
"""`text` escaped one character at a time and cut to a UTF-8 byte budget.
|
|
219
|
+
|
|
220
|
+
A cut marks the echo with an ellipsis, and whole characters are popped until the ellipsis fits
|
|
221
|
+
too, so the result never exceeds `budget` bytes and never ends mid-character. `escape` keeps
|
|
222
|
+
the caller's own quoting rules (plain controls, or quotes and backslashes as well).
|
|
223
|
+
"""
|
|
224
|
+
ellipsis = len(_ELLIPSIS.encode("utf-8"))
|
|
225
|
+
if budget <= ellipsis:
|
|
226
|
+
return ""
|
|
227
|
+
escaped: list[str] = []
|
|
228
|
+
size = 0
|
|
229
|
+
truncated = False
|
|
230
|
+
for char in text:
|
|
231
|
+
piece = escape(char)
|
|
232
|
+
width = len(piece.encode("utf-8", errors="ignore"))
|
|
233
|
+
if size + width > budget:
|
|
234
|
+
truncated = True
|
|
235
|
+
break
|
|
236
|
+
escaped.append(piece)
|
|
237
|
+
size += width
|
|
238
|
+
if not truncated:
|
|
239
|
+
return "".join(escaped)
|
|
240
|
+
while escaped and size + ellipsis > budget:
|
|
241
|
+
size -= len(escaped.pop().encode("utf-8", errors="ignore"))
|
|
242
|
+
return f"{''.join(escaped)}{_ELLIPSIS}"
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _quoted_value(value: str) -> str:
|
|
246
|
+
"""A query-supplied value as one bounded, quoted echo.
|
|
247
|
+
|
|
248
|
+
Controls, separators, bidi controls and lone surrogates are escaped so they cannot forge or
|
|
249
|
+
reorder a line, and `'`/`\\` are escaped too so the surrounding quotes stay unambiguous. The
|
|
250
|
+
whole echo, quotes included, stays inside the 63-byte suggestion budget.
|
|
251
|
+
"""
|
|
252
|
+
body = _bounded_echo(value, budget=_MAX_SUGGESTION_BYTES - 2, escape=_quote_escape)
|
|
253
|
+
return f"'{body}'"
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _quote_escape(char: str) -> str:
|
|
257
|
+
"""One character escaped for a single-quoted echo: quotes and backslashes first."""
|
|
258
|
+
if char == "'":
|
|
259
|
+
return "\\'"
|
|
260
|
+
if char == "\\":
|
|
261
|
+
return "\\\\"
|
|
262
|
+
return _escape_char(char)
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _joined(items: list[str], *, lead: str, separator: str, last_separator: str | None) -> str:
|
|
266
|
+
"""`items` joined, the last gap written as `last_separator` when one is given."""
|
|
267
|
+
if last_separator is None or len(items) < 2:
|
|
268
|
+
return f"{lead}{separator.join(items)}"
|
|
269
|
+
return f"{lead}{separator.join(items[:-1])}{last_separator}{items[-1]}"
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _listing(
|
|
273
|
+
names: Iterable[str],
|
|
274
|
+
*,
|
|
275
|
+
prefix: str,
|
|
276
|
+
lead: str,
|
|
277
|
+
separator: str,
|
|
278
|
+
last_separator: str | None,
|
|
279
|
+
budget: int,
|
|
280
|
+
) -> tuple[str, bool]:
|
|
281
|
+
"""The bounded listing, and whether every name is shown.
|
|
282
|
+
|
|
283
|
+
`last_separator` only ever writes the gap between the last two names of a complete listing;
|
|
284
|
+
a list that had to drop names always uses `separator`, so the ellipsis never follows a
|
|
285
|
+
conjunction.
|
|
286
|
+
"""
|
|
287
|
+
items = [f"{prefix}{name}" for name in names]
|
|
288
|
+
if not items:
|
|
289
|
+
return "", True
|
|
290
|
+
listed = _joined(items, lead=lead, separator=separator, last_separator=last_separator)
|
|
291
|
+
if len(listed.encode("utf-8", errors="ignore")) <= budget:
|
|
292
|
+
return listed, True
|
|
293
|
+
ellipsis = len(_ELLIPSIS.encode("utf-8"))
|
|
294
|
+
lead_size = len(lead.encode("utf-8", errors="ignore"))
|
|
295
|
+
if lead_size + ellipsis > budget:
|
|
296
|
+
return "", False
|
|
297
|
+
kept: list[str] = []
|
|
298
|
+
size = lead_size
|
|
299
|
+
for item in items:
|
|
300
|
+
added = len(item.encode("utf-8", errors="ignore")) + (
|
|
301
|
+
len(separator.encode("utf-8", errors="ignore")) if kept else 0
|
|
302
|
+
)
|
|
303
|
+
if size + added + ellipsis > budget:
|
|
304
|
+
break
|
|
305
|
+
kept.append(item)
|
|
306
|
+
size += added
|
|
307
|
+
return f"{lead}{separator.join(kept)}{_ELLIPSIS}", False
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def bounded_names(
|
|
311
|
+
names: Iterable[str],
|
|
312
|
+
*,
|
|
313
|
+
prefix: str = "",
|
|
314
|
+
lead: str = "",
|
|
315
|
+
separator: str = ", ",
|
|
316
|
+
budget: int = _MAX_SUGGESTION_BYTES,
|
|
317
|
+
) -> str:
|
|
318
|
+
"""Declared names in declaration order, inside a hint budget of UTF-8 bytes.
|
|
319
|
+
|
|
320
|
+
`lead` introduces the list, `prefix` is written before each name (e.g. `:`) and `separator`
|
|
321
|
+
joins them. Names are kept whole; a list that does not fit ends with an ellipsis instead of
|
|
322
|
+
being cut mid-name.
|
|
323
|
+
"""
|
|
324
|
+
return _listing(
|
|
325
|
+
names,
|
|
326
|
+
prefix=prefix,
|
|
327
|
+
lead=lead,
|
|
328
|
+
separator=separator,
|
|
329
|
+
last_separator=None,
|
|
330
|
+
budget=budget,
|
|
331
|
+
)[0]
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def did_you_mean(token: str, candidates: Iterable[str], *, prefix: str = "") -> str | None:
|
|
335
|
+
"""A `did you mean ...?` hint built from declared names only, or `None`.
|
|
336
|
+
|
|
337
|
+
Edit distance is capped at three and tokens over 63 bytes get no hint, so a query never
|
|
338
|
+
learns about names that are not in the schema; equally close candidates are listed in name
|
|
339
|
+
order, which keeps messages deterministic.
|
|
340
|
+
"""
|
|
341
|
+
try:
|
|
342
|
+
too_long = len(token.encode("utf-8")) > _MAX_SUGGESTION_BYTES
|
|
343
|
+
except UnicodeEncodeError:
|
|
344
|
+
return None
|
|
345
|
+
if too_long:
|
|
346
|
+
return None
|
|
347
|
+
scored = [
|
|
348
|
+
(distance, name)
|
|
349
|
+
for name in candidates
|
|
350
|
+
if (distance := _edit_distance(token, name)) <= _MAX_DISTANCE
|
|
351
|
+
]
|
|
352
|
+
if not scored:
|
|
353
|
+
return None
|
|
354
|
+
closest = min(distance for distance, _ in scored)
|
|
355
|
+
names = sorted(name for distance, name in scored if distance == closest)
|
|
356
|
+
# Bound the whole list here, not only each name: a candidate set can be schema-sized, and
|
|
357
|
+
# the 63-byte guarantee must hold in this function wherever a caller uses it. The ` or `
|
|
358
|
+
# separator is chosen before the join is measured — swapping it in afterwards would add two
|
|
359
|
+
# bytes and could push a 63-byte list over its budget.
|
|
360
|
+
listed, complete = _listing(
|
|
361
|
+
names,
|
|
362
|
+
prefix=prefix,
|
|
363
|
+
lead="",
|
|
364
|
+
separator=", ",
|
|
365
|
+
last_separator=" or ",
|
|
366
|
+
budget=_MAX_SUGGESTION_BYTES,
|
|
367
|
+
)
|
|
368
|
+
if not complete:
|
|
369
|
+
listed = _listing(
|
|
370
|
+
names,
|
|
371
|
+
prefix=prefix,
|
|
372
|
+
lead="",
|
|
373
|
+
separator=", ",
|
|
374
|
+
last_separator=None,
|
|
375
|
+
budget=_MAX_SUGGESTION_BYTES,
|
|
376
|
+
)[0]
|
|
377
|
+
return f"did you mean {listed}?"
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def _edit_distance(left: str, right: str) -> int:
|
|
381
|
+
"""Levenshtein distance; the length difference alone often exceeds the cap."""
|
|
382
|
+
if abs(len(left) - len(right)) > _MAX_DISTANCE:
|
|
383
|
+
return _MAX_DISTANCE + 1
|
|
384
|
+
previous = list(range(len(right) + 1))
|
|
385
|
+
for row, left_char in enumerate(left, 1):
|
|
386
|
+
current = [row]
|
|
387
|
+
for column, right_char in enumerate(right, 1):
|
|
388
|
+
current.append(
|
|
389
|
+
min(
|
|
390
|
+
previous[column] + 1,
|
|
391
|
+
current[column - 1] + 1,
|
|
392
|
+
previous[column - 1] + (left_char != right_char),
|
|
393
|
+
)
|
|
394
|
+
)
|
|
395
|
+
previous = current
|
|
396
|
+
return previous[-1]
|
cypher2sql/_infer.py
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
"""Inferred paths: the shortest declared edges that relate two node types.
|
|
2
|
+
|
|
3
|
+
An untyped relationship whose endpoints no single edge joins follows the shortest declared path
|
|
4
|
+
between them, a deliberate extension of Cypher's single-relationship `--`. This module answers one
|
|
5
|
+
question for the binder: every shortest such path, left to right, in declaration order — or the
|
|
6
|
+
documented error. It works on labels only (one representative per declared node type), is driven by
|
|
7
|
+
one frozen `_PathFinder` per bind, never emits SQL and never re-parses text.
|
|
8
|
+
|
|
9
|
+
Two label-level BFS runs, forward from the start and backward from the goal, give the answers that
|
|
10
|
+
need no path: the shortest distance (so "path too long" is diagnosed without enumerating anything)
|
|
11
|
+
and the layered DAG every shortest path runs through. Paths are only walked once their exact
|
|
12
|
+
number is inside `max_inferred_paths`, so a branching schema can never explode the frontier or the
|
|
13
|
+
SQL; Python big ints keep the count exact, even past CPython's int-to-string digit cap.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import sys
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
|
|
21
|
+
from ._ast import Direction, RelPat
|
|
22
|
+
from ._errors import CypherSemanticError, LimitExceededError
|
|
23
|
+
from ._ir import Carrier, Orientation, carrier
|
|
24
|
+
from ._schema import EdgeType, NodeType, Schema, quote_ident
|
|
25
|
+
|
|
26
|
+
_NO_EDGE = "declare an Edge between :{} and :{}"
|
|
27
|
+
|
|
28
|
+
#: One hop: the declared edge, which way it is walked, and the node type it lands on.
|
|
29
|
+
type _Step = tuple[EdgeType, Orientation, NodeType]
|
|
30
|
+
#: Every declared hop out of a label, in declaration order.
|
|
31
|
+
type _Steps = dict[str, tuple[_Step, ...]]
|
|
32
|
+
#: One shortest path, left to right, as the edge and orientation of each hop.
|
|
33
|
+
type _Path = tuple[tuple[EdgeType, Orientation], ...]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True, slots=True)
|
|
37
|
+
class _PathFinder:
|
|
38
|
+
"""Every shortest declared path between two node types, for one bind of one query.
|
|
39
|
+
|
|
40
|
+
`text` is only the query the errors point into; no value or name from it reaches SQL.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
schema: Schema
|
|
44
|
+
text: str
|
|
45
|
+
|
|
46
|
+
def paths(self, start: NodeType, goal: NodeType, pattern: RelPat) -> tuple[_Path, ...]:
|
|
47
|
+
"""Every shortest declared path from `start` to `goal`, or the documented error."""
|
|
48
|
+
limits = self.schema.limits
|
|
49
|
+
direction = pattern.direction
|
|
50
|
+
if goal.label == start.label:
|
|
51
|
+
# The label-level model keeps one representative per label, so a pattern whose two
|
|
52
|
+
# ends are the same node type has no inferred path to walk.
|
|
53
|
+
raise self._no_path(start, goal, pattern)
|
|
54
|
+
steps = self._adjacency(direction)
|
|
55
|
+
forward = self._layers(start, steps, until=goal.label)
|
|
56
|
+
distance = forward.get(goal.label)
|
|
57
|
+
if distance is None:
|
|
58
|
+
raise self._no_path(start, goal, pattern)
|
|
59
|
+
if distance > limits.max_path_length:
|
|
60
|
+
raise LimitExceededError(
|
|
61
|
+
f"shortest path from :{start.label} to :{goal.label} is {distance} "
|
|
62
|
+
f"relationships; max_path_length is {limits.max_path_length}",
|
|
63
|
+
query=self.text,
|
|
64
|
+
span=pattern.span,
|
|
65
|
+
hint=f"raise Limits(max_path_length={distance}) or declare an Edge between "
|
|
66
|
+
f":{start.label} and :{goal.label}",
|
|
67
|
+
)
|
|
68
|
+
backwards = _backwards(direction)
|
|
69
|
+
backward_steps = steps if backwards is direction else self._adjacency(backwards)
|
|
70
|
+
on_shortest = self._on_shortest(forward, goal, distance, backward_steps)
|
|
71
|
+
cap = limits.max_inferred_paths
|
|
72
|
+
count = self._count(start, goal, on_shortest, steps)
|
|
73
|
+
if count > cap:
|
|
74
|
+
raise LimitExceededError(
|
|
75
|
+
f"{_count_text(count)} shortest paths from :{start.label} to :{goal.label}; "
|
|
76
|
+
f"max_inferred_paths is {cap}",
|
|
77
|
+
query=self.text,
|
|
78
|
+
span=pattern.span,
|
|
79
|
+
hint=_path_limit_hint(start.label, goal.label, count),
|
|
80
|
+
)
|
|
81
|
+
return self._alternatives(start, on_shortest, steps, distance)
|
|
82
|
+
|
|
83
|
+
def _no_path(self, start: NodeType, goal: NodeType, pattern: RelPat) -> CypherSemanticError:
|
|
84
|
+
return CypherSemanticError(
|
|
85
|
+
f"no relationship connects :{start.label} and :{goal.label}",
|
|
86
|
+
query=self.text,
|
|
87
|
+
span=pattern.span,
|
|
88
|
+
hint=self._fk_hint(start, goal),
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
def _adjacency(self, direction: Direction) -> _Steps:
|
|
92
|
+
"""`label -> steps` over every declared edge, in one schema pass, in declaration order.
|
|
93
|
+
|
|
94
|
+
One scan of the edges replaces a per-label scan, so a walk costs `labels + edges` instead
|
|
95
|
+
of a scan per label; forward then backward per edge keeps each label's steps in the same
|
|
96
|
+
order the emitted paths always had.
|
|
97
|
+
"""
|
|
98
|
+
adjacency: dict[str, list[_Step]] = {}
|
|
99
|
+
for edge in self.schema.edges:
|
|
100
|
+
if direction is not Direction.IN:
|
|
101
|
+
adjacency.setdefault(edge.source.label, []).append(
|
|
102
|
+
(edge, Orientation.FORWARD, edge.target)
|
|
103
|
+
)
|
|
104
|
+
if direction is not Direction.OUT:
|
|
105
|
+
adjacency.setdefault(edge.target.label, []).append(
|
|
106
|
+
(edge, Orientation.BACKWARD, edge.source)
|
|
107
|
+
)
|
|
108
|
+
return {label: tuple(steps) for label, steps in adjacency.items()}
|
|
109
|
+
|
|
110
|
+
def _layers(
|
|
111
|
+
self,
|
|
112
|
+
start: NodeType,
|
|
113
|
+
steps: _Steps,
|
|
114
|
+
*,
|
|
115
|
+
until: str | None = None,
|
|
116
|
+
max_depth: int | None = None,
|
|
117
|
+
) -> dict[str, int]:
|
|
118
|
+
"""Distances from `start` over the label graph, stopping once the answer is complete.
|
|
119
|
+
|
|
120
|
+
`until` ends the walk after the layer holding that label is fully expanded; `max_depth`
|
|
121
|
+
ends it after that many layers. Every label returned holds its true distance, so a caller
|
|
122
|
+
that only needs those layers pays for them and for nothing beyond them.
|
|
123
|
+
"""
|
|
124
|
+
layers = {start.label: 0}
|
|
125
|
+
frontier: tuple[NodeType, ...] = (start,)
|
|
126
|
+
depth = 0
|
|
127
|
+
while frontier and (max_depth is None or depth < max_depth):
|
|
128
|
+
depth += 1
|
|
129
|
+
reached: list[NodeType] = []
|
|
130
|
+
for node in frontier:
|
|
131
|
+
for _edge, _orientation, other in steps.get(node.label, ()):
|
|
132
|
+
if other.label not in layers:
|
|
133
|
+
layers[other.label] = depth
|
|
134
|
+
reached.append(other)
|
|
135
|
+
if until is not None and until in layers:
|
|
136
|
+
break
|
|
137
|
+
frontier = tuple(reached)
|
|
138
|
+
return layers
|
|
139
|
+
|
|
140
|
+
def _on_shortest(
|
|
141
|
+
self,
|
|
142
|
+
forward: dict[str, int],
|
|
143
|
+
goal: NodeType,
|
|
144
|
+
distance: int,
|
|
145
|
+
backward_steps: _Steps,
|
|
146
|
+
) -> dict[str, int]:
|
|
147
|
+
"""The labels on a shortest `start`→`goal` path, each at its distance from `start`.
|
|
148
|
+
|
|
149
|
+
A label is kept when its distance from the start plus its distance to the goal is exactly
|
|
150
|
+
the shortest distance; every other label lies off every shortest path. The backward run
|
|
151
|
+
only needs `distance` layers, so deeper labels are never visited.
|
|
152
|
+
"""
|
|
153
|
+
backward = self._layers(goal, backward_steps, max_depth=distance)
|
|
154
|
+
return {
|
|
155
|
+
label: at
|
|
156
|
+
for label, at in forward.items()
|
|
157
|
+
if label in backward and at + backward[label] == distance
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
def _count(
|
|
161
|
+
self,
|
|
162
|
+
start: NodeType,
|
|
163
|
+
goal: NodeType,
|
|
164
|
+
on_shortest: dict[str, int],
|
|
165
|
+
steps: _Steps,
|
|
166
|
+
) -> int:
|
|
167
|
+
"""The exact number of shortest simple paths from `start` to `goal`.
|
|
168
|
+
|
|
169
|
+
A shortest path uses each label exactly at its BFS distance, so the layered DAG counts
|
|
170
|
+
them exactly in one pass over the layers; labels off those paths are skipped, so a dense
|
|
171
|
+
region that reaches no goal cannot inflate the count or the work. Python big ints keep
|
|
172
|
+
the answer exact however many paths there are; the layer scan itself stays linear.
|
|
173
|
+
"""
|
|
174
|
+
counts = {start.label: 1}
|
|
175
|
+
for label in sorted(on_shortest, key=lambda label: on_shortest[label]):
|
|
176
|
+
total = counts.get(label, 0)
|
|
177
|
+
for _edge, _orientation, other in steps.get(label, ()):
|
|
178
|
+
if on_shortest.get(other.label) == on_shortest[label] + 1:
|
|
179
|
+
counts[other.label] = counts.get(other.label, 0) + total
|
|
180
|
+
return counts.get(goal.label, 0)
|
|
181
|
+
|
|
182
|
+
def _alternatives(
|
|
183
|
+
self,
|
|
184
|
+
start: NodeType,
|
|
185
|
+
on_shortest: dict[str, int],
|
|
186
|
+
steps: _Steps,
|
|
187
|
+
distance: int,
|
|
188
|
+
) -> tuple[_Path, ...]:
|
|
189
|
+
"""Walk the layered DAG for every shortest path, in the documented order.
|
|
190
|
+
|
|
191
|
+
Only labels on a shortest path are entered, so every step extends to a full alternative:
|
|
192
|
+
the walk visits at most one prefix of each emitted path per step. Steps stay in declaration
|
|
193
|
+
order (forward before backward per edge), which keeps the emitted order shortest, then
|
|
194
|
+
declaration order.
|
|
195
|
+
"""
|
|
196
|
+
found: list[_Path] = []
|
|
197
|
+
stack: list[tuple[NodeType, _Path, int]] = [(start, (), 0)]
|
|
198
|
+
while stack:
|
|
199
|
+
node, path, offset = stack.pop()
|
|
200
|
+
if len(path) == distance:
|
|
201
|
+
found.append(path)
|
|
202
|
+
continue
|
|
203
|
+
node_steps = steps.get(node.label, ())
|
|
204
|
+
if offset == len(node_steps):
|
|
205
|
+
continue
|
|
206
|
+
stack.append((node, path, offset + 1))
|
|
207
|
+
edge, orientation, other = node_steps[offset]
|
|
208
|
+
if on_shortest.get(other.label) == len(path) + 1:
|
|
209
|
+
stack.append((other, (*path, (edge, orientation)), 0))
|
|
210
|
+
return tuple(found)
|
|
211
|
+
|
|
212
|
+
def _fk_hint(self, start: NodeType, goal: NodeType) -> str:
|
|
213
|
+
joins = self._joins(start)
|
|
214
|
+
if goal.label != start.label:
|
|
215
|
+
joins = "; ".join(part for part in (joins, self._joins(goal)) if part)
|
|
216
|
+
return joins or _NO_EDGE.format(start.label, goal.label)
|
|
217
|
+
|
|
218
|
+
def _joins(self, node: NodeType) -> str:
|
|
219
|
+
parts: list[str] = []
|
|
220
|
+
for edge in self.schema.edges:
|
|
221
|
+
if edge.source.label == node.label:
|
|
222
|
+
parts.append(
|
|
223
|
+
f":{edge.source.label} joins :{edge.target.label} on "
|
|
224
|
+
f"{_columns(edge, edge.source)}"
|
|
225
|
+
)
|
|
226
|
+
elif edge.target.label == node.label:
|
|
227
|
+
parts.append(
|
|
228
|
+
f":{edge.target.label} joins :{edge.source.label} on "
|
|
229
|
+
f"{_columns(edge, edge.target)}"
|
|
230
|
+
)
|
|
231
|
+
return "; ".join(parts)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _columns(edge: EdgeType, side: NodeType) -> str:
|
|
235
|
+
"""The foreign-key columns that relate the two labels, for the error hint.
|
|
236
|
+
|
|
237
|
+
A join table has a column pointing at each end, so the answer depends on the side asked
|
|
238
|
+
about; a foreign key lives in one end's row, so that column set is the answer either way.
|
|
239
|
+
"""
|
|
240
|
+
match carrier(edge):
|
|
241
|
+
case Carrier.TARGET:
|
|
242
|
+
columns = edge.source_columns
|
|
243
|
+
case Carrier.SOURCE:
|
|
244
|
+
columns = edge.target_columns
|
|
245
|
+
case _:
|
|
246
|
+
columns = (
|
|
247
|
+
edge.source_columns if side.label == edge.source.label else edge.target_columns
|
|
248
|
+
)
|
|
249
|
+
return ", ".join(f"{quote_ident(edge.table)}.{quote_ident(column)}" for column in columns)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _backwards(direction: Direction) -> Direction:
|
|
253
|
+
"""The direction that walks the same declared edges the other way around."""
|
|
254
|
+
match direction:
|
|
255
|
+
case Direction.OUT:
|
|
256
|
+
return Direction.IN
|
|
257
|
+
case Direction.IN:
|
|
258
|
+
return Direction.OUT
|
|
259
|
+
case _:
|
|
260
|
+
return Direction.BOTH
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
# CPython's `str(int)` digit cap is a runtime setting (`PYTHONINTMAXSTRDIGITS`); 0 means none.
|
|
264
|
+
def _count_prints(count: int) -> bool:
|
|
265
|
+
"""Whether this interpreter will let the count be printed."""
|
|
266
|
+
digits = sys.get_int_max_str_digits()
|
|
267
|
+
return digits == 0 or count < 10**digits
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _count_text(count: int) -> str:
|
|
271
|
+
"""`count` in decimal, or a truthful lower bound when CPython would refuse to print it."""
|
|
272
|
+
if _count_prints(count):
|
|
273
|
+
return str(count)
|
|
274
|
+
return f"at least 10**{sys.get_int_max_str_digits()}"
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _path_limit_hint(start: str, goal: str, count: int) -> str:
|
|
278
|
+
"""The fix for `max_inferred_paths`, naming a runnable limit whenever the count prints."""
|
|
279
|
+
if not _count_prints(count):
|
|
280
|
+
return (
|
|
281
|
+
f"declare an Edge between :{start} and :{goal}; {_count_text(count)} alternatives "
|
|
282
|
+
"make a raised max_inferred_paths impractical"
|
|
283
|
+
)
|
|
284
|
+
return (
|
|
285
|
+
f"declare an Edge between :{start} and :{goal}, or raise "
|
|
286
|
+
f"Limits(max_inferred_paths={count}); each alternative adds one OR EXISTS branch"
|
|
287
|
+
)
|