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/_lexer.py
ADDED
|
@@ -0,0 +1,557 @@
|
|
|
1
|
+
"""Cypher text → tokens with source spans; owns `Limits.max_query_length`.
|
|
2
|
+
|
|
3
|
+
The scanner is single pass and never backtracks. Keywords are case-insensitive but keep their
|
|
4
|
+
source text, names are case-sensitive, and every token carries the half-open `[start, end)` span
|
|
5
|
+
that errors point at. String literals decode their escapes here; the parser never re-reads text.
|
|
6
|
+
|
|
7
|
+
A query may also be a PEP 750 template (`str | Template`). Its `.strings` are scanned exactly like
|
|
8
|
+
a `str` query, and each interpolation becomes one `TokenKind.INTERPOLATION` token whose value is
|
|
9
|
+
the interpolation's index: a value is never spliced into Cypher text, and the interpolation as
|
|
10
|
+
written (`{expr}`, `{expr!r}`, `{expr:>5}`) is only the text errors point at. The stdlib
|
|
11
|
+
`string.templatelib` is never imported; any object with read-only `strings` and `interpolations` is
|
|
12
|
+
accepted, so this module loads unchanged on Python 3.12/3.13.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from collections.abc import Mapping
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from enum import StrEnum
|
|
20
|
+
from types import MappingProxyType
|
|
21
|
+
|
|
22
|
+
from ._errors import CypherSyntaxError, LimitExceededError, Span, _limit_hint, bounded_text
|
|
23
|
+
from ._limits import Limits
|
|
24
|
+
from ._template import Interpolation, TemplateLike
|
|
25
|
+
|
|
26
|
+
_KEYWORDS = frozenset(
|
|
27
|
+
{
|
|
28
|
+
"AND",
|
|
29
|
+
"AS",
|
|
30
|
+
"ASC",
|
|
31
|
+
"BY",
|
|
32
|
+
"CALL",
|
|
33
|
+
"CASE",
|
|
34
|
+
"CONTAINS",
|
|
35
|
+
"CREATE",
|
|
36
|
+
"DELETE",
|
|
37
|
+
"DESC",
|
|
38
|
+
"DETACH",
|
|
39
|
+
"DISTINCT",
|
|
40
|
+
"ELSE",
|
|
41
|
+
"END",
|
|
42
|
+
"ENDS",
|
|
43
|
+
"EXISTS",
|
|
44
|
+
"FALSE",
|
|
45
|
+
"FOREACH",
|
|
46
|
+
"IN",
|
|
47
|
+
"IS",
|
|
48
|
+
"LIMIT",
|
|
49
|
+
"MATCH",
|
|
50
|
+
"MERGE",
|
|
51
|
+
"NOT",
|
|
52
|
+
"NULL",
|
|
53
|
+
"ON",
|
|
54
|
+
"OPTIONAL",
|
|
55
|
+
"OR",
|
|
56
|
+
"ORDER",
|
|
57
|
+
"REMOVE",
|
|
58
|
+
"RETURN",
|
|
59
|
+
"SET",
|
|
60
|
+
"SKIP",
|
|
61
|
+
"STARTS",
|
|
62
|
+
"THEN",
|
|
63
|
+
"TRUE",
|
|
64
|
+
"UNION",
|
|
65
|
+
"UNWIND",
|
|
66
|
+
"USING",
|
|
67
|
+
"WHEN",
|
|
68
|
+
"WHERE",
|
|
69
|
+
"WITH",
|
|
70
|
+
"XOR",
|
|
71
|
+
"YIELD",
|
|
72
|
+
}
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
_DIGITS = frozenset("0123456789")
|
|
76
|
+
_SIMPLE_ESCAPES = {
|
|
77
|
+
"\\": "\\",
|
|
78
|
+
"'": "'",
|
|
79
|
+
'"': '"',
|
|
80
|
+
"b": "\b",
|
|
81
|
+
"f": "\f",
|
|
82
|
+
"n": "\n",
|
|
83
|
+
"r": "\r",
|
|
84
|
+
"t": "\t",
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class TokenKind(StrEnum):
|
|
89
|
+
"""The lexical classes the parser dispatches on; symbols render as themselves."""
|
|
90
|
+
|
|
91
|
+
IDENT = "identifier"
|
|
92
|
+
KEYWORD = "keyword"
|
|
93
|
+
INTEGER = "integer"
|
|
94
|
+
FLOAT = "float"
|
|
95
|
+
STRING = "string"
|
|
96
|
+
PARAM = "parameter"
|
|
97
|
+
INTERPOLATION = "interpolation"
|
|
98
|
+
LPAREN = "("
|
|
99
|
+
RPAREN = ")"
|
|
100
|
+
LBRACE = "{"
|
|
101
|
+
RBRACE = "}"
|
|
102
|
+
LBRACKET = "["
|
|
103
|
+
RBRACKET = "]"
|
|
104
|
+
COLON = ":"
|
|
105
|
+
COMMA = ","
|
|
106
|
+
DOT = "."
|
|
107
|
+
PIPE = "|"
|
|
108
|
+
MINUS = "-"
|
|
109
|
+
PLUS = "+"
|
|
110
|
+
STAR = "*"
|
|
111
|
+
SLASH = "/"
|
|
112
|
+
EQ = "="
|
|
113
|
+
REGEX = "=~"
|
|
114
|
+
NE = "<>"
|
|
115
|
+
LT = "<"
|
|
116
|
+
LE = "<="
|
|
117
|
+
GT = ">"
|
|
118
|
+
GE = ">="
|
|
119
|
+
EOF = "end of query"
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
_TWO_CHAR: dict[str, TokenKind] = {
|
|
123
|
+
"=~": TokenKind.REGEX,
|
|
124
|
+
"<>": TokenKind.NE,
|
|
125
|
+
"<=": TokenKind.LE,
|
|
126
|
+
">=": TokenKind.GE,
|
|
127
|
+
}
|
|
128
|
+
_ONE_CHAR: dict[str, TokenKind] = {
|
|
129
|
+
"(": TokenKind.LPAREN,
|
|
130
|
+
")": TokenKind.RPAREN,
|
|
131
|
+
"{": TokenKind.LBRACE,
|
|
132
|
+
"}": TokenKind.RBRACE,
|
|
133
|
+
"[": TokenKind.LBRACKET,
|
|
134
|
+
"]": TokenKind.RBRACKET,
|
|
135
|
+
":": TokenKind.COLON,
|
|
136
|
+
",": TokenKind.COMMA,
|
|
137
|
+
".": TokenKind.DOT,
|
|
138
|
+
"|": TokenKind.PIPE,
|
|
139
|
+
"-": TokenKind.MINUS,
|
|
140
|
+
"+": TokenKind.PLUS,
|
|
141
|
+
"*": TokenKind.STAR,
|
|
142
|
+
"/": TokenKind.SLASH,
|
|
143
|
+
"=": TokenKind.EQ,
|
|
144
|
+
"<": TokenKind.LT,
|
|
145
|
+
">": TokenKind.GT,
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
@dataclass(frozen=True, slots=True)
|
|
150
|
+
class Token:
|
|
151
|
+
"""One lexeme: its class, its source text, its span, and a decoded value when it has one."""
|
|
152
|
+
|
|
153
|
+
kind: TokenKind
|
|
154
|
+
text: str
|
|
155
|
+
span: Span
|
|
156
|
+
value: int | float | str | None = None
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
@dataclass(frozen=True, slots=True)
|
|
160
|
+
class QuerySource:
|
|
161
|
+
"""One tokenised query and what later stages need to resolve and name its value tokens.
|
|
162
|
+
|
|
163
|
+
`text` is the query every error points into: a `str` unchanged, a template with each
|
|
164
|
+
interpolation as written. `values` maps the name of each `Param` to its value and `labels` maps
|
|
165
|
+
it to the way the developer wrote it (`$name` or the rendered interpolation), so no message
|
|
166
|
+
shows an internal index and no value ever enters one. `interpolations` holds the span of each
|
|
167
|
+
interpolation token, which is how the binder tells one from a `$name` in a template's text.
|
|
168
|
+
"""
|
|
169
|
+
|
|
170
|
+
tokens: tuple[Token, ...]
|
|
171
|
+
text: str
|
|
172
|
+
values: Mapping[str, object]
|
|
173
|
+
labels: Mapping[str, str]
|
|
174
|
+
interpolations: frozenset[Span]
|
|
175
|
+
template: bool
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def describe(token: Token) -> str:
|
|
179
|
+
"""How a token is named inside `found ...` in a syntax error.
|
|
180
|
+
|
|
181
|
+
A token's text is caller input, so it is quoted inside the documented 63-byte budget; a
|
|
182
|
+
syntax error never grows with the query text.
|
|
183
|
+
"""
|
|
184
|
+
return token.kind.value if token.kind is TokenKind.EOF else f"'{bounded_text(token.text)}'"
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def tokenize(text: str, limits: Limits) -> tuple[Token, ...]:
|
|
188
|
+
"""Tokenise `text`, refusing anything longer than `limits.max_query_length` first."""
|
|
189
|
+
if len(text) > limits.max_query_length:
|
|
190
|
+
raise LimitExceededError(
|
|
191
|
+
f"query is {len(text)} characters; max_query_length is {limits.max_query_length}",
|
|
192
|
+
query=text,
|
|
193
|
+
span=(limits.max_query_length, min(len(text), limits.max_query_length + 1)),
|
|
194
|
+
hint=_limit_hint("max_query_length", "send a shorter query"),
|
|
195
|
+
)
|
|
196
|
+
return (*_Scanner(text).scan(), _end_token(len(text)))
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def lex(
|
|
200
|
+
source: str | TemplateLike,
|
|
201
|
+
limits: Limits,
|
|
202
|
+
params: Mapping[str, object] | None = None,
|
|
203
|
+
) -> QuerySource:
|
|
204
|
+
"""Tokenise a `str` query or a template; the front-end checks on a template happen here.
|
|
205
|
+
|
|
206
|
+
`params` supplies a `str` query's `$name` values; a template ignores it (it carries its own).
|
|
207
|
+
"""
|
|
208
|
+
if isinstance(source, str):
|
|
209
|
+
return QuerySource(
|
|
210
|
+
tokens=tokenize(source, limits),
|
|
211
|
+
text=source,
|
|
212
|
+
values=MappingProxyType({}) if params is None else params,
|
|
213
|
+
labels=MappingProxyType({}),
|
|
214
|
+
interpolations=frozenset(),
|
|
215
|
+
template=False,
|
|
216
|
+
)
|
|
217
|
+
strings, interpolations = _template_parts(source)
|
|
218
|
+
return _template_source(strings, interpolations, limits)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _end_token(end: int) -> Token:
|
|
222
|
+
return Token(TokenKind.EOF, "", (end, end))
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _count(count: int, noun: str) -> str:
|
|
226
|
+
return f"{count} {noun}" if count == 1 else f"{count} {noun}s"
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _template_parts(
|
|
230
|
+
source: TemplateLike,
|
|
231
|
+
) -> tuple[tuple[str, ...], tuple[Interpolation, ...]]:
|
|
232
|
+
"""The template's literal text and interpolations, after the structural shape check."""
|
|
233
|
+
strings = tuple(source.strings)
|
|
234
|
+
raw = tuple(source.interpolations)
|
|
235
|
+
if len(strings) != len(raw) + 1:
|
|
236
|
+
raise TypeError(
|
|
237
|
+
"a template needs one more string than interpolations: "
|
|
238
|
+
f"{_count(len(strings), 'string')} for {_count(len(raw), 'interpolation')}"
|
|
239
|
+
)
|
|
240
|
+
for index, segment in enumerate(strings):
|
|
241
|
+
if not isinstance(segment, str):
|
|
242
|
+
raise TypeError(f"template string {index} must be a str, not {type(segment).__name__}")
|
|
243
|
+
interpolations: list[Interpolation] = []
|
|
244
|
+
for index, interpolation in enumerate(raw):
|
|
245
|
+
if not isinstance(interpolation, Interpolation):
|
|
246
|
+
raise TypeError(
|
|
247
|
+
f"template interpolation {index} must have value, expression, conversion and "
|
|
248
|
+
"format_spec"
|
|
249
|
+
)
|
|
250
|
+
interpolations.append(interpolation)
|
|
251
|
+
return strings, tuple(interpolations)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _template_source(
|
|
255
|
+
strings: tuple[str, ...], interpolations: tuple[Interpolation, ...], limits: Limits
|
|
256
|
+
) -> QuerySource:
|
|
257
|
+
"""Scan a template's text segments around its value tokens, in rendered-text positions."""
|
|
258
|
+
text, spans = _render(strings, interpolations)
|
|
259
|
+
_check_length(strings, interpolations, text, limits)
|
|
260
|
+
for index, interpolation in enumerate(interpolations):
|
|
261
|
+
_check_interpolation(interpolation, spans[index], text)
|
|
262
|
+
tokens: list[Token] = []
|
|
263
|
+
values: dict[str, object] = {}
|
|
264
|
+
labels: dict[str, str] = {}
|
|
265
|
+
offset = 0
|
|
266
|
+
for index, segment in enumerate(strings):
|
|
267
|
+
tokens.extend(_Scanner(segment, document=text, base=offset).scan())
|
|
268
|
+
offset += len(segment)
|
|
269
|
+
if index < len(interpolations):
|
|
270
|
+
name = str(index)
|
|
271
|
+
label = text[spans[index][0] : spans[index][1]]
|
|
272
|
+
values[name] = interpolations[index].value
|
|
273
|
+
labels[name] = label
|
|
274
|
+
tokens.append(Token(TokenKind.INTERPOLATION, label, spans[index], name))
|
|
275
|
+
offset = spans[index][1]
|
|
276
|
+
tokens.append(_end_token(len(text)))
|
|
277
|
+
return QuerySource(
|
|
278
|
+
tokens=tuple(tokens),
|
|
279
|
+
text=text,
|
|
280
|
+
values=MappingProxyType(values),
|
|
281
|
+
labels=MappingProxyType(labels),
|
|
282
|
+
interpolations=frozenset(spans),
|
|
283
|
+
template=True,
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _render(
|
|
288
|
+
strings: tuple[str, ...], interpolations: tuple[Interpolation, ...]
|
|
289
|
+
) -> tuple[str, tuple[Span, ...]]:
|
|
290
|
+
"""The text errors point into, and where each interpolation sits in it, as written."""
|
|
291
|
+
parts: list[str] = []
|
|
292
|
+
spans: list[Span] = []
|
|
293
|
+
offset = 0
|
|
294
|
+
for index, segment in enumerate(strings):
|
|
295
|
+
parts.append(segment)
|
|
296
|
+
offset += len(segment)
|
|
297
|
+
if index < len(interpolations):
|
|
298
|
+
written = _written(interpolations[index])
|
|
299
|
+
parts.append(written)
|
|
300
|
+
spans.append((offset, offset + len(written)))
|
|
301
|
+
offset += len(written)
|
|
302
|
+
return "".join(parts), tuple(spans)
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _written(interpolation: Interpolation) -> str:
|
|
306
|
+
"""The interpolation exactly as the developer wrote it: `{expr}`, `{expr!r}`, `{expr:>5}`."""
|
|
307
|
+
written = "{" + interpolation.expression
|
|
308
|
+
if interpolation.conversion:
|
|
309
|
+
written += "!" + interpolation.conversion
|
|
310
|
+
if interpolation.format_spec:
|
|
311
|
+
written += ":" + _format_spec(interpolation.format_spec)
|
|
312
|
+
return written + "}"
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def _format_spec(spec: object) -> str:
|
|
316
|
+
"""A format spec as text; a nested one (a Template) is shortened rather than imported."""
|
|
317
|
+
return spec if isinstance(spec, str) else "\u2026"
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _check_length(
|
|
321
|
+
strings: tuple[str, ...],
|
|
322
|
+
interpolations: tuple[Interpolation, ...],
|
|
323
|
+
text: str,
|
|
324
|
+
limits: Limits,
|
|
325
|
+
) -> None:
|
|
326
|
+
"""A template counts its joined text plus one character per interpolation slot."""
|
|
327
|
+
counted = sum(len(segment) for segment in strings) + len(interpolations)
|
|
328
|
+
if counted <= limits.max_query_length:
|
|
329
|
+
return
|
|
330
|
+
offset = min(_counted_offset(strings, interpolations, limits.max_query_length), len(text))
|
|
331
|
+
raise LimitExceededError(
|
|
332
|
+
f"query is {counted} characters; max_query_length is {limits.max_query_length}",
|
|
333
|
+
query=text,
|
|
334
|
+
span=(offset, min(len(text), offset + 1)),
|
|
335
|
+
hint=_limit_hint("max_query_length", "send a shorter query"),
|
|
336
|
+
)
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def _counted_offset(
|
|
340
|
+
strings: tuple[str, ...], interpolations: tuple[Interpolation, ...], limit: int
|
|
341
|
+
) -> int:
|
|
342
|
+
"""Where in the rendered text the counted length first passes `limit`."""
|
|
343
|
+
counted = 0
|
|
344
|
+
offset = 0
|
|
345
|
+
for index, segment in enumerate(strings):
|
|
346
|
+
if counted + len(segment) > limit:
|
|
347
|
+
return offset + (limit - counted)
|
|
348
|
+
counted += len(segment)
|
|
349
|
+
offset += len(segment)
|
|
350
|
+
if index < len(interpolations):
|
|
351
|
+
if counted + 1 > limit:
|
|
352
|
+
return offset
|
|
353
|
+
counted += 1
|
|
354
|
+
offset += len(interpolations[index].expression) + 2
|
|
355
|
+
return offset
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def _check_interpolation(interpolation: Interpolation, span: Span, text: str) -> None:
|
|
359
|
+
"""An interpolation only ever joins the values: `{x!r}` and `{x:>5}` are rejected here."""
|
|
360
|
+
written = text[span[0] : span[1]]
|
|
361
|
+
expression_end = span[0] + 1 + len(interpolation.expression)
|
|
362
|
+
hint = f"an interpolation is a value: write {{{interpolation.expression}}}"
|
|
363
|
+
if interpolation.conversion:
|
|
364
|
+
raise CypherSyntaxError(
|
|
365
|
+
f"interpolation {written} cannot use a conversion",
|
|
366
|
+
query=text,
|
|
367
|
+
span=(expression_end, expression_end + 1 + len(interpolation.conversion)),
|
|
368
|
+
hint=hint,
|
|
369
|
+
)
|
|
370
|
+
if interpolation.format_spec:
|
|
371
|
+
spec = _format_spec(interpolation.format_spec)
|
|
372
|
+
raise CypherSyntaxError(
|
|
373
|
+
f"interpolation {written} cannot use a format spec",
|
|
374
|
+
query=text,
|
|
375
|
+
span=(expression_end, expression_end + 1 + len(spec)),
|
|
376
|
+
hint=hint,
|
|
377
|
+
)
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
class _Scanner:
|
|
381
|
+
"""A single-pass scanner over one text segment, reporting spans in the whole query."""
|
|
382
|
+
|
|
383
|
+
def __init__(self, text: str, *, document: str | None = None, base: int = 0) -> None:
|
|
384
|
+
self._text = text
|
|
385
|
+
self._document = text if document is None else document
|
|
386
|
+
self._base = base
|
|
387
|
+
self._pos = 0
|
|
388
|
+
self._tokens: list[Token] = []
|
|
389
|
+
|
|
390
|
+
def scan(self) -> tuple[Token, ...]:
|
|
391
|
+
while self._pos < len(self._text):
|
|
392
|
+
char = self._text[self._pos]
|
|
393
|
+
if char.isspace():
|
|
394
|
+
self._pos += 1
|
|
395
|
+
elif char == "/" and self._peek(1) == "/":
|
|
396
|
+
self._skip_line_comment()
|
|
397
|
+
elif char == "/" and self._peek(1) == "*":
|
|
398
|
+
self._skip_block_comment()
|
|
399
|
+
elif char == "'" or char == '"':
|
|
400
|
+
self._string(char)
|
|
401
|
+
elif char == "`":
|
|
402
|
+
self._backtick_name(TokenKind.IDENT)
|
|
403
|
+
elif char == "$":
|
|
404
|
+
self._parameter()
|
|
405
|
+
elif char in _DIGITS:
|
|
406
|
+
self._number()
|
|
407
|
+
elif char == "_" or char.isalpha():
|
|
408
|
+
self._word()
|
|
409
|
+
else:
|
|
410
|
+
self._symbol()
|
|
411
|
+
return tuple(self._tokens)
|
|
412
|
+
|
|
413
|
+
def _peek(self, offset: int) -> str:
|
|
414
|
+
index = self._pos + offset
|
|
415
|
+
return self._text[index] if index < len(self._text) else ""
|
|
416
|
+
|
|
417
|
+
def _emit(self, kind: TokenKind, start: int, value: int | float | str | None = None) -> None:
|
|
418
|
+
span = (self._base + start, self._base + self._pos)
|
|
419
|
+
self._tokens.append(Token(kind, self._text[start : self._pos], span, value))
|
|
420
|
+
|
|
421
|
+
def _error(self, reason: str, start: int) -> CypherSyntaxError:
|
|
422
|
+
span = (self._base + start, self._base + max(self._pos, start + 1))
|
|
423
|
+
return CypherSyntaxError(reason, query=self._document, span=span)
|
|
424
|
+
|
|
425
|
+
def _skip_line_comment(self) -> None:
|
|
426
|
+
newline = self._text.find("\n", self._pos)
|
|
427
|
+
self._pos = len(self._text) if newline == -1 else newline + 1
|
|
428
|
+
|
|
429
|
+
def _skip_block_comment(self) -> None:
|
|
430
|
+
start = self._pos
|
|
431
|
+
close = self._text.find("*/", self._pos + 2)
|
|
432
|
+
if close == -1:
|
|
433
|
+
self._pos = len(self._text)
|
|
434
|
+
raise self._error("unterminated comment", start)
|
|
435
|
+
self._pos = close + 2
|
|
436
|
+
|
|
437
|
+
def _string(self, quote: str) -> None:
|
|
438
|
+
start = self._pos
|
|
439
|
+
self._pos += 1
|
|
440
|
+
decoded: list[str] = []
|
|
441
|
+
while self._pos < len(self._text):
|
|
442
|
+
char = self._text[self._pos]
|
|
443
|
+
if char == quote:
|
|
444
|
+
self._pos += 1
|
|
445
|
+
self._emit(TokenKind.STRING, start, "".join(decoded))
|
|
446
|
+
return
|
|
447
|
+
if char == "\\":
|
|
448
|
+
decoded.append(self._escape(start))
|
|
449
|
+
continue
|
|
450
|
+
decoded.append(char)
|
|
451
|
+
self._pos += 1
|
|
452
|
+
raise self._error("unterminated string", start)
|
|
453
|
+
|
|
454
|
+
def _escape(self, string_start: int) -> str:
|
|
455
|
+
escape_start = self._pos
|
|
456
|
+
self._pos += 1
|
|
457
|
+
char = self._peek(0)
|
|
458
|
+
if char == "":
|
|
459
|
+
raise self._error("unterminated string", string_start)
|
|
460
|
+
if char == "u":
|
|
461
|
+
digits = self._text[self._pos + 1 : self._pos + 5]
|
|
462
|
+
if len(digits) != 4 or any(digit not in "0123456789abcdefABCDEF" for digit in digits):
|
|
463
|
+
raise self._error("invalid \\u escape: expected four hex digits", escape_start)
|
|
464
|
+
self._pos += 5
|
|
465
|
+
return chr(int(digits, 16))
|
|
466
|
+
if char in _SIMPLE_ESCAPES:
|
|
467
|
+
self._pos += 1
|
|
468
|
+
return _SIMPLE_ESCAPES[char]
|
|
469
|
+
raise self._error(f"unknown escape sequence '\\{char}'", escape_start)
|
|
470
|
+
|
|
471
|
+
def _backtick_name(self, kind: TokenKind, start: int | None = None) -> None:
|
|
472
|
+
if start is None:
|
|
473
|
+
start = self._pos
|
|
474
|
+
self._pos += 1
|
|
475
|
+
decoded: list[str] = []
|
|
476
|
+
while self._pos < len(self._text):
|
|
477
|
+
char = self._text[self._pos]
|
|
478
|
+
if char == "`":
|
|
479
|
+
if self._peek(1) == "`":
|
|
480
|
+
decoded.append("`")
|
|
481
|
+
self._pos += 2
|
|
482
|
+
continue
|
|
483
|
+
self._pos += 1
|
|
484
|
+
if not decoded:
|
|
485
|
+
raise self._error("empty name", start)
|
|
486
|
+
self._emit(kind, start, "".join(decoded))
|
|
487
|
+
return
|
|
488
|
+
decoded.append(char)
|
|
489
|
+
self._pos += 1
|
|
490
|
+
raise self._error("unterminated name", start)
|
|
491
|
+
|
|
492
|
+
def _parameter(self) -> None:
|
|
493
|
+
start = self._pos
|
|
494
|
+
self._pos += 1
|
|
495
|
+
char = self._peek(0)
|
|
496
|
+
if char == "`":
|
|
497
|
+
self._backtick_name(TokenKind.PARAM, start)
|
|
498
|
+
return
|
|
499
|
+
if char == "" or not (char == "_" or char.isalpha()):
|
|
500
|
+
raise self._error("expected a parameter name after '$'", start)
|
|
501
|
+
name_start = self._pos
|
|
502
|
+
while (char := self._peek(0)) and (char == "_" or char.isalnum()):
|
|
503
|
+
self._pos += 1
|
|
504
|
+
self._emit(TokenKind.PARAM, start, self._text[name_start : self._pos])
|
|
505
|
+
|
|
506
|
+
def _number(self) -> None:
|
|
507
|
+
start = self._pos
|
|
508
|
+
while self._peek(0) in _DIGITS:
|
|
509
|
+
self._pos += 1
|
|
510
|
+
fractional = False
|
|
511
|
+
if self._peek(0) == "." and self._peek(1) in _DIGITS:
|
|
512
|
+
fractional = True
|
|
513
|
+
self._pos += 1
|
|
514
|
+
while self._peek(0) in _DIGITS:
|
|
515
|
+
self._pos += 1
|
|
516
|
+
if self._peek(0) in ("e", "E"):
|
|
517
|
+
exponent_start = self._pos
|
|
518
|
+
self._pos += 1
|
|
519
|
+
if self._peek(0) in ("+", "-"):
|
|
520
|
+
self._pos += 1
|
|
521
|
+
if self._peek(0) in _DIGITS:
|
|
522
|
+
fractional = True
|
|
523
|
+
while self._peek(0) in _DIGITS:
|
|
524
|
+
self._pos += 1
|
|
525
|
+
else:
|
|
526
|
+
self._pos = exponent_start
|
|
527
|
+
source = self._text[start : self._pos]
|
|
528
|
+
if fractional:
|
|
529
|
+
self._emit(TokenKind.FLOAT, start, float(source))
|
|
530
|
+
return
|
|
531
|
+
try:
|
|
532
|
+
value = int(source)
|
|
533
|
+
except ValueError:
|
|
534
|
+
raise self._error("integer literal is out of range", start) from None
|
|
535
|
+
self._emit(TokenKind.INTEGER, start, value)
|
|
536
|
+
|
|
537
|
+
def _word(self) -> None:
|
|
538
|
+
start = self._pos
|
|
539
|
+
while (char := self._peek(0)) and (char == "_" or char.isalnum()):
|
|
540
|
+
self._pos += 1
|
|
541
|
+
word = self._text[start : self._pos]
|
|
542
|
+
kind = TokenKind.KEYWORD if word.upper() in _KEYWORDS else TokenKind.IDENT
|
|
543
|
+
self._emit(kind, start)
|
|
544
|
+
|
|
545
|
+
def _symbol(self) -> None:
|
|
546
|
+
start = self._pos
|
|
547
|
+
pair = self._text[start : start + 2]
|
|
548
|
+
kind = _TWO_CHAR.get(pair)
|
|
549
|
+
if kind is not None:
|
|
550
|
+
self._pos += 2
|
|
551
|
+
self._emit(kind, start)
|
|
552
|
+
return
|
|
553
|
+
kind = _ONE_CHAR.get(self._text[start])
|
|
554
|
+
if kind is None:
|
|
555
|
+
raise self._error(f"unexpected character '{self._text[start]}'", start)
|
|
556
|
+
self._pos += 1
|
|
557
|
+
self._emit(kind, start)
|
cypher2sql/_limits.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""`Limits`: the resource bounds applied to untrusted Cypher text."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import cast
|
|
7
|
+
|
|
8
|
+
from ._errors import SchemaError
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
12
|
+
class Limits:
|
|
13
|
+
"""Resource limits for untrusted queries; every bound is a real `int` of at least one."""
|
|
14
|
+
|
|
15
|
+
max_query_length: int = 10_000
|
|
16
|
+
max_nesting: int = 32
|
|
17
|
+
max_pattern_size: int = 32
|
|
18
|
+
max_path_length: int = 8
|
|
19
|
+
max_inferred_paths: int = 32
|
|
20
|
+
max_edge_branches: int = 32
|
|
21
|
+
open_path_length: int | None = None
|
|
22
|
+
|
|
23
|
+
def __post_init__(self) -> None:
|
|
24
|
+
_validate_limits(self)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _validate_limits(limits: object) -> None:
|
|
28
|
+
"""Reject a limits object that cannot bound anything; `Schema` re-checks what it is given."""
|
|
29
|
+
for name in (
|
|
30
|
+
"max_query_length",
|
|
31
|
+
"max_nesting",
|
|
32
|
+
"max_pattern_size",
|
|
33
|
+
"max_path_length",
|
|
34
|
+
"max_inferred_paths",
|
|
35
|
+
"max_edge_branches",
|
|
36
|
+
):
|
|
37
|
+
_positive_int(limits, name)
|
|
38
|
+
_open_path_length(limits)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _copy_limits(limits: object) -> Limits:
|
|
42
|
+
"""Snapshot any limits object into a real `Limits`, so callers cannot change it later."""
|
|
43
|
+
_validate_limits(limits)
|
|
44
|
+
return Limits(
|
|
45
|
+
max_query_length=cast(int, _field(limits, "max_query_length")),
|
|
46
|
+
max_nesting=cast(int, _field(limits, "max_nesting")),
|
|
47
|
+
max_pattern_size=cast(int, _field(limits, "max_pattern_size")),
|
|
48
|
+
max_path_length=cast(int, _field(limits, "max_path_length")),
|
|
49
|
+
max_inferred_paths=cast(int, _field(limits, "max_inferred_paths")),
|
|
50
|
+
max_edge_branches=cast(int, _field(limits, "max_edge_branches")),
|
|
51
|
+
open_path_length=cast(int | None, _field(limits, "open_path_length")),
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _field(limits: object, name: str) -> object:
|
|
56
|
+
try:
|
|
57
|
+
return getattr(limits, name)
|
|
58
|
+
except AttributeError:
|
|
59
|
+
raise SchemaError(f"Limits: missing {name}") from None
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _positive_int(limits: object, name: str) -> None:
|
|
63
|
+
value = _field(limits, name)
|
|
64
|
+
if type(value) is not int or value < 1:
|
|
65
|
+
raise SchemaError(f"Limits: {name} must be a positive integer, got {value!r}")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _open_path_length(limits: object) -> None:
|
|
69
|
+
"""`open_path_length` is either unset or a positive bound within `max_path_length`."""
|
|
70
|
+
value = _field(limits, "open_path_length")
|
|
71
|
+
if value is None:
|
|
72
|
+
return
|
|
73
|
+
if type(value) is not int or value < 1:
|
|
74
|
+
raise SchemaError(f"Limits: open_path_length must be a positive integer, got {value!r}")
|
|
75
|
+
longest = cast(int, _field(limits, "max_path_length"))
|
|
76
|
+
if value > longest:
|
|
77
|
+
raise SchemaError(
|
|
78
|
+
f"Limits: open_path_length must not exceed max_path_length, got {value!r} > {longest!r}"
|
|
79
|
+
)
|