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,354 @@
1
+ """Pure path arithmetic over the declared edges: chains, landings and walk depths.
2
+
3
+ A declared edge can be traversed in one orientation per direction it declares. These helpers
4
+ answer which orientations a step may take, where a step lands, and how deep a walk may go before
5
+ it stops landing on the endpoint. Nothing here reads a query's text or touches binder state."""
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Iterator
10
+ from typing import cast
11
+
12
+ from cypher2sql._ast import (
13
+ Direction,
14
+ Length,
15
+ NodePat,
16
+ RelPat,
17
+ )
18
+ from cypher2sql._errors import (
19
+ bounded_text,
20
+ )
21
+ from cypher2sql._ir import (
22
+ Orientation,
23
+ )
24
+ from cypher2sql._schema import (
25
+ EdgeType,
26
+ NodeType,
27
+ )
28
+
29
+ from ._base import _Chain, _NodeSlot
30
+
31
+
32
+ def _zero_left_key(
33
+ elements: tuple[NodePat | RelPat, ...], path_index: int, index: int
34
+ ) -> tuple[int, int] | None:
35
+ """The node position a `*0..0` relationship makes this node identical to, if any."""
36
+ if index < 2:
37
+ return None
38
+ previous = elements[index - 1]
39
+ if not isinstance(previous, RelPat) or previous.length is None:
40
+ return None
41
+ if previous.length.min != 0 or previous.length.max != 0:
42
+ return None
43
+ return (path_index, index - 2)
44
+
45
+
46
+ def _expansion_range(length: Length | None) -> tuple[int, int] | None:
47
+ """The hop counts an expansion stands for, as `(lowest, highest)`; `None` for one hop.
48
+
49
+ The binder resolves every open-ended bound before inference, so both ends are real; checking
50
+ a whole range never enumerates its lengths.
51
+ """
52
+ if length is None:
53
+ return None
54
+ return length.min, cast(int, length.max)
55
+
56
+
57
+ def _expansion_size(length: Length) -> int:
58
+ """The elements one expansion emits: every hop of every length it stands for.
59
+
60
+ A `k`-hop chain is `k` edges and `k-1` intermediate nodes, so the total for `a..b` is
61
+ `Σ(2k-1) = (b-a+1)(a+b-1)`: closed form, never a loop over the bound. The zero-hop
62
+ alternative reads no row and emits no element; a bound whose upper end is zero is skipped by
63
+ the caller.
64
+ """
65
+ low = max(length.min, 1)
66
+ high = cast(int, length.max)
67
+ if high < low:
68
+ return 0
69
+ return (high - low + 1) * (low + high - 1)
70
+
71
+
72
+ def _as_chain(steps: tuple[tuple[EdgeType, Orientation], ...]) -> _Chain:
73
+ """An inferred path's single-orientation hops as an expansion chain."""
74
+ return tuple((edge, frozenset({orientation})) for edge, orientation in steps)
75
+
76
+
77
+ def _hop(
78
+ edge: EdgeType, direction: Direction, label: str
79
+ ) -> tuple[str, frozenset[Orientation]] | None:
80
+ """One hop of `edge` out of `label`, with the orientations that make it: or `None`."""
81
+ forward = direction is not Direction.IN and label == edge.source.label
82
+ backward = direction is not Direction.OUT and label == edge.target.label
83
+ if forward and backward:
84
+ return edge.target.label, frozenset({Orientation.FORWARD, Orientation.BACKWARD})
85
+ if forward:
86
+ return edge.target.label, frozenset({Orientation.FORWARD})
87
+ if backward:
88
+ return edge.source.label, frozenset({Orientation.BACKWARD})
89
+ return None
90
+
91
+
92
+ def _walk(
93
+ edge: EdgeType, direction: Direction, start: str, depth: int
94
+ ) -> tuple[_Chain, str] | None:
95
+ """Walk `depth` hops of one declared edge from `start`; the chain and the label it lands on."""
96
+ steps: list[tuple[EdgeType, frozenset[Orientation]]] = []
97
+ current = start
98
+ for _ in range(depth):
99
+ hop = _hop(edge, direction, current)
100
+ if hop is None:
101
+ return None
102
+ current, orientations = hop
103
+ steps.append((edge, orientations))
104
+ return tuple(steps), current
105
+
106
+
107
+ def _landing(edge: EdgeType, direction: Direction, start: str, depth: int) -> str | None:
108
+ """The label a `depth`-hop walk of `edge` from `start` lands on; `None` when it gets stuck."""
109
+ walked = _walk(edge, direction, start, depth)
110
+ return None if walked is None else walked[1]
111
+
112
+
113
+ def _landings(
114
+ edge: EdgeType, direction: Direction, start: str, low: int, high: int
115
+ ) -> tuple[str, ...]:
116
+ """The distinct labels any walk of `low..high` hops from `start` can land on.
117
+
118
+ One declared edge either stays on its one label or alternates two, so the labels repeat with a
119
+ period of at most two: the first two depths of the range name every label the range can reach.
120
+ A `low` of zero is the start's own label, and zero hops read no row.
121
+ """
122
+ labels: list[str] = []
123
+ if low > high:
124
+ return ()
125
+ if low == 0:
126
+ labels.append(start)
127
+ low = 1
128
+ if low > high:
129
+ return tuple(labels)
130
+ first = _landing(edge, direction, start, low)
131
+ if first is None:
132
+ return tuple(labels)
133
+ labels.append(first)
134
+ if low + 1 <= high:
135
+ second = _landing(edge, direction, start, low + 1)
136
+ if second is not None and second not in labels:
137
+ labels.append(second)
138
+ return tuple(labels)
139
+
140
+
141
+ def _deepest(
142
+ edge: EdgeType,
143
+ direction: Direction,
144
+ start: str,
145
+ end: str,
146
+ low: int,
147
+ high: int,
148
+ ) -> int:
149
+ """The deepest hop count in `low..high` that lands on `end`; `0` when none does."""
150
+ low = max(low, 1)
151
+ if low > high:
152
+ return 0
153
+ first = _landing(edge, direction, start, 1)
154
+ if first is None:
155
+ return 0
156
+ second = _landing(edge, direction, start, 2)
157
+ if second is None:
158
+ # A directed edge between two labels can only be walked once.
159
+ return 1 if low <= 1 and end == first else 0
160
+ if first == second:
161
+ # A self-labelled edge (or an undirected one between equal labels) never changes label.
162
+ return high if end == first else 0
163
+ if end == first:
164
+ parity = 1
165
+ elif end == second:
166
+ parity = 2
167
+ else:
168
+ return 0
169
+ deepest = high - ((high - parity) % 2)
170
+ return deepest if deepest >= low else 0
171
+
172
+
173
+ def _expansion_connects(
174
+ edge: EdgeType,
175
+ direction: Direction,
176
+ span: tuple[int, int],
177
+ left: tuple[NodeType, ...],
178
+ right: tuple[NodeType, ...],
179
+ ) -> bool:
180
+ """Whether some length in `span` leads from a candidate left type to a candidate right one."""
181
+ starts, _ = _expansion_ends(edge, direction, span, left, right)
182
+ return bool(starts)
183
+
184
+
185
+ def _expansion_ends(
186
+ edge: EdgeType,
187
+ direction: Direction,
188
+ span: tuple[int, int],
189
+ left: tuple[NodeType, ...],
190
+ right: tuple[NodeType, ...],
191
+ ) -> tuple[tuple[NodeType, ...], tuple[NodeType, ...]]:
192
+ """The candidate start and end types of the chains of `edge` between these endpoints."""
193
+ starts: list[NodeType] = []
194
+ ends: list[NodeType] = []
195
+ right_labels = {node.label for node in right}
196
+ low, high = span
197
+ for start in left:
198
+ for label in _landings(edge, direction, start.label, low, high):
199
+ if label not in right_labels:
200
+ continue
201
+ if start not in starts:
202
+ starts.append(start)
203
+ end = edge.source if label == edge.source.label else edge.target
204
+ if end not in ends:
205
+ ends.append(end)
206
+ return tuple(starts), tuple(ends)
207
+
208
+
209
+ def _labels(candidates: tuple[NodeType, ...], slot: _NodeSlot) -> str:
210
+ if len(candidates) == 1:
211
+ return f":{candidates[0].label}"
212
+ return bounded_text(slot.pattern.var.text) if slot.pattern.var is not None else "the node"
213
+
214
+
215
+ def _only(candidates: tuple[NodeType, ...], allowed: list[NodeType]) -> tuple[NodeType, ...]:
216
+ labels = {node.label for node in allowed}
217
+ return tuple(node for node in candidates if node.label in labels)
218
+
219
+
220
+ def _untyped_hops(
221
+ edges: tuple[EdgeType, ...], direction: Direction
222
+ ) -> Iterator[tuple[int, EdgeType, Orientation]]:
223
+ """Every declared edge in every orientation the pattern's arrow allows, in schema order.
224
+
225
+ `tag` is the edge's declaration position: all its orientations share one identity, because
226
+ they read the same row.
227
+ """
228
+ for tag, edge in enumerate(edges):
229
+ for orientation in (Orientation.FORWARD, Orientation.BACKWARD):
230
+ if _allows(direction, orientation):
231
+ yield tag, edge, orientation
232
+
233
+
234
+ def _allows(direction: Direction, orientation: Orientation) -> bool:
235
+ """Whether a pattern's arrow lets one hop traverse an edge in this orientation."""
236
+ match direction:
237
+ case Direction.OUT:
238
+ return orientation is Orientation.FORWARD
239
+ case Direction.IN:
240
+ return orientation is Orientation.BACKWARD
241
+ case _:
242
+ return True
243
+
244
+
245
+ def _leaving_label(edge: EdgeType, orientation: Orientation) -> str:
246
+ """The label a hop in this orientation leaves."""
247
+ end = edge.source if orientation is Orientation.FORWARD else edge.target
248
+ return end.label
249
+
250
+
251
+ def _landing_label(edge: EdgeType, orientation: Orientation) -> str:
252
+ """The label a hop in this orientation arrives at."""
253
+ end = edge.target if orientation is Orientation.FORWARD else edge.source
254
+ return end.label
255
+
256
+
257
+ def _untyped_levels(
258
+ edges: tuple[EdgeType, ...], direction: Direction, start: str, high: int
259
+ ) -> dict[int, frozenset[str]]:
260
+ """Every label reachable from `start` in exactly `depth` hops, for each depth up to `high`.
261
+
262
+ One untyped walk ignores relationship types, so the label graph is every declared edge in the
263
+ direction the pattern allows. Depths beyond `high` are never asked for; the walk's own depth
264
+ bound is `max_path_length`, at most a handful, so the level walk is tiny.
265
+ """
266
+ levels: dict[int, frozenset[str]] = {0: frozenset({start})}
267
+ frontier = frozenset({start})
268
+ for depth in range(1, high + 1):
269
+ arrived = frozenset(
270
+ _landing_label(edge, orientation)
271
+ for label in frontier
272
+ for _, edge, orientation in _untyped_hops(edges, direction)
273
+ if _leaving_label(edge, orientation) == label
274
+ )
275
+ levels[depth] = arrived
276
+ frontier = arrived
277
+ return levels
278
+
279
+
280
+ def _untyped_reaches(
281
+ edges: tuple[EdgeType, ...], direction: Direction, start: str, end: str, hops: int
282
+ ) -> bool:
283
+ """Whether `end` is reachable from `start` in at most `hops` hops of the untyped edge set."""
284
+ if hops < 0:
285
+ return False
286
+ levels = _untyped_levels(edges, direction, start, hops)
287
+ return any(end in levels[depth] for depth in range(hops + 1))
288
+
289
+
290
+ def _untyped_ends(
291
+ edges: tuple[EdgeType, ...],
292
+ direction: Direction,
293
+ span: tuple[int, int],
294
+ left: tuple[NodeType, ...],
295
+ right: tuple[NodeType, ...],
296
+ ) -> tuple[tuple[NodeType, ...], tuple[NodeType, ...]]:
297
+ """The candidate start and end node types one untyped walk of `span` hops can connect."""
298
+ low, high = span
299
+ right_labels = {node.label for node in right}
300
+ reach = {
301
+ node.label: _untyped_levels(edges, direction, node.label, high) for node in (*left, *right)
302
+ }
303
+ starts: list[NodeType] = []
304
+ for start in left:
305
+ levels = reach[start.label]
306
+ if any(levels[depth] & right_labels for depth in range(low, high + 1)):
307
+ starts.append(start)
308
+ ends: list[NodeType] = []
309
+ for end in right:
310
+ if any(
311
+ end.label in reach[start.label][depth]
312
+ for start in left
313
+ for depth in range(low, high + 1)
314
+ ):
315
+ ends.append(end)
316
+ return tuple(starts), tuple(ends)
317
+
318
+
319
+ def _unique_types(edges: tuple[EdgeType, ...]) -> tuple[EdgeType, ...]:
320
+ seen: set[str] = set()
321
+ unique: list[EdgeType] = []
322
+ for edge in edges:
323
+ if edge.type not in seen:
324
+ seen.add(edge.type)
325
+ unique.append(edge)
326
+ return tuple(unique)
327
+
328
+
329
+ def _endpoint_types(edge: EdgeType, is_left: bool, direction: Direction) -> tuple[NodeType, ...]:
330
+ """The types this edge allows on one side of a relationship pattern."""
331
+ if direction is Direction.OUT:
332
+ return (edge.source,) if is_left else (edge.target,)
333
+ if direction is Direction.IN:
334
+ return (edge.target,) if is_left else (edge.source,)
335
+ return (edge.source, edge.target)
336
+
337
+
338
+ def _connects(
339
+ edge: EdgeType,
340
+ left: tuple[NodeType, ...],
341
+ right: tuple[NodeType, ...],
342
+ direction: Direction,
343
+ ) -> bool:
344
+ left_labels = {node.label for node in left}
345
+ right_labels = {node.label for node in right}
346
+ forward = edge.source.label in left_labels and edge.target.label in right_labels
347
+ backward = edge.source.label in right_labels and edge.target.label in left_labels
348
+ match direction:
349
+ case Direction.OUT:
350
+ return forward
351
+ case Direction.IN:
352
+ return backward
353
+ case _:
354
+ return forward or backward
@@ -0,0 +1,72 @@
1
+ """Name hints and error text: how a name from the query is answered and echoed.
2
+
3
+ A hint is built only from declared names and static text, and stays inside the 63-byte budget every
4
+ schema name already obeys, so a caller-sized name can never make a caller-sized hint. A token no
5
+ declared name could be (one over the byte limit) is answered with its size and never echoed."""
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Mapping
10
+
11
+ from cypher2sql._errors import (
12
+ _MAX_SUGGESTION_BYTES,
13
+ bounded_names,
14
+ bounded_text,
15
+ did_you_mean,
16
+ )
17
+ from cypher2sql._schema import Column
18
+
19
+
20
+ def _declared_properties_hint(properties: Mapping[str, Column]) -> str | None:
21
+ """An edge's declared properties, in declaration order, inside the 63-byte hint budget."""
22
+ return bounded_names(properties, lead="its properties: ") or None
23
+
24
+
25
+ def _declared_hint(kind: str, declared: tuple[str, ...]) -> str | None:
26
+ """The bounded list of declared names, or `None` when the schema declares none."""
27
+ listed = bounded_names(declared, prefix=":", lead=f"{kind}s: ")
28
+ return bounded_text(listed) or None
29
+
30
+
31
+ def _utf8_size(name: str) -> int | None:
32
+ """`name`'s UTF-8 size in bytes, or `None` when the text cannot be encoded."""
33
+ try:
34
+ return len(name.encode("utf-8"))
35
+ except UnicodeEncodeError:
36
+ return None
37
+
38
+
39
+ def _over_length_hint(name: str) -> str | None:
40
+ """The static hint for a name no declared name could be, or `None` when it could be one.
41
+
42
+ Every schema name is at most 63 UTF-8 bytes (`Schema` enforces it), so a longer token cannot
43
+ be suggested or listed; naming its size teaches both limits without echoing it, inside the
44
+ same 63-byte budget as every other name hint.
45
+ """
46
+ size = _utf8_size(name)
47
+ if size is None or size <= _MAX_SUGGESTION_BYTES:
48
+ return None
49
+ return f"declared names are at most {_MAX_SUGGESTION_BYTES} bytes; this one is {size}"
50
+
51
+
52
+ def _name_hint(name: str, kind: str, declared: tuple[str, ...]) -> str | None:
53
+ """The teaching hint for a name from the query that names no declaration.
54
+
55
+ A near miss names the suggestion, otherwise the declared names are listed; a name over 63
56
+ bytes gets the static size clause. The suggestion and the list stay inside the 63-byte
57
+ budget.
58
+ """
59
+ over = _over_length_hint(name)
60
+ if over is not None:
61
+ return over
62
+ suggestion = did_you_mean(name, declared, prefix=":")
63
+ hint = suggestion if suggestion is not None else _declared_hint(kind, declared)
64
+ return None if hint is None else bounded_text(hint)
65
+
66
+
67
+ def _property_name_hint(key: str, properties: Mapping[str, Column]) -> str | None:
68
+ """A near-miss property, the declared properties, or the clause for an over-long name."""
69
+ over = _over_length_hint(key)
70
+ if over is not None:
71
+ return over
72
+ return did_you_mean(key, properties) or _declared_properties_hint(properties)