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,90 @@
|
|
|
1
|
+
"""Recursive-descent parser: tokens → AST; owns `Limits.max_nesting`.
|
|
2
|
+
|
|
3
|
+
Operator levels are fixed by precedence, `AND`/`OR`/`XOR` chains are built by loops into n-ary
|
|
4
|
+
nodes, and every unbounded recursion (parentheses, `NOT`) goes through a depth counter, so a long
|
|
5
|
+
query can never exhaust the stack: it raises `LimitExceededError` instead. The finished tree is
|
|
6
|
+
checked too, so mixed operator nesting cannot exceed the limit either.
|
|
7
|
+
|
|
8
|
+
The stage is one class in three modules: `_base` holds the state, token access, the nesting
|
|
9
|
+
budget and the fixed tables, `_grammar` the patterns, expressions and `EXISTS` bodies, and
|
|
10
|
+
`_clauses` the clauses in order — split that way because the grammar is one recursive cycle.
|
|
11
|
+
`parse` below is the only entry point.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from cypher2sql._ast import (
|
|
17
|
+
And,
|
|
18
|
+
Cmp,
|
|
19
|
+
ExistsSubquery,
|
|
20
|
+
Expr,
|
|
21
|
+
HasLabel,
|
|
22
|
+
In,
|
|
23
|
+
IsNull,
|
|
24
|
+
ListLit,
|
|
25
|
+
Lit,
|
|
26
|
+
Match,
|
|
27
|
+
Not,
|
|
28
|
+
Or,
|
|
29
|
+
Param,
|
|
30
|
+
PatternPredicate,
|
|
31
|
+
Prop,
|
|
32
|
+
Query,
|
|
33
|
+
Regex,
|
|
34
|
+
StringPredicate,
|
|
35
|
+
Var,
|
|
36
|
+
With,
|
|
37
|
+
Xor,
|
|
38
|
+
)
|
|
39
|
+
from cypher2sql._errors import LimitExceededError, _limit_hint
|
|
40
|
+
from cypher2sql._lexer import Token
|
|
41
|
+
from cypher2sql._limits import Limits
|
|
42
|
+
|
|
43
|
+
from ._clauses import _Parser
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def parse(tokens: tuple[Token, ...], query: str, limits: Limits) -> Query:
|
|
47
|
+
"""Parse one token stream into a `Query`; `query` is the source text errors point into."""
|
|
48
|
+
parsed = _Parser(tokens, query, limits).parse_query()
|
|
49
|
+
for clause in parsed.clauses:
|
|
50
|
+
if (
|
|
51
|
+
isinstance(clause, Match | With)
|
|
52
|
+
and clause.where is not None
|
|
53
|
+
and _depth_of(clause.where.expr) > limits.max_nesting
|
|
54
|
+
):
|
|
55
|
+
raise LimitExceededError(
|
|
56
|
+
f"nesting is deeper than max_nesting ({limits.max_nesting})",
|
|
57
|
+
query=query,
|
|
58
|
+
span=clause.where.span,
|
|
59
|
+
hint=_limit_hint("max_nesting", "simplify the parentheses"),
|
|
60
|
+
)
|
|
61
|
+
return parsed
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _depth_of(expr: Expr) -> int:
|
|
65
|
+
"""Operator nesting of an expression: atoms are 0, each operator adds one level."""
|
|
66
|
+
match expr:
|
|
67
|
+
case Lit() | Param() | Var() | Prop():
|
|
68
|
+
return 0
|
|
69
|
+
case ListLit(items=items):
|
|
70
|
+
return 1 + max((_depth_of(item) for item in items), default=0)
|
|
71
|
+
case Cmp(left=left, right=right):
|
|
72
|
+
return 1 + max(_depth_of(left), _depth_of(right))
|
|
73
|
+
case In(left=left):
|
|
74
|
+
return 1 + _depth_of(left)
|
|
75
|
+
case StringPredicate(left=left, right=right) | Regex(left=left, pattern=right):
|
|
76
|
+
return 1 + max(_depth_of(left), _depth_of(right))
|
|
77
|
+
case And(items=items) | Or(items=items) | Xor(items=items):
|
|
78
|
+
return 1 + max(_depth_of(item) for item in items)
|
|
79
|
+
case Not(operand=operand) | IsNull(operand=operand):
|
|
80
|
+
return 1 + _depth_of(operand)
|
|
81
|
+
case HasLabel():
|
|
82
|
+
return 1
|
|
83
|
+
case PatternPredicate():
|
|
84
|
+
return 1
|
|
85
|
+
case ExistsSubquery(clauses=clauses):
|
|
86
|
+
body = max(
|
|
87
|
+
(_depth_of(clause.where.expr) for clause in clauses if clause.where is not None),
|
|
88
|
+
default=0,
|
|
89
|
+
)
|
|
90
|
+
return 1 + body
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
"""Parser state, token access and the grammar's fixed tables.
|
|
2
|
+
|
|
3
|
+
One parse carries its token stream, the source text every error points into, its `Limits` and its
|
|
4
|
+
current nesting depth; every unbounded recursion (parentheses, `NOT`, a list, an `EXISTS` body)
|
|
5
|
+
goes through `_nested`, so a long query raises `LimitExceededError` instead of exhausting the
|
|
6
|
+
stack. The keyword tables, hints and int64 bounds below are the vocabulary the rest of the package
|
|
7
|
+
reads, and a name token is decoded here once, so no later module reads token text its own way.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from collections.abc import Iterator
|
|
13
|
+
from contextlib import contextmanager
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from typing import cast
|
|
16
|
+
|
|
17
|
+
from cypher2sql._ast import (
|
|
18
|
+
Comparison,
|
|
19
|
+
LabelRef,
|
|
20
|
+
Name,
|
|
21
|
+
Param,
|
|
22
|
+
Selector,
|
|
23
|
+
)
|
|
24
|
+
from cypher2sql._errors import (
|
|
25
|
+
CypherSyntaxError,
|
|
26
|
+
LimitExceededError,
|
|
27
|
+
Span,
|
|
28
|
+
UnsupportedCypherError,
|
|
29
|
+
_limit_hint,
|
|
30
|
+
)
|
|
31
|
+
from cypher2sql._lexer import (
|
|
32
|
+
Token,
|
|
33
|
+
TokenKind,
|
|
34
|
+
describe,
|
|
35
|
+
)
|
|
36
|
+
from cypher2sql._limits import Limits
|
|
37
|
+
from cypher2sql._unsupported import hint_for
|
|
38
|
+
|
|
39
|
+
_INT64_MIN = -(2**63)
|
|
40
|
+
_INT64_MAX = 2**63 - 1
|
|
41
|
+
|
|
42
|
+
_WITH_PATTERN_HINT = (
|
|
43
|
+
"a pattern is a condition; filter with WHERE, and use EXISTS { MATCH ... } for a subquery"
|
|
44
|
+
)
|
|
45
|
+
_WITH_EXISTS_HINT = (
|
|
46
|
+
"EXISTS is a condition; write it in WHERE, and list only whole variables in WITH"
|
|
47
|
+
)
|
|
48
|
+
_EXISTS_RETURN_HINT = (
|
|
49
|
+
"drop RETURN and return an outer variable, or move that MATCH out of EXISTS if you need it"
|
|
50
|
+
)
|
|
51
|
+
_EXISTS_RETURN_LAST_HINT = (
|
|
52
|
+
"move RETURN to the end of the EXISTS body, or drop it: it changes no answer"
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True, slots=True)
|
|
57
|
+
class _RefusedClause:
|
|
58
|
+
"""One refused clause keyword: the construct the refusal names, and its table row."""
|
|
59
|
+
|
|
60
|
+
construct: str
|
|
61
|
+
key: str | None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
#: Every clause keyword the parser refuses, how the refusal names it and the `_unsupported` table
|
|
65
|
+
#: row its documented hint comes from; a clause with no row (`USING`, `YIELD`, a misplaced
|
|
66
|
+
#: `LIMIT`) is refused without a hint.
|
|
67
|
+
_UNSUPPORTED_CLAUSES: dict[str, _RefusedClause] = {
|
|
68
|
+
"CALL": _RefusedClause("CALL", "call"),
|
|
69
|
+
"DELETE": _RefusedClause("DELETE", "write"),
|
|
70
|
+
"DETACH": _RefusedClause("DETACH DELETE", "write"),
|
|
71
|
+
"FOREACH": _RefusedClause("FOREACH", "foreach"),
|
|
72
|
+
"LIMIT": _RefusedClause("LIMIT", None),
|
|
73
|
+
"MERGE": _RefusedClause("MERGE", "write"),
|
|
74
|
+
"ORDER": _RefusedClause("ORDER BY", None),
|
|
75
|
+
"REMOVE": _RefusedClause("REMOVE", "write"),
|
|
76
|
+
"SET": _RefusedClause("SET", "write"),
|
|
77
|
+
"SKIP": _RefusedClause("SKIP", None),
|
|
78
|
+
"UNION": _RefusedClause("UNION", "union"),
|
|
79
|
+
"UNWIND": _RefusedClause("UNWIND", "unwind"),
|
|
80
|
+
"USING": _RefusedClause("USING", None),
|
|
81
|
+
"YIELD": _RefusedClause("YIELD", None),
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
_LITERAL_KEYWORDS = frozenset({"TRUE", "FALSE", "NULL"})
|
|
85
|
+
_AGGREGATE_FUNCTIONS = frozenset(
|
|
86
|
+
{
|
|
87
|
+
"AVG",
|
|
88
|
+
"COLLECT",
|
|
89
|
+
"COUNT",
|
|
90
|
+
"MAX",
|
|
91
|
+
"MIN",
|
|
92
|
+
"PERCENTILECONT",
|
|
93
|
+
"PERCENTILEDISC",
|
|
94
|
+
"STDEV",
|
|
95
|
+
"STDEVP",
|
|
96
|
+
"SUM",
|
|
97
|
+
}
|
|
98
|
+
)
|
|
99
|
+
_WITH_ITEM_HINT = hint_for("with-projection")
|
|
100
|
+
_WITH_ORDER_HINT = hint_for("with-order")
|
|
101
|
+
_ORDER_HINT = hint_for("order-by")
|
|
102
|
+
_RETURN_COMPREHENSION_HINT = hint_for("comprehension")
|
|
103
|
+
_PAGE_HINT = "write an integer literal or a $parameter, e.g. SKIP 10 or LIMIT $limit"
|
|
104
|
+
_CLAUSE_ORDER_HINT = "write RETURN v ORDER BY v SKIP n LIMIT n, in that order"
|
|
105
|
+
_ORDERING_CLAUSES = frozenset({"ORDER", "SKIP", "LIMIT"})
|
|
106
|
+
_OPERATOR_KEYWORDS = frozenset(
|
|
107
|
+
{"AND", "OR", "XOR", "NOT", "IS", "IN", "STARTS", "ENDS", "CONTAINS"}
|
|
108
|
+
)
|
|
109
|
+
_ARITHMETIC = frozenset({TokenKind.PLUS, TokenKind.MINUS, TokenKind.STAR, TokenKind.SLASH})
|
|
110
|
+
_COMPARISONS: dict[TokenKind, Comparison] = {
|
|
111
|
+
TokenKind.EQ: Comparison.EQ,
|
|
112
|
+
TokenKind.NE: Comparison.NE,
|
|
113
|
+
TokenKind.LT: Comparison.LT,
|
|
114
|
+
TokenKind.LE: Comparison.LE,
|
|
115
|
+
TokenKind.GT: Comparison.GT,
|
|
116
|
+
TokenKind.GE: Comparison.GE,
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _token_name(token: Token) -> str:
|
|
121
|
+
"""The decoded name of a name token: backticked names carry their unescaped text."""
|
|
122
|
+
return token.value if isinstance(token.value, str) else token.text
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class _ParserBase:
|
|
126
|
+
"""One parse of one token stream; all state is per query."""
|
|
127
|
+
|
|
128
|
+
def __init__(self, tokens: tuple[Token, ...], query: str, limits: Limits) -> None:
|
|
129
|
+
self._tokens = tokens
|
|
130
|
+
self._query = query
|
|
131
|
+
self._limits = limits
|
|
132
|
+
self._index = 0
|
|
133
|
+
self._depth = 0
|
|
134
|
+
|
|
135
|
+
# ---------------------------------------------------------------- token access
|
|
136
|
+
|
|
137
|
+
def _peek(self, offset: int = 0) -> Token:
|
|
138
|
+
return self._tokens[min(self._index + offset, len(self._tokens) - 1)]
|
|
139
|
+
|
|
140
|
+
def _advance(self) -> Token:
|
|
141
|
+
token = self._peek()
|
|
142
|
+
if token.kind is not TokenKind.EOF:
|
|
143
|
+
self._index += 1
|
|
144
|
+
return token
|
|
145
|
+
|
|
146
|
+
def _at_keyword(self, *words: str) -> bool:
|
|
147
|
+
token = self._peek()
|
|
148
|
+
return token.kind is TokenKind.KEYWORD and token.text.upper() in words
|
|
149
|
+
|
|
150
|
+
def _syntax(self, reason: str, span: Span, *, hint: str | None = None) -> CypherSyntaxError:
|
|
151
|
+
return CypherSyntaxError(reason, query=self._query, span=span, hint=hint)
|
|
152
|
+
|
|
153
|
+
def _unsupported(
|
|
154
|
+
self, token: Token, feature: str, *, hint: str | None = None
|
|
155
|
+
) -> UnsupportedCypherError:
|
|
156
|
+
return UnsupportedCypherError(
|
|
157
|
+
f"{feature} is not supported yet", query=self._query, span=token.span, hint=hint
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
def _unsupported_clause(self, token: Token) -> UnsupportedCypherError:
|
|
161
|
+
"""A refused clause keyword, carrying its documented construct's hint when it has one."""
|
|
162
|
+
refusal = _UNSUPPORTED_CLAUSES[token.text.upper()]
|
|
163
|
+
hint = hint_for(refusal.key) if refusal.key is not None else None
|
|
164
|
+
return self._unsupported(token, refusal.construct, hint=hint)
|
|
165
|
+
|
|
166
|
+
def _reject_named_path(self) -> None:
|
|
167
|
+
"""`MATCH p = …` and `CREATE p = …` bind a path name, which 0.1.0 does not compile."""
|
|
168
|
+
first = self._peek()
|
|
169
|
+
assignment = self._peek(1)
|
|
170
|
+
if first.kind in (TokenKind.IDENT, TokenKind.KEYWORD) and assignment.kind is TokenKind.EQ:
|
|
171
|
+
raise UnsupportedCypherError(
|
|
172
|
+
"a named path is not supported yet",
|
|
173
|
+
query=self._query,
|
|
174
|
+
span=(first.span[0], assignment.span[1]),
|
|
175
|
+
hint=hint_for("named-path"),
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
def _case_error(self, token: Token) -> UnsupportedCypherError:
|
|
179
|
+
"""`CASE` builds a value, which a key-set compiler does not project."""
|
|
180
|
+
return UnsupportedCypherError(
|
|
181
|
+
"CASE is not supported yet",
|
|
182
|
+
query=self._query,
|
|
183
|
+
span=token.span,
|
|
184
|
+
hint=hint_for("case"),
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
def _expect(self, kind: TokenKind) -> Token:
|
|
188
|
+
token = self._peek()
|
|
189
|
+
if token.kind is not kind:
|
|
190
|
+
raise self._syntax(f"expected {kind.value!r}, found {describe(token)}", token.span)
|
|
191
|
+
return self._advance()
|
|
192
|
+
|
|
193
|
+
def _name(self, what: str) -> Name:
|
|
194
|
+
token = self._peek()
|
|
195
|
+
if token.kind is TokenKind.INTERPOLATION:
|
|
196
|
+
raise self._interpolation_in_name(token)
|
|
197
|
+
if token.kind not in (TokenKind.IDENT, TokenKind.KEYWORD):
|
|
198
|
+
raise self._syntax(f"expected {what}, found {describe(token)}", token.span)
|
|
199
|
+
self._advance()
|
|
200
|
+
return Name(_token_name(token), token.span)
|
|
201
|
+
|
|
202
|
+
def _label_ref(self, what: str) -> LabelRef:
|
|
203
|
+
"""A label or type position: a literal name, or one `$param` compile-time selector."""
|
|
204
|
+
token = self._peek()
|
|
205
|
+
if token.kind is TokenKind.PARAM:
|
|
206
|
+
self._advance()
|
|
207
|
+
return Selector(Param(cast(str, token.value), token.span))
|
|
208
|
+
return self._name(what)
|
|
209
|
+
|
|
210
|
+
def _interpolation_in_name(self, token: Token) -> CypherSyntaxError:
|
|
211
|
+
"""An interpolation is a value; a label, type, property or variable is written as text."""
|
|
212
|
+
return self._syntax("interpolations are values; names come from the query text", token.span)
|
|
213
|
+
|
|
214
|
+
@contextmanager
|
|
215
|
+
def _nested(self, span: Span) -> Iterator[None]:
|
|
216
|
+
"""Count one nesting level; the limit is a real bound, not a warning."""
|
|
217
|
+
self._depth += 1
|
|
218
|
+
try:
|
|
219
|
+
if self._depth > self._limits.max_nesting:
|
|
220
|
+
raise LimitExceededError(
|
|
221
|
+
f"nesting is deeper than max_nesting ({self._limits.max_nesting})",
|
|
222
|
+
query=self._query,
|
|
223
|
+
span=span,
|
|
224
|
+
hint=_limit_hint("max_nesting", "simplify the parentheses"),
|
|
225
|
+
)
|
|
226
|
+
yield
|
|
227
|
+
finally:
|
|
228
|
+
self._depth -= 1
|
|
229
|
+
|
|
230
|
+
def _expect_keyword(self, word: str) -> Token:
|
|
231
|
+
token = self._peek()
|
|
232
|
+
if not self._at_keyword(word):
|
|
233
|
+
raise self._syntax(f"expected {word}, found {describe(token)}", token.span)
|
|
234
|
+
return self._advance()
|