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,437 @@
1
+ """Binder state, working types and the schema lookups every later stage calls.
2
+
3
+ One binder carries the names its query declared, the values bound so far and the pattern slots of
4
+ the clause being flattened. Each module of this package adds one stage on top of that state —
5
+ value checks, pattern resolution, path building, expressions, clauses — as a subclass of the one
6
+ before it, so every method body sees the whole binder and no module re-parses or re-derives what
7
+ another already decided. A lookup answers only from the declared schema: an unknown name is a
8
+ compile error that suggests declared names only, and the name taken from the query text is echoed
9
+ through a bounded amount of text, never verbatim."""
10
+
11
+ from __future__ import annotations
12
+
13
+ from dataclasses import dataclass
14
+ from decimal import Decimal
15
+
16
+ from cypher2sql._ast import (
17
+ Comparison,
18
+ Length,
19
+ Name,
20
+ NodePat,
21
+ RelPat,
22
+ )
23
+ from cypher2sql._compare import (
24
+ _ValueSource,
25
+ )
26
+ from cypher2sql._errors import (
27
+ _MAX_SUGGESTION_BYTES,
28
+ CypherSemanticError,
29
+ ParameterError,
30
+ Span,
31
+ UnsupportedCypherError,
32
+ bounded_text,
33
+ )
34
+ from cypher2sql._infer import _PathFinder
35
+ from cypher2sql._ir import (
36
+ BCol,
37
+ BConst,
38
+ BExpr,
39
+ BHop,
40
+ BInferred,
41
+ BNode,
42
+ BNodeRef,
43
+ BOwner,
44
+ BRel,
45
+ BRelRef,
46
+ BTrail,
47
+ BValue,
48
+ BWalk,
49
+ Carrier,
50
+ ConstValue,
51
+ Op,
52
+ Orientation,
53
+ PgType,
54
+ pg_type,
55
+ )
56
+ from cypher2sql._lexer import QuerySource
57
+ from cypher2sql._schema import (
58
+ EdgeType,
59
+ NodeType,
60
+ Schema,
61
+ )
62
+
63
+ from ._names import _name_hint, _property_name_hint, _utf8_size
64
+
65
+ _DECLARE_IN_MATCH = "declare it in MATCH"
66
+
67
+
68
+ _DROPPED_BY_WITH = "it was dropped by WITH; list it there to keep it"
69
+
70
+
71
+ _WITH_ITEMS_SEE_BEFORE = "a WITH item sees the scope before WITH; chain another WITH"
72
+
73
+
74
+ _NOT_A_CONDITION = "a WHERE clause filters with a condition, e.g. n.prop = $value"
75
+
76
+
77
+ _PATTERN_VARIABLE_HINT = (
78
+ "a pattern predicate names variables already bound; use EXISTS { MATCH ... } to introduce one"
79
+ )
80
+
81
+
82
+ _OPS: dict[Comparison, Op] = {
83
+ Comparison.EQ: Op.EQ,
84
+ Comparison.NE: Op.NE,
85
+ Comparison.LT: Op.LT,
86
+ Comparison.LE: Op.LE,
87
+ Comparison.GT: Op.GT,
88
+ Comparison.GE: Op.GE,
89
+ }
90
+
91
+
92
+ # Cypher has one numeric domain for a *value*, and no ordering for booleans.
93
+ _NUMERIC_TYPES = frozenset({int, float, Decimal})
94
+
95
+
96
+ _UNORDERED = frozenset({bool})
97
+
98
+
99
+ @dataclass(frozen=True, slots=True)
100
+ class _Conditional:
101
+ """A bound boolean expression used as a comparison operand, e.g. `(a = b) = true`."""
102
+
103
+ expr: BExpr
104
+
105
+
106
+ type _Operand = BCol | _ValueSource | _Conditional
107
+
108
+
109
+ @dataclass(slots=True)
110
+ class _NodeSlot:
111
+ """One node occurrence while the pattern is resolved; `label` is already a declared name.
112
+
113
+ A *constraint* slot belongs to a pattern predicate or an `EXISTS` body that the clause's
114
+ inference reads to narrow the pattern's labels; it is never built, so it needs no type of
115
+ its own (`_infer` skips its ambiguity check) and is charged when its own body is bound.
116
+ """
117
+
118
+ pattern: NodePat
119
+ label: Name | None
120
+ constraint: bool = False
121
+ bound: BNode | None = None
122
+
123
+
124
+ @dataclass(frozen=True, slots=True)
125
+ class _Parts:
126
+ """What one `MATCH` clause resolved to, before it is merged into the query's `Bound`."""
127
+
128
+ nodes: tuple[BNode, ...]
129
+ rels: tuple[BRel, ...]
130
+ inferred: tuple[BInferred, ...]
131
+ recursive: tuple[BWalk, ...]
132
+ trails: tuple[BTrail, ...]
133
+ properties: tuple[BExpr, ...]
134
+ unsat: bool
135
+
136
+
137
+ @dataclass(frozen=True, slots=True)
138
+ class _ClauseState:
139
+ """The per-clause slot machine, so a subquery can bind a pattern without disturbing it."""
140
+
141
+ node_slots: list[_NodeSlot]
142
+ rel_slots: list[_RelSlot]
143
+ node_slot_by_key: dict[tuple[int, int], int]
144
+ rel_slot_by_key: dict[tuple[int, int], int]
145
+ node_candidates: list[tuple[NodeType, ...]]
146
+ rel_allowed: list[tuple[EdgeType, ...]]
147
+ resolutions: list[_Resolution]
148
+ inferred_slot: dict[int, int]
149
+ recursive_slot: dict[int, int]
150
+ inline: bool
151
+
152
+
153
+ @dataclass(slots=True)
154
+ class _RelSlot:
155
+ """One relationship occurrence while the pattern is being resolved."""
156
+
157
+ pattern: RelPat
158
+ type_name: Name | None
159
+ path: int
160
+ left: int
161
+ right: int
162
+ candidates: tuple[EdgeType, ...]
163
+ unsat: bool = False
164
+ bound: Length | None = None
165
+ recursive: bool = False
166
+ constraint: bool = False
167
+
168
+
169
+ #: One expansion path: each hop as the declared edge plus the orientations that traverse it.
170
+ type _Chain = tuple[tuple[EdgeType, frozenset[Orientation]], ...]
171
+
172
+
173
+ @dataclass(frozen=True, slots=True)
174
+ class _EdgeResolution:
175
+ """One declared edge, in the orientations that make it hold between the two nodes."""
176
+
177
+ edge: EdgeType
178
+ orientations: frozenset[Orientation]
179
+
180
+
181
+ @dataclass(frozen=True, slots=True)
182
+ class _PathResolution:
183
+ """Every shortest declared path between two endpoints, left to right."""
184
+
185
+ alternatives: tuple[tuple[tuple[EdgeType, Orientation], ...], ...]
186
+
187
+
188
+ @dataclass(frozen=True, slots=True)
189
+ class _ExpansionResolution:
190
+ """Every path length a bounded `[*a..b]` stands for, left to right.
191
+
192
+ One chain per length that lands on the right endpoint; an empty chain is the zero-hop
193
+ alternative, where the two endpoints are the same node and no edge row is read.
194
+ """
195
+
196
+ alternatives: tuple[_Chain, ...]
197
+
198
+
199
+ @dataclass(frozen=True, slots=True)
200
+ class _RecursiveResolution:
201
+ """One declared edge walked by a `WITH RECURSIVE` CTE instead of one join per hop."""
202
+
203
+ edge: EdgeType
204
+
205
+
206
+ @dataclass(frozen=True, slots=True)
207
+ class _UntypedResolution:
208
+ """Every declared edge an untyped walk may read, and the depth landing on the right node.
209
+
210
+ `base` leaves the left node; `steps` leaves a node type the walk can stand on before its last
211
+ hop; `max_depth` is the deepest hop count that lands on the right endpoint (zero when none).
212
+ """
213
+
214
+ base: tuple[BHop, ...]
215
+ steps: tuple[BHop, ...]
216
+ max_depth: int
217
+
218
+
219
+ type _Resolution = (
220
+ _EdgeResolution
221
+ | _PathResolution
222
+ | _ExpansionResolution
223
+ | _RecursiveResolution
224
+ | _UntypedResolution
225
+ )
226
+
227
+
228
+ class _BindBase:
229
+ """The binder's state and the schema lookups every later stage calls."""
230
+
231
+ def __init__(self, source: QuerySource, schema: Schema) -> None:
232
+ self._text = source.text
233
+ self._schema = schema
234
+ self._paths = _PathFinder(schema, source.text)
235
+ self._params = source.values
236
+ self._labels = source.labels
237
+ self._interpolations = source.interpolations
238
+ self._template = source.template
239
+ self._values: list[object] = []
240
+ # The whole query: names and pattern positions continue across clauses, so reusing a
241
+ # variable in a later `MATCH` resolves to the node it already names.
242
+ self._variables: dict[str, BNode] = {}
243
+ self._rel_vars: dict[str, tuple[BRel | None, RelPat]] = {}
244
+ self._optional_of: dict[str, int] = {}
245
+ # Names a `WITH` dropped: a later reference names the drop instead of blaming MATCH.
246
+ self._dropped: set[str] = set()
247
+ # Groups a later mandatory clause forces to be present, whichever variable it names.
248
+ self._present_groups: set[int] = set()
249
+ self._used = 0
250
+ self._next_node = 0
251
+ self._next_rel = 0
252
+ self._optional_group: int | None = None
253
+ self._clause = 0
254
+ # A pattern predicate may only name variables already bound; an `EXISTS` body may declare
255
+ # its own. The flag is on while a predicate's body is flattened.
256
+ self._refuse_new = False
257
+ # Subquery bodies are numbered in bind order, so their walks never share a CTE name.
258
+ self._body_number = 0
259
+ self._start_clause()
260
+
261
+ def _start_clause(self) -> None:
262
+ """Forget the previous clause's slots; names, ids and the budget keep counting."""
263
+ self._node_slots: list[_NodeSlot] = []
264
+ self._rel_slots: list[_RelSlot] = []
265
+ self._node_slot_by_key: dict[tuple[int, int], int] = {}
266
+ self._rel_slot_by_key: dict[tuple[int, int], int] = {}
267
+ self._node_candidates: list[tuple[NodeType, ...]] = []
268
+ self._rel_allowed: list[tuple[EdgeType, ...]] = []
269
+ self._resolutions: list[_Resolution] = []
270
+ self._inferred_slot: dict[int, int] = {}
271
+ self._recursive_slot: dict[int, int] = {}
272
+ self._inline = True
273
+
274
+ def _clause_state(self) -> _ClauseState:
275
+ """The per-clause slot machine, saved while a subquery binds a pattern of its own."""
276
+ return _ClauseState(
277
+ self._node_slots,
278
+ self._rel_slots,
279
+ self._node_slot_by_key,
280
+ self._rel_slot_by_key,
281
+ self._node_candidates,
282
+ self._rel_allowed,
283
+ self._resolutions,
284
+ self._inferred_slot,
285
+ self._recursive_slot,
286
+ self._inline,
287
+ )
288
+
289
+ def _restore_clause_state(self, saved: _ClauseState) -> None:
290
+ self._node_slots = saved.node_slots
291
+ self._rel_slots = saved.rel_slots
292
+ self._node_slot_by_key = saved.node_slot_by_key
293
+ self._rel_slot_by_key = saved.rel_slot_by_key
294
+ self._node_candidates = saved.node_candidates
295
+ self._rel_allowed = saved.rel_allowed
296
+ self._resolutions = saved.resolutions
297
+ self._inferred_slot = saved.inferred_slot
298
+ self._recursive_slot = saved.recursive_slot
299
+ self._inline = saved.inline
300
+
301
+ def _boolean_param(self, name: str, span: Span) -> BExpr:
302
+ source = self._param_value(name, span)
303
+ if source.value is None:
304
+ return BConst(ConstValue.NULL)
305
+ if not isinstance(source.value, bool):
306
+ raise ParameterError(
307
+ f"parameter {bounded_text(source.shown)} is not a valid bool",
308
+ query=self._text,
309
+ span=span,
310
+ )
311
+ return self._value(source.value, PgType.BOOLEAN)
312
+
313
+ def _property(self, owner: str, key: str, key_span: Span, span: Span) -> BCol:
314
+ node = self._variables.get(owner)
315
+ if node is not None:
316
+ column = node.node_type.properties.get(key)
317
+ if column is None:
318
+ raise CypherSemanticError(
319
+ f"unknown property {bounded_text(key)} on :{node.node_type.label}",
320
+ query=self._text,
321
+ span=key_span,
322
+ hint=self._property_hint(node.node_type, key),
323
+ )
324
+ return BCol(BNodeRef(node.id), column.name, pg_type(column.type))
325
+ relation = self._rel_vars.get(owner)
326
+ if relation is None:
327
+ raise self._unknown_variable(owner, (span[0], min(span[1], span[0] + len(owner))))
328
+ rel, pattern = relation
329
+ if rel is None:
330
+ raise UnsupportedCypherError(
331
+ "a property of an inferred relationship is not supported yet",
332
+ query=self._text,
333
+ span=key_span,
334
+ )
335
+ column = rel.edge_type.properties.get(key)
336
+ if column is None:
337
+ raise CypherSemanticError(
338
+ f"unknown property {bounded_text(key)} on :{rel.edge_type.type}",
339
+ query=self._text,
340
+ span=key_span,
341
+ hint=self._rel_property_hint(rel.edge_type, key),
342
+ )
343
+ return BCol(self._rel_owner(rel, pattern), column.name, pg_type(column.type))
344
+
345
+ def _variable(self, name: str, span: Span) -> BNode:
346
+ node = self._variables.get(name)
347
+ if node is None:
348
+ raise self._unknown_variable(name, span)
349
+ return node
350
+
351
+ def _param_value(self, name: str, span: Span) -> _ValueSource:
352
+ if self._template:
353
+ # A template carries its values as `{expr}`, so only an interpolation token resolves;
354
+ # a `$name` from its text never does, even spelled `` $`0` `` (same index name).
355
+ if span in self._interpolations:
356
+ return _ValueSource(self._params[name], name, span, self._labels[name])
357
+ elif name in self._params:
358
+ return _ValueSource(self._params[name], name, span, self._label(name))
359
+ raise ParameterError(
360
+ f"missing parameter ${bounded_text(name)}",
361
+ query=self._text,
362
+ span=span,
363
+ hint=self._missing_hint(name),
364
+ )
365
+
366
+ def _label(self, name: str) -> str:
367
+ """How a message names one value token: `$name` or `{expression}`, as written."""
368
+ return self._labels.get(name, f"${name}")
369
+
370
+ def _value(self, value: object, pg: PgType) -> BValue:
371
+ self._values.append(value)
372
+ return BValue(len(self._values) - 1, pg)
373
+
374
+ def _find_node_type(self, name: Name) -> NodeType:
375
+ for node in self._schema.nodes:
376
+ if node.label == name.text:
377
+ return node
378
+ labels = [node.label for node in self._schema.nodes]
379
+ raise CypherSemanticError(
380
+ f"unknown label :{bounded_text(name.text)}",
381
+ query=self._text,
382
+ span=name.span,
383
+ hint=_name_hint(name.text, "label", tuple(labels)),
384
+ )
385
+
386
+ def _unknown_variable(
387
+ self, name: str, span: Span, hint: str | None = None
388
+ ) -> CypherSemanticError:
389
+ """`hint` replaces the default one for a clause that resolves names its own way."""
390
+ if hint is None:
391
+ hint = _DROPPED_BY_WITH if name in self._dropped else _DECLARE_IN_MATCH
392
+ return CypherSemanticError(
393
+ f"unknown variable {bounded_text(name)}", query=self._text, span=span, hint=hint
394
+ )
395
+
396
+ def _missing_hint(self, name: str) -> str:
397
+ """A `str` query takes a `params` entry; a template takes an interpolation."""
398
+ size = _utf8_size(name)
399
+ if size is not None and size > _MAX_SUGGESTION_BYTES:
400
+ # A truncated name is not a key anyone can pass: name its size, not a fake key.
401
+ if self._template:
402
+ return f"use an interpolation under the name the query shows ({size} bytes)"
403
+ return f"pass it in params under the name the query shows ({size} bytes)"
404
+ if self._template:
405
+ return f"use an interpolation instead: {{{name}}}"
406
+ return f'pass it in params: to_sql(cypher, {{"{name}": ...}})'
407
+
408
+ def _property_hint(self, node_type: NodeType, key: str) -> str | None:
409
+ if key in node_type.key:
410
+ return (
411
+ f"`{bounded_text(key)}` is the primary key of {node_type.label}; "
412
+ "add it to properties"
413
+ )
414
+ return _property_name_hint(key, node_type.properties)
415
+
416
+ def _rel_property_hint(self, edge_type: EdgeType, key: str) -> str | None:
417
+ if key in edge_type.key:
418
+ return (
419
+ f"`{bounded_text(key)}` identifies one :{edge_type.type} relationship; "
420
+ "add it to properties"
421
+ )
422
+ return _property_name_hint(key, edge_type.properties)
423
+
424
+ def _rel_owner(self, rel: BRel, pattern: RelPat) -> BOwner:
425
+ if rel.carrier is Carrier.OWN:
426
+ return BRelRef(rel.id)
427
+ if len(rel.orientations) > 1:
428
+ raise CypherSemanticError(
429
+ "a property map on this relationship needs one direction",
430
+ query=self._text,
431
+ span=pattern.span,
432
+ hint="give it -> or <-",
433
+ )
434
+ orientation = next(iter(rel.orientations))
435
+ if rel.carrier is Carrier.SOURCE:
436
+ return BNodeRef(rel.left if orientation is Orientation.FORWARD else rel.right)
437
+ return BNodeRef(rel.right if orientation is Orientation.FORWARD else rel.left)