agent-semantic-layer 0.0.1__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.
- agent_semantic_layer/__init__.py +63 -0
- agent_semantic_layer/backends/__init__.py +1 -0
- agent_semantic_layer/backends/sqlalchemy.py +38 -0
- agent_semantic_layer/backends/sqlalchemy_compiler.py +525 -0
- agent_semantic_layer/core/__init__.py +1 -0
- agent_semantic_layer/core/backend.py +23 -0
- agent_semantic_layer/core/context.py +197 -0
- agent_semantic_layer/core/errors.py +5 -0
- agent_semantic_layer/core/loader.py +77 -0
- agent_semantic_layer/core/model.py +347 -0
- agent_semantic_layer/core/prompt.py +153 -0
- agent_semantic_layer/core/query.py +131 -0
- agent_semantic_layer/integrations/__init__.py +1 -0
- agent_semantic_layer/integrations/langchain_middleware.py +85 -0
- agent_semantic_layer/integrations/langchain_tools.py +63 -0
- agent_semantic_layer/semantic-view.schema.json +1054 -0
- agent_semantic_layer-0.0.1.dist-info/METADATA +201 -0
- agent_semantic_layer-0.0.1.dist-info/RECORD +20 -0
- agent_semantic_layer-0.0.1.dist-info/WHEEL +4 -0
- agent_semantic_layer-0.0.1.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Core semantic models and built-in backend exports."""
|
|
2
|
+
|
|
3
|
+
from .backends.sqlalchemy import SQLAlchemyQueryBackend
|
|
4
|
+
from .backends.sqlalchemy_compiler import compile_sqlalchemy
|
|
5
|
+
from .core.backend import SemanticQueryBackend
|
|
6
|
+
from .core.errors import CompileError
|
|
7
|
+
from .core.loader import (
|
|
8
|
+
SemanticViewLoadError,
|
|
9
|
+
load_semantic_view,
|
|
10
|
+
load_semantic_view_from_string,
|
|
11
|
+
)
|
|
12
|
+
from .core.model import (
|
|
13
|
+
BaseTable,
|
|
14
|
+
DerivedMetric,
|
|
15
|
+
Dimension,
|
|
16
|
+
Fact,
|
|
17
|
+
KeySpec,
|
|
18
|
+
LogicalTable,
|
|
19
|
+
Metric,
|
|
20
|
+
NamedFilter,
|
|
21
|
+
Relationship,
|
|
22
|
+
RelationshipColumn,
|
|
23
|
+
ResolvedItem,
|
|
24
|
+
SemanticView,
|
|
25
|
+
Variable,
|
|
26
|
+
VerifiedQuery,
|
|
27
|
+
)
|
|
28
|
+
from .core.query import (
|
|
29
|
+
FilterCondition,
|
|
30
|
+
FilterGroup,
|
|
31
|
+
OrderBy,
|
|
32
|
+
SelectionItem,
|
|
33
|
+
SemanticQuery,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
__all__ = [
|
|
37
|
+
"BaseTable",
|
|
38
|
+
"CompileError",
|
|
39
|
+
"DerivedMetric",
|
|
40
|
+
"Dimension",
|
|
41
|
+
"Fact",
|
|
42
|
+
"FilterCondition",
|
|
43
|
+
"FilterGroup",
|
|
44
|
+
"KeySpec",
|
|
45
|
+
"LogicalTable",
|
|
46
|
+
"Metric",
|
|
47
|
+
"NamedFilter",
|
|
48
|
+
"OrderBy",
|
|
49
|
+
"Relationship",
|
|
50
|
+
"RelationshipColumn",
|
|
51
|
+
"ResolvedItem",
|
|
52
|
+
"SQLAlchemyQueryBackend",
|
|
53
|
+
"SelectionItem",
|
|
54
|
+
"SemanticQuery",
|
|
55
|
+
"SemanticQueryBackend",
|
|
56
|
+
"SemanticView",
|
|
57
|
+
"SemanticViewLoadError",
|
|
58
|
+
"Variable",
|
|
59
|
+
"VerifiedQuery",
|
|
60
|
+
"compile_sqlalchemy",
|
|
61
|
+
"load_semantic_view",
|
|
62
|
+
"load_semantic_view_from_string",
|
|
63
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Implementations for executing semantic queries."""
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""SQLAlchemy backend for synchronous and asynchronous engines."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from sqlalchemy.engine import Engine
|
|
9
|
+
from sqlalchemy.ext.asyncio import AsyncEngine
|
|
10
|
+
|
|
11
|
+
from ..core.model import SemanticView
|
|
12
|
+
from ..core.query import SemanticQuery
|
|
13
|
+
from .sqlalchemy_compiler import compile_sqlalchemy
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class SQLAlchemyQueryBackend:
|
|
17
|
+
"""Execute semantic queries using an externally managed SQLAlchemy engine."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, engine: Engine | AsyncEngine) -> None:
|
|
20
|
+
self.engine = engine
|
|
21
|
+
|
|
22
|
+
async def execute(
|
|
23
|
+
self, view: SemanticView, query: SemanticQuery
|
|
24
|
+
) -> list[dict[str, Any]]:
|
|
25
|
+
statement, params = compile_sqlalchemy(view, query)
|
|
26
|
+
if isinstance(self.engine, AsyncEngine):
|
|
27
|
+
async with self.engine.connect() as connection:
|
|
28
|
+
result = await connection.execute(statement, params)
|
|
29
|
+
return [dict(row) for row in result.mappings()]
|
|
30
|
+
|
|
31
|
+
engine = self.engine
|
|
32
|
+
|
|
33
|
+
def execute_sync() -> list[dict[str, Any]]:
|
|
34
|
+
with engine.connect() as connection:
|
|
35
|
+
result = connection.execute(statement, params)
|
|
36
|
+
return [dict(row) for row in result.mappings()]
|
|
37
|
+
|
|
38
|
+
return await asyncio.to_thread(execute_sync)
|
|
@@ -0,0 +1,525 @@
|
|
|
1
|
+
"""Compile a semantic query into a SQLAlchemy statement.
|
|
2
|
+
|
|
3
|
+
This module never touches a database. It builds a SQLAlchemy select and a
|
|
4
|
+
parameter dictionary from a semantic view and query.
|
|
5
|
+
|
|
6
|
+
Filter values use bind parameters; output identifiers are validated. Physical
|
|
7
|
+
expressions and table names come from the trusted, author-supplied model.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
from typing import Any, ClassVar
|
|
14
|
+
|
|
15
|
+
from sqlalchemy import bindparam, literal_column, select, text
|
|
16
|
+
from sqlalchemy.sql import Select
|
|
17
|
+
|
|
18
|
+
from ..core.errors import CompileError
|
|
19
|
+
from ..core.model import LogicalTable, ResolvedItem, SemanticView
|
|
20
|
+
from ..core.query import (
|
|
21
|
+
FilterCondition,
|
|
22
|
+
FilterGroup,
|
|
23
|
+
FilterNode,
|
|
24
|
+
SelectionItem,
|
|
25
|
+
SemanticQuery,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
# Operators that render as a simple binary comparison.
|
|
29
|
+
_BINARY_OPS = {
|
|
30
|
+
"eq": "=",
|
|
31
|
+
"ne": "<>",
|
|
32
|
+
"gt": ">",
|
|
33
|
+
"gte": ">=",
|
|
34
|
+
"lt": "<",
|
|
35
|
+
"lte": "<=",
|
|
36
|
+
"like": "LIKE",
|
|
37
|
+
"not_like": "NOT LIKE",
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class _ParamBag:
|
|
42
|
+
"""Allocates unique, safe bind-parameter names."""
|
|
43
|
+
|
|
44
|
+
def __init__(self) -> None:
|
|
45
|
+
self._values: dict[str, Any] = {}
|
|
46
|
+
self._counter = 0
|
|
47
|
+
|
|
48
|
+
def add(self, value: Any) -> str:
|
|
49
|
+
name = f"p{self._counter}"
|
|
50
|
+
self._counter += 1
|
|
51
|
+
self._values[name] = value
|
|
52
|
+
return name
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def values(self) -> dict[str, Any]:
|
|
56
|
+
return self._values
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class _Compiler:
|
|
60
|
+
"""Holds per-compilation state (alias map, params, join plan)."""
|
|
61
|
+
|
|
62
|
+
def __init__(self, model: SemanticView, query: SemanticQuery):
|
|
63
|
+
self.model = model
|
|
64
|
+
self.query = query
|
|
65
|
+
self.params = _ParamBag()
|
|
66
|
+
# logical table name -> SQL alias (t0, t1, ...)
|
|
67
|
+
self.aliases: dict[str, str] = {}
|
|
68
|
+
# ordered list of touched logical tables (root first)
|
|
69
|
+
self.touched: list[LogicalTable] = []
|
|
70
|
+
|
|
71
|
+
# -- entry point --------------------------------------------------
|
|
72
|
+
|
|
73
|
+
# Kinds a resolved item must have to legally sit in each selection list.
|
|
74
|
+
_ALLOWED_KINDS: ClassVar[dict[str, set[str]]] = {
|
|
75
|
+
"metrics": {"metric", "derived_metric"},
|
|
76
|
+
"dimensions": {"dimension"},
|
|
77
|
+
"facts": {"fact"},
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
def _prepare(self) -> None:
|
|
81
|
+
if self.query.model != self.model.name:
|
|
82
|
+
raise CompileError(
|
|
83
|
+
f"query model {self.query.model!r} does not match view {self.model.name!r}"
|
|
84
|
+
)
|
|
85
|
+
self._check_selection_kinds()
|
|
86
|
+
self._collect_touched_tables()
|
|
87
|
+
self._assign_aliases()
|
|
88
|
+
|
|
89
|
+
def compile_sqlalchemy(self) -> tuple[Select, dict[str, Any]]:
|
|
90
|
+
"""Build a SQLAlchemy statement while retaining trusted model expressions."""
|
|
91
|
+
self._prepare()
|
|
92
|
+
selections = (*self.query.dimensions, *self.query.facts, *self.query.metrics)
|
|
93
|
+
if not selections:
|
|
94
|
+
raise CompileError("empty selection")
|
|
95
|
+
columns = []
|
|
96
|
+
selected: dict[str, Any] = {}
|
|
97
|
+
ambiguous_order_fields: set[str] = set()
|
|
98
|
+
output_names: set[str] = set()
|
|
99
|
+
for item in selections:
|
|
100
|
+
resolved = self._resolve(item.name)
|
|
101
|
+
name = self._out_name(item, resolved)
|
|
102
|
+
if name in output_names:
|
|
103
|
+
raise CompileError(f"duplicate output identifier: {name!r}")
|
|
104
|
+
output_names.add(name)
|
|
105
|
+
column = literal_column(self._render_selectable(resolved)).label(name)
|
|
106
|
+
columns.append(column)
|
|
107
|
+
for field in (item.name, name):
|
|
108
|
+
previous = selected.get(field)
|
|
109
|
+
if previous is not None and previous is not column:
|
|
110
|
+
ambiguous_order_fields.add(field)
|
|
111
|
+
else:
|
|
112
|
+
selected[field] = column
|
|
113
|
+
|
|
114
|
+
statement = select(*columns).select_from(text(self._build_from_and_joins()))
|
|
115
|
+
for predicate, method in (
|
|
116
|
+
(self._build_where(), "where"),
|
|
117
|
+
(self._build_having(), "having"),
|
|
118
|
+
):
|
|
119
|
+
if predicate:
|
|
120
|
+
clause = text(predicate)
|
|
121
|
+
for name, value in self.params.values.items():
|
|
122
|
+
if isinstance(value, list) and re.search(
|
|
123
|
+
rf":{re.escape(name)}(?![A-Za-z0-9_])", predicate
|
|
124
|
+
):
|
|
125
|
+
clause = clause.bindparams(bindparam(name, expanding=True))
|
|
126
|
+
statement = getattr(statement, method)(clause)
|
|
127
|
+
if self.query.is_aggregated():
|
|
128
|
+
for item in self.query.dimensions:
|
|
129
|
+
statement = statement.group_by(
|
|
130
|
+
literal_column(self._render_selectable(self._resolve(item.name)))
|
|
131
|
+
)
|
|
132
|
+
for order in self.query.order_by:
|
|
133
|
+
if order.field in ambiguous_order_fields:
|
|
134
|
+
raise CompileError(f"ambiguous order_by field: {order.field!r}")
|
|
135
|
+
column = selected.get(order.field)
|
|
136
|
+
if column is None:
|
|
137
|
+
column = literal_column(
|
|
138
|
+
self._render_selectable(self._resolve(order.field))
|
|
139
|
+
)
|
|
140
|
+
statement = statement.order_by(
|
|
141
|
+
column.desc() if order.direction == "desc" else column.asc()
|
|
142
|
+
)
|
|
143
|
+
if self.query.limit is not None:
|
|
144
|
+
statement = statement.limit(self.query.limit)
|
|
145
|
+
if self.query.offset is not None:
|
|
146
|
+
statement = statement.offset(self.query.offset)
|
|
147
|
+
return statement, self.params.values
|
|
148
|
+
|
|
149
|
+
# -- table collection & join planning -----------------------------
|
|
150
|
+
|
|
151
|
+
def _check_selection_kinds(self) -> None:
|
|
152
|
+
"""Reject a query before it can compile into invalid SQL.
|
|
153
|
+
|
|
154
|
+
Placing a raw ``fact`` in ``metrics`` would put the query in aggregated
|
|
155
|
+
mode (``GROUP BY``) while selecting an unaggregated column. Catch the
|
|
156
|
+
mismatch here instead, with a message the LLM can act on.
|
|
157
|
+
"""
|
|
158
|
+
if self.query.metrics and self.query.facts:
|
|
159
|
+
raise CompileError(
|
|
160
|
+
"facts cannot be selected with metrics; aggregate queries may select "
|
|
161
|
+
"dimensions and metrics only"
|
|
162
|
+
)
|
|
163
|
+
for bucket, allowed in self._ALLOWED_KINDS.items():
|
|
164
|
+
for sel in getattr(self.query, bucket):
|
|
165
|
+
resolved = self._resolve(sel.name)
|
|
166
|
+
if resolved.kind not in allowed:
|
|
167
|
+
expected = " or ".join(sorted(allowed))
|
|
168
|
+
raise CompileError(
|
|
169
|
+
f"'{sel.name}' is a {resolved.kind}, but `{bucket}` requires a "
|
|
170
|
+
f"{expected}. Move it to the matching list, or select a declared "
|
|
171
|
+
"metric that aggregates it if you need a grouped total."
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
def _resolve(self, name: str) -> ResolvedItem:
|
|
175
|
+
item = self.model.resolve(name)
|
|
176
|
+
if item is None:
|
|
177
|
+
raise CompileError(
|
|
178
|
+
f"cannot resolve '{name}' uniquely in model '{self.model.name}'"
|
|
179
|
+
)
|
|
180
|
+
return item
|
|
181
|
+
|
|
182
|
+
def _touch(self, table: LogicalTable | None) -> None:
|
|
183
|
+
if table is None:
|
|
184
|
+
return
|
|
185
|
+
if table.name not in {t.name for t in self.touched}:
|
|
186
|
+
self.touched.append(table)
|
|
187
|
+
|
|
188
|
+
def _collect_touched_tables(self) -> None:
|
|
189
|
+
"""Walk every referenced item and record the tables it touches."""
|
|
190
|
+
for sel in (*self.query.metrics, *self.query.dimensions, *self.query.facts):
|
|
191
|
+
self._touch(self._resolve(sel.name).table)
|
|
192
|
+
|
|
193
|
+
for node in (self.query.filters, self.query.having):
|
|
194
|
+
if node is not None:
|
|
195
|
+
self._touch_filter(node)
|
|
196
|
+
|
|
197
|
+
selected_names = {
|
|
198
|
+
name
|
|
199
|
+
for sel in (*self.query.metrics, *self.query.dimensions, *self.query.facts)
|
|
200
|
+
for name in (sel.name, self._out_name(sel, self._resolve(sel.name)))
|
|
201
|
+
}
|
|
202
|
+
for order in self.query.order_by:
|
|
203
|
+
if order.field not in selected_names:
|
|
204
|
+
resolved = self._resolve(order.field)
|
|
205
|
+
self._touch(resolved.table)
|
|
206
|
+
if resolved.kind == "derived_metric":
|
|
207
|
+
self._touch_derived(resolved)
|
|
208
|
+
|
|
209
|
+
# A derived (view-level) metric can reference tables not otherwise
|
|
210
|
+
# touched; pull in every table it names as ``table.item``.
|
|
211
|
+
for sel in self.query.metrics:
|
|
212
|
+
resolved = self._resolve(sel.name)
|
|
213
|
+
if resolved.kind == "derived_metric":
|
|
214
|
+
self._touch_derived(resolved)
|
|
215
|
+
|
|
216
|
+
if not self.touched:
|
|
217
|
+
raise CompileError("query touches no tables")
|
|
218
|
+
|
|
219
|
+
def _touch_filter(self, node: FilterNode) -> None:
|
|
220
|
+
if isinstance(node, FilterGroup):
|
|
221
|
+
for child in node.conditions:
|
|
222
|
+
self._touch_filter(child)
|
|
223
|
+
else:
|
|
224
|
+
resolved = self._resolve(node.field)
|
|
225
|
+
self._touch(resolved.table)
|
|
226
|
+
if resolved.kind == "derived_metric":
|
|
227
|
+
self._touch_derived(resolved)
|
|
228
|
+
|
|
229
|
+
def _touch_derived(self, resolved: ResolvedItem) -> None:
|
|
230
|
+
# Derived metric exprs reference items as ``table.item``. Find any
|
|
231
|
+
# declared table name that appears in the expr and touch it.
|
|
232
|
+
for table in self.model.tables:
|
|
233
|
+
if f"{table.name}." in resolved.expr:
|
|
234
|
+
self._touch(table)
|
|
235
|
+
|
|
236
|
+
def _assign_aliases(self) -> None:
|
|
237
|
+
for i, table in enumerate(self.touched):
|
|
238
|
+
self.aliases[table.name] = f"t{i}"
|
|
239
|
+
|
|
240
|
+
# -- expr rendering (alias-qualified) -----------------------------
|
|
241
|
+
|
|
242
|
+
def _base_ref(self, table: LogicalTable) -> str:
|
|
243
|
+
"""The FROM-clause reference for a table's physical binding."""
|
|
244
|
+
if table.base_table.is_query():
|
|
245
|
+
return f"({table.base_table.definition})"
|
|
246
|
+
return table.base_table.qualified_name()
|
|
247
|
+
|
|
248
|
+
def _qualify(self, resolved: ResolvedItem) -> str:
|
|
249
|
+
"""Prefix a table-scoped expr's bare column refs with its SQL alias.
|
|
250
|
+
|
|
251
|
+
Derived metrics already reference ``table.item`` and are rewritten
|
|
252
|
+
separately, so they must not pass through here.
|
|
253
|
+
"""
|
|
254
|
+
assert resolved.table is not None
|
|
255
|
+
alias = self.aliases[resolved.table.name]
|
|
256
|
+
return self._alias_expr(resolved.expr, alias)
|
|
257
|
+
|
|
258
|
+
@staticmethod
|
|
259
|
+
def _alias_expr(expr: str, alias: str) -> str:
|
|
260
|
+
"""Best-effort qualification of column identifiers in a physical expr.
|
|
261
|
+
|
|
262
|
+
Physical exprs are model-authored (trusted). For a single-table item we
|
|
263
|
+
prefix bare identifiers with the table alias so the SQL is unambiguous
|
|
264
|
+
once tables are joined. Identifiers already qualified, SQL keywords, and
|
|
265
|
+
function-call names are left alone.
|
|
266
|
+
|
|
267
|
+
A double-quoted identifier (e.g. a column like ``"2026_AMOUNT"`` that
|
|
268
|
+
must be quoted because it starts with a digit) is treated as a single
|
|
269
|
+
column reference and alias-qualified as a whole (``t0."2026_AMOUNT"``),
|
|
270
|
+
never split apart. A single-quoted string literal is left completely
|
|
271
|
+
untouched. Without this, the plain bare-word tokenizer would match a
|
|
272
|
+
substring inside the quotes (e.g. ``_AMOUNT``) and corrupt it.
|
|
273
|
+
"""
|
|
274
|
+
# SQL tokens that must never be treated as a column to qualify.
|
|
275
|
+
keywords = {
|
|
276
|
+
"SUM",
|
|
277
|
+
"AVG",
|
|
278
|
+
"COUNT",
|
|
279
|
+
"MIN",
|
|
280
|
+
"MAX",
|
|
281
|
+
"DISTINCT",
|
|
282
|
+
"NULLIF",
|
|
283
|
+
"COALESCE",
|
|
284
|
+
"CASE",
|
|
285
|
+
"WHEN",
|
|
286
|
+
"THEN",
|
|
287
|
+
"ELSE",
|
|
288
|
+
"END",
|
|
289
|
+
"AND",
|
|
290
|
+
"OR",
|
|
291
|
+
"NOT",
|
|
292
|
+
"NULL",
|
|
293
|
+
"CAST",
|
|
294
|
+
"AS",
|
|
295
|
+
"LEFT",
|
|
296
|
+
"RIGHT",
|
|
297
|
+
"SUBSTR",
|
|
298
|
+
"SUBSTRING",
|
|
299
|
+
"IN",
|
|
300
|
+
"IS",
|
|
301
|
+
"BETWEEN",
|
|
302
|
+
"LIKE",
|
|
303
|
+
"OVER",
|
|
304
|
+
"PARTITION",
|
|
305
|
+
"BY",
|
|
306
|
+
"ORDER",
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
token = re.compile(
|
|
310
|
+
r"'(?:[^']|'')*'" # single-quoted string literal
|
|
311
|
+
r'|"(?:[^"]|"")*"' # double-quoted identifier
|
|
312
|
+
r"|[A-Za-z_][A-Za-z0-9_]*" # bare identifier
|
|
313
|
+
)
|
|
314
|
+
|
|
315
|
+
out: list[str] = []
|
|
316
|
+
last = 0
|
|
317
|
+
for m in token.finditer(expr):
|
|
318
|
+
start, end = m.span()
|
|
319
|
+
word = m.group(0)
|
|
320
|
+
out.append(expr[last:start])
|
|
321
|
+
prev = expr[:start].rstrip()
|
|
322
|
+
nxt = expr[end:].lstrip()
|
|
323
|
+
is_qualified = prev.endswith(".")
|
|
324
|
+
is_func_call = nxt.startswith("(")
|
|
325
|
+
if word.startswith("'"):
|
|
326
|
+
out.append(word) # string literal: never touch
|
|
327
|
+
elif word.startswith('"'):
|
|
328
|
+
out.append(word if is_qualified else f"{alias}.{word}")
|
|
329
|
+
elif is_qualified or is_func_call or word.upper() in keywords:
|
|
330
|
+
out.append(word)
|
|
331
|
+
else:
|
|
332
|
+
out.append(f"{alias}.{word}")
|
|
333
|
+
last = end
|
|
334
|
+
out.append(expr[last:])
|
|
335
|
+
return "".join(out)
|
|
336
|
+
|
|
337
|
+
def _render_derived(self, resolved: ResolvedItem) -> str:
|
|
338
|
+
"""Rewrite a derived metric expr's ``table.item`` refs to alias-qualified SQL."""
|
|
339
|
+
references: dict[str, tuple[LogicalTable, str, str]] = {}
|
|
340
|
+
for table in self.model.tables:
|
|
341
|
+
alias = self.aliases.get(table.name)
|
|
342
|
+
if alias is None:
|
|
343
|
+
continue
|
|
344
|
+
for item in _table_item_names(table):
|
|
345
|
+
logical = f"{table.name}.{item}"
|
|
346
|
+
references[logical] = (table, item, alias)
|
|
347
|
+
if not references:
|
|
348
|
+
return resolved.expr
|
|
349
|
+
|
|
350
|
+
alternatives = "|".join(
|
|
351
|
+
re.escape(name) for name in sorted(references, key=len, reverse=True)
|
|
352
|
+
)
|
|
353
|
+
pattern = re.compile(rf"(?<![A-Za-z0-9_])(?:{alternatives})(?![A-Za-z0-9_])")
|
|
354
|
+
replacements: dict[str, str] = {}
|
|
355
|
+
for logical in set(pattern.findall(resolved.expr)):
|
|
356
|
+
table, item, alias = references[logical]
|
|
357
|
+
physical = self._item_expr(table, item)
|
|
358
|
+
replacements[logical] = self._alias_expr(physical, alias)
|
|
359
|
+
return pattern.sub(lambda match: replacements[match.group(0)], resolved.expr)
|
|
360
|
+
|
|
361
|
+
def _item_expr(self, table: LogicalTable, item_name: str) -> str:
|
|
362
|
+
resolved = self.model._resolve_in_table(table, item_name)
|
|
363
|
+
if resolved is None:
|
|
364
|
+
raise CompileError(
|
|
365
|
+
f"'{table.name}.{item_name}' not found for derived metric"
|
|
366
|
+
)
|
|
367
|
+
return resolved.expr
|
|
368
|
+
|
|
369
|
+
def _render_selectable(self, resolved: ResolvedItem) -> str:
|
|
370
|
+
if resolved.kind == "derived_metric":
|
|
371
|
+
return self._render_derived(resolved)
|
|
372
|
+
return self._qualify(resolved)
|
|
373
|
+
|
|
374
|
+
# -- SELECT -------------------------------------------------------
|
|
375
|
+
|
|
376
|
+
@staticmethod
|
|
377
|
+
def _out_name(sel: SelectionItem, resolved: ResolvedItem) -> str:
|
|
378
|
+
name = sel.alias if sel.alias else resolved.name
|
|
379
|
+
if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name):
|
|
380
|
+
raise CompileError(f"invalid output identifier: {name!r}")
|
|
381
|
+
return name
|
|
382
|
+
|
|
383
|
+
# -- FROM / JOIN --------------------------------------------------
|
|
384
|
+
|
|
385
|
+
def _build_from_and_joins(self) -> str:
|
|
386
|
+
root = self.touched[0]
|
|
387
|
+
root_alias = self.aliases[root.name]
|
|
388
|
+
sql = f"{self._base_ref(root)} {root_alias}"
|
|
389
|
+
|
|
390
|
+
joined = {root.name}
|
|
391
|
+
remaining = [t for t in self.touched[1:]]
|
|
392
|
+
|
|
393
|
+
# Greedily attach remaining tables via any relationship touching a
|
|
394
|
+
# table already joined. Loop until fixpoint.
|
|
395
|
+
progress = True
|
|
396
|
+
while remaining and progress:
|
|
397
|
+
progress = False
|
|
398
|
+
for table in list(remaining):
|
|
399
|
+
rel = self._find_relationship(joined, table.name)
|
|
400
|
+
if rel is None:
|
|
401
|
+
continue
|
|
402
|
+
sql += "\n" + self._render_join(rel, joined, table)
|
|
403
|
+
joined.add(table.name)
|
|
404
|
+
remaining.remove(table)
|
|
405
|
+
progress = True
|
|
406
|
+
|
|
407
|
+
if remaining:
|
|
408
|
+
names = ", ".join(t.name for t in remaining)
|
|
409
|
+
raise CompileError(f"unjoinable table(s): {names}")
|
|
410
|
+
return sql
|
|
411
|
+
|
|
412
|
+
def _find_relationship(self, joined: set[str], candidate: str):
|
|
413
|
+
for rel in self.model.relationships:
|
|
414
|
+
pair = {rel.left_table, rel.right_table}
|
|
415
|
+
if candidate in pair and (pair - {candidate}) & joined:
|
|
416
|
+
return rel
|
|
417
|
+
return None
|
|
418
|
+
|
|
419
|
+
def _render_join(self, rel, joined: set[str], new_table: LogicalTable) -> str:
|
|
420
|
+
# Orient so the already-joined side supplies its columns and the new
|
|
421
|
+
# side is the one being added. Relationships use LEFT JOIN.
|
|
422
|
+
new_alias = self.aliases[new_table.name]
|
|
423
|
+
if rel.left_table == new_table.name:
|
|
424
|
+
existing_name, new_name = rel.right_table, rel.left_table
|
|
425
|
+
else:
|
|
426
|
+
existing_name, new_name = rel.left_table, rel.right_table
|
|
427
|
+
existing_alias = self.aliases[existing_name]
|
|
428
|
+
|
|
429
|
+
conds = []
|
|
430
|
+
for col in rel.relationship_columns:
|
|
431
|
+
if col.type is not None:
|
|
432
|
+
raise CompileError(
|
|
433
|
+
f"relationship {rel.name!r} uses unsupported {col.type!r} join"
|
|
434
|
+
)
|
|
435
|
+
if rel.left_table == new_name:
|
|
436
|
+
left = f"{new_alias}.{col.left_column}"
|
|
437
|
+
right = f"{existing_alias}.{col.right_column}"
|
|
438
|
+
else:
|
|
439
|
+
left = f"{existing_alias}.{col.left_column}"
|
|
440
|
+
right = f"{new_alias}.{col.right_column}"
|
|
441
|
+
conds.append(f"{left} = {right}")
|
|
442
|
+
on = " AND ".join(conds)
|
|
443
|
+
return f"LEFT JOIN {self._base_ref(new_table)} {new_alias} ON {on}"
|
|
444
|
+
|
|
445
|
+
# -- WHERE / HAVING -----------------------------------------------
|
|
446
|
+
|
|
447
|
+
def _build_where(self) -> str:
|
|
448
|
+
if self.query.filters is None:
|
|
449
|
+
return ""
|
|
450
|
+
return self._render_filter(self.query.filters, clause="WHERE")
|
|
451
|
+
|
|
452
|
+
def _build_having(self) -> str:
|
|
453
|
+
if self.query.having is None:
|
|
454
|
+
return ""
|
|
455
|
+
return self._render_filter(self.query.having, clause="HAVING")
|
|
456
|
+
|
|
457
|
+
def _render_filter(self, node: FilterNode, *, clause: str) -> str:
|
|
458
|
+
if isinstance(node, FilterGroup):
|
|
459
|
+
joiner = f" {node.op.upper()} "
|
|
460
|
+
rendered = [self._render_filter(c, clause=clause) for c in node.conditions]
|
|
461
|
+
return "(" + joiner.join(rendered) + ")"
|
|
462
|
+
return self._render_condition(node, clause=clause)
|
|
463
|
+
|
|
464
|
+
def _render_condition(self, cond: FilterCondition, *, clause: str) -> str:
|
|
465
|
+
resolved = self._resolve(cond.field)
|
|
466
|
+
allowed = (
|
|
467
|
+
{"dimension", "fact"} if clause == "WHERE" else {"metric", "derived_metric"}
|
|
468
|
+
)
|
|
469
|
+
if resolved.kind not in allowed:
|
|
470
|
+
expected = (
|
|
471
|
+
"row-level dimensions or facts" if clause == "WHERE" else "metrics"
|
|
472
|
+
)
|
|
473
|
+
raise CompileError(
|
|
474
|
+
f"{clause} condition '{cond.field}' resolves to a {resolved.kind}; "
|
|
475
|
+
f"{clause} requires {expected}"
|
|
476
|
+
)
|
|
477
|
+
col = self._render_selectable(resolved)
|
|
478
|
+
op = cond.operator
|
|
479
|
+
|
|
480
|
+
if op in ("is_null", "is_not_null"):
|
|
481
|
+
if cond.value is not None:
|
|
482
|
+
raise CompileError(f"{op} does not accept a value")
|
|
483
|
+
sql_op = "IS NULL" if op == "is_null" else "IS NOT NULL"
|
|
484
|
+
return f"{col} {sql_op}"
|
|
485
|
+
|
|
486
|
+
if op in _BINARY_OPS:
|
|
487
|
+
if cond.value is None or isinstance(cond.value, list):
|
|
488
|
+
raise CompileError(f"{op} requires a scalar value")
|
|
489
|
+
pname = self.params.add(cond.value)
|
|
490
|
+
return f"{col} {_BINARY_OPS[op]} :{pname}"
|
|
491
|
+
|
|
492
|
+
if op in ("in", "not_in"):
|
|
493
|
+
if not isinstance(cond.value, list):
|
|
494
|
+
raise CompileError(f"{op} requires an array value")
|
|
495
|
+
pname = self.params.add(cond.value)
|
|
496
|
+
sql_op = "IN" if op == "in" else "NOT IN"
|
|
497
|
+
# SQLAlchemy's expanding bind supplies the surrounding parentheses.
|
|
498
|
+
return f"{col} {sql_op} :{pname}"
|
|
499
|
+
|
|
500
|
+
if op == "between":
|
|
501
|
+
if not isinstance(cond.value, list) or len(cond.value) != 2:
|
|
502
|
+
raise CompileError("between requires a [low, high] value")
|
|
503
|
+
low = self.params.add(cond.value[0])
|
|
504
|
+
high = self.params.add(cond.value[1])
|
|
505
|
+
return f"{col} BETWEEN :{low} AND :{high}"
|
|
506
|
+
|
|
507
|
+
raise CompileError(f"unsupported operator '{op}'")
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def _table_item_names(table: LogicalTable) -> list[str]:
|
|
511
|
+
names = [d.name for d in table.all_dimensions()]
|
|
512
|
+
names += [f.name for f in table.facts]
|
|
513
|
+
names += [m.name for m in table.metrics]
|
|
514
|
+
return names
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
def compile_sqlalchemy(
|
|
518
|
+
model: SemanticView, query: SemanticQuery
|
|
519
|
+
) -> tuple[Select, dict[str, Any]]:
|
|
520
|
+
"""Build a SQLAlchemy Core select and its semantic filter parameters.
|
|
521
|
+
|
|
522
|
+
The dialect handles SQL syntax such as pagination and bind placeholders.
|
|
523
|
+
Model-authored SQL expressions and physical references are not translated.
|
|
524
|
+
"""
|
|
525
|
+
return _Compiler(model, query).compile_sqlalchemy()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Framework-independent semantic models and query contracts."""
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Backend contract for executing structured semantic queries."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from typing import Any, Protocol
|
|
7
|
+
|
|
8
|
+
from .model import SemanticView
|
|
9
|
+
from .query import SemanticQuery
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class SemanticQueryBackend(Protocol):
|
|
13
|
+
"""Execute a structured query against a trusted semantic view.
|
|
14
|
+
|
|
15
|
+
Implementations must validate query semantics and enforce access rules before
|
|
16
|
+
sending anything to their database. Errors should be raised, not hidden.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
async def execute(
|
|
20
|
+
self, view: SemanticView, query: SemanticQuery
|
|
21
|
+
) -> Sequence[dict[str, Any]]:
|
|
22
|
+
"""Return result rows as mappings from output names to values."""
|
|
23
|
+
...
|