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/_compare.py ADDED
@@ -0,0 +1,265 @@
1
+ """Value fitting and folding: how a literal or a `$param` compares with a declared type.
2
+
3
+ A value compared with a property is decided against the declared Python type before PostgreSQL
4
+ sees it: it either fits the type's cast exactly (per the api.md table) or it does not, and an
5
+ unfitting *literal* folds to Cypher's three-valued answer while an unfitting `$param` raises
6
+ `ParameterError` naming the parameter and the type, never the value. Two values compared with
7
+ each other (two literals, two parameters) are decided in Python: one `_category` per value, NaN
8
+ false (`<>` true), booleans unordered, and an unstorable string refused in an ordering.
9
+
10
+ The fold shapes are the ones design.md documents: `N` is the OR of the columns' `IS NULL`, and
11
+ `=`/`<>` are `(N AND NULL)` / `(NOT N OR NULL)` so the row's null-ness the answer keeps. Nothing
12
+ here emits SQL or quotes an identifier; a fold is an IR expression the planner and emitter treat
13
+ like any other predicate.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import math
19
+ from dataclasses import dataclass
20
+ from datetime import date, datetime
21
+ from decimal import Decimal
22
+ from typing import Any
23
+ from uuid import UUID
24
+
25
+ from ._errors import (
26
+ CypherSemanticError,
27
+ ParameterError,
28
+ Span,
29
+ UnsupportedCypherError,
30
+ bounded_text,
31
+ )
32
+ from ._ir import BCol, BConst, BExpr, BFold, BIsNull, BOr, ConstValue, Op, PgType
33
+ from ._schema import PropertyType
34
+
35
+ _INT64_MIN = -(2**63)
36
+ _INT64_MAX = 2**63 - 1
37
+ _DECIMAL_PRECISION = 131072
38
+ _DECIMAL_SCALE = 16383
39
+ _NAN_TYPES = frozenset({PgType.DOUBLE_PRECISION, PgType.NUMERIC})
40
+
41
+
42
+ @dataclass(frozen=True, slots=True)
43
+ class _ValueSource:
44
+ """A literal or a value token, before it is cast to whatever it is compared with.
45
+
46
+ `label` is how the query wrote it (`$name` or `{expression}`), so a message never shows the
47
+ internal index a template interpolation is addressed by, and never its value.
48
+ """
49
+
50
+ value: object
51
+ param: str | None
52
+ span: Span
53
+ label: str | None = None
54
+
55
+ @property
56
+ def shown(self) -> str:
57
+ """How a message names this token; set together with `param`, never alone."""
58
+ if self.param is None or self.label is None:
59
+ # Unreachable by construction: only a value token is ever named in a message.
60
+ raise RuntimeError("a literal has no written name to show in a message")
61
+ return self.label
62
+
63
+
64
+ def _mismatch(op: Op, columns: tuple[BCol, ...]) -> BExpr:
65
+ """A comparison Cypher decides alone, keeping its null-ness: false/true on a value row."""
66
+ guard: BExpr = (
67
+ BIsNull(columns[0])
68
+ if len(columns) == 1
69
+ else BOr(tuple(BIsNull(column) for column in columns))
70
+ )
71
+ match op:
72
+ case Op.EQ:
73
+ return BFold(guard)
74
+ case Op.NE:
75
+ return BFold(guard, negated=True)
76
+ case _:
77
+ return BConst(ConstValue.NULL)
78
+
79
+
80
+ def _nan_fold(op: Op, column: BCol) -> BExpr:
81
+ """A NaN value against a column: false (`<>` true) on a value row, NULL on a NULL row."""
82
+ return _mismatch(Op.NE if op is Op.NE else Op.EQ, (column,))
83
+
84
+
85
+ def _property_type_hint(declared: PropertyType) -> str | None:
86
+ """The one static hint an unfit `$param` gets, per declared property type."""
87
+ if declared is str:
88
+ return "pass a str with no NUL or surrogate"
89
+ if declared in (int, float):
90
+ return "pass an int in int64 range or a float"
91
+ if declared is Decimal:
92
+ return "pass an int or Decimal"
93
+ return None
94
+
95
+
96
+ def _nan_cast(column: BCol, other: BCol) -> PgType:
97
+ """The NaN literal's type: the column's own if PostgreSQL has NaN for it, else its peer's."""
98
+ return column.pg_type if column.pg_type in _NAN_TYPES else other.pg_type
99
+
100
+
101
+ def _fold_values(
102
+ op: Op, left: _ValueSource, right: _ValueSource, text: str, span: Span
103
+ ) -> ConstValue:
104
+ """Compare two values Cypher decides alone (two literals, or two `$parameters`)."""
105
+ if left.value is None or right.value is None:
106
+ return ConstValue.NULL
107
+ for side in (left, right):
108
+ if side.param is not None and _category(side.value) is None:
109
+ raise ParameterError(
110
+ f"parameter {bounded_text(side.shown)} has unsupported type "
111
+ f"{type(side.value).__name__}",
112
+ query=text,
113
+ span=side.span,
114
+ )
115
+ if _is_nan(left.value) or _is_nan(right.value):
116
+ return ConstValue.TRUE if op is Op.NE else ConstValue.FALSE
117
+ left_category = _category(left.value)
118
+ if left_category is None or left_category != _category(right.value):
119
+ match op:
120
+ case Op.EQ:
121
+ return ConstValue.FALSE
122
+ case Op.NE:
123
+ return ConstValue.TRUE
124
+ case _:
125
+ return ConstValue.NULL
126
+ if isinstance(left.value, bool) and op not in (Op.EQ, Op.NE):
127
+ # Booleans are not ordered in Cypher, whatever PostgreSQL says about false < true.
128
+ return ConstValue.NULL
129
+ if left_category == "str" and op not in (Op.EQ, Op.NE):
130
+ unstorable = next(
131
+ (
132
+ side
133
+ for side in (left, right)
134
+ if isinstance(side.value, str) and not _str_fits(side.value)
135
+ ),
136
+ None,
137
+ )
138
+ if unstorable is not None:
139
+ raise UnsupportedCypherError(
140
+ "a string PostgreSQL cannot store cannot be ordered",
141
+ query=text,
142
+ span=unstorable.span,
143
+ hint="compare it with = or <> instead",
144
+ )
145
+ try:
146
+ answer = _compare(op, left.value, right.value)
147
+ except TypeError:
148
+ # Two values of one kind can still be incomparable in Python (naive vs aware datetimes).
149
+ raise CypherSemanticError(
150
+ "values cannot be compared",
151
+ query=text,
152
+ span=span,
153
+ hint=_incomparable_hint(left, right),
154
+ ) from None
155
+ return ConstValue.TRUE if answer else ConstValue.FALSE
156
+
157
+
158
+ def _incomparable_hint(left: _ValueSource, right: _ValueSource) -> str | None:
159
+ """Name the value tokens only; their values never enter a message."""
160
+ names: list[str] = []
161
+ for side in (left, right):
162
+ if side.label is not None:
163
+ names.append(bounded_text(side.label))
164
+ if not names:
165
+ return None
166
+ return f"{' and '.join(names)} must hold values of the same kind"
167
+
168
+
169
+ def _compare(op: Op, left: Any, right: Any) -> bool: # Any: both sides share one _category
170
+ if op is Op.EQ:
171
+ return bool(left == right)
172
+ if op is Op.NE:
173
+ return bool(left != right)
174
+ if op is Op.LT:
175
+ return bool(left < right)
176
+ if op is Op.LE:
177
+ return bool(left <= right)
178
+ if op is Op.GT:
179
+ return bool(left > right)
180
+ return bool(left >= right)
181
+
182
+
183
+ def _category(value: object) -> str | None:
184
+ if isinstance(value, bool):
185
+ return "bool"
186
+ if isinstance(value, (int, float, Decimal)):
187
+ return "number"
188
+ if isinstance(value, str):
189
+ return "str"
190
+ if isinstance(value, datetime):
191
+ return "datetime"
192
+ if isinstance(value, date):
193
+ return "date"
194
+ if isinstance(value, UUID):
195
+ return "uuid"
196
+ return None
197
+
198
+
199
+ def _is_nan(value: object) -> bool:
200
+ if isinstance(value, float):
201
+ return math.isnan(value)
202
+ if isinstance(value, Decimal):
203
+ return value.is_nan()
204
+ return False
205
+
206
+
207
+ def _fits(value: object, property_type: PropertyType) -> bool:
208
+ """Whether `value` is stored as the declared property type, per the api.md table.
209
+
210
+ A numeric value of the other kind is not stored: the binder compares the `float`/`int` pair in
211
+ Cypher's one numeric domain before this check.
212
+ """
213
+ if value is None:
214
+ return True
215
+ if property_type is str:
216
+ return isinstance(value, str) and _str_fits(value)
217
+ if property_type is bool:
218
+ return isinstance(value, bool)
219
+ if property_type is int:
220
+ return _int_fits(value)
221
+ if property_type is float:
222
+ return isinstance(value, float) or _int_fits(value)
223
+ if property_type is Decimal:
224
+ return _decimal_fits(value)
225
+ if property_type is date:
226
+ return isinstance(value, date) and not isinstance(value, datetime)
227
+ if property_type is datetime:
228
+ return isinstance(value, datetime)
229
+ if property_type is UUID:
230
+ return isinstance(value, UUID)
231
+ return False
232
+
233
+
234
+ def _str_fits(value: str) -> bool:
235
+ if "\x00" in value:
236
+ return False
237
+ try:
238
+ value.encode("utf-8")
239
+ except UnicodeEncodeError:
240
+ return False
241
+ return True
242
+
243
+
244
+ def _int_fits(value: object) -> bool:
245
+ return (
246
+ isinstance(value, int) and not isinstance(value, bool) and _INT64_MIN <= value <= _INT64_MAX
247
+ )
248
+
249
+
250
+ def _decimal_fits(value: object) -> bool:
251
+ if _int_fits(value):
252
+ return True
253
+ if not isinstance(value, Decimal):
254
+ return False
255
+ if value.is_nan():
256
+ return True
257
+ if value.is_infinite():
258
+ return False
259
+ digits = value.as_tuple().digits
260
+ exponent = value.as_tuple().exponent
261
+ if not isinstance(exponent, int):
262
+ return False
263
+ whole = max(len(digits) + exponent, 0)
264
+ fraction = max(-exponent, 0)
265
+ return whole <= _DECIMAL_PRECISION and fraction <= _DECIMAL_SCALE
@@ -0,0 +1,42 @@
1
+ """Plan → SQL text plus parameters: the only place identifiers are quoted and `%s` written.
2
+
3
+ Every table and column name is double quoted (embedded quotes doubled), every value becomes a
4
+ `%s::<cast>` placeholder appended in textual order, and keywords are upper case. Nothing here
5
+ decides what to select: that was decided by the planner. Operators are parenthesised by the node
6
+ they belong to, so a comparison's operands can themselves be comparisons (`(a = b) <> (c = d)`).
7
+
8
+ A query with a hoisted walk opens with one `WITH RECURSIVE` clause: its anchor entries, then the
9
+ materialized recursive walks, before the `SELECT` that matches the target against them.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from cypher2sql._plan import Select
15
+ from cypher2sql._schema import SQLQuery, quote_ident
16
+
17
+ from ._walks import _WalkEmitter
18
+
19
+
20
+ def emit(select: Select, values: tuple[object, ...]) -> SQLQuery:
21
+ """Render one `SELECT`, collecting each value as its placeholder is written.
22
+
23
+ A query with a hoisted walk opens with `WITH RECURSIVE`: one entry per walk, written before
24
+ the `SELECT` so the endpoint set is computed once for the whole statement.
25
+ """
26
+ emitter = _WalkEmitter(values)
27
+ keyword = "SELECT DISTINCT" if select.distinct else "SELECT"
28
+ lines: list[str] = []
29
+ if select.walks:
30
+ lines.append("WITH RECURSIVE\n" + ",\n".join(emitter.walk_sources(select.walks)))
31
+ lines.append(f"{keyword} {', '.join(emitter.projection(item) for item in select.columns)}")
32
+ lines.append(f"FROM {quote_ident(select.table)} AS {select.alias}")
33
+ for lateral in select.laterals:
34
+ lines.extend(emitter.lateral(lateral, 0))
35
+ lines.extend(emitter.where(select.where, 0))
36
+ lines.extend(emitter.order(select.order))
37
+ lines.extend(emitter.page(select.offset, select.limit))
38
+ return SQLQuery(
39
+ sql="\n".join(lines),
40
+ params=tuple(emitter.params),
41
+ columns=tuple(item.name for item in select.columns),
42
+ )
@@ -0,0 +1,362 @@
1
+ """The emitter core shared by every plan node: clauses, expressions and their delimiters.
2
+
3
+ Values are bound in textual order as `%s::<cast>` placeholders, identifiers only ever come from
4
+ `_schema.quote_ident`, and the layout decisions belong to the plan nodes. A walk's own CTE and
5
+ endpoint check are written by `_walks`, which extends this core.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Iterable
11
+
12
+ from cypher2sql._ir import BStringOp, ConstValue, Orientation
13
+ from cypher2sql._plan import (
14
+ And,
15
+ AnyEq,
16
+ AnyOf,
17
+ Bool,
18
+ CaseNull,
19
+ Cmp,
20
+ Collate,
21
+ ColRef,
22
+ Conjunct,
23
+ CrossJoin,
24
+ Eq,
25
+ Exists,
26
+ Group,
27
+ IsNull,
28
+ Join,
29
+ Lateral,
30
+ Nan,
31
+ Not,
32
+ Or,
33
+ OrderColumn,
34
+ Parity,
35
+ Placeholder,
36
+ Projection,
37
+ Recursive,
38
+ Regex,
39
+ SqlExpr,
40
+ StringCall,
41
+ TupleNe,
42
+ UntypedWalk,
43
+ WalkIn,
44
+ )
45
+ from cypher2sql._schema import quote_ident
46
+
47
+ _CONST_TEXT: dict[ConstValue, str] = {
48
+ ConstValue.TRUE: "TRUE",
49
+ ConstValue.FALSE: "FALSE",
50
+ ConstValue.NULL: "NULL",
51
+ }
52
+ #: The code-point collation every text comparison, key and identity is pinned to. It is spelled
53
+ #: here once; the `Collate` plan node is the way a planned comparison asks for it.
54
+ _PIN = ' COLLATE "C"'
55
+ #: Nodes whose rendering is already one delimited operand: no extra brackets around them, so a
56
+ #: negated subquery reads `NOT EXISTS (…)` and a CASE expression is not wrapped twice. A walk or
57
+ #: an OR-of-`EXISTS` is deliberately absent: `group()` brackets it, because its block rendering
58
+ #: (and the CTE inside it) is not an atom a surrounding operator can order itself against.
59
+ _SELF_DELIMITED = (
60
+ ColRef,
61
+ Placeholder,
62
+ Bool,
63
+ Nan,
64
+ Collate,
65
+ And,
66
+ Or,
67
+ CaseNull,
68
+ Exists,
69
+ WalkIn,
70
+ )
71
+
72
+
73
+ class _Emitter:
74
+ """One render of one plan; holds the parameter list while the text is written."""
75
+
76
+ def __init__(self, values: tuple[object, ...]) -> None:
77
+ self._values = values
78
+ self.params: list[object] = []
79
+
80
+ def column(self, column: ColRef) -> str:
81
+ return f"{column.alias}.{quote_ident(column.column)}"
82
+
83
+ def projection(self, item: Projection) -> str:
84
+ """One select-list expression; the name it returns is decided by the planner."""
85
+ return self.expression(item.expr, 0)
86
+
87
+ # ---------------------------------------------------------------- clauses
88
+
89
+ def where(self, conjuncts: tuple[Conjunct, ...], indent: int) -> list[str]:
90
+ """The `WHERE` clause as lines already indented for the place they go."""
91
+ if not conjuncts:
92
+ return []
93
+ pad = " " * indent
94
+ lines = [f"{pad}WHERE {self.conjunct(conjuncts[0], indent)}"]
95
+ lines.extend(f"{pad} AND {self.conjunct(item, indent + 2)}" for item in conjuncts[1:])
96
+ return lines
97
+
98
+ def order(self, order: tuple[OrderColumn, ...]) -> list[str]:
99
+ """`ORDER BY` every key operand, each `DESC` when the query reversed the key.
100
+
101
+ An operand is the same expression the select list projects, so a `SELECT DISTINCT` and
102
+ its `ORDER BY` always agree. A text key is a `Collate` node ordered by code point, the
103
+ same rule a string comparison follows; a key with no declared type keeps its collation.
104
+ """
105
+ if not order:
106
+ return []
107
+ operands: list[str] = []
108
+ for item in order:
109
+ operand = self.expression(item.operand, 0)
110
+ if item.descending:
111
+ operand += " DESC"
112
+ operands.append(operand)
113
+ return ["ORDER BY " + ", ".join(operands)]
114
+
115
+ def page(self, offset: Placeholder | None, limit: Placeholder | None) -> list[str]:
116
+ """`OFFSET`/`FETCH FIRST`, each a bound `bigint`; never a number from the query text.
117
+
118
+ `OFFSET` is written first, so the parameter order follows the query's own `SKIP` then
119
+ `LIMIT`. PostgreSQL's `FETCH FIRST` takes only a `c_expr`, which a cast is not, so the
120
+ placeholder is parenthesised there (`FETCH FIRST (%s::bigint) ROWS ONLY`); `OFFSET` takes a
121
+ full expression and needs none. Both clauses are valid without an `ORDER BY`; the row
122
+ choice is then PostgreSQL's.
123
+ """
124
+ lines: list[str] = []
125
+ if offset is not None:
126
+ lines.append(f"OFFSET {self.expression(offset, 0)}")
127
+ if limit is not None:
128
+ lines.append(f"FETCH FIRST ({self.expression(limit, 0)}) ROWS ONLY")
129
+ return lines
130
+
131
+ def conjunct(self, expr: Conjunct, indent: int) -> str:
132
+ """One top-level conjunct; continuation lines carry their own absolute indentation."""
133
+ match expr:
134
+ case Exists(group=group):
135
+ return self.exists(group, indent)
136
+ case WalkIn() | Recursive() | UntypedWalk():
137
+ return self.walk_conjunct(expr, indent)
138
+ case AnyOf(items=items):
139
+ return self.any_of(items, indent)
140
+ case _:
141
+ return self.expression(expr, indent)
142
+
143
+ def walk_conjunct(self, expr: WalkIn | Recursive | UntypedWalk, indent: int) -> str:
144
+ """One walk conjunct: `_WalkEmitter` supplies the block rendering the core does not."""
145
+ raise AssertionError("internal error: a walk reached the emitter core")
146
+
147
+ def lateral(self, lateral: Lateral, indent: int) -> list[str]:
148
+ """`LEFT JOIN LATERAL (…) AS o<i> ON TRUE`, one null-tolerant row scope."""
149
+ body_indent = indent + 2
150
+ rendered = [
151
+ f"{self.expression(column.expr, body_indent)} AS {quote_ident(column.name)}"
152
+ for column in lateral.columns
153
+ ]
154
+ lines = [f"{' ' * indent}LEFT JOIN LATERAL ("]
155
+ lines.extend(self.group_body(lateral.group, body_indent, ", ".join(rendered)))
156
+ lines.append(f"{' ' * indent}) AS {lateral.alias} ON TRUE")
157
+ return lines
158
+
159
+ def exists(self, group: Group, indent: int) -> str:
160
+ body_indent = indent + 2
161
+ body = self.group_body(group, body_indent, "1")
162
+ return "EXISTS (\n" + "\n".join(body) + "\n" + " " * indent + ")"
163
+
164
+ def group_body(self, group: Group, body_indent: int, projection: str) -> list[str]:
165
+ """One group's `SELECT` list, `FROM`, joins and `WHERE`, indented for its place."""
166
+ pad = " " * body_indent
167
+ body = [f"{pad}SELECT {projection}"]
168
+ if group.table is not None:
169
+ # A lateral scope with no row of its own has no `FROM`: its `WHERE` reads the columns
170
+ # earlier scopes expose.
171
+ body.append(f"{pad}FROM {quote_ident(group.table)} AS {group.alias}")
172
+ for join in group.joins:
173
+ match join:
174
+ case Join(table=table, alias=alias, on=on):
175
+ body.append(
176
+ f"{pad}JOIN {quote_ident(table)} AS {alias} "
177
+ f"ON {self.expression(on, body_indent)}"
178
+ )
179
+ case CrossJoin(table=table, alias=alias):
180
+ body.append(f"{pad}CROSS JOIN {quote_ident(table)} AS {alias}")
181
+ body.extend(self.where(group.where, body_indent))
182
+ return body
183
+
184
+ def any_of(self, items: tuple[Conjunct, ...], indent: int) -> str:
185
+ body_indent = indent + 2
186
+ lines: list[str] = []
187
+ for index, item in enumerate(items):
188
+ rendered = self.conjunct(item, body_indent).split("\n")
189
+ prefix = " " * body_indent + ("OR " if index else "")
190
+ lines.append(prefix + rendered[0])
191
+ lines.extend(rendered[1:])
192
+ lines.append(" " * indent + ")")
193
+ return "(\n" + "\n".join(lines)
194
+
195
+ # ---------------------------------------------------------------- expressions
196
+
197
+ def group(self, expr: Conjunct, indent: int, *, comparison: bool = False) -> str:
198
+ """An operand of an operator: a bare atom, or a parenthesised compound expression.
199
+
200
+ `comparison` says the operand is a comparison side. `CASE … END` is an atom everywhere
201
+ else (`NOT CASE … END` is scoped by `END`), but a comparison must bracket it so the
202
+ NULL-preserving guard stays the whole operand rather than being read as part of the
203
+ comparison.
204
+ """
205
+ text = self.conjunct(expr, indent)
206
+ if isinstance(expr, CaseNull) and comparison:
207
+ return f"({text})"
208
+ # `AND`/`OR`, a real parity chain, `CASE … END` and every correlated subquery delimit
209
+ # themselves; anything else — a walk or an OR-of-`EXISTS` included — needs brackets.
210
+ if isinstance(expr, _SELF_DELIMITED) or (isinstance(expr, Parity) and len(expr.items) > 1):
211
+ return text
212
+ return f"({text})"
213
+
214
+ def string_call(self, op: BStringOp, column: SqlExpr, operand: SqlExpr, indent: int) -> str:
215
+ """One string predicate as a PostgreSQL function or a substring test.
216
+
217
+ `starts_with` exists since PostgreSQL 15. PostgreSQL has no `ends_with` (checked on the
218
+ test server, 18), so the suffix test is `right(string, length(needle)) = needle`. The
219
+ substring test is `position` (never `LIKE`, so `%`, `_` and a backslash are data).
220
+
221
+ The column is already a `Collate`, so `starts_with` and `position` search by code point,
222
+ and `right` inherits that collation so its `=` compares by code point too. A needle that
223
+ is itself a column is a `Collate` as well, so no text operand keeps its column's
224
+ collation; a bound value stays a bare `%s::text`, because the column's pin decides the
225
+ comparison.
226
+ """
227
+ left = f"({self.group(column, indent)})"
228
+ match op:
229
+ case BStringOp.CONTAINS:
230
+ # `position(substring in string)` takes a `b_expr` before `in`, and a bare
231
+ # `COLLATE` is only an `a_expr`, so a pinned column needle needs its own brackets.
232
+ needle = self.group(operand, indent)
233
+ if isinstance(operand, Collate):
234
+ needle = f"({needle})"
235
+ return f"position({needle} in {left}) > 0"
236
+ case BStringOp.STARTS_WITH:
237
+ return f"starts_with({left}, {self.group(operand, indent)})"
238
+ case BStringOp.ENDS_WITH:
239
+ # The suffix test is `right(string, length(needle)) = needle`; the needle is
240
+ # written twice, so its value is bound twice (textual order keeps them equal).
241
+ pattern = self.group(operand, indent)
242
+ return f"right({left}, length({pattern})) = {self.group(operand, indent)}"
243
+
244
+ def expression(self, expr: SqlExpr, indent: int) -> str:
245
+ match expr:
246
+ case ColRef():
247
+ return self.column(expr)
248
+ case Placeholder(value_index=index, pg_type=pg_type, array=array):
249
+ self.params.append(self._values[index])
250
+ cast = f"{pg_type}[]" if array else pg_type
251
+ return f"%s::{cast}"
252
+ case Bool(value=value):
253
+ return _CONST_TEXT[value]
254
+ case Nan(pg_type=pg_type):
255
+ return f"'NaN'::{pg_type}"
256
+ case AnyEq(column=column, values=values):
257
+ return (
258
+ f"{self.group(column, indent, comparison=True)} = "
259
+ f"ANY({self.expression(values, indent)})"
260
+ )
261
+ case StringCall(op=op, column=column, operand=operand):
262
+ return self.string_call(op, column, operand, indent)
263
+ case Regex(column=column, pattern=pattern, negated=negated):
264
+ operator = "!~" if negated else "~"
265
+ return (
266
+ f"({self.group(column, indent)}) {operator} "
267
+ f"('^(?:' || {self.group(pattern, indent)} || ')$')"
268
+ )
269
+ case Collate(operand=operand):
270
+ return f"{self.group(operand, indent)}{_PIN}"
271
+ case IsNull(operand=operand, negated=negated):
272
+ suffix = "IS NOT NULL" if negated else "IS NULL"
273
+ return f"{self.group(operand, indent)} {suffix}"
274
+ case Eq(left=left, right=right):
275
+ return f"{self.group(left, indent)} = {self.group(right, indent)}"
276
+ case Cmp(op=op, left=left, right=right):
277
+ return (
278
+ f"{self.group(left, indent, comparison=True)} {op.value} "
279
+ f"{self.group(right, indent, comparison=True)}"
280
+ )
281
+ case Not(operand=operand):
282
+ return f"NOT {self.group(operand, indent)}"
283
+ case Parity(items=items):
284
+ # SQL's `<>` is non-associative, so the parity is an explicit left fold. Built
285
+ # with a loop, never recursion: a flat chain may be thousands of terms long.
286
+ text = self.group(items[0], indent)
287
+ for item in items[1:]:
288
+ text = f"({text} <> {self.group(item, indent)})"
289
+ return text
290
+ case TupleNe(left=left, right=right):
291
+ return (
292
+ f"({', '.join(self.expression(column, indent) for column in left)}) <> "
293
+ f"({', '.join(self.expression(column, indent) for column in right)})"
294
+ )
295
+ case And(items=items):
296
+ joined = " AND ".join(self.conjunct(item, indent) for item in items)
297
+ return f"({joined})"
298
+ case Or(items=items):
299
+ joined = " OR ".join(self.conjunct(item, indent) for item in items)
300
+ return f"({joined})"
301
+ case CaseNull(guard=guard, value=value):
302
+ return (
303
+ f"CASE WHEN {self.group(guard, indent)} THEN NULL "
304
+ f"ELSE {self.group(value, indent)} END"
305
+ )
306
+
307
+
308
+ def _row(columns: Iterable[str]) -> str:
309
+ """A row constructor whose fields are raw SQL column references."""
310
+ return "ROW(" + ", ".join(columns) + ")"
311
+
312
+
313
+ def _array_text(fields: Iterable[str]) -> str:
314
+ """One text value holding the fields in order, so tuples of any width compare as one key."""
315
+ return "ARRAY[" + ", ".join(fields) + "]::text"
316
+
317
+
318
+ def _pinned(text: str, pinned: bool) -> str:
319
+ """A text expression pinned to code-point order, or left bare when it is not text."""
320
+ return f"({text}{_PIN})" if pinned else text
321
+
322
+
323
+ def _code_point(text: str) -> str:
324
+ """One text identity pinned to code-point order; it is always text, so it is always pinned."""
325
+ return f"{text}{_PIN}"
326
+
327
+
328
+ def _text_literal(text: str) -> str:
329
+ """A schema-derived constant as a SQL string literal (`'` doubled)."""
330
+ return "'" + text.replace("'", "''") + "'"
331
+
332
+
333
+ def _all(parts: list[str]) -> str:
334
+ """A conjunction of SQL texts, parenthesised only when it has more than one part."""
335
+ return parts[0] if len(parts) == 1 else "(" + " AND ".join(parts) + ")"
336
+
337
+
338
+ def _any(parts: list[str]) -> str:
339
+ """A disjunction of SQL texts, parenthesised only when it has more than one part."""
340
+ return parts[0] if len(parts) == 1 else "(" + " OR ".join(parts) + ")"
341
+
342
+
343
+ def _ends(columns: tuple[str, ...], prefix: str) -> tuple[str, ...]:
344
+ """One edge end's state column names: `src1`, `src2`, … or `dst1`, `dst2`, …."""
345
+ return tuple(f"{prefix}{index + 1}" for index in range(len(columns)))
346
+
347
+
348
+ def _single_orientation(recursive: Recursive) -> Orientation | None:
349
+ """The one orientation every hop may take; `None` when the walk may go either way."""
350
+ orientations = {*recursive.base, *(orientation for _, orientation in recursive.steps)}
351
+ return next(iter(orientations)) if len(orientations) == 1 else None
352
+
353
+
354
+ def _arrival(orientations: tuple[Orientation, ...], forwards: list[str]) -> str:
355
+ """`TRUE` when every hop lands on an edge row's target end, `FALSE` when none does."""
356
+ forward = Orientation.FORWARD in orientations
357
+ backward = Orientation.BACKWARD in orientations
358
+ if forward and not backward:
359
+ return "TRUE"
360
+ if backward and not forward:
361
+ return "FALSE"
362
+ return f"CASE WHEN {_any(forwards)} THEN TRUE ELSE FALSE END"