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,664 @@
1
+ """Property values against declared types: comparisons, lists, strings and POSIX regexps.
2
+
3
+ A literal or `$param` value is checked against the property's declared type before it is bound, so
4
+ PostgreSQL never sees a cast it would have to guess: a value that cannot fit folds per Cypher, a
5
+ `$param` that cannot fit raises. A string pattern's anchors, classes and escapes are validated
6
+ here too, so the emitter only ever writes a pattern PostgreSQL can compile."""
7
+
8
+ from __future__ import annotations
9
+
10
+ import math
11
+ from decimal import Decimal
12
+ from typing import cast
13
+
14
+ from cypher2sql._ast import (
15
+ ExistsSubquery,
16
+ Expr,
17
+ In,
18
+ ListLit,
19
+ Lit,
20
+ Name,
21
+ Param,
22
+ PatternPredicate,
23
+ Regex,
24
+ StringOp,
25
+ StringPredicate,
26
+ Var,
27
+ )
28
+ from cypher2sql._compare import (
29
+ _INT64_MAX,
30
+ _INT64_MIN,
31
+ _NAN_TYPES,
32
+ _fits,
33
+ _int_fits,
34
+ _is_nan,
35
+ _mismatch,
36
+ _nan_cast,
37
+ _nan_fold,
38
+ _property_type_hint,
39
+ _str_fits,
40
+ _ValueSource,
41
+ )
42
+ from cypher2sql._errors import (
43
+ CypherSemanticError,
44
+ ParameterError,
45
+ Span,
46
+ UnsupportedCypherError,
47
+ bounded_text,
48
+ )
49
+ from cypher2sql._ir import (
50
+ BAnd,
51
+ BArray,
52
+ BCmp,
53
+ BCol,
54
+ BConst,
55
+ BExpr,
56
+ BFold,
57
+ BIsNull,
58
+ BNaN,
59
+ BNot,
60
+ BOr,
61
+ BOwner,
62
+ BPresent,
63
+ BStringOp,
64
+ ConstValue,
65
+ Op,
66
+ PgType,
67
+ pg_type,
68
+ property_type,
69
+ )
70
+ from cypher2sql._schema import (
71
+ Column,
72
+ PropertyType,
73
+ _property_type_label,
74
+ )
75
+
76
+ from ._base import _NUMERIC_TYPES, _UNORDERED, _BindBase, _Conditional, _Operand
77
+
78
+ _B_STRING_OP: dict[StringOp, BStringOp] = {
79
+ StringOp.STARTS_WITH: BStringOp.STARTS_WITH,
80
+ StringOp.ENDS_WITH: BStringOp.ENDS_WITH,
81
+ StringOp.CONTAINS: BStringOp.CONTAINS,
82
+ }
83
+
84
+
85
+ #: A list element the compared column can never equal: dropped from a literal list, refused when
86
+ #: it came from a `$parameter` list.
87
+ _UNMATCHABLE = object()
88
+
89
+
90
+ def _list_hint(declared: PropertyType) -> str:
91
+ """The one static hint an unfit list `$parameter` gets, per declared property type."""
92
+ return f"each element must be {_property_type_label(declared)} or null"
93
+
94
+
95
+ def _leading_flags(pattern: str) -> str | None:
96
+ """The letters of a leading `(?flags)` group, or `None` when the pattern has none.
97
+
98
+ Only a group that closes immediately after ASCII letters is a flag group; `(?:…)`,
99
+ `(?i:…)` and a lookahead are ordinary balanced groups.
100
+ """
101
+ if not pattern.startswith("(?"):
102
+ return None
103
+ end = pattern.find(")", 2)
104
+ if end == -1:
105
+ return None
106
+ flags = pattern[2:end]
107
+ if flags and flags.isascii() and flags.isalpha():
108
+ return flags
109
+ return None
110
+
111
+
112
+ def _class_end(pattern: str, start: int) -> int:
113
+ """The index just past the `]` closing the bracket expression opened at `start`.
114
+
115
+ A `]` is literal as the first character (after `^`), and `[. .]`, `[: :]` and `[= =]` are
116
+ bracket expressions whose own `]` does not close the outer class, exactly as POSIX ARE reads
117
+ them. An unterminated class returns `len(pattern)`: PostgreSQL rejects it at execute, so it
118
+ cannot hide a group close from this balance check.
119
+ """
120
+ index = start + 1
121
+ if index < len(pattern) and pattern[index] == "^":
122
+ index += 1
123
+ if index < len(pattern) and pattern[index] == "]":
124
+ index += 1
125
+ while index < len(pattern):
126
+ char = pattern[index]
127
+ if char == "\\":
128
+ index += 2
129
+ continue
130
+ if char == "[" and index + 1 < len(pattern) and pattern[index + 1] in ".:=":
131
+ end = pattern.find(pattern[index + 1] + "]", index + 2)
132
+ if end == -1:
133
+ return len(pattern)
134
+ index = end + 2
135
+ continue
136
+ if char == "]":
137
+ return index + 1
138
+ index += 1
139
+ return len(pattern)
140
+
141
+
142
+ def _list_element(source: _ValueSource, declared: PropertyType, text: str) -> object:
143
+ """One list element as the array will carry it, or `_UNMATCHABLE`.
144
+
145
+ Cypher compares every element with the column's value, so an element of another type is
146
+ simply never equal; NaN is never equal to anything either, and PostgreSQL would make it equal
147
+ itself, so it is dropped too. A `$parameter` list is a caller mistake instead: it raises,
148
+ naming the parameter and the declared type, never the value.
149
+ """
150
+ value = source.value
151
+ if value is None:
152
+ return None
153
+ converted = _list_value(value, declared)
154
+ if converted is not _UNMATCHABLE:
155
+ return converted
156
+ if source.param is not None:
157
+ raise ParameterError(
158
+ f"parameter {bounded_text(source.shown)} is not a list of "
159
+ f"{_property_type_label(declared)}",
160
+ query=text,
161
+ span=source.span,
162
+ hint=_list_hint(declared),
163
+ )
164
+ return _UNMATCHABLE
165
+
166
+
167
+ def _list_value(value: object, declared: PropertyType) -> object:
168
+ """One element in the array's element type, or `_UNMATCHABLE` when it cannot be one."""
169
+ if _is_nan(value):
170
+ return _UNMATCHABLE
171
+ if declared is int:
172
+ if _int_fits(value):
173
+ return value
174
+ # Cypher's one numeric domain: an integral float inside int64 *is* that integer.
175
+ if isinstance(value, float) and value.is_integer() and _INT64_MIN <= value <= _INT64_MAX:
176
+ return int(value)
177
+ return _UNMATCHABLE
178
+ if declared is float:
179
+ if isinstance(value, float):
180
+ return value
181
+ if _int_fits(value):
182
+ nearest = float(cast(int, value))
183
+ # No double equals the integer, so no `double precision` column can equal it.
184
+ return nearest if nearest == value else _UNMATCHABLE
185
+ return _UNMATCHABLE
186
+ return value if _fits(value, declared) else _UNMATCHABLE
187
+
188
+
189
+ def _fold_string(
190
+ op: StringOp, left: _ValueSource, right: _ValueSource, text: str, span: Span
191
+ ) -> ConstValue:
192
+ """Two values compared by a string predicate: Cypher decides it, keeping NULL's answer."""
193
+ if left.value is None or right.value is None:
194
+ return ConstValue.NULL
195
+ for side in (left, right):
196
+ if side.param is not None and not isinstance(side.value, str):
197
+ raise ParameterError(
198
+ f"parameter {bounded_text(side.shown)} is not a valid str",
199
+ query=text,
200
+ span=side.span,
201
+ hint=_property_type_hint(str),
202
+ )
203
+ if not isinstance(left.value, str) or not isinstance(right.value, str):
204
+ return ConstValue.NULL
205
+ match op:
206
+ case StringOp.STARTS_WITH:
207
+ answer = left.value.startswith(right.value)
208
+ case StringOp.ENDS_WITH:
209
+ answer = left.value.endswith(right.value)
210
+ case StringOp.CONTAINS:
211
+ answer = right.value in left.value
212
+ return ConstValue.TRUE if answer else ConstValue.FALSE
213
+
214
+
215
+ def _flip(op: Op) -> Op:
216
+ match op:
217
+ case Op.LT:
218
+ return Op.GT
219
+ case Op.LE:
220
+ return Op.GE
221
+ case Op.GT:
222
+ return Op.LT
223
+ case Op.GE:
224
+ return Op.LE
225
+ case _:
226
+ return op
227
+
228
+
229
+ class _Values(_BindBase):
230
+ """Value binding: declared-type checks, folds and the list/string/regexp forms."""
231
+
232
+ def _mapped_value(self, owner: BOwner, column: Column, expr: Expr) -> BExpr:
233
+ """A property map's `key: value`: equality with a literal or a `$parameter`."""
234
+ column_ref = BCol(owner, column.name, pg_type(column.type))
235
+ match expr:
236
+ case Lit(value=value, span=span):
237
+ return self._value_comparison(Op.EQ, column_ref, _ValueSource(value, None, span))
238
+ case Param(name=name, span=span):
239
+ return self._value_comparison(Op.EQ, column_ref, self._param_value(name, span))
240
+ case _:
241
+ raise UnsupportedCypherError(
242
+ "a property map value must be a literal or a $parameter",
243
+ query=self._text,
244
+ span=expr.span,
245
+ )
246
+
247
+ def _condition_not_a_value(
248
+ self, expr: In | StringPredicate | Regex | PatternPredicate | ExistsSubquery
249
+ ) -> CypherSemanticError:
250
+ """A construct that is only ever a condition, used where a value is required.
251
+
252
+ `EXISTS` and a pattern predicate are questions with no `IS NULL` answer; `IN`, a string
253
+ predicate and `=~` are conditions too, so no comparison or string-predicate operand has an
254
+ answer for them. Saying so is a teaching error, never an internal assertion that escapes
255
+ as a crash.
256
+ """
257
+ match expr:
258
+ case In(span=span):
259
+ return CypherSemanticError(
260
+ "IN is a condition, not a value",
261
+ query=self._text,
262
+ span=span,
263
+ hint="use it as a condition, e.g. n.prop IN $values",
264
+ )
265
+ case StringPredicate(op=op, span=span):
266
+ return CypherSemanticError(
267
+ f"{op.value} is a condition, not a value",
268
+ query=self._text,
269
+ span=span,
270
+ hint="use it as a condition, e.g. n.name STARTS WITH $text",
271
+ )
272
+ case Regex(span=span):
273
+ return CypherSemanticError(
274
+ "=~ is a condition, not a value",
275
+ query=self._text,
276
+ span=span,
277
+ hint="use it as a condition, e.g. n.name =~ 'A.*'",
278
+ )
279
+ case PatternPredicate(span=span):
280
+ return CypherSemanticError(
281
+ "a pattern predicate is a condition, not a value",
282
+ query=self._text,
283
+ span=span,
284
+ hint="use it as a condition; when a variable it names may be missing, "
285
+ "test that variable with IS NULL",
286
+ )
287
+ case ExistsSubquery(span=span):
288
+ return CypherSemanticError(
289
+ "EXISTS is a condition, not a value",
290
+ query=self._text,
291
+ span=span,
292
+ hint="EXISTS is false, never NULL, when no row matches; use it as a condition",
293
+ )
294
+
295
+ def _conditional_comparison(self, op: Op, left: _Operand, right: _Operand, span: Span) -> BExpr:
296
+ """Comparing boolean expressions: only equality is Cypher's, ordering is null."""
297
+ if op not in (Op.EQ, Op.NE):
298
+ return BConst(ConstValue.NULL)
299
+ sides: list[BExpr] = []
300
+ for side in (left, right):
301
+ match side:
302
+ case _Conditional(expr=expr):
303
+ sides.append(expr)
304
+ case _ValueSource(value=None):
305
+ return BConst(ConstValue.NULL)
306
+ case _ValueSource(value=value, param=param) if isinstance(value, bool):
307
+ sides.append(
308
+ BConst(ConstValue.TRUE if value else ConstValue.FALSE)
309
+ if param is None
310
+ else self._value(value, PgType.BOOLEAN)
311
+ )
312
+ case _:
313
+ raise UnsupportedCypherError(
314
+ "comparing this expression is not supported yet",
315
+ query=self._text,
316
+ span=span,
317
+ )
318
+ return BCmp(op, sides[0], sides[1])
319
+
320
+ def _column_comparison(
321
+ self,
322
+ op: Op,
323
+ left: BCol,
324
+ right: BCol,
325
+ left_name: str,
326
+ right_name: str,
327
+ span: Span,
328
+ ) -> BExpr:
329
+ left_type = property_type(left.pg_type)
330
+ right_type = property_type(right.pg_type)
331
+ other_type = right_type if left_type is float else left_type
332
+ # A float with an int/Decimal property goes through `double precision`: refuse.
333
+ if (left_type is float) != (right_type is float) and other_type in (int, Decimal):
334
+ float_name, other_name = (
335
+ (left_name, right_name) if left_type is float else (right_name, left_name)
336
+ )
337
+ raise UnsupportedCypherError(
338
+ f"cannot compare float property {bounded_text(float_name)} with "
339
+ f"{_property_type_label(other_type)} property {bounded_text(other_name)} exactly",
340
+ query=self._text,
341
+ span=span,
342
+ hint="PostgreSQL compares the pair through double precision, which rounds values "
343
+ "that need more than 53 bits; compare each property with a value, or store both in "
344
+ "columns of one exact numeric type (e.g. numeric)",
345
+ )
346
+ if left_type is not right_type and not (
347
+ left_type in _NUMERIC_TYPES and right_type in _NUMERIC_TYPES
348
+ ):
349
+ return _mismatch(op, (left, right))
350
+ if left_type in _UNORDERED and op not in (Op.EQ, Op.NE):
351
+ # Cypher has no ordering for booleans: it is null, never PostgreSQL's false < true.
352
+ return BConst(ConstValue.NULL)
353
+ comparison = BCmp(op, left, right)
354
+ if left.pg_type not in _NAN_TYPES and right.pg_type not in _NAN_TYPES:
355
+ return comparison
356
+ if op is Op.NE:
357
+ extras = tuple(
358
+ BAnd((BCmp(Op.EQ, column, BNaN(_nan_cast(column, other))), BIsNull(other, True)))
359
+ for column, other in ((left, right), (right, left))
360
+ )
361
+ return BOr((comparison, *extras))
362
+ guards = tuple(
363
+ BOr((BCmp(Op.NE, column, BNaN(_nan_cast(column, other))), BIsNull(other)))
364
+ for column, other in ((left, right), (right, left))
365
+ )
366
+ return BAnd((comparison, *guards))
367
+
368
+ def _value_comparison(self, op: Op, column: BCol, value: _ValueSource) -> BExpr:
369
+ if value.value is None:
370
+ return BConst(ConstValue.NULL)
371
+ declared = property_type(column.pg_type)
372
+ if declared is int and isinstance(value.value, float):
373
+ return self._int_float_comparison(op, column, value.value)
374
+ if not _fits(value.value, declared):
375
+ if value.param is not None:
376
+ raise ParameterError(
377
+ f"parameter {bounded_text(value.shown)} is not a valid "
378
+ f"{_property_type_label(declared)}",
379
+ query=self._text,
380
+ span=value.span,
381
+ hint=_property_type_hint(declared),
382
+ )
383
+ return self._literal_mismatch(op, column, value)
384
+ if _is_nan(value.value):
385
+ # A NaN value keeps its null-ness: ordering is false on a value row, null on NULL.
386
+ return _nan_fold(op, column)
387
+ if declared is float and isinstance(value.value, int):
388
+ return self._int_float_column_comparison(op, column, value.value)
389
+ if declared in _UNORDERED and op not in (Op.EQ, Op.NE):
390
+ # Booleans are not ordered in Cypher, so `active > true` is null, not PostgreSQL's
391
+ # `TRUE > FALSE`.
392
+ return BConst(ConstValue.NULL)
393
+ if isinstance(value.value, bool) and value.param is None:
394
+ return BCmp(op, column, BConst(ConstValue.TRUE if value.value else ConstValue.FALSE))
395
+ comparison = BCmp(op, column, self._value(value.value, column.pg_type))
396
+ if op in (Op.GT, Op.GE) and column.pg_type in _NAN_TYPES:
397
+ return BAnd((comparison, BCmp(Op.NE, column, BNaN(column.pg_type))))
398
+ return comparison
399
+
400
+ def _int_float_comparison(self, op: Op, column: BCol, number: float) -> BExpr:
401
+ """A float compared with an int property, in Cypher's one numeric domain.
402
+
403
+ An integral float inside int64 is exactly an integer, so it binds as that `int` and
404
+ compares `%s::bigint` — exact and index-friendly on the column. A fractional float, or a
405
+ magnitude outside int64, binds as the double's exact decimal value and casts
406
+ `%s::numeric`, so the `bigint` column is promoted exactly and no int64 bit is ever
407
+ rounded. NaN folds like every other NaN value, and ±infinity is beyond every int64, so
408
+ its answer is definite and only null-ness is kept.
409
+ """
410
+ if math.isnan(number):
411
+ return _nan_fold(op, column)
412
+ if math.isinf(number):
413
+ match op:
414
+ case Op.EQ:
415
+ answer = False
416
+ case Op.NE:
417
+ answer = True
418
+ case Op.LT | Op.LE:
419
+ answer = number > 0
420
+ case _:
421
+ answer = number < 0
422
+ return BFold(BIsNull(column), negated=answer)
423
+ if number.is_integer() and _INT64_MIN <= number <= _INT64_MAX:
424
+ return BCmp(op, column, self._value(int(number), PgType.BIGINT))
425
+ return BCmp(op, column, self._value(Decimal(number), PgType.NUMERIC))
426
+
427
+ def _int_float_column_comparison(self, op: Op, column: BCol, number: int) -> BExpr:
428
+ """An int compared with a float property, exactly, through the nearest double.
429
+
430
+ `float(number)` is the nearest double. When it is the number itself one `double
431
+ precision` comparison is exact. Otherwise no double equals the number, so `=`/`<>` fold
432
+ and ordering compares against the nearest double with the operator its side demands: if
433
+ the double is below the number, `d < n` is `d <= nearest`; if above, `d < n` is
434
+ `d < nearest`, and `>` mirrors. Only a `>`/`>=` needs the NaN-column guard, because
435
+ PostgreSQL sorts NaN above every double while Cypher makes the comparison false.
436
+ """
437
+ nearest = float(number)
438
+ if nearest == number:
439
+ comparison = BCmp(op, column, self._value(nearest, column.pg_type))
440
+ elif op is Op.EQ:
441
+ return BFold(BIsNull(column))
442
+ elif op is Op.NE:
443
+ return BFold(BIsNull(column), negated=True)
444
+ else:
445
+ match op:
446
+ case Op.LT | Op.LE:
447
+ operator = Op.LE if nearest < number else Op.LT
448
+ case _:
449
+ operator = Op.GE if nearest > number else Op.GT
450
+ comparison = BCmp(operator, column, self._value(nearest, column.pg_type))
451
+ if op in (Op.GT, Op.GE):
452
+ # A float property is always `double precision`, which PostgreSQL has NaN for.
453
+ return BAnd((comparison, BCmp(Op.NE, column, BNaN(column.pg_type))))
454
+ return comparison
455
+
456
+ def _literal_mismatch(self, op: Op, column: BCol, value: _ValueSource) -> BExpr:
457
+ """A literal Cypher decides alone folds; an unstorable string never arrives as SQL."""
458
+ if (
459
+ property_type(column.pg_type) is str
460
+ and isinstance(value.value, str)
461
+ and not _str_fits(value.value)
462
+ and op not in (Op.EQ, Op.NE)
463
+ ):
464
+ raise UnsupportedCypherError(
465
+ "a string PostgreSQL cannot store cannot be ordered",
466
+ query=self._text,
467
+ span=value.span,
468
+ hint="compare it with = or <> instead",
469
+ )
470
+ return _mismatch(op, (column,))
471
+
472
+ def _list_sources(
473
+ self, items: ListLit | Param, declared: PropertyType | None
474
+ ) -> tuple[_ValueSource, ...]:
475
+ """The list's elements as value tokens; a `$parameter` must hold a list, never a scalar.
476
+
477
+ `declared` names the compared property's type in a mismatch message, or is `None` when the
478
+ left side has no declared type.
479
+ """
480
+ match items:
481
+ case ListLit(items=elements):
482
+ return tuple(self._list_item(element) for element in elements)
483
+ case Param(name=name, span=span):
484
+ whole = self._param_value(name, span)
485
+ if not isinstance(whole.value, list | tuple):
486
+ raise self._not_a_list(whole, declared)
487
+ return tuple(
488
+ _ValueSource(value, whole.param, whole.span, whole.label)
489
+ for value in whole.value
490
+ )
491
+
492
+ def _list_item(self, element: Expr) -> _ValueSource:
493
+ """One item of a list literal: a literal or a `$parameter`, never a computed value."""
494
+ match element:
495
+ case Lit(value=value, span=span):
496
+ return _ValueSource(value, None, span)
497
+ case Param(name=name, span=span):
498
+ return self._param_value(name, span)
499
+ case _:
500
+ raise UnsupportedCypherError(
501
+ "a list element must be a literal or a $parameter",
502
+ query=self._text,
503
+ span=element.span,
504
+ hint="write the values in the list, or pass the whole list as one $parameter",
505
+ )
506
+
507
+ def _not_a_list(self, source: _ValueSource, declared: PropertyType | None) -> ParameterError:
508
+ """A list parameter that is not a list, or whose elements cannot be the declared type."""
509
+ detail = "" if declared is None else f" of {_property_type_label(declared)}"
510
+ hint = "pass a list of values" if declared is None else _list_hint(declared)
511
+ return ParameterError(
512
+ f"parameter {bounded_text(source.shown)} is not a list{detail}",
513
+ query=self._text,
514
+ span=source.span,
515
+ hint=hint,
516
+ )
517
+
518
+ def _array(self, values: list[object], pg: PgType) -> BArray:
519
+ self._values.append(values)
520
+ return BArray(len(self._values) - 1, pg)
521
+
522
+ def _string_operand(self, column: BCol, operand: _Operand, span: Span) -> _ValueSource | BExpr:
523
+ """A string literal or `$parameter`, or the constant a bad one folds to.
524
+
525
+ A non-string literal makes the answer NULL, as in Cypher; a `$parameter` that is not a
526
+ string, or is a string PostgreSQL cannot store, raises naming the parameter and never its
527
+ value. Both the string predicates and `=~` share this check, so their answers cannot
528
+ drift apart.
529
+ """
530
+ match operand:
531
+ case _ValueSource(value=None):
532
+ return BConst(ConstValue.NULL)
533
+ case _ValueSource(value=value, param=param) as source:
534
+ if not isinstance(value, str):
535
+ if param is not None:
536
+ raise self._not_a_string(source)
537
+ return BConst(ConstValue.NULL)
538
+ if not _str_fits(value):
539
+ if param is not None:
540
+ raise self._not_a_string(source)
541
+ return BFold(BIsNull(column))
542
+ return source
543
+ case _:
544
+ raise self._string_operand_error(span)
545
+
546
+ def _string_operand_error(self, span: Span) -> UnsupportedCypherError:
547
+ return UnsupportedCypherError(
548
+ "a string predicate compares a property with a literal, a $parameter or a property",
549
+ query=self._text,
550
+ span=span,
551
+ hint="write the property on the left, e.g. n.name STARTS WITH $text",
552
+ )
553
+
554
+ def _check_regex(self, source: _ValueSource) -> None:
555
+ """Refuse a pattern that could break the anchor wrapper or needs inline flags.
556
+
557
+ PostgreSQL applies `~` to the pattern as its own program. An unescaped `)` at depth zero
558
+ would close the `(?: … )` wrapper the emitter writes and turn the anchors into a
559
+ fail-open alternation, so group balance is checked here, outside `[...]` classes and
560
+ backslash escapes. A leading `(?flags)` group is refused too: PostgreSQL applies inline
561
+ options only at the very start of a pattern, which is outside the wrapper, and the only
562
+ way to hoist it is to put caller text into the SQL string.
563
+ """
564
+ pattern = cast(str, source.value)
565
+ flags = _leading_flags(pattern)
566
+ if flags is not None:
567
+ raise self._regex_pattern_error(
568
+ source,
569
+ f"starts with a (?{flags}) group",
570
+ "write the pattern without the flag, matching each case explicitly "
571
+ "(e.g. 'ABC|abc')",
572
+ )
573
+ depth = 0
574
+ index = 0
575
+ while index < len(pattern):
576
+ char = pattern[index]
577
+ if char == "\\":
578
+ index += 2
579
+ continue
580
+ if char == "[":
581
+ index = _class_end(pattern, index)
582
+ continue
583
+ if char == "(":
584
+ depth += 1
585
+ elif char == ")":
586
+ depth -= 1
587
+ if depth < 0:
588
+ break
589
+ index += 1
590
+ if depth != 0:
591
+ raise self._regex_pattern_error(
592
+ source,
593
+ "has unbalanced parentheses",
594
+ "escape parentheses or use a character class",
595
+ )
596
+
597
+ def _regex_pattern_error(
598
+ self, source: _ValueSource, problem: str, hint: str
599
+ ) -> CypherSemanticError | ParameterError:
600
+ """A malformed pattern: a `$param` names itself, a literal names the query text."""
601
+ if source.param is not None:
602
+ return ParameterError(
603
+ f"parameter {bounded_text(source.shown)} {problem}",
604
+ query=self._text,
605
+ span=source.span,
606
+ hint=hint,
607
+ )
608
+ return CypherSemanticError(
609
+ f"the regular expression {problem}",
610
+ query=self._text,
611
+ span=source.span,
612
+ hint=hint,
613
+ )
614
+
615
+ def _not_a_string(self, source: _ValueSource) -> ParameterError:
616
+ return ParameterError(
617
+ f"parameter {bounded_text(source.shown)} is not a valid str",
618
+ query=self._text,
619
+ span=source.span,
620
+ hint=_property_type_hint(str),
621
+ )
622
+
623
+ def _has_label(self, operand: Var, label: Name) -> BExpr:
624
+ """Labels are static: the inferred node type decides the predicate at bind time.
625
+
626
+ A node an earlier `OPTIONAL MATCH` may leave unbound is not static: `b:B` is null when the
627
+ optional side matched nothing, so the predicate cannot be folded without changing whether
628
+ a row survives a `NOT`.
629
+ """
630
+ if operand.name in self._rel_vars:
631
+ raise CypherSemanticError(
632
+ f"a relationship cannot have a label: {bounded_text(operand.name)}",
633
+ query=self._text,
634
+ span=operand.span,
635
+ hint="labels apply to nodes",
636
+ )
637
+ group = self._optional_of.get(operand.name)
638
+ if group is not None and group != self._optional_group:
639
+ node = self._variable(operand.name, operand.span)
640
+ node_type = self._find_node_type(label)
641
+ if node_type.label == node.node_type.label:
642
+ # Present and the right label, or missing: the group's presence is exactly the
643
+ # `TRUE`/`NULL` this predicate has, so a `NOT` keeps NULL as NULL.
644
+ return BPresent(group)
645
+ # The variable's one label cannot change, so a different label is `FALSE` when the
646
+ # optional side matched and `NULL` when it did not.
647
+ return BAnd((BNot(BPresent(group)), BConst(ConstValue.NULL)))
648
+ node = self._variable(operand.name, operand.span)
649
+ node_type = self._find_node_type(label)
650
+ return BConst(
651
+ ConstValue.TRUE if node.node_type.label == node_type.label else ConstValue.FALSE
652
+ )
653
+
654
+ def _condition_property(self, owner: str, key: str, key_span: Span, span: Span) -> BExpr:
655
+ """A boolean property is a condition by itself; anything else is not one."""
656
+ column = self._property(owner, key, key_span, span)
657
+ if column.pg_type is not PgType.BOOLEAN:
658
+ raise CypherSemanticError(
659
+ "expected a condition",
660
+ query=self._text,
661
+ span=key_span,
662
+ hint="compare it, e.g. n.prop = $value",
663
+ )
664
+ return column