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,104 @@
1
+ """Which elements one scope declared, and which of them an expression reads.
2
+
3
+ A subquery body is collected into its own body with the scope elements it reads. None of these
4
+ read a plan node: they answer questions about the bound query the planner would otherwise
5
+ recompute per alias."""
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Iterable, Iterator
10
+
11
+ from cypher2sql._ir import (
12
+ BAnd,
13
+ BCol,
14
+ BConst,
15
+ BExists,
16
+ BExpr,
17
+ BIsNull,
18
+ BOwner,
19
+ BPresent,
20
+ BRel,
21
+ BScope,
22
+ ConstValue,
23
+ expr_children,
24
+ walk_expr,
25
+ )
26
+
27
+ from ._working import _Element
28
+
29
+
30
+ def _element_set(members: list[int], rels: list[BRel]) -> set[_Element]:
31
+ return {("node", node_id) for node_id in members} | {("rel", rel.id) for rel in rels}
32
+
33
+
34
+ def _scope_elements(scope: BScope) -> frozenset[_Element]:
35
+ """Every element one scope declared: nodes, edges, and its alternative paths' hops.
36
+
37
+ A walk's endpoints are pattern nodes, declared by this scope (and then in `nodes`) or by an
38
+ earlier one, so they never make an element this scope's.
39
+ """
40
+ elements = _element_set([node.id for node in scope.nodes], list(scope.rels))
41
+ for inferred in scope.inferred:
42
+ for path in inferred.alternatives:
43
+ elements |= _element_set([node.id for node in path.nodes], list(path.rels))
44
+ return frozenset(elements)
45
+
46
+
47
+ def _absent_groups(where: BExpr) -> frozenset[int]:
48
+ """The optional scopes the outer `WHERE` pins to their null row, so they cannot multiply."""
49
+ groups: set[int] = set()
50
+ for conjunct in _conjuncts(where):
51
+ if (
52
+ isinstance(conjunct, BIsNull)
53
+ and not conjunct.negated
54
+ and isinstance(conjunct.operand, BPresent)
55
+ ):
56
+ groups.add(conjunct.operand.index)
57
+ return frozenset(groups)
58
+
59
+
60
+ def _referenced(expr: BExpr) -> set[BOwner]:
61
+ """Every *outer* column owner an expression names; empty for a constant or a NaN literal.
62
+
63
+ A correlated subquery names only what it reads from outside itself: its own rows are not
64
+ elements the enclosing pattern may be grouped by.
65
+ """
66
+ if isinstance(expr, BExists):
67
+ return set(expr.refs)
68
+ owners: set[BOwner] = {expr.owner} if isinstance(expr, BCol) else set()
69
+ for child in expr_children(expr):
70
+ owners |= _referenced(child)
71
+ return owners
72
+
73
+
74
+ def _optional_references(expr: BExpr) -> set[int]:
75
+ """Every `OPTIONAL MATCH` group whose presence an expression reads."""
76
+ if isinstance(expr, BExists):
77
+ return set(expr.groups)
78
+ found: set[int] = {expr.index} if isinstance(expr, BPresent) else set()
79
+ for child in expr_children(expr):
80
+ found |= _optional_references(child)
81
+ return found
82
+
83
+
84
+ def _collect_bodies(expressions: Iterable[tuple[BExpr, ...]]) -> tuple[BExists, ...]:
85
+ """Every `EXISTS` body an expression tree holds, outer before nested, in written order."""
86
+ return tuple(
87
+ body
88
+ for group in expressions
89
+ for expr in group
90
+ for body in walk_expr(expr)
91
+ if isinstance(body, BExists)
92
+ )
93
+
94
+
95
+ def _conjuncts(expr: BExpr) -> Iterator[BExpr]:
96
+ """Flatten `AND`, dropping the empty predicate's `TRUE`."""
97
+ match expr:
98
+ case BAnd(items=items):
99
+ for item in items:
100
+ yield from _conjuncts(item)
101
+ case BConst(value=ConstValue.TRUE):
102
+ return
103
+ case _:
104
+ yield expr
@@ -0,0 +1,84 @@
1
+ """Which rows a plan must compare, and which it can skip.
2
+
3
+ An expansion's alternatives and a walk's hops are identified by the declared edge they read, so
4
+ uniqueness can tell two occurrences of one edge apart. None of these read a plan node: they answer
5
+ questions about the bound query the planner would otherwise recompute per alias."""
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Iterable
10
+
11
+ from cypher2sql._ir import (
12
+ BInferred,
13
+ BRel,
14
+ BTrail,
15
+ BWalk,
16
+ Carrier,
17
+ Orientation,
18
+ edge_identity,
19
+ walk_identities,
20
+ )
21
+
22
+
23
+ def _orientations(rel: BRel) -> tuple[Orientation, ...]:
24
+ return tuple(
25
+ orientation
26
+ for orientation in (Orientation.FORWARD, Orientation.BACKWARD)
27
+ if orientation in rel.orientations
28
+ )
29
+
30
+
31
+ def _row_varies(rel: BRel) -> bool:
32
+ """An end-row edge that holds both ways between two nodes is one of two rows."""
33
+ return rel.carrier is not Carrier.OWN and len(rel.orientations) > 1 and rel.left != rel.right
34
+
35
+
36
+ def _detached_rows(
37
+ groups: list[
38
+ tuple[tuple[BRel, ...], tuple[BTrail, ...], tuple[BInferred, ...], tuple[BWalk, ...]]
39
+ ],
40
+ ) -> frozenset[int]:
41
+ """End-row edges whose row depends on the orientation, so uniqueness must name it.
42
+
43
+ An edge stored in an end's own table can be either end's row when it is undirected and joins
44
+ two different nodes. Comparing it with another occurrence of the same declared edge, or seeding
45
+ a walk from it, needs an alias pinned to the row the chosen orientation binds. A recursive
46
+ walk is one such occurrence even though it carries no `BRel` of its own: its edge identity
47
+ detaches the declared rel, and an untyped walk detaches every declared edge it can read.
48
+ Each group (the mandatory part, then one per `OPTIONAL MATCH`) is its own set of trails.
49
+ """
50
+ scopes: list[tuple[list[BRel], frozenset[tuple[str, str, str]]]] = []
51
+ for rels, trails, inferred, recursive in groups:
52
+ scopes.append((list(rels), frozenset()))
53
+ for trail in trails:
54
+ for index in trail.expansions:
55
+ for path in inferred[index].alternatives:
56
+ scopes.append(([*trail.rels, *path.rels], frozenset()))
57
+ if trail.recursions:
58
+ walks = frozenset(
59
+ identity
60
+ for index in trail.recursions
61
+ for identity in walk_identities(recursive[index])
62
+ )
63
+ scopes.append((list(trail.rels), walks))
64
+ detached: set[int] = set()
65
+ for row_rels, walks in scopes:
66
+ identities = [edge_identity(rel.edge_type) for rel in row_rels]
67
+ for rel in row_rels:
68
+ if not _row_varies(rel):
69
+ continue
70
+ identity = edge_identity(rel.edge_type)
71
+ if identity in walks or identities.count(identity) > 1:
72
+ detached.add(rel.id)
73
+ return frozenset(detached)
74
+
75
+
76
+ def _identity_pairs(rels: Iterable[BRel]) -> list[tuple[BRel, BRel]]:
77
+ """Every pair of occurrences that stand for the same declared edge, in written order."""
78
+ items = list(rels)
79
+ return [
80
+ (first, second)
81
+ for index, first in enumerate(items)
82
+ for second in items[index + 1 :]
83
+ if edge_identity(first.edge_type) == edge_identity(second.edge_type)
84
+ ]
@@ -0,0 +1,99 @@
1
+ """Planner-only working types: how one scope plans its rows, never a SQL construct itself.
2
+
3
+ `_Link` is one equality the planner emits for an edge row; `_Expansion` and `_WalkPlan` are an
4
+ inferred path or a recursive walk as one scope plans it, paired with the trail its hops must not
5
+ repeat; `_Unit` is one row scope of a lateral plan. The emitter never sees any of them: it renders
6
+ the `_nodes` tree these types were only used to build."""
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+
12
+ from cypher2sql._ir import (
13
+ BExpr,
14
+ BInferred,
15
+ BRel,
16
+ BTrail,
17
+ BWalk,
18
+ Orientation,
19
+ )
20
+
21
+ from ._nodes import ColRef, Eq, SqlExpr, _keyed
22
+
23
+
24
+ @dataclass(frozen=True, slots=True)
25
+ class _Link:
26
+ """One equality of an edge's row column with an end's key column.
27
+
28
+ `row` is the edge row's column and `key` the pattern node's; `row_text` and `key_text` say
29
+ which of them is declared text, so each is pinned to code points when the link is rendered.
30
+ """
31
+
32
+ rel: int
33
+ orientation: Orientation
34
+ index: int
35
+ row: ColRef
36
+ key: ColRef
37
+ row_text: bool = False
38
+ key_text: bool = False
39
+
40
+ def row_expr(self) -> SqlExpr:
41
+ """The edge row's side of the link, collated when it is text."""
42
+ return _keyed(self.row, self.row_text)
43
+
44
+ def key_expr(self) -> SqlExpr:
45
+ """The pattern node's side of the link, collated when it is text."""
46
+ return _keyed(self.key, self.key_text)
47
+
48
+ def equality(self) -> SqlExpr:
49
+ """`row = key`, row side first."""
50
+ return Eq(self.row_expr(), self.key_expr())
51
+
52
+ def reversed(self) -> SqlExpr:
53
+ """`key = row`, for a join that puts the new row on the left."""
54
+ return Eq(self.key_expr(), self.row_expr())
55
+
56
+
57
+ type _Element = tuple[str, int]
58
+
59
+
60
+ @dataclass(frozen=True, slots=True)
61
+ class _Expansion:
62
+ """One inferred relationship as a scope plans it, with the path its hops must not repeat."""
63
+
64
+ relation: BInferred
65
+ trail: BTrail
66
+
67
+
68
+ @dataclass(frozen=True, slots=True)
69
+ class _WalkPlan:
70
+ """One recursive walk as a scope plans it: its query-wide number, the walk and its path.
71
+
72
+ `number` names the walk's SQL (`reach<n>`, `e<n>`, `step<n>`): the pattern's walks keep their
73
+ own positions and each scope's continue after them, so no two walks of one query share a name.
74
+ """
75
+
76
+ number: int
77
+ walk: BWalk
78
+ trail: BTrail
79
+
80
+
81
+ @dataclass(slots=True)
82
+ class _Unit:
83
+ """One row scope of a lateral plan: a component of the pattern, or one `BScope`.
84
+
85
+ `scope` is the `Bound.scopes` index, or `None` for a component of the pattern every row has.
86
+ `required` units must match (their `found` column is required in the outer `WHERE`); an
87
+ optional scope's unit may yield its null row.
88
+ """
89
+
90
+ alias: str
91
+ scope: int | None
92
+ required: bool
93
+ node_ids: list[int]
94
+ rels: list[BRel]
95
+ inferred: list[_Expansion]
96
+ recursive: list[_WalkPlan]
97
+ trails: list[BTrail]
98
+ properties: tuple[BExpr, ...]
99
+ predicates: tuple[BExpr, ...]