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/_schema.py ADDED
@@ -0,0 +1,519 @@
1
+ """Schema declarations: node and edge types, columns, and the validated `Schema`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib
6
+ import sys
7
+ from collections.abc import Iterable, Mapping
8
+ from dataclasses import dataclass
9
+ from datetime import date, datetime
10
+ from decimal import Decimal
11
+ from types import MappingProxyType
12
+ from typing import TYPE_CHECKING, Any, Protocol, cast, get_args, runtime_checkable
13
+ from uuid import UUID
14
+
15
+ from ._errors import SchemaError, bounded_text
16
+ from ._lexer import lex
17
+ from ._limits import Limits, _copy_limits
18
+ from ._template import TemplateLike
19
+
20
+ if TYPE_CHECKING:
21
+ if sys.version_info >= (3, 14):
22
+ from string.templatelib import Template
23
+ else:
24
+ # No `string.templatelib` before 3.14; `SQLQuery.to_template()` raises before it is built.
25
+ Template = Any
26
+
27
+ type PropertyType = (
28
+ type[str]
29
+ | type[int]
30
+ | type[float]
31
+ | type[bool]
32
+ | type[Decimal]
33
+ | type[date]
34
+ | type[datetime]
35
+ | type[UUID]
36
+ )
37
+
38
+ # Derived from `PropertyType` itself so the accepted classes, the error text and the alias agree.
39
+
40
+
41
+ def _property_type_label(value: object) -> str:
42
+ """A property type as documented: `str`, `decimal.Decimal`, `datetime.date`, ..."""
43
+ if not isinstance(value, type):
44
+ return repr(value)
45
+ if value.__module__ == "builtins":
46
+ return value.__name__
47
+ return f"{value.__module__}.{value.__qualname__}"
48
+
49
+
50
+ _PROPERTY_TYPES: tuple[type[object], ...] = tuple(
51
+ get_args(argument)[0] for argument in get_args(PropertyType.__value__)
52
+ )
53
+
54
+ _PROPERTY_TYPE_NAMES = tuple(_property_type_label(kind) for kind in _PROPERTY_TYPES)
55
+ _PROPERTY_TYPE_HELP = "{} or {}".format(
56
+ ", ".join(_PROPERTY_TYPE_NAMES[:-1]), _PROPERTY_TYPE_NAMES[-1]
57
+ )
58
+
59
+ _MAX_IDENTIFIER_BYTES = 63
60
+
61
+
62
+ @dataclass(frozen=True, slots=True)
63
+ class Column:
64
+ """A property's column: `Column("price_cents", int)` renames `price` to `price_cents`."""
65
+
66
+ name: str
67
+ type: PropertyType
68
+
69
+ def __post_init__(self) -> None:
70
+ prefix = _column_prefix(self.name)
71
+ _require_identifier(self.name, "name", prefix)
72
+ _require_property_type(self.type, prefix)
73
+
74
+
75
+ @runtime_checkable
76
+ class NodeType(Protocol):
77
+ """What `Schema` needs from a node declaration; `Node` is the shipped implementation."""
78
+
79
+ @property
80
+ def label(self) -> str:
81
+ """The Cypher label, matched exactly and case-sensitively."""
82
+ ...
83
+
84
+ @property
85
+ def table(self) -> str:
86
+ """The table whose rows are the nodes."""
87
+ ...
88
+
89
+ @property
90
+ def key(self) -> tuple[str, ...]:
91
+ """The primary-key columns, in key order."""
92
+ ...
93
+
94
+ @property
95
+ def properties(self) -> Mapping[str, Column]:
96
+ """Every property the query may name, mapped to the column that holds it."""
97
+ ...
98
+
99
+
100
+ @runtime_checkable
101
+ class EdgeType(Protocol):
102
+ """What `Schema` needs from an edge declaration; `Edge` is the shipped implementation."""
103
+
104
+ @property
105
+ def type(self) -> str:
106
+ """The Cypher relationship type."""
107
+ ...
108
+
109
+ @property
110
+ def source(self) -> NodeType:
111
+ """The node type the relationship starts at."""
112
+ ...
113
+
114
+ @property
115
+ def target(self) -> NodeType:
116
+ """The node type the relationship ends at."""
117
+ ...
118
+
119
+ @property
120
+ def table(self) -> str:
121
+ """The table holding one row per relationship."""
122
+ ...
123
+
124
+ @property
125
+ def source_columns(self) -> tuple[str, ...]:
126
+ """The columns holding the source's key."""
127
+ ...
128
+
129
+ @property
130
+ def target_columns(self) -> tuple[str, ...]:
131
+ """The columns holding the target's key."""
132
+ ...
133
+
134
+ @property
135
+ def key(self) -> tuple[str, ...]:
136
+ """The columns that name one relationship row."""
137
+ ...
138
+
139
+ @property
140
+ def properties(self) -> Mapping[str, Column]:
141
+ """Every property a relationship may name, mapped to the column that holds it."""
142
+ ...
143
+
144
+
145
+ @dataclass(frozen=True, slots=True, init=False)
146
+ class Node:
147
+ """One table whose rows are nodes with one label."""
148
+
149
+ label: str
150
+ table: str
151
+ key: tuple[str, ...]
152
+ properties: Mapping[str, Column]
153
+
154
+ def __init__(
155
+ self,
156
+ label: str,
157
+ *,
158
+ table: str,
159
+ key: str | tuple[str, ...],
160
+ properties: Mapping[str, PropertyType | Column] | None = None,
161
+ ) -> None:
162
+ prefix = _node_prefix(label)
163
+ # The label becomes a SQL text literal (a walk's node identity), never a bare token.
164
+ _require_identifier(label, "label", prefix)
165
+ _require_identifier(table, "table", prefix)
166
+ key_columns = _column_tuple(key, "key", prefix)
167
+ if not key_columns:
168
+ raise SchemaError(f"{prefix}: key must not be empty")
169
+ for column in key_columns:
170
+ _require_identifier(column, f'key column "{_shown(column)}"', prefix)
171
+ object.__setattr__(self, "label", label)
172
+ object.__setattr__(self, "table", table)
173
+ object.__setattr__(self, "key", key_columns)
174
+ object.__setattr__(self, "properties", _properties(properties, prefix))
175
+
176
+
177
+ @dataclass(frozen=True, slots=True, init=False)
178
+ class Edge:
179
+ """`(source)-[:type]->(target)`, stored as `(table, source_columns, target_columns)`."""
180
+
181
+ type: str
182
+ source: NodeType
183
+ target: NodeType
184
+ table: str
185
+ source_columns: tuple[str, ...]
186
+ target_columns: tuple[str, ...]
187
+ key: tuple[str, ...]
188
+ properties: Mapping[str, Column]
189
+
190
+ def __init__(
191
+ self,
192
+ type: str,
193
+ source: NodeType,
194
+ target: NodeType,
195
+ *,
196
+ source_columns: str | tuple[str, ...] | None = None,
197
+ target_columns: str | tuple[str, ...] | None = None,
198
+ table: str | None = None,
199
+ properties: Mapping[str, PropertyType | Column] | None = None,
200
+ key: str | tuple[str, ...] | None = None,
201
+ ) -> None:
202
+ prefix = _edge_prefix(type, source, target)
203
+ # The type becomes a SQL text literal in a walk's trail tag, never a bare token.
204
+ _require_identifier(type, "type", prefix)
205
+ source_columns = _column_tuple(source_columns, "source_columns", prefix)
206
+ target_columns = _column_tuple(target_columns, "target_columns", prefix)
207
+ if not source_columns and not target_columns:
208
+ raise SchemaError(
209
+ f"{prefix}: name source_columns (foreign key in {_shown(target.label)}'s table), "
210
+ f"target_columns (foreign key in {_shown(source.label)}'s table), or both with "
211
+ "table= (join table)"
212
+ )
213
+ table, source_columns, target_columns = _resolve_table(
214
+ prefix, source, target, source_columns, target_columns, table
215
+ )
216
+ _require_identifier(table, "table", prefix)
217
+ for column in source_columns:
218
+ _require_identifier(column, f'source_columns entry "{_shown(column)}"', prefix)
219
+ for column in target_columns:
220
+ _require_identifier(column, f'target_columns entry "{_shown(column)}"', prefix)
221
+ _require_same_width(prefix, "source_columns", source_columns, source)
222
+ _require_same_width(prefix, "target_columns", target_columns, target)
223
+ if key is None:
224
+ key_columns = tuple(dict.fromkeys((*source_columns, *target_columns)))
225
+ else:
226
+ key_columns = _column_tuple(key, "key", prefix)
227
+ if not key_columns:
228
+ raise SchemaError(f"{prefix}: key must not be empty")
229
+ for column in key_columns:
230
+ _require_identifier(column, f'key column "{_shown(column)}"', prefix)
231
+ object.__setattr__(self, "type", type)
232
+ object.__setattr__(self, "source", source)
233
+ object.__setattr__(self, "target", target)
234
+ object.__setattr__(self, "table", table)
235
+ object.__setattr__(self, "source_columns", source_columns)
236
+ object.__setattr__(self, "target_columns", target_columns)
237
+ object.__setattr__(self, "key", key_columns)
238
+ object.__setattr__(self, "properties", _properties(properties, prefix))
239
+
240
+
241
+ @dataclass(frozen=True, slots=True)
242
+ class SQLQuery:
243
+ """One `SELECT` over the schema, its bound parameters, and the key column names."""
244
+
245
+ sql: str
246
+ params: tuple[object, ...]
247
+ columns: tuple[str, ...]
248
+
249
+ def to_template(self) -> Template:
250
+ """This query as a PEP 750 `Template`, to nest into a psycopg ≥ 3.3 t-string query.
251
+
252
+ Built from an emitted query: `sql` carries one `%s` per param and no other `%`; `%%`,
253
+ if ever emitted for a literal `%`, becomes `%`. Each `%s` becomes one `Interpolation`
254
+ carrying `params[i]`, in textual order, and no value ever becomes text. The result is
255
+ deterministic — the same `SQLQuery` always yields the same `.strings` and interpolation
256
+ values. Needs Python 3.14; below it, this raises `RuntimeError`.
257
+ """
258
+ if sys.version_info < (3, 14):
259
+ version = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
260
+ raise RuntimeError(
261
+ "SQLQuery.to_template() requires Python 3.14 (PEP 750 t-strings); this is "
262
+ f"Python {version}. Use q.sql with q.params instead."
263
+ )
264
+ templatelib = importlib.import_module("string.templatelib")
265
+ parts: list[object] = []
266
+ buffer: list[str] = []
267
+ bound = 0
268
+ index = 0
269
+ while index < len(self.sql):
270
+ if self.sql.startswith("%s", index):
271
+ parts.append("".join(buffer))
272
+ buffer.clear()
273
+ parts.append(templatelib.Interpolation(self.params[bound], f"q.params[{bound}]"))
274
+ bound += 1
275
+ index += 2
276
+ elif self.sql.startswith("%%", index):
277
+ buffer.append("%")
278
+ index += 2
279
+ else:
280
+ buffer.append(self.sql[index])
281
+ index += 1
282
+ parts.append("".join(buffer))
283
+ template: Template = templatelib.Template(*parts)
284
+ return template
285
+
286
+
287
+ @dataclass(frozen=True, slots=True, init=False)
288
+ class Schema:
289
+ """Your validated graph view of the database; copies every declaration at construction."""
290
+
291
+ nodes: tuple[Node, ...]
292
+ edges: tuple[Edge, ...]
293
+ limits: Limits
294
+
295
+ def __init__(
296
+ self,
297
+ *,
298
+ nodes: Iterable[NodeType],
299
+ edges: Iterable[EdgeType] = (),
300
+ limits: Limits = Limits(), # noqa: B008 # frozen; docs/api.md shows Limits() verbatim
301
+ ) -> None:
302
+ copied_limits = _copy_limits(limits)
303
+ declared_nodes = list(nodes)
304
+ copied_nodes = tuple(
305
+ Node(node.label, table=node.table, key=node.key, properties=node.properties)
306
+ for node in declared_nodes
307
+ )
308
+ labels: set[str] = set()
309
+ for node in copied_nodes:
310
+ if node.label in labels:
311
+ raise SchemaError(f"Schema: duplicate node label {_shown(node.label)}")
312
+ labels.add(node.label)
313
+ copied_by_identity = {
314
+ id(original): copy for original, copy in zip(declared_nodes, copied_nodes, strict=True)
315
+ }
316
+ copied_edges: list[Edge] = []
317
+ identities: set[tuple[str, str, str]] = set()
318
+ for edge in edges:
319
+ source = copied_by_identity.get(id(edge.source))
320
+ target = copied_by_identity.get(id(edge.target))
321
+ if source is None or target is None:
322
+ raise SchemaError(
323
+ f"Schema: edge {_shown(edge.type)} has an endpoint that is not in nodes"
324
+ )
325
+ copied = Edge(
326
+ edge.type,
327
+ source,
328
+ target,
329
+ source_columns=edge.source_columns,
330
+ target_columns=edge.target_columns,
331
+ table=edge.table,
332
+ properties=edge.properties,
333
+ key=edge.key,
334
+ )
335
+ identity = (copied.type, source.label, target.label)
336
+ if identity in identities:
337
+ raise SchemaError(
338
+ f"Schema: duplicate edge {_shown(copied.type)} between "
339
+ f"{_shown(source.label)} and {_shown(target.label)}"
340
+ )
341
+ identities.add(identity)
342
+ copied_edges.append(copied)
343
+ object.__setattr__(self, "nodes", copied_nodes)
344
+ object.__setattr__(self, "edges", tuple(copied_edges))
345
+ object.__setattr__(self, "limits", copied_limits)
346
+
347
+ def to_sql(
348
+ self, cypher: str | TemplateLike, params: Mapping[str, object] | None = None
349
+ ) -> SQLQuery:
350
+ """Compile one Cypher query into a parameterized `SELECT` over this schema.
351
+
352
+ Pure: it never touches a database, and the same query and parameters always produce
353
+ byte-identical SQL. A query it cannot compile raises a `QueryError` subclass.
354
+ """
355
+ if not isinstance(cypher, str):
356
+ if not isinstance(cypher, TemplateLike):
357
+ raise TypeError(
358
+ f"cypher must be a str or a t-string template, not {type(cypher).__name__}"
359
+ )
360
+ if params is not None:
361
+ raise TypeError(
362
+ "params is only for a str query; a t-string carries its values in "
363
+ "{name} interpolations"
364
+ )
365
+ elif params is not None and not isinstance(params, Mapping):
366
+ raise TypeError(
367
+ "params must be a mapping of parameter names to values, "
368
+ f"not {type(params).__name__}"
369
+ )
370
+ # Imported here because the stages import `_schema` for the public types: a module-level
371
+ # import would close the cycle.
372
+ from ._bind import bind
373
+ from ._emit import emit
374
+ from ._parser import parse
375
+ from ._plan import plan
376
+
377
+ source = lex(cypher, self.limits, params)
378
+ query = parse(source.tokens, source.text, self.limits)
379
+ bound = bind(query, source, self)
380
+ return emit(plan(bound), bound.values)
381
+
382
+
383
+ def _resolve_table(
384
+ prefix: str,
385
+ source: NodeType,
386
+ target: NodeType,
387
+ source_columns: tuple[str, ...],
388
+ target_columns: tuple[str, ...],
389
+ table: str | None,
390
+ ) -> tuple[str, tuple[str, ...], tuple[str, ...]]:
391
+ """Fill in the side the declaration leaves implicit; a lone side plus `table=` is an error."""
392
+ if table is not None:
393
+ if not source_columns:
394
+ raise SchemaError(
395
+ f"{prefix}: table is implied by target_columns (the foreign key is in "
396
+ f'"{_shown(source.table)}"); remove table='
397
+ )
398
+ if not target_columns:
399
+ raise SchemaError(
400
+ f"{prefix}: table is implied by source_columns (the foreign key is in "
401
+ f'"{_shown(target.table)}"); remove table='
402
+ )
403
+ return table, source_columns, target_columns
404
+ if source_columns and target_columns:
405
+ raise SchemaError(
406
+ f"{prefix}: table is required when both source_columns and target_columns are given"
407
+ )
408
+ if source_columns:
409
+ return target.table, source_columns, tuple(target.key)
410
+ return source.table, tuple(source.key), target_columns
411
+
412
+
413
+ def _require_same_width(prefix: str, what: str, columns: tuple[str, ...], node: NodeType) -> None:
414
+ """Each named side must name every column of the key it points at."""
415
+ if len(columns) != len(node.key):
416
+ raise SchemaError(
417
+ f"{prefix}: {what} has {len(columns)} {_plural(len(columns))} but the key of "
418
+ f"{_shown(node.label)} has {len(node.key)} {_plural(len(node.key))}"
419
+ )
420
+
421
+
422
+ def _properties(
423
+ properties: Mapping[str, PropertyType | Column] | None, prefix: str
424
+ ) -> Mapping[str, Column]:
425
+ """Copy and normalise a property map; a bare type means a same-named column."""
426
+ if properties is None:
427
+ return MappingProxyType({})
428
+ if not isinstance(properties, Mapping):
429
+ raise SchemaError(
430
+ f"{prefix}: properties must be a mapping of property names to types, "
431
+ f"not {type(properties).__name__}"
432
+ )
433
+ declared: dict[str, Column] = {}
434
+ for name, value in properties.items():
435
+ declared[name] = _as_column(name, value)
436
+ return MappingProxyType(declared)
437
+
438
+
439
+ def _as_column(name: str, value: PropertyType | Column) -> Column:
440
+ if isinstance(value, Column):
441
+ return Column(value.name, value.type)
442
+ return Column(name, value)
443
+
444
+
445
+ def _column_tuple(value: object, what: str, prefix: str) -> tuple[str, ...]:
446
+ """Normalise `str | tuple[str, ...]` (or its absence); anything else names the declaration."""
447
+ if value is None:
448
+ return ()
449
+ if isinstance(value, str):
450
+ return (value,)
451
+ if isinstance(value, tuple):
452
+ for item in value:
453
+ if not isinstance(item, str):
454
+ raise SchemaError(
455
+ f"{prefix}: {what} must contain only str, not {type(item).__name__}"
456
+ )
457
+ return cast(tuple[str, ...], value)
458
+ raise SchemaError(
459
+ f"{prefix}: {what} must be a str or a tuple of str, not {type(value).__name__}"
460
+ )
461
+
462
+
463
+ def quote_ident(name: str) -> str:
464
+ """Quote a schema identifier: always double quoted, embedded `"` doubled."""
465
+ return '"' + name.replace('"', '""') + '"'
466
+
467
+
468
+ def _require_identifier(value: str, what: str, prefix: str) -> None:
469
+ """Reject text that cannot safely become a quoted PostgreSQL identifier."""
470
+ if not isinstance(value, str):
471
+ raise SchemaError(f"{prefix}: {what} must be a string, not {type(value).__name__}")
472
+ if not value:
473
+ raise SchemaError(f"{prefix}: {what} must not be empty")
474
+ if "\x00" in value:
475
+ raise SchemaError(f"{prefix}: {what} must not contain NUL")
476
+ if "%" in value:
477
+ raise SchemaError(f"{prefix}: {what} must not contain '%'")
478
+ try:
479
+ size = len(value.encode("utf-8"))
480
+ except UnicodeEncodeError:
481
+ raise SchemaError(f"{prefix}: {what} must be valid UTF-8 text") from None
482
+ if size > _MAX_IDENTIFIER_BYTES:
483
+ raise SchemaError(
484
+ f"{prefix}: {what} is {size} bytes; PostgreSQL identifiers are at most "
485
+ f"{_MAX_IDENTIFIER_BYTES}"
486
+ )
487
+
488
+
489
+ def _require_property_type(property_type: object, prefix: str) -> None:
490
+ if isinstance(property_type, type) and any(
491
+ property_type is allowed for allowed in _PROPERTY_TYPES
492
+ ):
493
+ return
494
+ raise SchemaError(
495
+ f"{prefix}: type must be one of {_PROPERTY_TYPE_HELP}, "
496
+ f"not {bounded_text(_property_type_label(property_type))}"
497
+ )
498
+
499
+
500
+ def _plural(count: int) -> str:
501
+ return "column" if count == 1 else "columns"
502
+
503
+
504
+ def _shown(name: object) -> str:
505
+ """A declared name in a message: escaped and cut to the documented name budget."""
506
+ return bounded_text(name if isinstance(name, str) else repr(name))
507
+
508
+
509
+ def _node_prefix(label: str) -> str:
510
+ return f"Node {_shown(label)}" if label else "Node"
511
+
512
+
513
+ def _edge_prefix(edge_type: str, source: NodeType, target: NodeType) -> str:
514
+ name = f"Edge {_shown(edge_type)}" if edge_type else "Edge"
515
+ return f"{name} ({_shown(source.label)} -> {_shown(target.label)})"
516
+
517
+
518
+ def _column_prefix(name: str) -> str:
519
+ return f"Column {_shown(name)}" if name else "Column"
@@ -0,0 +1,61 @@
1
+ """The public structural shape of a PEP 750 template, importable on every Python version.
2
+
3
+ A real `string.templatelib.Template` satisfies this protocol, but so does any object carrying the
4
+ same two read-only attributes. That is what lets a 3.12 caller build the shape itself and what
5
+ keeps `to_sql` free of a 3.14-only import; only the `t"..."` syntax itself needs 3.14.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Protocol, runtime_checkable
11
+
12
+
13
+ @runtime_checkable
14
+ class Interpolation(Protocol):
15
+ """One `{expr}` of a PEP 750 template (`string.templatelib.Interpolation` satisfies it).
16
+
17
+ Only the value is ever read by the compiler; the other three fields are part of the shape so
18
+ a value token can show how the interpolation was written and refuse a conversion or format
19
+ spec. A `!s`, `!r` or `!a` conversion appears here and never turns a value into query text.
20
+ """
21
+
22
+ @property
23
+ def value(self) -> object:
24
+ """The evaluated value; it only ever becomes a bound parameter."""
25
+ ...
26
+
27
+ @property
28
+ def expression(self) -> str:
29
+ """The source text inside the braces, used to name the value in errors."""
30
+ ...
31
+
32
+ @property
33
+ def conversion(self) -> str | None:
34
+ """`!s`/`!r`/`!a`, which a value token never accepts."""
35
+ ...
36
+
37
+ @property
38
+ def format_spec(self) -> object:
39
+ """`:>5`, which a value token never accepts."""
40
+ ...
41
+
42
+
43
+ @runtime_checkable
44
+ class TemplateLike(Protocol):
45
+ """A template's literal strings and its interpolations, in source order.
46
+
47
+ `strings` has one more entry than `interpolations`: the text before the first `{expr}`, the
48
+ text between each pair, and the text after the last one. Each interpolation is a value object
49
+ with `value`, `expression`, `conversion` and `format_spec` (stdlib `Interpolation`), but only
50
+ the value is ever read by the compiler.
51
+ """
52
+
53
+ @property
54
+ def strings(self) -> tuple[str, ...]:
55
+ """The literal text: one more entry than there are interpolations."""
56
+ ...
57
+
58
+ @property
59
+ def interpolations(self) -> tuple[Interpolation, ...]:
60
+ """The values, in source order; each becomes one bound parameter."""
61
+ ...