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,387 @@
1
+ """The query's clauses in order, and the values they bind.
2
+
3
+ `bind` walks the clauses, keeping the names, ids and parameter budget across them, and returns the
4
+ `Bound` the planner consumes. This module is the stage's entry point: `cypher2sql._bind.bind` is
5
+ this method behind a function."""
6
+
7
+ from __future__ import annotations
8
+
9
+ from cypher2sql._ast import (
10
+ Create,
11
+ Lit,
12
+ Match,
13
+ Page,
14
+ Param,
15
+ Query,
16
+ RelPat,
17
+ Return,
18
+ SortDirection,
19
+ With,
20
+ )
21
+ from cypher2sql._compare import (
22
+ _INT64_MAX,
23
+ )
24
+ from cypher2sql._errors import (
25
+ CypherSemanticError,
26
+ CypherSyntaxError,
27
+ ParameterError,
28
+ UnsupportedCypherError,
29
+ bounded_text,
30
+ )
31
+ from cypher2sql._ir import (
32
+ BAnd,
33
+ BConst,
34
+ BExpr,
35
+ BInferred,
36
+ BIsNull,
37
+ BNode,
38
+ BOrder,
39
+ BOrderKey,
40
+ Bound,
41
+ BPresent,
42
+ BRel,
43
+ BScope,
44
+ BTrail,
45
+ BValue,
46
+ BWalk,
47
+ ConstValue,
48
+ PgType,
49
+ text_key,
50
+ )
51
+ from cypher2sql._unsupported import hint_for
52
+
53
+ from ._base import _DECLARE_IN_MATCH, _DROPPED_BY_WITH, _WITH_ITEMS_SEE_BEFORE
54
+ from ._predicates import _Predicates
55
+
56
+
57
+ class _Binder(_Predicates):
58
+ """One bind of one query; accumulates the parameter values in textual order."""
59
+
60
+ def bind(self, query: Query) -> Bound:
61
+ target_return: Return | None = None
62
+ nodes: list[BNode] = []
63
+ rels: list[BRel] = []
64
+ inferred: list[BInferred] = []
65
+ recursive: list[BWalk] = []
66
+ trails: list[BTrail] = []
67
+ properties: list[BExpr] = []
68
+ wheres: list[BExpr] = []
69
+ scopes: list[BScope] = []
70
+ unsatisfiable = False
71
+ for clause in query.clauses:
72
+ match clause:
73
+ case Create():
74
+ raise UnsupportedCypherError(
75
+ "CREATE is not supported yet",
76
+ query=self._text,
77
+ span=clause.span,
78
+ hint=hint_for("write"),
79
+ )
80
+ case With():
81
+ # A `WITH` is a variable-scope boundary, not a pattern clause: its `WHERE`
82
+ # filters the rows produced so far, so it joins the outer `WHERE` and is
83
+ # never folded into an optional expansion's body.
84
+ filter_expr = self._with(clause)
85
+ if not (
86
+ isinstance(filter_expr, BConst) and filter_expr.value is ConstValue.TRUE
87
+ ):
88
+ wheres.append(filter_expr)
89
+ continue
90
+ case Return():
91
+ target_return = clause
92
+ continue
93
+ case Match():
94
+ pass
95
+ # One number per pattern scope: a `BTrail`'s uniqueness holds only among the
96
+ # occurrences that share it, and a subquery's clauses take their own.
97
+ self._clause += 1
98
+ self._optional_group = len(scopes) if clause.optional else None
99
+ rel_names = set(self._rel_vars)
100
+ self._start_clause()
101
+ parts = self._pattern(clause.paths, clause.where, clause.span)
102
+ where = (
103
+ self._condition(clause.where.expr)
104
+ if clause.where is not None
105
+ else BConst(ConstValue.TRUE)
106
+ )
107
+ declares = bool(parts.nodes or parts.rels or parts.inferred or parts.recursive)
108
+ if clause.optional or (scopes and declares):
109
+ # From the first OPTIONAL MATCH on, a clause is a row scope of its own: it can only
110
+ # name what earlier clauses declared, so the scopes are planned in clause order and
111
+ # a relationship's uniqueness never spans two of them.
112
+ index = len(scopes)
113
+ if parts.unsat and clause.optional:
114
+ # An empty interval matches nothing, so the optional side is its null row.
115
+ where = BConst(ConstValue.FALSE)
116
+ unsatisfiable = unsatisfiable or (parts.unsat and not clause.optional)
117
+ scopes.append(
118
+ BScope(
119
+ index,
120
+ clause.optional,
121
+ parts.nodes,
122
+ parts.rels,
123
+ parts.inferred,
124
+ parts.recursive,
125
+ parts.trails,
126
+ parts.properties,
127
+ where,
128
+ )
129
+ )
130
+ if clause.optional:
131
+ # Every variable this clause declared may be missing afterwards, nodes and
132
+ # relationships alike (a variable-length one included): `IS [NOT] NULL` on any
133
+ # reads the scope's presence, and a later mandatory clause naming a node
134
+ # requires it to be present.
135
+ declared = {node.id for node in parts.nodes}
136
+ for name, known in self._variables.items():
137
+ if known.id in declared:
138
+ self._optional_of[name] = index
139
+ for name in set(self._rel_vars) - rel_names:
140
+ self._optional_of[name] = index
141
+ continue
142
+ # The pattern every row has: indices into the merged expansions and walks continue
143
+ # across clauses, so each trail still names its own clause's ones.
144
+ trails.extend(
145
+ BTrail(
146
+ trail.rels,
147
+ tuple(position + len(inferred) for position in trail.expansions),
148
+ tuple(position + len(recursive) for position in trail.recursions),
149
+ trail.clause,
150
+ )
151
+ for trail in parts.trails
152
+ )
153
+ nodes.extend(parts.nodes)
154
+ rels.extend(parts.rels)
155
+ inferred.extend(parts.inferred)
156
+ recursive.extend(parts.recursive)
157
+ properties.extend(parts.properties)
158
+ if not (isinstance(where, BConst) and where.value is ConstValue.TRUE):
159
+ wheres.append(where)
160
+ unsatisfiable = unsatisfiable or parts.unsat
161
+ # A variable a mandatory clause names again is present from that clause on, and one
162
+ # presence test per group covers every later naming of it.
163
+ wheres.extend(
164
+ BIsNull(BPresent(group), negated=True) for group in sorted(self._present_groups)
165
+ )
166
+ if target_return is None:
167
+ raise CypherSemanticError(
168
+ "a query must end with RETURN", query=self._text, span=query.span
169
+ )
170
+ target = self._variables.get(target_return.var.text)
171
+ if target is None and target_return.var.text in self._rel_vars:
172
+ # A relationship has no key set of its own; the result is one node type's keys.
173
+ raise UnsupportedCypherError(
174
+ "returning a relationship is not supported yet",
175
+ query=self._text,
176
+ span=target_return.var.span,
177
+ hint=hint_for("projection"),
178
+ )
179
+ if target is None:
180
+ raise self._unknown_variable(target_return.var.text, target_return.var.span)
181
+ if any(node.id == target.id for scope in scopes if scope.optional for node in scope.nodes):
182
+ raise UnsupportedCypherError(
183
+ "cannot return a variable an OPTIONAL MATCH may leave unbound",
184
+ query=self._text,
185
+ span=target_return.var.span,
186
+ hint="a null row is not a key set; return the variable the optional side hangs "
187
+ "off, so every returned row has its keys",
188
+ )
189
+ if not wheres:
190
+ where = BConst(ConstValue.TRUE)
191
+ elif len(wheres) == 1:
192
+ where = wheres[0]
193
+ else:
194
+ where = BAnd(tuple(wheres))
195
+ # The page is validated before anything is returned, so a bad `$skip`/`$limit` is the
196
+ # error even when the pattern itself is unsatisfiable and no row could ever come back.
197
+ order = self._order(target_return, target)
198
+ page_values: list[object] = []
199
+ skip = None if target_return.skip is None else self._page(target_return.skip, page_values)
200
+ limit = (
201
+ None if target_return.limit is None else self._page(target_return.limit, page_values)
202
+ )
203
+ if unsatisfiable:
204
+ # An empty interval cannot match: `WHERE FALSE`, with no `EXISTS` and no parameter
205
+ # left behind (every value bound while validating the pattern is dropped with it).
206
+ return Bound(
207
+ target,
208
+ (),
209
+ (),
210
+ (),
211
+ (),
212
+ (),
213
+ (),
214
+ BConst(ConstValue.FALSE),
215
+ tuple(page_values),
216
+ order=order,
217
+ skip=skip,
218
+ limit=limit,
219
+ )
220
+ values = tuple(self._values)
221
+ if skip is not None:
222
+ skip = BValue(skip.index + len(values), skip.pg_type)
223
+ if limit is not None:
224
+ limit = BValue(limit.index + len(values), limit.pg_type)
225
+ return Bound(
226
+ target,
227
+ tuple(nodes),
228
+ tuple(rels),
229
+ tuple(inferred),
230
+ tuple(recursive),
231
+ tuple(trails),
232
+ tuple(properties),
233
+ where,
234
+ values + tuple(page_values),
235
+ tuple(scopes),
236
+ order=order,
237
+ skip=skip,
238
+ limit=limit,
239
+ )
240
+
241
+ def _order(self, clause: Return, target: BNode) -> BOrder | None:
242
+ """Resolve `ORDER BY v` against the returned variable and its declared key types.
243
+
244
+ The result is a key set, so ordering is by the target's key columns alone: naming any
245
+ other variable is refused with a hint, and an unknown name is the usual semantic error.
246
+ A key column whose declared property type is `str` orders by code point (the planner
247
+ pins `COLLATE "C"`); a key column no property declares has no declared type of its own.
248
+ """
249
+ item = clause.order
250
+ if item is None:
251
+ return None
252
+ if item.var.text != clause.var.text:
253
+ if item.var.text not in self._variables:
254
+ raise self._unknown_variable(item.var.text, item.var.span)
255
+ raise UnsupportedCypherError(
256
+ "cannot order by a variable other than the returned one",
257
+ query=self._text,
258
+ span=item.var.span,
259
+ hint=hint_for("order-by"),
260
+ )
261
+ node_type = target.node_type
262
+ keys = tuple(BOrderKey(column, text_key(node_type, column)) for column in node_type.key)
263
+ return BOrder(keys, item.direction is SortDirection.DESC)
264
+
265
+ def _page(self, page: Page, values: list[object]) -> BValue:
266
+ """One `SKIP`/`LIMIT` operand as a bound `bigint`: a literal, or a checked `$param`.
267
+
268
+ Either operand is a value, never SQL text, so the emitted SQL always reads `%s::bigint`.
269
+ A negative or out-of-int64 literal is a compile error; the same in a `$param` is a
270
+ `ParameterError` naming the parameter and never echoing its value.
271
+ """
272
+ match page.value:
273
+ case Lit(value=value, span=span):
274
+ if not isinstance(value, int) or isinstance(value, bool):
275
+ raise AssertionError("internal error: a page literal must be an int")
276
+ if value < 0:
277
+ raise CypherSyntaxError(
278
+ f"{page.keyword} must be a non-negative integer",
279
+ query=self._text,
280
+ span=span,
281
+ hint="a page value is zero or more; leave SKIP or LIMIT out instead",
282
+ )
283
+ values.append(value)
284
+ return BValue(len(values) - 1, PgType.BIGINT)
285
+ case Param(name=name, span=span):
286
+ source = self._param_value(name, span)
287
+ page_value = source.value
288
+ if type(page_value) is not int:
289
+ raise ParameterError(
290
+ f"parameter {bounded_text(source.shown)} must be an integer",
291
+ query=self._text,
292
+ span=span,
293
+ hint="pass a non-negative int for SKIP or LIMIT",
294
+ )
295
+ if page_value < 0:
296
+ raise ParameterError(
297
+ f"parameter {bounded_text(source.shown)} must be non-negative",
298
+ query=self._text,
299
+ span=span,
300
+ hint="a page value is zero or more",
301
+ )
302
+ if page_value > _INT64_MAX:
303
+ raise ParameterError(
304
+ f"parameter {bounded_text(source.shown)} is beyond bigint",
305
+ query=self._text,
306
+ span=span,
307
+ hint=f"pass at most {_INT64_MAX}",
308
+ )
309
+ values.append(page_value)
310
+ return BValue(len(values) - 1, PgType.BIGINT)
311
+
312
+ def _with(self, clause: With) -> BExpr:
313
+ """Apply one `WITH`: resolve its items, bind its filter, then commit the new scope.
314
+
315
+ Cypher evaluates a `WITH`'s `WHERE` against the names it projects *and* the names still
316
+ bound when the clause starts (the TCK's "WHERE sees a variable bound before but not after
317
+ WITH"), so the filter is bound over both; only the projected names survive it. A name
318
+ absent from the items is unbound afterwards, and a later reference is a semantic error
319
+ naming it. `DISTINCT` is accepted and changes nothing: the result is a key set already.
320
+ """
321
+ self._optional_group = None
322
+ kept_nodes: dict[str, BNode] = {}
323
+ kept_rels: dict[str, tuple[BRel | None, RelPat]] = {}
324
+ kept_optional: dict[str, int] = {}
325
+ projected: set[str] = set()
326
+ for item in clause.items:
327
+ source = item.name.text
328
+ target = (item.alias if item.alias is not None else item.name).text
329
+ if target in kept_nodes or target in kept_rels:
330
+ raise CypherSemanticError(
331
+ f"variable {bounded_text(target)} is declared twice by WITH",
332
+ query=self._text,
333
+ span=(item.alias if item.alias is not None else item.name).span,
334
+ hint="give each projected name its own variable",
335
+ )
336
+ node = self._variables.get(source)
337
+ if node is not None:
338
+ kept_nodes[target] = node
339
+ else:
340
+ relation = self._rel_vars.get(source)
341
+ if relation is None:
342
+ raise self._unknown_variable(
343
+ source, item.name.span, self._with_item_hint(source, projected)
344
+ )
345
+ kept_rels[target] = relation
346
+ group = self._optional_of.get(source)
347
+ if group is not None:
348
+ kept_optional[target] = group
349
+ projected.add(target)
350
+ dropped = (set(self._variables) | set(self._rel_vars)) - set(kept_nodes) - set(kept_rels)
351
+ before = (self._variables, self._rel_vars, self._optional_of)
352
+ # A projected name replaces whatever it shadowed, in every scope map: an alias may take
353
+ # the name of a variable the WITH does not keep, and must not inherit its null-ness.
354
+ self._variables = {
355
+ name: node for name, node in self._variables.items() if name not in projected
356
+ } | kept_nodes
357
+ self._rel_vars = {
358
+ name: rel for name, rel in self._rel_vars.items() if name not in projected
359
+ } | kept_rels
360
+ self._optional_of = {
361
+ name: group for name, group in self._optional_of.items() if name not in projected
362
+ } | kept_optional
363
+ try:
364
+ where = (
365
+ self._condition(clause.where.expr)
366
+ if clause.where is not None
367
+ else BConst(ConstValue.TRUE)
368
+ )
369
+ finally:
370
+ self._variables, self._rel_vars, self._optional_of = before
371
+ self._variables = kept_nodes
372
+ self._rel_vars = kept_rels
373
+ self._optional_of = kept_optional
374
+ self._dropped |= dropped
375
+ self._dropped -= projected
376
+ return where
377
+
378
+ def _with_item_hint(self, source: str, projected: set[str]) -> str:
379
+ """Why a `WITH` item's name did not resolve.
380
+
381
+ The items read the scope the clause starts with, so a name only an earlier item of the
382
+ same `WITH` introduced (`WITH a AS b, b AS c`) is not visible to a later one; a name an
383
+ earlier `WITH` dropped keeps the drop's own hint.
384
+ """
385
+ if source in self._dropped:
386
+ return _DROPPED_BY_WITH
387
+ return _WITH_ITEMS_SEE_BEFORE if source in projected else _DECLARE_IN_MATCH