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.
@@ -0,0 +1,404 @@
1
+ """The clauses in written order: `MATCH`, `OPTIONAL MATCH`, `WITH`, `CREATE` and `RETURN`.
2
+
3
+ `parse_query` walks the stream clause by clause and refuses a query that does not end with
4
+ `RETURN` (or a `CREATE`) or that continues past the last clause, naming the clause that would have
5
+ to move. `RETURN`'s ordering and its page are parsed here but decided by the binder — an ordering
6
+ of anything but the returned variable, a page that is not an integer literal, and a repeated
7
+ clause are refused before they can reach it.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import Never, cast
13
+
14
+ from cypher2sql._ast import (
15
+ Clause,
16
+ Create,
17
+ Lit,
18
+ Match,
19
+ OrderItem,
20
+ Page,
21
+ Param,
22
+ Query,
23
+ Return,
24
+ SortDirection,
25
+ With,
26
+ WithItem,
27
+ )
28
+ from cypher2sql._errors import UnsupportedCypherError
29
+ from cypher2sql._lexer import (
30
+ Token,
31
+ TokenKind,
32
+ describe,
33
+ )
34
+ from cypher2sql._unsupported import hint_for
35
+
36
+ from ._base import (
37
+ _AGGREGATE_FUNCTIONS,
38
+ _CLAUSE_ORDER_HINT,
39
+ _INT64_MAX,
40
+ _LITERAL_KEYWORDS,
41
+ _OPERATOR_KEYWORDS,
42
+ _ORDER_HINT,
43
+ _ORDERING_CLAUSES,
44
+ _PAGE_HINT,
45
+ _RETURN_COMPREHENSION_HINT,
46
+ _UNSUPPORTED_CLAUSES,
47
+ _WITH_EXISTS_HINT,
48
+ _WITH_ITEM_HINT,
49
+ _WITH_ORDER_HINT,
50
+ )
51
+ from ._grammar import _Grammar
52
+
53
+
54
+ class _Parser(_Grammar):
55
+ """The clauses, and the entry point `parse` builds once per query."""
56
+
57
+ def parse_query(self) -> Query:
58
+ clauses: list[Clause] = []
59
+ while self._peek().kind is not TokenKind.EOF:
60
+ if self._at_keyword("MATCH", "OPTIONAL"):
61
+ clauses.append(self._match())
62
+ elif self._at_keyword("WITH"):
63
+ clauses.append(self._with())
64
+ elif self._at_keyword("CREATE"):
65
+ clauses.append(self._create())
66
+ elif self._at_keyword("RETURN"):
67
+ clauses.append(self._return())
68
+ break
69
+ else:
70
+ self._raise_clause_error()
71
+ if not clauses or (
72
+ not isinstance(clauses[-1], Return)
73
+ and not any(isinstance(clause, Create) for clause in clauses)
74
+ ):
75
+ raise self._syntax("a query must end with RETURN", self._peek().span)
76
+ trailing = self._peek()
77
+ if trailing.kind is not TokenKind.EOF:
78
+ if trailing.kind is TokenKind.KEYWORD and trailing.text.upper() in _UNSUPPORTED_CLAUSES:
79
+ raise self._unsupported_clause(trailing)
80
+ raise self._syntax(f"expected end of query, found {describe(trailing)}", trailing.span)
81
+ return Query(tuple(clauses), (0, len(self._query)))
82
+
83
+ def _raise_clause_error(self) -> Never:
84
+ token = self._peek()
85
+ if token.kind is TokenKind.KEYWORD and token.text.upper() in _ORDERING_CLAUSES:
86
+ raise self._syntax(
87
+ f"{_UNSUPPORTED_CLAUSES[token.text.upper()].construct} must follow RETURN",
88
+ token.span,
89
+ hint="put ORDER BY, SKIP and LIMIT at the end of the query, after RETURN",
90
+ )
91
+ if token.kind is TokenKind.KEYWORD and token.text.upper() in _UNSUPPORTED_CLAUSES:
92
+ raise self._unsupported_clause(token)
93
+ raise self._syntax(f"expected a clause, found {describe(token)}", token.span)
94
+
95
+ def _match(self) -> Match:
96
+ start = self._peek()
97
+ optional = False
98
+ if self._at_keyword("OPTIONAL"):
99
+ self._advance()
100
+ optional = True
101
+ if not self._at_keyword("MATCH"):
102
+ raise self._syntax(
103
+ f"expected MATCH after OPTIONAL, found {describe(self._peek())}",
104
+ self._peek().span,
105
+ )
106
+ self._advance()
107
+ self._reject_named_path()
108
+ paths = tuple(self._paths())
109
+ where = self._where() if self._at_keyword("WHERE") else None
110
+ end = where.span[1] if where is not None else paths[-1].span[1]
111
+ return Match(paths, where, optional, (start.span[0], end))
112
+
113
+ def _create(self) -> Create:
114
+ start = self._advance()
115
+ self._reject_named_path()
116
+ paths = tuple(self._paths())
117
+ return Create(paths, (start.span[0], paths[-1].span[1]))
118
+
119
+ def _with(self) -> With:
120
+ """`WITH [DISTINCT] var [AS name], ... [WHERE expression]`.
121
+
122
+ Only whole variables survive a `WITH`: a projection, an aggregate, an ordering or a page
123
+ would change what the result is, so each is refused by name before it reaches the binder.
124
+ """
125
+ start = self._advance()
126
+ distinct = False
127
+ if self._at_keyword("DISTINCT"):
128
+ self._advance()
129
+ distinct = True
130
+ items = [self._with_item()]
131
+ while self._peek().kind is TokenKind.COMMA:
132
+ self._advance()
133
+ items.append(self._with_item())
134
+ self._reject_with_ordering()
135
+ where = self._where() if self._at_keyword("WHERE") else None
136
+ self._reject_with_ordering()
137
+ end = where.span[1] if where is not None else items[-1].span[1]
138
+ return With(tuple(items), where, distinct, (start.span[0], end))
139
+
140
+ def _with_item(self) -> WithItem:
141
+ token = self._peek()
142
+ if token.kind is TokenKind.STAR:
143
+ raise UnsupportedCypherError(
144
+ "WITH * is not supported yet",
145
+ query=self._query,
146
+ span=token.span,
147
+ hint=_WITH_ITEM_HINT,
148
+ )
149
+ if self._at_keyword("EXISTS") and self._peek(1).kind is TokenKind.LBRACE:
150
+ raise UnsupportedCypherError(
151
+ "a pattern expression in WITH is not supported yet",
152
+ query=self._query,
153
+ span=(token.span[0], self._peek(1).span[1]),
154
+ hint=_WITH_EXISTS_HINT,
155
+ )
156
+ if self._at_keyword("CASE"):
157
+ raise self._case_error(token)
158
+ var = self._name("a variable")
159
+ if self._peek().kind is TokenKind.LPAREN:
160
+ feature = (
161
+ "aggregation in WITH"
162
+ if var.text.upper() in _AGGREGATE_FUNCTIONS
163
+ else "a function call in WITH"
164
+ )
165
+ raise UnsupportedCypherError(
166
+ f"{feature} is not supported yet",
167
+ query=self._query,
168
+ span=var.span,
169
+ hint=_WITH_ITEM_HINT,
170
+ )
171
+ if self._peek().kind is TokenKind.DOT:
172
+ self._advance()
173
+ key = self._name("a property name")
174
+ raise UnsupportedCypherError(
175
+ "projecting a property in WITH is not supported yet",
176
+ query=self._query,
177
+ span=(var.span[0], key.span[1]),
178
+ hint=_WITH_ITEM_HINT,
179
+ )
180
+ alias = None
181
+ if self._at_keyword("AS"):
182
+ self._advance()
183
+ alias = self._name("a variable")
184
+ end = alias.span[1] if alias is not None else var.span[1]
185
+ return WithItem(var, alias, (var.span[0], end))
186
+
187
+ def _reject_with_ordering(self) -> None:
188
+ """`ORDER BY`/`SKIP`/`LIMIT` after `WITH` are out of the subset, with the reason."""
189
+ token = self._peek()
190
+ for word in ("ORDER", "SKIP", "LIMIT"):
191
+ if self._at_keyword(word):
192
+ raise UnsupportedCypherError(
193
+ f"{_UNSUPPORTED_CLAUSES[word].construct} in WITH is not supported yet",
194
+ query=self._query,
195
+ span=token.span,
196
+ hint=_WITH_ORDER_HINT,
197
+ )
198
+
199
+ def _return(self) -> Return:
200
+ """`RETURN [DISTINCT] var [ORDER BY var [ASC|DESC]] [SKIP operand] [LIMIT operand]`.
201
+
202
+ The ordering item and the two page operands are parsed here, but only the binder decides
203
+ whether the ordering names the returned variable and whether a page value is a
204
+ non-negative integer. `ORDER BY` of a property, a function or any other expression is
205
+ refused here, with the reason, before it can reach the binder as a value.
206
+ """
207
+ start = self._advance()
208
+ distinct = False
209
+ if self._at_keyword("DISTINCT"):
210
+ self._advance()
211
+ distinct = True
212
+ if self._peek().kind is TokenKind.STAR:
213
+ raise self._unsupported(self._peek(), "RETURN *", hint=hint_for("projection"))
214
+ if self._peek().kind is TokenKind.LBRACKET:
215
+ opening = self._peek()
216
+ raise UnsupportedCypherError(
217
+ "returning a list or a comprehension is not supported yet",
218
+ query=self._query,
219
+ span=opening.span,
220
+ hint=_RETURN_COMPREHENSION_HINT,
221
+ )
222
+ if self._at_keyword("CASE"):
223
+ raise self._case_error(self._peek())
224
+ var = self._name("a variable")
225
+ trailing = self._peek()
226
+ if trailing.kind is TokenKind.LPAREN:
227
+ aggregate = var.text.upper() in _AGGREGATE_FUNCTIONS
228
+ raise UnsupportedCypherError(
229
+ f"{'aggregation' if aggregate else 'a function call'} is not supported yet",
230
+ query=self._query,
231
+ span=(var.span[0], trailing.span[1]),
232
+ hint=hint_for("aggregation" if aggregate else "function-call"),
233
+ )
234
+ if trailing.kind is TokenKind.LBRACKET:
235
+ # `p[0]` and `p[0..2]`: a key set has no elements, so indexing is refused here
236
+ # rather than falling through to the trailing-token syntax error.
237
+ raise UnsupportedCypherError(
238
+ "list indexing is not supported yet",
239
+ query=self._query,
240
+ span=(var.span[0], trailing.span[1]),
241
+ hint=hint_for("list-index"),
242
+ )
243
+ if trailing.kind is TokenKind.DOT:
244
+ self._advance()
245
+ property_name = self._name("a property name")
246
+ raise UnsupportedCypherError(
247
+ "returning a property is not supported yet",
248
+ query=self._query,
249
+ span=(var.span[0], property_name.span[1]),
250
+ hint=hint_for("projection"),
251
+ )
252
+ if trailing.kind is TokenKind.COMMA:
253
+ raise self._unsupported(
254
+ trailing, "returning several values", hint=hint_for("projection")
255
+ )
256
+ order = self._order() if self._at_keyword("ORDER") else None
257
+ skip = self._page("SKIP") if self._at_keyword("SKIP") else None
258
+ limit = self._page("LIMIT") if self._at_keyword("LIMIT") else None
259
+ self._reject_page_misplacement(limit=limit is not None)
260
+ end = var.span[1]
261
+ for parsed in (order, skip, limit):
262
+ if parsed is not None:
263
+ end = parsed.span[1]
264
+ return Return(var, distinct, order, skip, limit, (start.span[0], end))
265
+
266
+ def _order(self) -> OrderItem:
267
+ """`ORDER BY var [ASC|DESC]`: one bare variable, never a property or expression."""
268
+ start = self._advance()
269
+ self._expect_keyword("BY")
270
+ token = self._peek()
271
+ if token.kind is TokenKind.EOF or (
272
+ token.kind is TokenKind.KEYWORD and token.text.upper() in {"ORDER", "SKIP", "LIMIT"}
273
+ ):
274
+ raise self._syntax(
275
+ f"ORDER BY needs the returned variable after it, found {describe(token)}",
276
+ token.span,
277
+ hint=_ORDER_HINT,
278
+ )
279
+ if not self._starts_order_name(token):
280
+ raise UnsupportedCypherError(
281
+ "ordering by an expression is not supported yet",
282
+ query=self._query,
283
+ span=token.span,
284
+ hint=_ORDER_HINT,
285
+ )
286
+ var = self._name("the returned variable")
287
+ if self._peek().kind is TokenKind.DOT:
288
+ self._advance()
289
+ key = self._name("a property name")
290
+ raise UnsupportedCypherError(
291
+ "ordering by a property is not supported yet",
292
+ query=self._query,
293
+ span=(var.span[0], key.span[1]),
294
+ hint=_ORDER_HINT,
295
+ )
296
+ if self._peek().kind is TokenKind.LPAREN:
297
+ raise UnsupportedCypherError(
298
+ "a function call is not supported yet",
299
+ query=self._query,
300
+ span=(var.span[0], self._peek().span[1]),
301
+ hint=_ORDER_HINT,
302
+ )
303
+ direction = SortDirection.ASC
304
+ end = var.span[1]
305
+ direction_token = self._peek()
306
+ written = direction_token.text.upper()
307
+ if written == "ASC":
308
+ end = self._advance().span[1]
309
+ elif written == "DESC":
310
+ self._advance()
311
+ direction = SortDirection.DESC
312
+ end = direction_token.span[1]
313
+ elif written in ("ASCENDING", "DESCENDING"):
314
+ raise self._syntax(
315
+ f"write {'ASC' if written == 'ASCENDING' else 'DESC'} for the direction, "
316
+ f"found {describe(direction_token)}",
317
+ direction_token.span,
318
+ hint="only ASC and DESC are compiled, in that spelling",
319
+ )
320
+ trailing = self._peek()
321
+ if trailing.kind is TokenKind.COMMA:
322
+ raise UnsupportedCypherError(
323
+ "ordering by several values is not supported yet",
324
+ query=self._query,
325
+ span=trailing.span,
326
+ hint=_ORDER_HINT,
327
+ )
328
+ if self._at_keyword("ORDER"):
329
+ raise self._syntax(
330
+ "ORDER BY may appear only once", trailing.span, hint=_CLAUSE_ORDER_HINT
331
+ )
332
+ if trailing.kind is not TokenKind.EOF and not self._at_keyword("SKIP", "LIMIT"):
333
+ raise UnsupportedCypherError(
334
+ "ordering by an expression is not supported yet",
335
+ query=self._query,
336
+ span=(start.span[0], trailing.span[1]),
337
+ hint=_ORDER_HINT,
338
+ )
339
+ return OrderItem(var, direction, (start.span[0], end))
340
+
341
+ def _starts_order_name(self, token: Token) -> bool:
342
+ """Whether the token after `ORDER BY` can open the one variable an order item names."""
343
+ if token.kind is TokenKind.KEYWORD and (
344
+ token.text.upper() in _LITERAL_KEYWORDS or token.text.upper() in _OPERATOR_KEYWORDS
345
+ ):
346
+ return False
347
+ return token.kind in (TokenKind.IDENT, TokenKind.KEYWORD)
348
+
349
+ def _page(self, keyword: str) -> Page:
350
+ """`SKIP`/`LIMIT` with an integer literal or a `$param`; a negative literal is parsed.
351
+
352
+ A literal above `2^63-1` is refused here, naming the clause; a negative literal is kept
353
+ so the binder can refuse it by name ("SKIP must be a non-negative integer") instead of a
354
+ syntax error about a missing value. Every other operand shape is refused here, with the
355
+ shape that was written.
356
+ """
357
+ start = self._advance()
358
+ token = self._peek()
359
+ value: Lit | Param
360
+ if token.kind is TokenKind.INTEGER:
361
+ self._advance()
362
+ value = self._page_literal(keyword, token, sign=1)
363
+ elif token.kind is TokenKind.MINUS and self._peek(1).kind is TokenKind.INTEGER:
364
+ minus = self._advance()
365
+ number = self._advance()
366
+ literal = self._page_literal(keyword, number, sign=-1)
367
+ value = Lit(literal.value, (minus.span[0], number.span[1]))
368
+ elif token.kind in (TokenKind.PARAM, TokenKind.INTERPOLATION):
369
+ self._advance()
370
+ value = Param(cast(str, token.value), token.span)
371
+ else:
372
+ raise self._syntax(
373
+ f"{keyword} must be an integer literal or a $parameter, found {describe(token)}",
374
+ token.span,
375
+ hint=_PAGE_HINT,
376
+ )
377
+ return Page(keyword, value, (start.span[0], value.span[1]))
378
+
379
+ def _page_literal(self, keyword: str, token: Token, *, sign: int) -> Lit:
380
+ """One page literal, refused at parse when it is above the `bigint` range."""
381
+ value = cast(int, token.value) * sign
382
+ if value > _INT64_MAX:
383
+ raise self._syntax(
384
+ f"{keyword} must be an integer in 0 … 2^63-1",
385
+ token.span,
386
+ hint="leave SKIP or LIMIT out instead of paging beyond bigint",
387
+ )
388
+ return Lit(value, token.span)
389
+
390
+ def _reject_page_misplacement(self, *, limit: bool) -> None:
391
+ """`ORDER BY`, `SKIP` and `LIMIT` appear once each, in that order, after `RETURN`."""
392
+ token = self._peek()
393
+ if self._at_keyword("ORDER"):
394
+ raise self._syntax(
395
+ "ORDER BY must come before SKIP and LIMIT",
396
+ token.span,
397
+ hint=_CLAUSE_ORDER_HINT,
398
+ )
399
+ if self._at_keyword("SKIP"):
400
+ raise self._syntax(
401
+ "SKIP must come before LIMIT" if limit else "SKIP may appear only once", token.span
402
+ )
403
+ if self._at_keyword("LIMIT"):
404
+ raise self._syntax("LIMIT may appear only once", token.span)