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/__init__.py ADDED
@@ -0,0 +1,36 @@
1
+ """cypher2sql: Cypher graph patterns over a relational schema, compiled to PostgreSQL."""
2
+
3
+ from ._errors import (
4
+ Cypher2SQLError,
5
+ CypherSemanticError,
6
+ CypherSyntaxError,
7
+ LimitExceededError,
8
+ ParameterError,
9
+ QueryError,
10
+ SchemaError,
11
+ UnsupportedCypherError,
12
+ )
13
+ from ._limits import Limits
14
+ from ._schema import Column, Edge, EdgeType, Node, NodeType, PropertyType, Schema, SQLQuery
15
+ from ._template import TemplateLike
16
+
17
+ __all__ = [
18
+ "Column",
19
+ "Cypher2SQLError",
20
+ "CypherSemanticError",
21
+ "CypherSyntaxError",
22
+ "Edge",
23
+ "EdgeType",
24
+ "LimitExceededError",
25
+ "Limits",
26
+ "Node",
27
+ "NodeType",
28
+ "ParameterError",
29
+ "PropertyType",
30
+ "QueryError",
31
+ "SQLQuery",
32
+ "Schema",
33
+ "SchemaError",
34
+ "TemplateLike",
35
+ "UnsupportedCypherError",
36
+ ]
cypher2sql/_ast.py ADDED
@@ -0,0 +1,426 @@
1
+ """The parser's AST: frozen, slotted nodes that each carry a source span.
2
+
3
+ Only the clauses and expressions this compiler understands are represented; anything else is
4
+ reported by the parser as unsupported. Names keep the span of their own token so semantic errors
5
+ can point at the exact label, property or variable that is wrong, not at the whole clause.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+ from enum import StrEnum
12
+
13
+ from ._errors import Span
14
+
15
+
16
+ @dataclass(frozen=True, slots=True)
17
+ class Name:
18
+ """A name from the query text and where it was written."""
19
+
20
+ text: str
21
+ span: Span
22
+
23
+
24
+ @dataclass(frozen=True, slots=True)
25
+ class Query:
26
+ """One query: its clauses in source order, ending with `RETURN`."""
27
+
28
+ clauses: tuple[Clause, ...]
29
+ span: Span
30
+
31
+
32
+ @dataclass(frozen=True, slots=True)
33
+ class Match:
34
+ """`[OPTIONAL] MATCH paths [WHERE expression]`."""
35
+
36
+ paths: tuple[Path, ...]
37
+ where: Where | None
38
+ optional: bool
39
+ span: Span
40
+
41
+
42
+ @dataclass(frozen=True, slots=True)
43
+ class WithItem:
44
+ """One `WITH` item: a bound variable, optionally renamed by `AS`.
45
+
46
+ `alias` is `None` when the item has no `AS`, so the variable keeps its name.
47
+ """
48
+
49
+ name: Name
50
+ alias: Name | None
51
+ span: Span
52
+
53
+
54
+ @dataclass(frozen=True, slots=True)
55
+ class With:
56
+ """`WITH [DISTINCT] item, ... [WHERE expression]`: a new variable scope plus a filter."""
57
+
58
+ items: tuple[WithItem, ...]
59
+ where: Where | None
60
+ distinct: bool
61
+ span: Span
62
+
63
+
64
+ class SortDirection(StrEnum):
65
+ """Which way `ORDER BY` sorts: ascending unless the query writes `DESC`."""
66
+
67
+ ASC = "ascending"
68
+ DESC = "descending"
69
+
70
+
71
+ @dataclass(frozen=True, slots=True)
72
+ class Page:
73
+ """One `SKIP`/`LIMIT` operand: an integer literal or one `$param` value.
74
+
75
+ `keyword` is `SKIP` or `LIMIT` as written, so a bind error names the clause it belongs to.
76
+ The operand is structure, never SQL text: both kinds bind as one `bigint` parameter.
77
+ """
78
+
79
+ keyword: str
80
+ value: Lit | Param
81
+ span: Span
82
+
83
+
84
+ @dataclass(frozen=True, slots=True)
85
+ class OrderItem:
86
+ """`ORDER BY var [ASC|DESC]`: the returned variable, whose key columns decide the order."""
87
+
88
+ var: Name
89
+ direction: SortDirection
90
+ span: Span
91
+
92
+
93
+ @dataclass(frozen=True, slots=True)
94
+ class Return:
95
+ """`RETURN [DISTINCT] var [ORDER BY var [ASC|DESC]] [SKIP operand] [LIMIT operand]`.
96
+
97
+ The variable names the table whose keys come back; `order` is only ever that variable, so a
98
+ plan orders by its key columns (composite keys included, in key order).
99
+ """
100
+
101
+ var: Name
102
+ distinct: bool
103
+ order: OrderItem | None
104
+ skip: Page | None
105
+ limit: Page | None
106
+ span: Span
107
+
108
+
109
+ @dataclass(frozen=True, slots=True)
110
+ class Create:
111
+ """`CREATE paths`, parsed for graph fixtures and rejected by the binder for now."""
112
+
113
+ paths: tuple[Path, ...]
114
+ span: Span
115
+
116
+
117
+ @dataclass(frozen=True, slots=True)
118
+ class Where:
119
+ """The `WHERE` keyword and its predicate expression."""
120
+
121
+ expr: Expr
122
+ span: Span
123
+
124
+
125
+ class Direction(StrEnum):
126
+ """Which way a relationship pattern points: `->`, `<-` or `--`."""
127
+
128
+ OUT = "->"
129
+ IN = "<-"
130
+ BOTH = "--"
131
+
132
+
133
+ @dataclass(frozen=True, slots=True)
134
+ class Path:
135
+ """A comma-separated pattern path: nodes and relationships, alternating."""
136
+
137
+ elements: tuple[NodePat | RelPat, ...]
138
+ span: Span
139
+
140
+
141
+ @dataclass(frozen=True, slots=True)
142
+ class Selector:
143
+ """A `$param` written where a label or a relationship type belongs.
144
+
145
+ It is a compile-time selector: the value names one declared label or type, and never becomes
146
+ an identifier. `text` is only how the query wrote it (`$kind`), so messages can point at it.
147
+ """
148
+
149
+ param: Param
150
+
151
+ @property
152
+ def span(self) -> Span:
153
+ """The span of the `$param` token."""
154
+ return self.param.span
155
+
156
+ @property
157
+ def text(self) -> str:
158
+ """The selector as written, `$name`; never a label or a type."""
159
+ return f"${self.param.name}"
160
+
161
+
162
+ type LabelRef = Name | Selector
163
+
164
+
165
+ @dataclass(frozen=True, slots=True)
166
+ class NodePat:
167
+ """`(var:Label {key: value, ...})`, every part optional; a label may be a `$param`."""
168
+
169
+ var: Name | None
170
+ labels: tuple[LabelRef, ...]
171
+ props: tuple[PropEntry, ...]
172
+ span: Span
173
+
174
+
175
+ @dataclass(frozen=True, slots=True)
176
+ class Length:
177
+ """The hop bound of a variable-length relationship, `*min..max`.
178
+
179
+ `max` is `None` for an open-ended bound (`*`, `*a..`); the parser always writes at least one
180
+ of the two numbers, and the binder resolves an open-ended one to `Limits.open_path_length`
181
+ before anything is planned (so it compiles as a bounded recursive walk).
182
+ """
183
+
184
+ min: int
185
+ max: int | None
186
+ span: Span
187
+
188
+
189
+ @dataclass(frozen=True, slots=True)
190
+ class RelPat:
191
+ """`-[var:TYPE {key: value}]->`, every part optional; `*a..b` adds a `Length`.
192
+
193
+ A type may be a `$param` selector.
194
+ """
195
+
196
+ var: Name | None
197
+ types: tuple[LabelRef, ...]
198
+ direction: Direction
199
+ length: Length | None
200
+ props: tuple[PropEntry, ...]
201
+ span: Span
202
+
203
+
204
+ @dataclass(frozen=True, slots=True)
205
+ class PropEntry:
206
+ """`key: value` inside a node's or relationship's property map."""
207
+
208
+ key: Name
209
+ value: Expr
210
+ span: Span
211
+
212
+
213
+ class Comparison(StrEnum):
214
+ """The comparison operators of the expression language."""
215
+
216
+ EQ = "="
217
+ NE = "<>"
218
+ LT = "<"
219
+ LE = "<="
220
+ GT = ">"
221
+ GE = ">="
222
+
223
+
224
+ class StringOp(StrEnum):
225
+ """The infix string predicates, spelled as the query writes them."""
226
+
227
+ STARTS_WITH = "STARTS WITH"
228
+ ENDS_WITH = "ENDS WITH"
229
+ CONTAINS = "CONTAINS"
230
+
231
+
232
+ @dataclass(frozen=True, slots=True)
233
+ class Lit:
234
+ """A literal: string, integer, float, boolean or null."""
235
+
236
+ value: str | int | float | bool | None
237
+ span: Span
238
+
239
+
240
+ @dataclass(frozen=True, slots=True)
241
+ class Param:
242
+ """`$name`; the value comes from the caller's `params` mapping."""
243
+
244
+ name: str
245
+ span: Span
246
+
247
+
248
+ @dataclass(frozen=True, slots=True)
249
+ class Var:
250
+ """A variable declared in a pattern."""
251
+
252
+ name: str
253
+ span: Span
254
+
255
+
256
+ @dataclass(frozen=True, slots=True)
257
+ class Prop:
258
+ """`owner.key`, a property read; `key_span` points at the property name alone."""
259
+
260
+ owner: str
261
+ key: str
262
+ key_span: Span
263
+ span: Span
264
+
265
+
266
+ @dataclass(frozen=True, slots=True)
267
+ class Cmp:
268
+ """A binary comparison; `op_span` points at the operator token alone."""
269
+
270
+ op: Comparison
271
+ left: Expr
272
+ right: Expr
273
+ op_span: Span
274
+ span: Span
275
+
276
+
277
+ @dataclass(frozen=True, slots=True)
278
+ class ListLit:
279
+ """`[item, ...]`: a list written in the query, only ever an `IN` operand for now."""
280
+
281
+ items: tuple[Expr, ...]
282
+ span: Span
283
+
284
+
285
+ @dataclass(frozen=True, slots=True)
286
+ class In:
287
+ """`left IN [items]` or `left IN $parameter`: membership in a list of values.
288
+
289
+ `items` is a list literal or a `$param` holding the whole list; nothing else is a list this
290
+ compiler can compare against, so the parser refuses it there rather than at bind.
291
+ """
292
+
293
+ left: Expr
294
+ items: ListLit | Param
295
+ op_span: Span
296
+ span: Span
297
+
298
+
299
+ @dataclass(frozen=True, slots=True)
300
+ class StringPredicate:
301
+ """`left STARTS WITH right`, `ENDS WITH` or `CONTAINS`, a condition, never a value."""
302
+
303
+ op: StringOp
304
+ left: Expr
305
+ right: Expr
306
+ op_span: Span
307
+ span: Span
308
+
309
+
310
+ @dataclass(frozen=True, slots=True)
311
+ class Regex:
312
+ """`left =~ pattern`: Cypher's whole-string regular-expression match.
313
+
314
+ `!~` is not a Cypher operator; a `NOT` around this node is what PostgreSQL's `!~` emits.
315
+ """
316
+
317
+ left: Expr
318
+ pattern: Expr
319
+ op_span: Span
320
+ span: Span
321
+
322
+
323
+ @dataclass(frozen=True, slots=True)
324
+ class And:
325
+ """Conjunction, n-ary so `a AND b AND c` is one node and one nesting level."""
326
+
327
+ items: tuple[Expr, ...]
328
+ span: Span
329
+
330
+
331
+ @dataclass(frozen=True, slots=True)
332
+ class Or:
333
+ """Disjunction, n-ary like `And`."""
334
+
335
+ items: tuple[Expr, ...]
336
+ span: Span
337
+
338
+
339
+ @dataclass(frozen=True, slots=True)
340
+ class Xor:
341
+ """Exclusive disjunction, n-ary like `And`."""
342
+
343
+ items: tuple[Expr, ...]
344
+ span: Span
345
+
346
+
347
+ @dataclass(frozen=True, slots=True)
348
+ class Not:
349
+ """`NOT operand`."""
350
+
351
+ operand: Expr
352
+ span: Span
353
+
354
+
355
+ @dataclass(frozen=True, slots=True)
356
+ class IsNull:
357
+ """`operand IS [NOT] NULL`."""
358
+
359
+ operand: Expr
360
+ negated: bool
361
+ span: Span
362
+
363
+
364
+ @dataclass(frozen=True, slots=True)
365
+ class HasLabel:
366
+ """`var:Label`, a label predicate."""
367
+
368
+ operand: Var
369
+ label: Name
370
+ span: Span
371
+
372
+
373
+ @dataclass(frozen=True, slots=True)
374
+ class PatternPredicate:
375
+ """`(n)-[:T]->()` written in a `WHERE`: whether one path matches, never fetched.
376
+
377
+ A pattern predicate is a condition, not a value: it can only name variables already bound,
378
+ because a pattern expression introduces no new one (use `EXISTS { MATCH ... }` for that).
379
+ """
380
+
381
+ path: Path
382
+ span: Span
383
+
384
+
385
+ @dataclass(frozen=True, slots=True)
386
+ class ExistsMatch:
387
+ """One `[MATCH] paths [WHERE expression]` clause inside an `EXISTS { ... }` body."""
388
+
389
+ paths: tuple[Path, ...]
390
+ where: Where | None
391
+ span: Span
392
+
393
+
394
+ @dataclass(frozen=True, slots=True)
395
+ class ExistsSubquery:
396
+ """`EXISTS { [MATCH] paths [WHERE ...] [MATCH paths [WHERE ...]] ... }`.
397
+
398
+ The body is a list of pattern clauses evaluated together: the subquery matches when at least
399
+ one combination of their rows exists. An optional trailing `RETURN <literal>` is accepted and
400
+ dropped — an `EXISTS` body only asks whether a row exists.
401
+ """
402
+
403
+ clauses: tuple[ExistsMatch, ...]
404
+ span: Span
405
+
406
+
407
+ type Clause = Match | With | Return | Create
408
+ type Expr = (
409
+ Lit
410
+ | Param
411
+ | Var
412
+ | Prop
413
+ | Cmp
414
+ | ListLit
415
+ | In
416
+ | StringPredicate
417
+ | Regex
418
+ | And
419
+ | Or
420
+ | Xor
421
+ | Not
422
+ | IsNull
423
+ | HasLabel
424
+ | PatternPredicate
425
+ | ExistsSubquery
426
+ )
@@ -0,0 +1,46 @@
1
+ """AST + Schema → bound IR: name resolution, pattern/type inference, parameter typing.
2
+
3
+ Every lookup key is a name from the query; every answer comes from the declared schema. Unknown
4
+ names are compile errors that suggest declared names only, and a `$param` value must fit the
5
+ property's type before PostgreSQL ever sees it. Values are appended to `Bound.values`; no property
6
+ value is ever part of a message or of the plan. A name taken from the query text — a selector's
7
+ rejected text, an unknown label, type, property, variable or `$param` name — is echoed in a message
8
+ only through `bounded_text`, so a caller-sized name cannot make a caller-sized message; a declared
9
+ name is bounded by the schema and is named as declared.
10
+
11
+ Relationships are resolved here, not in the planner: a typed relationship must name one declared
12
+ edge, an untyped or undirected one may instead follow the shortest declared path between its
13
+ endpoints (`_infer.py`), and a node without a label is narrowed by the edges around it to a
14
+ fixpoint. A single inferred path is inlined into the pattern; several stay `BInferred` so the
15
+ planner can OR them.
16
+
17
+ Comparisons are decided against the declared types: a literal that cannot fit folds per Cypher
18
+ (`=` false/null, `<>` true/null, ordering null) and a `$param` that cannot fit raises instead, so
19
+ no value ever reaches PostgreSQL as a mismatched cast. Numbers are one domain for a *value*
20
+ compared with a property: a finite `float` against an `int` property binds its exact value — an
21
+ integral float inside int64 as that `int` (`%s::bigint`, index-friendly), otherwise as the double's
22
+ exact decimal (`%s::numeric`) — so the `bigint` column is promoted exactly and never rounded; an
23
+ `int` against a `float` property binds as the nearest double, and an integer no double equals folds
24
+ `=`/`<>` and orders against the neighbouring double, so neither direction rounds an int64. A `float`
25
+ property never compares against an `int` or `Decimal` property, though: PostgreSQL's common type for
26
+ the pair rounds through `double precision`, and no exact cast exists, so the bind raises
27
+ `UnsupportedCypherError` naming both properties and the fix. A NaN value folds, while a NaN column
28
+ keeps its three-valued answer through an explicit guard; ±infinity against an `int` property folds
29
+ to its definite answer, keeping the row's null-ness. Labels are static, so `n:Label` folds to a
30
+ constant. String ordering never depends on the database collation: the planner pins `COLLATE "C"`,
31
+ and a string PostgreSQL cannot store is refused in an ordering comparison.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ from cypher2sql._ast import Query
37
+ from cypher2sql._ir import Bound
38
+ from cypher2sql._lexer import QuerySource
39
+ from cypher2sql._schema import Schema
40
+
41
+ from ._binder import _Binder
42
+
43
+
44
+ def bind(query: Query, source: QuerySource, schema: Schema) -> Bound:
45
+ """Resolve one parsed query against `schema`, `source` supplying the value tokens."""
46
+ return _Binder(source, schema).bind(query)