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,560 @@
1
+ """Boolean expressions and their operands: `WHERE`, `EXISTS` bodies and pattern predicates.
2
+
3
+ Cypher's three-valued logic decides at bind time what it can — a comparison of two literals folds,
4
+ a label predicate folds against the static schema — and keeps the rest as bound nodes the planner
5
+ renders with explicit null guards. An `EXISTS` body is flattened and built like a match clause; a
6
+ pattern predicate may only name variables already bound, and a variable an `OPTIONAL MATCH` may
7
+ have left unbound makes the predicate NULL instead of FALSE."""
8
+
9
+ from __future__ import annotations
10
+
11
+ from cypher2sql._ast import (
12
+ And,
13
+ Cmp,
14
+ Comparison,
15
+ ExistsMatch,
16
+ ExistsSubquery,
17
+ Expr,
18
+ HasLabel,
19
+ In,
20
+ IsNull,
21
+ ListLit,
22
+ Lit,
23
+ NodePat,
24
+ Not,
25
+ Or,
26
+ Param,
27
+ Path,
28
+ PatternPredicate,
29
+ Prop,
30
+ Regex,
31
+ RelPat,
32
+ StringOp,
33
+ StringPredicate,
34
+ Var,
35
+ Where,
36
+ Xor,
37
+ )
38
+ from cypher2sql._compare import (
39
+ _fold_values,
40
+ _ValueSource,
41
+ )
42
+ from cypher2sql._errors import (
43
+ CypherSemanticError,
44
+ Span,
45
+ UnsupportedCypherError,
46
+ )
47
+ from cypher2sql._ir import (
48
+ BAnd,
49
+ BCol,
50
+ BConst,
51
+ BExists,
52
+ BExpr,
53
+ BFold,
54
+ BIn,
55
+ BInferred,
56
+ BIsNull,
57
+ BNode,
58
+ BNodeRef,
59
+ BNot,
60
+ BNullWhen,
61
+ BOr,
62
+ BOwner,
63
+ BPresent,
64
+ BRegex,
65
+ BRel,
66
+ BRelRef,
67
+ BString,
68
+ BTrail,
69
+ BWalk,
70
+ BXor,
71
+ ConstValue,
72
+ Op,
73
+ PgType,
74
+ expr_children,
75
+ property_type,
76
+ )
77
+
78
+ from ._base import _NOT_A_CONDITION, _OPS, _Conditional, _Operand
79
+ from ._build import _Build
80
+ from ._values import _B_STRING_OP, _UNMATCHABLE, _flip, _fold_string, _list_element
81
+
82
+
83
+ def _path_names(path: Path) -> frozenset[str]:
84
+ """Every variable a pattern path names, in written order."""
85
+ return frozenset(
86
+ element.var.text
87
+ for element in path.elements
88
+ if isinstance(element, NodePat | RelPat) and element.var is not None
89
+ )
90
+
91
+
92
+ def _body_elements(
93
+ nodes: list[BNode], rels: list[BRel], inferred: list[BInferred]
94
+ ) -> frozenset[BOwner]:
95
+ """Every column owner whose columns a subquery body's own rows carry."""
96
+ owners: set[BOwner] = {BNodeRef(node.id) for node in nodes}
97
+ owners |= {BRelRef(rel.id) for rel in rels}
98
+ for relation in inferred:
99
+ for path in relation.alternatives:
100
+ owners |= {BNodeRef(node.id) for node in path.nodes}
101
+ owners |= {BRelRef(rel.id) for rel in path.rels}
102
+ return frozenset(owners)
103
+
104
+
105
+ def _body_refs(
106
+ expressions: tuple[BExpr, ...], own: frozenset[BOwner]
107
+ ) -> tuple[set[BOwner], set[int]]:
108
+ """What a subquery body reads from outside itself: outer columns, optional-scope presences.
109
+
110
+ A nested body's references to this body's own elements stay inside it, so only the ones that
111
+ escape are propagated — that is what lets the planner see which group a correlated body
112
+ belongs to.
113
+ """
114
+ owners: set[BOwner] = set()
115
+ groups: set[int] = set()
116
+
117
+ def walk(expr: BExpr) -> None:
118
+ if isinstance(expr, BExists):
119
+ owners.update(owner for owner in expr.refs if owner not in own)
120
+ groups.update(expr.groups)
121
+ return
122
+ if isinstance(expr, BPresent):
123
+ groups.add(expr.index)
124
+ return
125
+ if isinstance(expr, BCol) and expr.owner not in own:
126
+ owners.add(expr.owner)
127
+ for child in expr_children(expr):
128
+ walk(child)
129
+
130
+ for expression in expressions:
131
+ walk(expression)
132
+ return owners, groups
133
+
134
+
135
+ def _body_end_refs(
136
+ nodes: list[BNode],
137
+ rels: list[BRel],
138
+ inferred: list[BInferred],
139
+ recursive: list[BWalk],
140
+ ) -> set[BOwner]:
141
+ """The outer nodes a body's relationship endpoints name, beyond the body's own nodes.
142
+
143
+ An endpoint an earlier clause bound is not one of the body's nodes: the body reads the row
144
+ that clause already produced, exactly like a column reference, so the planner has to place
145
+ the body where that alias is in scope.
146
+ """
147
+ own = {node.id for node in nodes}
148
+ own |= {
149
+ node.id for relation in inferred for path in relation.alternatives for node in path.nodes
150
+ }
151
+ ends: set[int] = set()
152
+ for rel in rels:
153
+ ends |= {rel.left, rel.right}
154
+ for relation in inferred:
155
+ ends |= {relation.left, relation.right}
156
+ for walk in recursive:
157
+ ends |= {walk.left, walk.right}
158
+ return {BNodeRef(end) for end in ends if end not in own}
159
+
160
+
161
+ def _all_wheres(wheres: list[BExpr]) -> BExpr:
162
+ """One conjunction of the body's filters; `TRUE` when it has none."""
163
+ if not wheres:
164
+ return BConst(ConstValue.TRUE)
165
+ if len(wheres) == 1:
166
+ return wheres[0]
167
+ return BAnd(tuple(wheres))
168
+
169
+
170
+ class _Predicates(_Build):
171
+ """Expression binding: conditions, comparisons, operands and subquery bodies."""
172
+
173
+ def _condition(self, expr: Expr) -> BExpr:
174
+ """Bind one boolean expression; every node is either a predicate or a comparison."""
175
+ match expr:
176
+ case And(items=items):
177
+ return BAnd(tuple(self._condition(item) for item in items))
178
+ case Or(items=items):
179
+ return BOr(tuple(self._condition(item) for item in items))
180
+ case Xor(items=items):
181
+ # A flat chain stays one n-ary node; only parentheses nest another level.
182
+ return BXor(tuple(self._condition(item) for item in items))
183
+ case Not(operand=operand):
184
+ return BNot(self._condition(operand))
185
+ case Cmp(op=op, left=left, right=right, op_span=op_span, span=span):
186
+ return self._comparison(op, left, right, op_span, span)
187
+ case In(left=left, items=items, span=span):
188
+ return self._in(left, items, span)
189
+ case StringPredicate(op=op, left=left, right=right, span=span):
190
+ return self._string_predicate(op, left, right, span)
191
+ case Regex(left=left, pattern=pattern, span=span):
192
+ return self._regex(left, pattern, span)
193
+ case IsNull(operand=operand, negated=negated):
194
+ return self._is_null(operand, negated)
195
+ case HasLabel(operand=operand, label=label):
196
+ return self._has_label(operand, label)
197
+ case PatternPredicate(path=path, span=span):
198
+ return self._pattern_predicate(path, span)
199
+ case ExistsSubquery(clauses=clauses, span=span):
200
+ return self._exists_subquery(clauses, span)
201
+ case Prop(owner=owner, key=key, key_span=key_span, span=span):
202
+ return self._condition_property(owner, key, key_span, span)
203
+ case Lit(value=value) if value is True:
204
+ return BConst(ConstValue.TRUE)
205
+ case Lit(value=value) if value is False:
206
+ return BConst(ConstValue.FALSE)
207
+ case Lit(value=None):
208
+ return BConst(ConstValue.NULL)
209
+ case Param(name=name, span=span):
210
+ return self._boolean_param(name, span)
211
+ case Var(name=name, span=span):
212
+ # `WHERE (a)` with `a` unbound names a variable that is not there: saying so is
213
+ # more use than "expected a condition", which is about a bound node.
214
+ if name not in self._variables and name not in self._rel_vars:
215
+ raise self._unknown_variable(name, span)
216
+ raise CypherSemanticError(
217
+ "expected a condition",
218
+ query=self._text,
219
+ span=span,
220
+ hint=_NOT_A_CONDITION,
221
+ )
222
+ case _:
223
+ raise CypherSemanticError(
224
+ "expected a condition",
225
+ query=self._text,
226
+ span=expr.span,
227
+ hint=_NOT_A_CONDITION,
228
+ )
229
+
230
+ def _comparison(
231
+ self, op: Comparison, left: Expr, right: Expr, op_span: Span, span: Span
232
+ ) -> BExpr:
233
+ operator = _OPS[op]
234
+ match (left, right):
235
+ case (
236
+ Prop(owner=left_owner, key=left_key, key_span=left_key_span, span=left_span),
237
+ Prop(owner=right_owner, key=right_key, key_span=right_key_span, span=right_span),
238
+ ):
239
+ return self._column_comparison(
240
+ operator,
241
+ self._property(left_owner, left_key, left_key_span, left_span),
242
+ self._property(right_owner, right_key, right_key_span, right_span),
243
+ left_key,
244
+ right_key,
245
+ span,
246
+ )
247
+ left_operand = self._operand(left)
248
+ right_operand = self._operand(right)
249
+ match (left_operand, right_operand):
250
+ case (BCol() as column, _ValueSource() as value):
251
+ return self._value_comparison(operator, column, value)
252
+ case (_ValueSource() as value, BCol() as column):
253
+ return self._value_comparison(_flip(operator), column, value)
254
+ case (_ValueSource() as left_value, _ValueSource() as right_value):
255
+ return BConst(_fold_values(operator, left_value, right_value, self._text, op_span))
256
+ case _:
257
+ return self._conditional_comparison(operator, left_operand, right_operand, span)
258
+
259
+ def _in(self, left: Expr, items: ListLit | Param, span: Span) -> BExpr:
260
+ """`left IN list`: one bound array, with Cypher's null answer kept.
261
+
262
+ A list literal element the compared type can never equal is dropped (Cypher compares it
263
+ and gets false); a `$parameter` list is checked element by element and a mismatch raises,
264
+ naming the parameter and the declared type, never a value. An empty list matches nothing —
265
+ `null IN []` is false, not NULL — and a list whose every element is unmatchable keeps the
266
+ column's null-ness through `BFold`.
267
+ """
268
+ match left:
269
+ case Prop(owner=owner, key=key, key_span=key_span, span=left_span):
270
+ column = self._property(owner, key, key_span, left_span)
271
+ case _:
272
+ return self._value_in(left, self._list_sources(items, None), span)
273
+ declared = property_type(column.pg_type)
274
+ sources = self._list_sources(items, declared)
275
+ if not sources:
276
+ return BConst(ConstValue.FALSE)
277
+ values: list[object] = []
278
+ for source in sources:
279
+ converted = _list_element(source, declared, self._text)
280
+ if converted is not _UNMATCHABLE:
281
+ values.append(converted)
282
+ if not values:
283
+ return BFold(BIsNull(column))
284
+ return BIn(column, self._array(values, column.pg_type))
285
+
286
+ def _is_null(self, operand: Expr, negated: bool) -> BExpr:
287
+ match operand:
288
+ case Prop(owner=owner, key=key, key_span=key_span, span=span):
289
+ return BIsNull(self._property(owner, key, key_span, span), negated)
290
+ case Param(name=name, span=span):
291
+ null = self._param_value(name, span).value is None
292
+ case Lit(value=value):
293
+ null = value is None
294
+ case Var(name=name, span=span):
295
+ # A bound node or relationship is never missing, unless a previous clause made it
296
+ # optional: then only the optional scope's own presence column knows.
297
+ if name not in self._rel_vars:
298
+ self._variable(name, span)
299
+ group = self._optional_of.get(name)
300
+ if group is not None and group != self._optional_group:
301
+ return BIsNull(BPresent(group), negated)
302
+ null = False
303
+ case HasLabel(operand=operand, label=label):
304
+ # Validate the operand and the label first: a relationship has none, and an
305
+ # unknown variable is a semantic error whatever an optional scope adds.
306
+ self._has_label(operand, label)
307
+ group = self._optional_of.get(operand.name)
308
+ if group is not None and group != self._optional_group:
309
+ # `b:Label` is NULL exactly when the optional row is missing, so its
310
+ # null-ness is the scope's absence, whichever label it names.
311
+ return BIsNull(BPresent(group), negated)
312
+ null = False
313
+ case PatternPredicate() as condition:
314
+ raise self._condition_not_a_value(condition)
315
+ case ExistsSubquery() as condition:
316
+ raise self._condition_not_a_value(condition)
317
+ case _:
318
+ return BIsNull(self._condition(operand), negated)
319
+ answer = not null if negated else null
320
+ return BConst(ConstValue.TRUE if answer else ConstValue.FALSE)
321
+
322
+ def _operand(self, expr: Expr) -> _Operand:
323
+ match expr:
324
+ case Prop(owner=owner, key=key, key_span=key_span, span=span):
325
+ return self._property(owner, key, key_span, span)
326
+ case Lit(value=value, span=span):
327
+ return _ValueSource(value, None, span)
328
+ case Param(name=name, span=span):
329
+ return self._param_value(name, span)
330
+ case Cmp() | And() | Or() | Xor() | Not() | IsNull() | HasLabel() as condition:
331
+ return _Conditional(self._condition(condition))
332
+ case In() | StringPredicate() | Regex() as condition:
333
+ raise self._condition_not_a_value(condition)
334
+ case PatternPredicate() as condition:
335
+ raise self._condition_not_a_value(condition)
336
+ case ExistsSubquery() as condition:
337
+ raise self._condition_not_a_value(condition)
338
+ case _:
339
+ raise CypherSemanticError(
340
+ "expected a value",
341
+ query=self._text,
342
+ span=expr.span,
343
+ hint="compare a property, a literal or a $parameter",
344
+ )
345
+
346
+ def _regex(self, left: Expr, pattern: Expr, span: Span) -> BExpr:
347
+ """`=~`: PostgreSQL's `~` over a POSIX pattern anchored to the whole string, never `LIKE`.
348
+
349
+ The pattern is a bound parameter; the anchors are built in SQL around it, so a value can
350
+ never become SQL text. A NUL or a surrogate cannot be a PostgreSQL string and raises, a
351
+ pattern whose parentheses would break the anchor wrapper is refused before emission, and
352
+ a non-string column or literal operand is NULL, as in Cypher.
353
+ """
354
+ match left:
355
+ case Prop(owner=owner, key=key, key_span=key_span, span=left_span):
356
+ column = self._property(owner, key, key_span, left_span)
357
+ case _:
358
+ raise UnsupportedCypherError(
359
+ "=~ compares a property with a literal or a $parameter",
360
+ query=self._text,
361
+ span=span,
362
+ hint="write the property on the left, e.g. n.name =~ 'A.*'",
363
+ )
364
+ if property_type(column.pg_type) is not str:
365
+ return BConst(ConstValue.NULL)
366
+ match self._operand(pattern):
367
+ case _ValueSource() as operand:
368
+ source = self._string_operand(column, operand, span)
369
+ case _:
370
+ raise UnsupportedCypherError(
371
+ "=~ compares a property with a literal or a $parameter",
372
+ query=self._text,
373
+ span=span,
374
+ hint="write the pattern as a literal or a $parameter",
375
+ )
376
+ if not isinstance(source, _ValueSource):
377
+ return source
378
+ self._check_regex(source)
379
+ return BRegex(column, self._value(source.value, PgType.TEXT))
380
+
381
+ def _string_predicate(self, op: StringOp, left: Expr, right: Expr, span: Span) -> BExpr:
382
+ """`STARTS WITH`/`ENDS WITH`/`CONTAINS`: a function over strings, never `LIKE`.
383
+
384
+ A non-string column or operand makes the answer NULL, as Cypher does; a `$parameter` that
385
+ is not a string raises instead, naming the parameter and the declared type. `%`, `_` and
386
+ a backslash are data, and NULL on either side makes the answer NULL.
387
+ """
388
+ match left:
389
+ case Prop(owner=owner, key=key, key_span=key_span, span=left_span):
390
+ column = self._property(owner, key, key_span, left_span)
391
+ case _:
392
+ return self._value_string(op, left, right, span)
393
+ if property_type(column.pg_type) is not str:
394
+ return BConst(ConstValue.NULL)
395
+ match self._operand(right):
396
+ case BCol() as other:
397
+ if other.pg_type is not PgType.TEXT:
398
+ return BConst(ConstValue.NULL)
399
+ return BString(_B_STRING_OP[op], column, other)
400
+ case _ as operand:
401
+ source = self._string_operand(column, operand, span)
402
+ if not isinstance(source, _ValueSource):
403
+ return source
404
+ return BString(_B_STRING_OP[op], column, self._value(source.value, PgType.TEXT))
405
+
406
+ def _value_in(self, left: Expr, sources: tuple[_ValueSource, ...], span: Span) -> BExpr:
407
+ """`value IN list` where the left side is not a column: Cypher decides it in Python."""
408
+ operand = self._operand(left)
409
+ if not isinstance(operand, _ValueSource):
410
+ raise UnsupportedCypherError(
411
+ "IN over a condition is not supported yet",
412
+ query=self._text,
413
+ span=span,
414
+ hint="compare a property, a literal or a $parameter with IN",
415
+ )
416
+ if not sources:
417
+ return BConst(ConstValue.FALSE)
418
+ if operand.value is None:
419
+ return BConst(ConstValue.NULL)
420
+ answer = ConstValue.FALSE
421
+ for element in sources:
422
+ if element.value is None:
423
+ answer = ConstValue.NULL
424
+ continue
425
+ folded = _fold_values(Op.EQ, operand, element, self._text, span)
426
+ if folded is ConstValue.TRUE:
427
+ return BConst(ConstValue.TRUE)
428
+ if folded is ConstValue.NULL:
429
+ answer = ConstValue.NULL
430
+ return BConst(answer)
431
+
432
+ def _value_string(self, op: StringOp, left: Expr, right: Expr, span: Span) -> BExpr:
433
+ """Both sides are values: Cypher decides the predicate in Python, never in SQL."""
434
+ left_operand = self._operand(left)
435
+ right_operand = self._operand(right)
436
+ if isinstance(left_operand, _ValueSource) and isinstance(right_operand, _ValueSource):
437
+ return BConst(_fold_string(op, left_operand, right_operand, self._text, span))
438
+ raise self._string_operand_error(span)
439
+
440
+ def _exists_body(
441
+ self,
442
+ clauses: tuple[tuple[tuple[Path, ...], Where | None], ...],
443
+ span: Span,
444
+ *,
445
+ new_variables: bool,
446
+ guarded: frozenset[int] = frozenset(),
447
+ ) -> BExists:
448
+ """Bind one subquery body: a pattern of its own, correlated to the names in scope.
449
+
450
+ The body's clauses are bound in order into their own slots but the same name maps, so a
451
+ later clause names what an earlier one declared; the maps are restored afterwards, so a
452
+ name the body introduced is local to it. Each clause is a uniqueness scope of its own. The
453
+ body's own elements are charged against `max_pattern_size` like any other pattern, and
454
+ the outer name maps are only read while binding, never mutated.
455
+
456
+ `guarded` names the optional scopes an enclosing `BNullWhen` already turns into NULL when
457
+ they are absent: requiring their presence again inside the body would be a conjunct that
458
+ only ever holds when it is evaluated.
459
+ """
460
+ saved = self._clause_state()
461
+ names = (dict(self._variables), dict(self._rel_vars), dict(self._optional_of))
462
+ present = self._present_groups
463
+ optional_group = self._optional_group
464
+ refuse_new = self._refuse_new
465
+ nodes: list[BNode] = []
466
+ rels: list[BRel] = []
467
+ inferred: list[BInferred] = []
468
+ recursive: list[BWalk] = []
469
+ trails: list[BTrail] = []
470
+ properties: list[BExpr] = []
471
+ wheres: list[BExpr] = []
472
+ try:
473
+ self._start_clause()
474
+ self._present_groups = set()
475
+ self._optional_group = None
476
+ self._refuse_new = not new_variables
477
+ for paths, where in clauses:
478
+ self._clause += 1
479
+ self._start_clause()
480
+ parts = self._pattern(paths, where, span)
481
+ trails.extend(
482
+ BTrail(
483
+ trail.rels,
484
+ tuple(position + len(inferred) for position in trail.expansions),
485
+ tuple(position + len(recursive) for position in trail.recursions),
486
+ trail.clause,
487
+ )
488
+ for trail in parts.trails
489
+ )
490
+ nodes.extend(parts.nodes)
491
+ rels.extend(parts.rels)
492
+ inferred.extend(parts.inferred)
493
+ recursive.extend(parts.recursive)
494
+ properties.extend(parts.properties)
495
+ body_where = (
496
+ self._condition(where.expr) if where is not None else BConst(ConstValue.TRUE)
497
+ )
498
+ if not (isinstance(body_where, BConst) and body_where.value is ConstValue.TRUE):
499
+ wheres.append(body_where)
500
+ wheres.extend(
501
+ BIsNull(BPresent(group), negated=True)
502
+ for group in sorted(self._present_groups - guarded)
503
+ )
504
+ own = _body_elements(nodes, rels, inferred)
505
+ refs, groups = _body_refs((*properties, *wheres), own)
506
+ # A relationship endpoint may be a node an earlier clause bound — `(c)-[:T]->(o)`
507
+ # with both names already in scope — and the body then reads that node's row, so it
508
+ # is a correlation like a column reference even when no expression names it.
509
+ refs |= _body_end_refs(nodes, rels, inferred, recursive)
510
+ number = self._body_number
511
+ self._body_number += 1
512
+ return BExists(
513
+ tuple(nodes),
514
+ tuple(rels),
515
+ tuple(inferred),
516
+ tuple(recursive),
517
+ tuple(trails),
518
+ tuple(properties),
519
+ _all_wheres(wheres),
520
+ frozenset(refs),
521
+ frozenset(groups),
522
+ number,
523
+ )
524
+ finally:
525
+ self._restore_clause_state(saved)
526
+ self._variables, self._rel_vars, self._optional_of = names
527
+ self._present_groups = present
528
+ self._optional_group = optional_group
529
+ self._refuse_new = refuse_new
530
+
531
+ def _exists_subquery(self, clauses: tuple[ExistsMatch, ...], span: Span) -> BExpr:
532
+ """`EXISTS { ... }`: two-valued, so it needs no null guard (a row exists or it does not)."""
533
+ return self._exists_body(
534
+ tuple((clause.paths, clause.where) for clause in clauses),
535
+ span,
536
+ new_variables=True,
537
+ )
538
+
539
+ def _pattern_predicate(self, path: Path, span: Span) -> BExpr:
540
+ """A path written in `WHERE`: an `EXISTS` body, NULL when a variable it names is missing.
541
+
542
+ A pattern expression introduces no variable, so every name in it must already be bound;
543
+ a name an `OPTIONAL MATCH` may have left unbound makes the whole predicate NULL (not
544
+ FALSE), and the guard keeps that answer through `NOT` and `OR`.
545
+ """
546
+ groups = sorted(
547
+ {
548
+ group
549
+ for name in _path_names(path)
550
+ if (group := self._optional_of.get(name)) is not None
551
+ and group != self._optional_group
552
+ }
553
+ )
554
+ body = self._exists_body(
555
+ (((path,), None),), span, new_variables=False, guarded=frozenset(groups)
556
+ )
557
+ if not groups:
558
+ return body
559
+ guard = BOr(tuple(BIsNull(BPresent(group)) for group in groups))
560
+ return BNullWhen(guard, body)