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/_ir.py ADDED
@@ -0,0 +1,663 @@
1
+ """The bound IR: an AST with every name resolved against the schema, plus its parameter values.
2
+
3
+ Literals and `$param` values never stay in the tree: they are appended to `Bound.values` and a
4
+ `BValue` keeps only the index and the PostgreSQL type the value travels as. Property predicates
5
+ are comparisons of a column with a value; anything PostgreSQL would not compare the Cypher way is
6
+ folded into a three-valued null expression instead, so a value can never reach PostgreSQL as a
7
+ mismatched cast.
8
+
9
+ A relationship resolves to a declared edge plus the orientations that make it hold between its
10
+ two nodes. A named type must resolve to exactly one declared edge between the endpoints (either
11
+ direction when undirected), else binding fails. An untyped relationship whose endpoints no single
12
+ edge joins becomes one or more *inferred* paths, kept as `BInferred`: each alternative is a chain
13
+ of intermediate nodes and edges that a plan can compile into an `EXISTS` of its own. A
14
+ variable-length relationship with no type is a `BUntypedRecursive`: one walk over every declared
15
+ edge the pattern's direction allows, since the rows it may read are not known until it runs.
16
+
17
+ The predicate tree mirrors the query's boolean structure: `BAnd`/`BOr`/`BXor` are n-ary, `BNot`
18
+ and `BIsNull` wrap one operand, and comparisons carry their operator. A comparison Cypher decides
19
+ alone stays a `BFold` over its `IS NULL` guard, so it keeps Cypher's three-valued answer; `BNaN`
20
+ is the `'NaN'::<type>` literal a NaN guard compares a column with.
21
+
22
+ Several `MATCH` clauses bind into one `Bound`. The mandatory clauses before the first
23
+ `OPTIONAL MATCH` merge into its pattern; from that clause on, every clause that declares a pattern
24
+ element of its own keeps its elements and its own predicates in a `BScope`, in clause order. An
25
+ optional scope may match nothing and the row survives with its variables missing; a required one
26
+ must match. A clause can only name what earlier clauses declared, so a scope only ever reads the
27
+ pattern and the scopes before it.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ from collections.abc import Iterator
33
+ from dataclasses import dataclass
34
+ from datetime import date, datetime
35
+ from decimal import Decimal
36
+ from enum import StrEnum
37
+ from uuid import UUID
38
+
39
+ from ._schema import EdgeType, NodeType, PropertyType
40
+
41
+
42
+ class PgType(StrEnum):
43
+ """The PostgreSQL cast type of a declared property, as documented in api.md."""
44
+
45
+ TEXT = "text"
46
+ BIGINT = "bigint"
47
+ DOUBLE_PRECISION = "double precision"
48
+ BOOLEAN = "boolean"
49
+ NUMERIC = "numeric"
50
+ DATE = "date"
51
+ TIMESTAMPTZ = "timestamptz"
52
+ UUID = "uuid"
53
+
54
+
55
+ _PG_TYPES: dict[PropertyType, PgType] = {
56
+ str: PgType.TEXT,
57
+ int: PgType.BIGINT,
58
+ float: PgType.DOUBLE_PRECISION,
59
+ bool: PgType.BOOLEAN,
60
+ Decimal: PgType.NUMERIC,
61
+ date: PgType.DATE,
62
+ datetime: PgType.TIMESTAMPTZ,
63
+ UUID: PgType.UUID,
64
+ }
65
+
66
+ _PROPERTY_TYPES: dict[PgType, PropertyType] = {pg: name for name, pg in _PG_TYPES.items()}
67
+
68
+
69
+ def pg_type(property_type: PropertyType) -> PgType:
70
+ """The cast a value of a property declared with this type travels as."""
71
+ return _PG_TYPES[property_type]
72
+
73
+
74
+ def property_type(pg: PgType) -> PropertyType:
75
+ """The declared Python type a column's PostgreSQL type stands for."""
76
+ return _PROPERTY_TYPES[pg]
77
+
78
+
79
+ def declared_pg_type(owner: NodeType | EdgeType, column: str) -> PgType | None:
80
+ """The PostgreSQL type a declared column travels as, or `None` when it is not declared.
81
+
82
+ A column the declaration does not list as a property has no declared type; only `Column`
83
+ entries carry one, and their Python type is the whole declaration. `Column` aliases let two
84
+ property names name one column: when those entries disagree the column has no single declared
85
+ type, so this returns `None` rather than whichever entry came first. Only a type that can be
86
+ trusted to describe the column may drive a cast; `text_key` keeps the pin regardless.
87
+ """
88
+ declared = {pg_type(entry.type) for entry in owner.properties.values() if entry.name == column}
89
+ return declared.pop() if len(declared) == 1 else None
90
+
91
+
92
+ def text_key(owner: NodeType | EdgeType, column: str) -> bool:
93
+ """Whether a key column is declared as a text property, so it compares by code point.
94
+
95
+ A key column the declaration does not list as a property has no declared type; its own
96
+ column collation then decides, so no `COLLATE "C"` is pinned for it. `edge_side_text` adds
97
+ the one thing a declaration does say about undeclared foreign keys: the key they point at.
98
+ Every entry naming the column is consulted: two property names may alias one column, and a
99
+ single non-text entry must not drop the pin the text entry asks for.
100
+ """
101
+ return any(
102
+ entry.name == column and pg_type(entry.type) is PgType.TEXT
103
+ for entry in owner.properties.values()
104
+ )
105
+
106
+
107
+ def edge_side_text(edge: EdgeType, column: str, node: NodeType, key: str) -> bool:
108
+ """Whether one edge row's column compares as text against the node key it points at.
109
+
110
+ A column the edge declares as a property decides its own type. An undeclared foreign-key
111
+ column holds the referenced node's key value, so it is text exactly when that node declares
112
+ its key column as text: an FK-carried text key is pinned like a declared one, and a collation
113
+ cannot make two different edge rows look like one.
114
+ """
115
+ return text_key(edge, column) or text_key(node, key)
116
+
117
+
118
+ def edge_key_text(edge: EdgeType) -> tuple[bool, ...]:
119
+ """Whether each column naming one edge row compares as text, so a trail pins code points.
120
+
121
+ A column that names both ends is decided by the first end that names it, in source-then-target
122
+ order, and each side's answer comes from `edge_side_text`.
123
+ """
124
+ carried: dict[str, tuple[NodeType, str]] = {}
125
+ for columns, node in ((edge.source_columns, edge.source), (edge.target_columns, edge.target)):
126
+ for column, key in zip(columns, node.key, strict=True):
127
+ carried.setdefault(column, (node, key))
128
+ texts: list[bool] = []
129
+ for column in edge.key:
130
+ side = carried.get(column)
131
+ texts.append(
132
+ text_key(edge, column) if side is None else edge_side_text(edge, column, *side)
133
+ )
134
+ return tuple(texts)
135
+
136
+
137
+ class Op(StrEnum):
138
+ """The comparison operators, mirroring the query's `Comparison`."""
139
+
140
+ EQ = "="
141
+ NE = "<>"
142
+ LT = "<"
143
+ LE = "<="
144
+ GT = ">"
145
+ GE = ">="
146
+
147
+
148
+ class ConstValue(StrEnum):
149
+ """The constants an expression can fold to, written as SQL keywords."""
150
+
151
+ TRUE = "TRUE"
152
+ FALSE = "FALSE"
153
+ NULL = "NULL"
154
+
155
+
156
+ class BStringOp(StrEnum):
157
+ """The infix string predicates, as the bound IR carries them."""
158
+
159
+ STARTS_WITH = "starts with"
160
+ ENDS_WITH = "ends with"
161
+ CONTAINS = "contains"
162
+
163
+
164
+ class Orientation(StrEnum):
165
+ """Which way one declared edge holds between the two pattern nodes it joins."""
166
+
167
+ FORWARD = "forward"
168
+ BACKWARD = "backward"
169
+
170
+
171
+ class Carrier(StrEnum):
172
+ """The row that stands for one declared edge: a join table's own row, or an end's row."""
173
+
174
+ OWN = "own"
175
+ SOURCE = "source"
176
+ TARGET = "target"
177
+
178
+
179
+ def carrier(edge: EdgeType) -> Carrier:
180
+ """Which row stands for one declared edge: a join table's row, or one end's own row."""
181
+ if edge.table == edge.target.table and edge.table != edge.source.table:
182
+ return Carrier.TARGET
183
+ if edge.table == edge.source.table and edge.table != edge.target.table:
184
+ return Carrier.SOURCE
185
+ if edge.source.table == edge.target.table:
186
+ source_is_key = edge.source_columns == edge.source.key
187
+ target_is_key = edge.target_columns == edge.target.key
188
+ if target_is_key and not source_is_key:
189
+ return Carrier.TARGET
190
+ if source_is_key and not target_is_key:
191
+ return Carrier.SOURCE
192
+ return Carrier.OWN
193
+
194
+
195
+ @dataclass(frozen=True, slots=True)
196
+ class BNode:
197
+ """One pattern element resolved to a declared node type; `id` is its pattern position."""
198
+
199
+ id: int
200
+ node_type: NodeType
201
+
202
+
203
+ @dataclass(frozen=True, slots=True)
204
+ class BRel:
205
+ """One relationship occurrence resolved to a declared edge and its orientations."""
206
+
207
+ id: int
208
+ edge_type: EdgeType
209
+ left: int
210
+ right: int
211
+ orientations: frozenset[Orientation]
212
+ carrier: Carrier
213
+ declared: bool = True
214
+
215
+
216
+ @dataclass(frozen=True, slots=True)
217
+ class BPath:
218
+ """One inferred path: its intermediate nodes and the edges linking them, left to right."""
219
+
220
+ nodes: tuple[BNode, ...]
221
+ rels: tuple[BRel, ...]
222
+
223
+
224
+ @dataclass(frozen=True, slots=True)
225
+ class BInferred:
226
+ """A relationship with no single edge of its own: one alternative per way it can hold.
227
+
228
+ An untyped/undirected `--` resolved to every shortest declared path, or a typed bounded
229
+ expansion `[*a..b]` resolved to one chain per length whose label walk lands on the right
230
+ endpoint (an empty chain is the zero-hop alternative: both ends are one node).
231
+ """
232
+
233
+ left: int
234
+ right: int
235
+ alternatives: tuple[BPath, ...]
236
+
237
+
238
+ @dataclass(frozen=True, slots=True)
239
+ class BRecursive:
240
+ """A variable-length relationship compiled as one `WITH RECURSIVE` walk of one edge.
241
+
242
+ `base` is every orientation the first hop may take from the left node; `steps` lists one
243
+ (arrived at the row's target end, orientation) pair per later hop the walk may take. A
244
+ one-way walk still lists both arrival ends, one of which no hop can reach; the emitter
245
+ drops that unreachable entry when it omits `at_target`.
246
+ `max_depth` is the deepest hop count that lands on the right endpoint and fits the bound
247
+ (`0` when no hop count does). Cycle safety is the depth counter: a walk stops at that depth,
248
+ while the trail array keeps it from reading an edge row the path already read.
249
+ """
250
+
251
+ left: int
252
+ right: int
253
+ edge_type: EdgeType
254
+ min_depth: int
255
+ max_depth: int
256
+ base: tuple[Orientation, ...]
257
+ steps: tuple[tuple[bool, Orientation], ...]
258
+
259
+
260
+ @dataclass(frozen=True, slots=True)
261
+ class BHop:
262
+ """One declared edge traversed one way inside an untyped walk.
263
+
264
+ `tag` identifies the declared edge, so every orientation of one edge shares it: reading the
265
+ same row forwards or backwards is still reading the same relationship. `edge_type` is the
266
+ whole declaration, so the hop carries its table, key and endpoint columns.
267
+ """
268
+
269
+ tag: int
270
+ edge_type: EdgeType
271
+ orientation: Orientation
272
+
273
+
274
+ @dataclass(frozen=True, slots=True)
275
+ class BUntypedRecursive:
276
+ """A variable-length relationship with no type: one walk over every declared edge.
277
+
278
+ `base` is every hop that leaves the left node at the first depth; `steps` is every hop that
279
+ leaves a node type the walk can stand on before its last hop, both in schema order (forward
280
+ before backward for each edge). A hop's `tag` names the declared edge in the trail, so a walk
281
+ never reads one edge row twice. `max_depth` is the deepest hop count that lands on the right
282
+ endpoint within the bound (`0` when no hop count does). The two endpoint labels and the
283
+ orientation decide which key columns are compared, and every key travels encoded as text with
284
+ its label, so a key of one node type can never be mistaken for another's.
285
+ """
286
+
287
+ left: int
288
+ right: int
289
+ min_depth: int
290
+ max_depth: int
291
+ base: tuple[BHop, ...]
292
+ steps: tuple[BHop, ...]
293
+
294
+
295
+ type BWalk = BRecursive | BUntypedRecursive
296
+
297
+
298
+ def edge_identity(edge: EdgeType) -> tuple[str, str, str]:
299
+ """What makes two occurrences of a relationship stand for the same declared rows."""
300
+ return (edge.type, edge.source.label, edge.target.label)
301
+
302
+
303
+ def walk_identities(walk: BWalk) -> tuple[tuple[str, str, str], ...]:
304
+ """The declared edges one walk can read, in written order: its trail identities."""
305
+ match walk:
306
+ case BRecursive(edge_type=edge):
307
+ return (edge_identity(edge),)
308
+ case BUntypedRecursive(base=base, steps=steps):
309
+ return tuple(dict.fromkeys(edge_identity(hop.edge_type) for hop in (*base, *steps)))
310
+
311
+
312
+ @dataclass(frozen=True, slots=True)
313
+ class BTrail:
314
+ """One path's relationship occurrences: declared rels, inlined chains, recursive walks.
315
+
316
+ No two occurrences in one trail may bind the same row, and Cypher's relationship uniqueness
317
+ holds between the paths of one `MATCH` clause too: `clause` numbers that clause across the
318
+ query, and two occurrences of different clauses may bind the same row. `rels` are the
319
+ occurrences planned in the path's own scope (declared relationships and the hops of a single
320
+ inferred path, inlined); `expansions` index the `inferred` of the pattern or `BScope` the
321
+ trail belongs to, and an expansion's hops live in its alternatives, each its own `EXISTS`;
322
+ `recursions` index that owner's `recursive`, whose right end is the state of one
323
+ `WITH RECURSIVE` walk (typed or untyped).
324
+ """
325
+
326
+ rels: tuple[BRel, ...]
327
+ expansions: tuple[int, ...]
328
+ recursions: tuple[int, ...] = ()
329
+ clause: int = 0
330
+
331
+
332
+ @dataclass(frozen=True, slots=True)
333
+ class BScope:
334
+ """One clause from the first `OPTIONAL MATCH` on that declares pattern elements of its own.
335
+
336
+ An optional scope may match nothing: the row then survives with every variable the clause
337
+ declared missing together, which is what a null-tolerant left join expresses, and its
338
+ `properties` and `where` filter that expansion alone — they never reject the outer row. A
339
+ required scope (a later `MATCH`) must match at least once. `nodes` and `rels` are the elements
340
+ the clause declared; the ones it names again belong to an earlier clause, so a scope only reads
341
+ the pattern and the scopes before it. `index` is this scope's position in `Bound.scopes`.
342
+ """
343
+
344
+ index: int
345
+ optional: bool
346
+ nodes: tuple[BNode, ...]
347
+ rels: tuple[BRel, ...]
348
+ inferred: tuple[BInferred, ...]
349
+ recursive: tuple[BWalk, ...]
350
+ trails: tuple[BTrail, ...]
351
+ properties: tuple[BExpr, ...]
352
+ where: BExpr
353
+
354
+
355
+ @dataclass(frozen=True, slots=True)
356
+ class BNodeRef:
357
+ """A column owner: the node at this pattern position."""
358
+
359
+ id: int
360
+
361
+
362
+ @dataclass(frozen=True, slots=True)
363
+ class BRelRef:
364
+ """A column owner: the relationship occurrence, i.e. its join table's row."""
365
+
366
+ id: int
367
+
368
+
369
+ type BOwner = BNodeRef | BRelRef
370
+
371
+
372
+ @dataclass(frozen=True, slots=True)
373
+ class BCol:
374
+ """A column of a bound node or relationship; `owner` names the alias that carries it."""
375
+
376
+ owner: BOwner
377
+ column: str
378
+ pg_type: PgType
379
+
380
+
381
+ @dataclass(frozen=True, slots=True)
382
+ class BPresent:
383
+ """Whether one optional scope matched: null exactly when it matched nothing.
384
+
385
+ `index` is the position of the `OPTIONAL MATCH` in `Bound.scopes`. It is the only null-ness
386
+ test that cannot be read off a column: a relationship carried by the outer row's table has no
387
+ column of its own that could go missing, yet the optional side as a whole still can.
388
+ """
389
+
390
+ index: int
391
+
392
+
393
+ @dataclass(frozen=True, slots=True)
394
+ class BValue:
395
+ """A caller value, bound at `Bound.values[index]` and cast to `pg_type`."""
396
+
397
+ index: int
398
+ pg_type: PgType
399
+
400
+
401
+ @dataclass(frozen=True, slots=True)
402
+ class BArray:
403
+ """A caller list, bound at `Bound.values[index]` and cast to an array: `%s::text[]`.
404
+
405
+ `pg_type` is the element type: one declared property type, because every element was checked
406
+ to fit it before the list reached here.
407
+ """
408
+
409
+ index: int
410
+ pg_type: PgType
411
+
412
+
413
+ @dataclass(frozen=True, slots=True)
414
+ class BIn:
415
+ """`column IN values`: membership of one column's value in a bound list.
416
+
417
+ Emitted as `column = ANY(%s::<type>[])`; the list may hold NULL, which makes the answer NULL
418
+ when no element matches, exactly as `= ANY` does.
419
+ """
420
+
421
+ column: BCol
422
+ values: BArray
423
+
424
+
425
+ @dataclass(frozen=True, slots=True)
426
+ class BString:
427
+ """`column STARTS WITH`, `ENDS WITH` or `CONTAINS` a value or another column.
428
+
429
+ Both operands are strings; the planner picks the PostgreSQL function, never `LIKE`, so `%`,
430
+ `_` and a backslash in a value are data, and pins the column with `COLLATE "C"` so the
431
+ search is by code point. Either side may be NULL, and then so is the answer.
432
+ """
433
+
434
+ op: BStringOp
435
+ column: BCol
436
+ operand: BExpr
437
+
438
+
439
+ @dataclass(frozen=True, slots=True)
440
+ class BRegex:
441
+ """`column =~ pattern`: a whole-string POSIX match; the planner pins the column to `"C"`."""
442
+
443
+ column: BCol
444
+ pattern: BValue
445
+
446
+
447
+ @dataclass(frozen=True, slots=True)
448
+ class BConst:
449
+ """A constant Cypher decides alone: TRUE, FALSE or NULL."""
450
+
451
+ value: ConstValue
452
+
453
+
454
+ @dataclass(frozen=True, slots=True)
455
+ class BNaN:
456
+ """PostgreSQL's `'NaN'` text, cast to a column's type by a NaN guard."""
457
+
458
+ pg_type: PgType
459
+
460
+
461
+ @dataclass(frozen=True, slots=True)
462
+ class BCmp:
463
+ """A comparison of two operands; every text *column* operand is planned as a `Collate`."""
464
+
465
+ op: Op
466
+ left: BExpr
467
+ right: BExpr
468
+
469
+
470
+ @dataclass(frozen=True, slots=True)
471
+ class BAnd:
472
+ """Conjunction, n-ary and flattened by the planner."""
473
+
474
+ items: tuple[BExpr, ...]
475
+
476
+
477
+ @dataclass(frozen=True, slots=True)
478
+ class BOr:
479
+ """Disjunction, n-ary like `BAnd`."""
480
+
481
+ items: tuple[BExpr, ...]
482
+
483
+
484
+ @dataclass(frozen=True, slots=True)
485
+ class BXor:
486
+ """Exclusive disjunction, n-ary: a flat chain is one level, emitted as one `<>` chain."""
487
+
488
+ items: tuple[BExpr, ...]
489
+
490
+
491
+ @dataclass(frozen=True, slots=True)
492
+ class BNot:
493
+ """`NOT operand`; SQL's three-valued negation is Cypher's."""
494
+
495
+ operand: BExpr
496
+
497
+
498
+ @dataclass(frozen=True, slots=True)
499
+ class BIsNull:
500
+ """`operand IS [NOT] NULL`."""
501
+
502
+ operand: BExpr
503
+ negated: bool = False
504
+
505
+
506
+ @dataclass(frozen=True, slots=True)
507
+ class BFold:
508
+ """A comparison Cypher decides alone, keeping its null-ness.
509
+
510
+ `guard` is `N`, the OR of `IS NULL` over the comparison's column operands: the fold is
511
+ `(N AND NULL)` (false on a value row) or, negated, `(NOT N OR NULL)` (true on a value row).
512
+ """
513
+
514
+ guard: BExpr
515
+ negated: bool = False
516
+
517
+
518
+ @dataclass(frozen=True, slots=True)
519
+ class BNullWhen:
520
+ """`operand`, NULL whenever `guard` holds: a pattern predicate over a missing variable.
521
+
522
+ A pattern expression over a variable an `OPTIONAL MATCH` may leave unbound is NULL, not
523
+ FALSE, when that side matched nothing, and `BNot` around it keeps NULL as NULL.
524
+ """
525
+
526
+ guard: BExpr
527
+ operand: BExpr
528
+
529
+
530
+ @dataclass(frozen=True, slots=True)
531
+ class BExists:
532
+ """One correlated `EXISTS` body: a pattern bound inside a predicate, never fetched.
533
+
534
+ `nodes`, `rels`, `inferred`, `recursive`, `trails` and `properties` are the body's own
535
+ elements — the pattern a `PatternPredicate` or an `EXISTS { ... }` subquery resolved to;
536
+ `where` filters it, and every `MATCH` of the body is a clause of its own for uniqueness.
537
+ `refs` and `groups` are what the body reads from outside it — the outer columns it
538
+ correlates through and the optional scopes whose presence it names — so nothing downstream
539
+ has to walk into the body to place it. `number` is the body's position in bind order, which
540
+ names the `WITH RECURSIVE` walks it contains (`reach<i>`) without colliding with another
541
+ body's.
542
+ """
543
+
544
+ nodes: tuple[BNode, ...]
545
+ rels: tuple[BRel, ...]
546
+ inferred: tuple[BInferred, ...]
547
+ recursive: tuple[BWalk, ...]
548
+ trails: tuple[BTrail, ...]
549
+ properties: tuple[BExpr, ...]
550
+ where: BExpr
551
+ refs: frozenset[BOwner]
552
+ groups: frozenset[int]
553
+ number: int
554
+
555
+
556
+ @dataclass(frozen=True, slots=True)
557
+ class BOrderKey:
558
+ """One key column of the result's order; `text` says its declared type is `str`.
559
+
560
+ A text key is pinned to code-point order (`COLLATE "C"`), exactly like a string comparison.
561
+ A key column the schema does not declare as a property has no declared type, so it orders
562
+ under the column's own collation and `text` is false.
563
+ """
564
+
565
+ column: str
566
+ text: bool
567
+
568
+
569
+ @dataclass(frozen=True, slots=True)
570
+ class BOrder:
571
+ """`ORDER BY v [ASC|DESC]`: the target's key columns, in key order, one direction."""
572
+
573
+ keys: tuple[BOrderKey, ...]
574
+ descending: bool
575
+
576
+
577
+ @dataclass(frozen=True, slots=True)
578
+ class Bound:
579
+ """A fully resolved query: the target node, the whole pattern, predicates and values.
580
+
581
+ `nodes`, `rels`, `inferred`, `recursive`, `trails`, `properties` and `where` are the pattern
582
+ every row has: the mandatory clauses before the first `OPTIONAL MATCH`, plus the predicates of
583
+ a later `MATCH` that declares nothing of its own. Every other clause keeps its own `BScope` in
584
+ `scopes`, in clause order, so nothing downstream has to re-derive which rows may be missing or
585
+ which clause a relationship's uniqueness belongs to.
586
+
587
+ `order`, `skip` and `limit` are the query's page: `order` names the key columns to sort by,
588
+ and the two values are bound at `values[skip.index]`/`values[limit.index]` as `bigint`.
589
+ """
590
+
591
+ target: BNode
592
+ nodes: tuple[BNode, ...]
593
+ rels: tuple[BRel, ...]
594
+ inferred: tuple[BInferred, ...]
595
+ recursive: tuple[BWalk, ...]
596
+ trails: tuple[BTrail, ...]
597
+ properties: tuple[BExpr, ...]
598
+ where: BExpr
599
+ values: tuple[object, ...]
600
+ scopes: tuple[BScope, ...] = ()
601
+ order: BOrder | None = None
602
+ skip: BValue | None = None
603
+ limit: BValue | None = None
604
+
605
+
606
+ type BExpr = (
607
+ BCol
608
+ | BValue
609
+ | BArray
610
+ | BConst
611
+ | BPresent
612
+ | BNaN
613
+ | BCmp
614
+ | BIn
615
+ | BString
616
+ | BRegex
617
+ | BAnd
618
+ | BOr
619
+ | BXor
620
+ | BNot
621
+ | BIsNull
622
+ | BFold
623
+ | BNullWhen
624
+ | BExists
625
+ )
626
+
627
+
628
+ def expr_children(expr: BExpr) -> tuple[BExpr, ...]:
629
+ """The sub-expressions of one predicate node, in written order; empty for a leaf.
630
+
631
+ An `EXISTS` body's children are its `properties` and its `where`: its nodes, relationships and
632
+ trails are pattern elements, not expressions, so a walk over expressions never visits them.
633
+ """
634
+ match expr:
635
+ case BCol() | BPresent() | BValue() | BArray() | BConst() | BNaN():
636
+ return ()
637
+ case BCmp(left=left, right=right):
638
+ return (left, right)
639
+ case BIn(column=column):
640
+ return (column,)
641
+ case BString(column=column, operand=operand):
642
+ return (column, operand)
643
+ case BRegex(column=column):
644
+ return (column,)
645
+ case BAnd(items=items) | BOr(items=items) | BXor(items=items):
646
+ return items
647
+ case BNot(operand=operand):
648
+ return (operand,)
649
+ case BIsNull(operand=operand):
650
+ return (operand,)
651
+ case BFold(guard=guard):
652
+ return (guard,)
653
+ case BNullWhen(guard=guard, operand=operand):
654
+ return (guard, operand)
655
+ case BExists(properties=properties, where=where):
656
+ return (*properties, where)
657
+
658
+
659
+ def walk_expr(expr: BExpr) -> Iterator[BExpr]:
660
+ """Every node of one predicate tree, pre-order, in written order: a node before its children."""
661
+ yield expr
662
+ for child in expr_children(expr):
663
+ yield from walk_expr(child)