qryndel 0.3.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.
qryndel/__init__.py ADDED
@@ -0,0 +1,50 @@
1
+ """Qryndel, an experimental SQLite implementation of Unified Data Language."""
2
+
3
+ __version__ = "0.3.0"
4
+
5
+ from qryndel.budgets import BudgetExceededError, QueryBudget
6
+ from qryndel.contracts import (
7
+ Compare,
8
+ ContractViolation,
9
+ NoMissing,
10
+ NonEmpty,
11
+ NonNull,
12
+ ResultContract,
13
+ RowCount,
14
+ Unique,
15
+ )
16
+ from qryndel.errors import SourceSpan, UdlError
17
+ from qryndel.executor import DatabaseLockedError, ExecutionError
18
+ from qryndel.explain import ExplainReport
19
+ from qryndel.metrics import ExecutionMetrics
20
+ from qryndel.safety import PreviewReport, SafetyError
21
+ from qryndel.schema import load_sqlite_schema
22
+ from qryndel.schema_drift import SchemaDriftReport, detect_type_drift
23
+ from qryndel.sdk import Client, QueryResult
24
+
25
+ __all__ = [
26
+ "BudgetExceededError",
27
+ "Client",
28
+ "Compare",
29
+ "ContractViolation",
30
+ "DatabaseLockedError",
31
+ "ExecutionError",
32
+ "ExecutionMetrics",
33
+ "ExplainReport",
34
+ "NoMissing",
35
+ "NonEmpty",
36
+ "NonNull",
37
+ "PreviewReport",
38
+ "QueryBudget",
39
+ "QueryResult",
40
+ "ResultContract",
41
+ "RowCount",
42
+ "SafetyError",
43
+ "SchemaDriftReport",
44
+ "SourceSpan",
45
+ "UdlError",
46
+ "Unique",
47
+ "__version__",
48
+ "detect_type_drift",
49
+ "load_sqlite_schema",
50
+ ]
qryndel/ast_nodes.py ADDED
@@ -0,0 +1,403 @@
1
+ """Abstract syntax tree nodes for the Qryndel v0.3.0 language.
2
+
3
+ Value expressions (``Expr``) are built from literals (plain Python values:
4
+ int, float, str, bool, None), ``ParameterRef``, ``FieldPath``,
5
+ ``AggregateField``, ``BinaryOp`` and ``Negate``.
6
+ """
7
+
8
+ from __future__ import annotations
9
+ from dataclasses import dataclass, field
10
+ from typing import Any, Dict, List, Optional, Union
11
+
12
+
13
+ # ---------------------------------------------------------------------------
14
+ # Core nodes (table queries)
15
+ # ---------------------------------------------------------------------------
16
+
17
+ @dataclass
18
+ class Source:
19
+ """The data source (table name, optionally aliased)."""
20
+ name: str
21
+ alias: Optional[str] = None
22
+
23
+ def __repr__(self) -> str:
24
+ if self.alias:
25
+ return f"Source({self.name} AS {self.alias})"
26
+ return f"Source({self.name})"
27
+
28
+
29
+ @dataclass
30
+ class FieldPath:
31
+ """A field/column reference supporting table qualifiers and nested paths.
32
+
33
+ ``qualifier`` is set when the reference explicitly starts with a table name
34
+ or alias (e.g. ``users.name`` or ``u.profile.address.city`` after
35
+ semantic resolution).
36
+ ``parts`` holds all dot-separated segments of the path.
37
+ """
38
+ parts: List[str]
39
+ qualifier: Optional[str] = None
40
+ # Set during validation: the real table the column belongs to, and a
41
+ # conversion to apply (``"NUMERIC"`` when a TYPE declares it a Number).
42
+ table: Optional[str] = field(default=None, compare=False)
43
+ cast: Optional[str] = field(default=None, compare=False)
44
+
45
+ @property
46
+ def name(self) -> str:
47
+ """The terminal field name (last segment)."""
48
+ return self.parts[-1]
49
+
50
+ def __repr__(self) -> str:
51
+ dotted = ".".join(self.parts)
52
+ if self.qualifier:
53
+ return f"FieldPath({self.qualifier}.{dotted})"
54
+ return f"FieldPath({dotted})"
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class AggregateField:
59
+ """An aggregate such as ``COUNT(*)``, ``SUM(amount)`` or ``SUM(qty * cost)``.
60
+
61
+ ``field`` is the argument expression, or ``None`` for ``COUNT(*)``.
62
+ """
63
+ function: str
64
+ field: Optional["Expr"] = None
65
+
66
+ def __repr__(self) -> str:
67
+ argument = "*" if self.field is None else self.field
68
+ return f"AggregateField({self.function}({argument}))"
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class GroupByClause:
73
+ fields: List[FieldPath]
74
+
75
+
76
+ @dataclass(frozen=True)
77
+ class HavingClause:
78
+ expression: WhereExpr
79
+
80
+
81
+ # ---------------------------------------------------------------------------
82
+ # WHERE expression tree
83
+ # ---------------------------------------------------------------------------
84
+
85
+ @dataclass
86
+ class Condition:
87
+ """A comparison: ``field op value``.
88
+
89
+ ``field`` is the left expression and ``value`` the right one. Either may
90
+ be a column, so ``l.current_stock != p.master_stock`` is a Condition.
91
+ """
92
+ field: Any
93
+ operator: str
94
+ value: Any
95
+
96
+ def __repr__(self) -> str:
97
+ return f"Condition({self.field} {self.operator} {self.value!r})"
98
+
99
+
100
+ @dataclass
101
+ class NullPredicate:
102
+ """A null or document-existence predicate on a field."""
103
+ field: FieldPath
104
+ predicate: str
105
+
106
+ def __repr__(self) -> str:
107
+ return f"NullPredicate({self.field} {self.predicate})"
108
+
109
+
110
+ @dataclass(frozen=True)
111
+ class ParameterRef:
112
+ """A named runtime value, such as ``$username``."""
113
+ name: str
114
+
115
+ def __repr__(self) -> str:
116
+ return f"ParameterRef(${self.name})"
117
+
118
+
119
+ @dataclass
120
+ class BinaryOp:
121
+ """Arithmetic: ``left op right`` where op is ``+``, ``-``, ``*`` or ``/``."""
122
+ op: str
123
+ left: "Expr"
124
+ right: "Expr"
125
+
126
+ def __repr__(self) -> str:
127
+ return f"({self.left!r} {self.op} {self.right!r})"
128
+
129
+
130
+ @dataclass
131
+ class Negate:
132
+ """Unary minus: ``-operand``."""
133
+ operand: "Expr"
134
+
135
+ def __repr__(self) -> str:
136
+ return f"(-{self.operand!r})"
137
+
138
+
139
+ @dataclass
140
+ class Convert:
141
+ """``NUMBER(expr)`` or ``TEXT(expr)``: an explicit type conversion."""
142
+ target: str # "NUMBER" or "TEXT"
143
+ operand: "Expr"
144
+
145
+ def __repr__(self) -> str:
146
+ return f"{self.target}({self.operand!r})"
147
+
148
+
149
+ Expr = Union[FieldPath, AggregateField, ParameterRef, BinaryOp, Negate, Convert, int, float, str, bool, None]
150
+
151
+
152
+ @dataclass
153
+ class ProjectionItem:
154
+ """A RETURN item that is computed or renamed: ``expr [AS alias]``.
155
+
156
+ Plain fields and aggregates without ``AS`` stay ``FieldPath`` /
157
+ ``AggregateField`` for backward compatibility.
158
+ """
159
+ expression: Expr
160
+ alias: Optional[str] = None
161
+
162
+ def __repr__(self) -> str:
163
+ suffix = f" AS {self.alias}" if self.alias else ""
164
+ return f"ProjectionItem({self.expression!r}{suffix})"
165
+
166
+
167
+ @dataclass
168
+ class AndCondition:
169
+ """Boolean AND of two sub-expressions."""
170
+ left: WhereExpr
171
+ right: WhereExpr
172
+
173
+ def __repr__(self) -> str:
174
+ return f"({self.left} AND {self.right})"
175
+
176
+
177
+ @dataclass
178
+ class OrCondition:
179
+ """Boolean OR of two sub-expressions."""
180
+ left: WhereExpr
181
+ right: WhereExpr
182
+
183
+ def __repr__(self) -> str:
184
+ return f"({self.left} OR {self.right})"
185
+
186
+
187
+ @dataclass
188
+ class NotCondition:
189
+ """Boolean NOT of a sub-expression."""
190
+ child: WhereExpr
191
+
192
+ def __repr__(self) -> str:
193
+ return f"(NOT {self.child})"
194
+
195
+
196
+ # ---------------------------------------------------------------------------
197
+ # Rule call
198
+ # ---------------------------------------------------------------------------
199
+
200
+ @dataclass
201
+ class RuleCall:
202
+ """A call to a defined rule, e.g. ``is_adult(u)``."""
203
+ name: str
204
+ argument: FieldPath
205
+
206
+ def __repr__(self) -> str:
207
+ return f"RuleCall({self.name}({self.argument}))"
208
+
209
+
210
+ WhereExpr = Union[
211
+ Condition,
212
+ NullPredicate,
213
+ AndCondition,
214
+ OrCondition,
215
+ NotCondition,
216
+ RuleCall,
217
+ ]
218
+
219
+
220
+ # ---------------------------------------------------------------------------
221
+ # ORDER BY
222
+ # ---------------------------------------------------------------------------
223
+
224
+ @dataclass
225
+ class OrderField:
226
+ """A single ORDER BY item (field, aggregate, expression or alias)."""
227
+ field: Any
228
+ direction: str = "ASC"
229
+ nulls: Optional[str] = None
230
+
231
+ def __repr__(self) -> str:
232
+ suffix = f" NULLS {self.nulls}" if self.nulls else ""
233
+ return f"{self.field} {self.direction}{suffix}".strip()
234
+
235
+
236
+ # ---------------------------------------------------------------------------
237
+ # JOIN support
238
+ # ---------------------------------------------------------------------------
239
+
240
+ @dataclass
241
+ class JoinCondition:
242
+ """A binary comparison of two fields: left op right."""
243
+ left: FieldPath
244
+ operator: str
245
+ right: FieldPath
246
+
247
+ def __repr__(self) -> str:
248
+ return f"JoinCondition({self.left} {self.operator} {self.right})"
249
+
250
+
251
+ @dataclass
252
+ class Join:
253
+ """A single JOIN clause (right side)."""
254
+ join_type: str # "INNER", "LEFT", "RIGHT", "FULL"
255
+ right: Source
256
+ alias: Optional[str] = None
257
+ condition: Optional[JoinCondition] = None
258
+
259
+ def __repr__(self) -> str:
260
+ alias_s = f" AS {self.alias}" if self.alias else ""
261
+ return f"{self.join_type} JOIN {self.right.name}{alias_s} ON {self.condition}"
262
+
263
+
264
+ # ---------------------------------------------------------------------------
265
+ # Top-level Query (table)
266
+ # ---------------------------------------------------------------------------
267
+
268
+ @dataclass
269
+ class Query:
270
+ """Top-level AST node for a complete Qryndel FROM query."""
271
+ source: Source
272
+ fields: List[Union[FieldPath, AggregateField, ProjectionItem]]
273
+ where: Optional[WhereExpr] = None
274
+ order: Optional[List[OrderField]] = None
275
+ limit: Optional[int] = None
276
+ distinct: bool = False
277
+ joins: List[Join] = field(default_factory=list)
278
+ group_by: Optional[List[FieldPath]] = None
279
+ having: Optional[WhereExpr] = None
280
+
281
+ def __repr__(self) -> str:
282
+ parts = [
283
+ f"Query(\n"
284
+ f" source={self.source},\n"
285
+ f" fields={self.fields},\n"
286
+ f" where={self.where},\n"
287
+ f" order={self.order},\n"
288
+ f" limit={self.limit},\n"
289
+ f" distinct={self.distinct},\n"
290
+ f" group_by={self.group_by},\n"
291
+ f" having={self.having},\n"
292
+ f" joins={self.joins}\n"
293
+ f")"
294
+ ]
295
+ return "\n".join(parts)
296
+
297
+
298
+ # ---------------------------------------------------------------------------
299
+ # Type definitions, rule definitions, and Program
300
+ # ---------------------------------------------------------------------------
301
+
302
+ @dataclass
303
+ class TypeField:
304
+ """A field declared by a language-level TYPE definition."""
305
+ name: str
306
+ type_name: str
307
+ required: bool = False
308
+
309
+
310
+ @dataclass
311
+ class TypeDefinition:
312
+ """A named UDL schema declaration, such as ``TYPE Student { ... }``."""
313
+ name: str
314
+ fields: List[TypeField]
315
+ allow_extra: bool = False
316
+
317
+ @dataclass
318
+ class RuleDefinition:
319
+ """A single rule definition, e.g. ``RULE is_adult(x) = x.age >= 18``."""
320
+ name: str
321
+ parameter: str
322
+ expression: WhereExpr
323
+
324
+ def __repr__(self) -> str:
325
+ return f"RuleDefinition({self.name}({self.parameter}) = {self.expression})"
326
+
327
+
328
+ @dataclass
329
+ class Assignment:
330
+ """A single ``field = expression`` assignment (for UPDATE)."""
331
+ field: FieldPath
332
+ value: Any
333
+
334
+ def __repr__(self) -> str:
335
+ return f"Assignment({self.field} = {self.value!r})"
336
+
337
+
338
+ @dataclass
339
+ class InsertStatement:
340
+ """INSERT INTO table { field: value, ... }."""
341
+ table: str
342
+ values: Dict[str, Any]
343
+ alias: Optional[str] = None
344
+
345
+ def __repr__(self) -> str:
346
+ return f"InsertStatement({self.table}, {self.values})"
347
+
348
+
349
+ @dataclass
350
+ class UpdateStatement:
351
+ """UPDATE table SET field = value, ... WHERE ..."""
352
+ table: str
353
+ assignments: List[Assignment]
354
+ where: Optional[WhereExpr] = None
355
+ alias: Optional[str] = None
356
+
357
+ def __repr__(self) -> str:
358
+ return f"UpdateStatement({self.table}, {self.assignments}, where={self.where})"
359
+
360
+
361
+ @dataclass
362
+ class DeleteStatement:
363
+ """DELETE FROM table WHERE ..."""
364
+ table: str
365
+ where: Optional[WhereExpr] = None
366
+ alias: Optional[str] = None
367
+
368
+ def __repr__(self) -> str:
369
+ return f"DeleteStatement({self.table}, where={self.where})"
370
+
371
+
372
+ @dataclass
373
+ class TransactionStatement:
374
+ """A local transaction containing multiple write statements."""
375
+ statements: List[Union[InsertStatement, UpdateStatement, DeleteStatement]]
376
+ action: str = "COMMIT"
377
+
378
+
379
+ Statement = Union[
380
+ Query,
381
+ InsertStatement,
382
+ UpdateStatement,
383
+ DeleteStatement,
384
+ TransactionStatement,
385
+ ]
386
+
387
+
388
+ @dataclass
389
+ class Program:
390
+ """A complete program: optional TYPE/RULE declarations and one statement."""
391
+ types: List[TypeDefinition]
392
+ rules: List[RuleDefinition]
393
+ statement: Optional[Statement]
394
+
395
+ @property
396
+ def query(self) -> Query:
397
+ """Return the statement when it is a table ``Query``."""
398
+ if isinstance(self.statement, Query):
399
+ return self.statement
400
+ raise TypeError(f"Program.statement is not a query: {type(self.statement).__name__}")
401
+
402
+ def __repr__(self) -> str:
403
+ return f"Program(types={self.types}, rules={self.rules}, statement={self.statement!r})"
@@ -0,0 +1,40 @@
1
+ """Backend registry. The v0.2.0 public release ships the SQLite backend only."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from qryndel.backends.base import BackendCompiler
6
+
7
+
8
+ _BACKENDS: dict[str, type[BackendCompiler]] = {}
9
+
10
+
11
+ def register_backend(name: str, cls: type[BackendCompiler]) -> None:
12
+ """Register a backend compiler class under *name*."""
13
+ _BACKENDS[name] = cls
14
+
15
+
16
+ def get_backend(name: str) -> BackendCompiler:
17
+ """Return an instance of the named backend compiler.
18
+
19
+ Raises ``ValueError`` if the backend is not registered.
20
+ """
21
+ if name not in _BACKENDS:
22
+ known = ", ".join(sorted(_BACKENDS))
23
+ raise ValueError(f"Unknown backend '{name}'. Known backends: {known}")
24
+ return _BACKENDS[name]()
25
+
26
+
27
+ def _init_backends() -> None:
28
+ from qryndel.backends.sqlite import SqliteBackend
29
+
30
+ register_backend("sqlite", SqliteBackend)
31
+
32
+
33
+ _init_backends()
34
+
35
+
36
+ __all__ = [
37
+ "BackendCompiler",
38
+ "get_backend",
39
+ "register_backend",
40
+ ]
@@ -0,0 +1,40 @@
1
+ """
2
+ Abstract base class for Qryndel backend compilers.
3
+
4
+ Every backend compiler must implement:
5
+
6
+ * ``compile(plan) -> Any`` — compile a logical plan into a backend-specific
7
+ representation (string, dict, or custom object).
8
+ * ``format_output(compiled) -> str`` — render the compiled output as a
9
+ human-readable string for the CLI.
10
+ """
11
+
12
+ from __future__ import annotations
13
+ from abc import ABC, abstractmethod
14
+ from typing import Any, Mapping
15
+
16
+ from qryndel.logical_plan import PlanNode
17
+ from qryndel.capabilities import Capabilities, preflight
18
+
19
+
20
+ class BackendCompiler(ABC):
21
+ """Interface all backend compilers must implement."""
22
+
23
+ name: str = "base"
24
+ capabilities: Capabilities = Capabilities(backend="base")
25
+
26
+ def preflight(self, plan: PlanNode) -> None:
27
+ preflight(plan, self.capabilities)
28
+
29
+ @abstractmethod
30
+ def compile(self, plan: PlanNode, parameters: Mapping[str, Any] | None = None) -> Any:
31
+ """Compile *plan* into a backend-specific representation.
32
+
33
+ Returns a string, dict, or custom object that ``format_output``
34
+ can render.
35
+ """
36
+ ...
37
+
38
+ def format_output(self, compiled: Any) -> str:
39
+ """Render *compiled* as a human-readable string (default: str)."""
40
+ return str(compiled)