scanisaur 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.
- scanisaur/__init__.py +10 -0
- scanisaur/__main__.py +3 -0
- scanisaur/cli.py +41 -0
- scanisaur/engine/__init__.py +1 -0
- scanisaur/engine/facts.py +444 -0
- scanisaur/py.typed +0 -0
- scanisaur-0.0.1.dist-info/METADATA +61 -0
- scanisaur-0.0.1.dist-info/RECORD +11 -0
- scanisaur-0.0.1.dist-info/WHEEL +4 -0
- scanisaur-0.0.1.dist-info/entry_points.txt +2 -0
- scanisaur-0.0.1.dist-info/licenses/LICENSE +201 -0
scanisaur/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""Scanisaur: schema-aware pre-flight checks for AI-agent SQL."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
__version__ = version("scanisaur")
|
|
7
|
+
except PackageNotFoundError: # running from a source tree that isn't installed
|
|
8
|
+
__version__ = "0.0.0"
|
|
9
|
+
|
|
10
|
+
__all__ = ["__version__"]
|
scanisaur/__main__.py
ADDED
scanisaur/cli.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Command-line entry point."""
|
|
2
|
+
|
|
3
|
+
from typing import Annotated
|
|
4
|
+
|
|
5
|
+
import typer
|
|
6
|
+
|
|
7
|
+
from scanisaur import __version__
|
|
8
|
+
|
|
9
|
+
app = typer.Typer(
|
|
10
|
+
name="scanisaur",
|
|
11
|
+
help="Schema-aware pre-flight checks for AI-agent SQL.",
|
|
12
|
+
no_args_is_help=True,
|
|
13
|
+
add_completion=False,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _print_version(value: bool) -> None:
|
|
18
|
+
if value:
|
|
19
|
+
typer.echo(f"scanisaur {__version__}")
|
|
20
|
+
raise typer.Exit
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@app.callback()
|
|
24
|
+
def main(
|
|
25
|
+
version: Annotated[
|
|
26
|
+
bool,
|
|
27
|
+
typer.Option(
|
|
28
|
+
"--version",
|
|
29
|
+
callback=_print_version,
|
|
30
|
+
is_eager=True,
|
|
31
|
+
help="Show the version and exit.",
|
|
32
|
+
),
|
|
33
|
+
] = False,
|
|
34
|
+
) -> None:
|
|
35
|
+
"""Schema-aware pre-flight checks for AI-agent SQL."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@app.command("version")
|
|
39
|
+
def version_command() -> None:
|
|
40
|
+
"""Show the version."""
|
|
41
|
+
typer.echo(f"scanisaur {__version__}")
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""SQL analysis engine."""
|
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+
"""Per-table facts extracted from a qualified SQL syntax tree.
|
|
2
|
+
|
|
3
|
+
Rules and the cost estimator read these facts instead of walking the syntax tree
|
|
4
|
+
themselves. The input must already be qualified (``sqlglot.optimizer.qualify``
|
|
5
|
+
with ``expand_stars=False``), so every column carries the alias of its source.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections import Counter
|
|
11
|
+
from collections.abc import Iterator
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from typing import Literal
|
|
14
|
+
|
|
15
|
+
from sqlglot import exp
|
|
16
|
+
from sqlglot.optimizer.scope import Scope, find_all_in_scope, traverse_scope
|
|
17
|
+
|
|
18
|
+
#: BigQuery pseudo-columns that sqlglot leaves unqualified.
|
|
19
|
+
PSEUDO_COLUMNS = frozenset({"_table_suffix", "_partitiontime", "_partitiondate"})
|
|
20
|
+
|
|
21
|
+
# sqlglot renames node arguments between major versions. Fail at import rather than
|
|
22
|
+
# silently treating every ``SELECT * EXCEPT (...)`` as reading all columns.
|
|
23
|
+
_STAR_EXCEPT_ARG = "except_"
|
|
24
|
+
if _STAR_EXCEPT_ARG not in exp.Star.arg_types: # pragma: no cover
|
|
25
|
+
raise ImportError(f"unsupported sqlglot version: exp.Star has no {_STAR_EXCEPT_ARG!r}")
|
|
26
|
+
|
|
27
|
+
ComparisonOp = Literal["=", "<", "<=", ">", ">=", "between", "in", "other"]
|
|
28
|
+
Clause = Literal["where", "on", "qualify"]
|
|
29
|
+
|
|
30
|
+
_COMPARISONS: dict[type[exp.Expr], ComparisonOp] = {
|
|
31
|
+
exp.EQ: "=",
|
|
32
|
+
exp.LT: "<",
|
|
33
|
+
exp.LTE: "<=",
|
|
34
|
+
exp.GT: ">",
|
|
35
|
+
exp.GTE: ">=",
|
|
36
|
+
}
|
|
37
|
+
_FLIPPED: dict[ComparisonOp, ComparisonOp] = {"<": ">", "<=": ">=", ">": "<", ">=": "<="}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True, slots=True)
|
|
41
|
+
class TableRef:
|
|
42
|
+
project: str | None
|
|
43
|
+
dataset: str | None
|
|
44
|
+
name: str
|
|
45
|
+
alias: str
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def qualified_name(self) -> str:
|
|
49
|
+
return ".".join(part for part in (self.project, self.dataset, self.name) if part)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(frozen=True, slots=True)
|
|
53
|
+
class Predicate:
|
|
54
|
+
"""A filter condition that involves columns of exactly one table reference."""
|
|
55
|
+
|
|
56
|
+
column: str
|
|
57
|
+
op: ComparisonOp
|
|
58
|
+
#: SQL of the compared value(s); empty unless ``constant``.
|
|
59
|
+
values: tuple[str, ...]
|
|
60
|
+
#: True when compared only against constants (literals, ``CURRENT_DATE()`` arithmetic).
|
|
61
|
+
constant: bool
|
|
62
|
+
#: Function wrapping the column, such as ``DATE`` or ``CAST``; None for a bare column.
|
|
63
|
+
wrapper: str | None
|
|
64
|
+
clause: Clause
|
|
65
|
+
sql: str
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass(frozen=True, slots=True)
|
|
69
|
+
class Join:
|
|
70
|
+
target: str
|
|
71
|
+
target_kind: Literal["table", "unnest", "derived"]
|
|
72
|
+
side: str | None
|
|
73
|
+
kind: str | None
|
|
74
|
+
has_condition: bool
|
|
75
|
+
#: Equality pairs such as ("e.user_id", "u.user_id"), from ON or from WHERE.
|
|
76
|
+
keys: tuple[tuple[str, str], ...]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass(frozen=True, slots=True)
|
|
80
|
+
class TableFacts:
|
|
81
|
+
table: TableRef
|
|
82
|
+
#: Columns read from the table; with ``star`` the query reads every column...
|
|
83
|
+
columns: frozenset[str]
|
|
84
|
+
star: bool
|
|
85
|
+
#: ...except these (BigQuery ``SELECT * EXCEPT (...)``).
|
|
86
|
+
star_except: frozenset[str]
|
|
87
|
+
predicates: tuple[Predicate, ...]
|
|
88
|
+
#: How many times the table is scanned; a CTE referenced twice counts twice.
|
|
89
|
+
scans: int
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@dataclass(frozen=True, slots=True)
|
|
93
|
+
class QueryFacts:
|
|
94
|
+
tables: tuple[TableFacts, ...]
|
|
95
|
+
joins: tuple[Join, ...]
|
|
96
|
+
outer_limit: int | None
|
|
97
|
+
outer_aggregated: bool
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def extract(expression: exp.Expr, dialect: str = "bigquery") -> QueryFacts:
|
|
101
|
+
"""Extract facts from a qualified query (SELECT, set operation, or pipe syntax)."""
|
|
102
|
+
scopes = traverse_scope(expression)
|
|
103
|
+
if not scopes:
|
|
104
|
+
raise ValueError("expression is not a query")
|
|
105
|
+
scans = _scan_counts(scopes)
|
|
106
|
+
|
|
107
|
+
tables: list[TableFacts] = []
|
|
108
|
+
joins: list[Join] = []
|
|
109
|
+
for scope in scopes:
|
|
110
|
+
if scans[id(scope)] == 0 or not isinstance(scope.expression, exp.Select):
|
|
111
|
+
continue
|
|
112
|
+
tables.extend(_table_facts(scope, scans[id(scope)], dialect))
|
|
113
|
+
joins.extend(_joins(scope))
|
|
114
|
+
|
|
115
|
+
root = _effective_root(scopes[-1])
|
|
116
|
+
limit, aggregated = _outer_shape(root.expression)
|
|
117
|
+
return QueryFacts(tuple(tables), tuple(joins), limit, aggregated)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _scan_counts(scopes: list[Scope]) -> Counter[int]:
|
|
121
|
+
"""Count how many times each scope runs: CTEs once per reference, unused CTEs zero."""
|
|
122
|
+
counts: Counter[int] = Counter({id(scopes[-1]): 1})
|
|
123
|
+
for scope in reversed(scopes): # traverse_scope yields children first
|
|
124
|
+
runs = counts[id(scope)]
|
|
125
|
+
for _node, source in scope.selected_sources.values():
|
|
126
|
+
if isinstance(source, Scope):
|
|
127
|
+
counts[id(source)] += runs
|
|
128
|
+
for child in [*scope.subquery_scopes, *scope.set_operation_scopes]:
|
|
129
|
+
counts[id(child)] += runs
|
|
130
|
+
return counts
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _table_sources(scope: Scope) -> dict[str, exp.Table]:
|
|
134
|
+
return {
|
|
135
|
+
alias: source
|
|
136
|
+
for alias, (_node, source) in scope.selected_sources.items()
|
|
137
|
+
if isinstance(source, exp.Table)
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _table_facts(scope: Scope, scans: int, dialect: str) -> Iterator[TableFacts]:
|
|
142
|
+
sources = _table_sources(scope)
|
|
143
|
+
if not sources:
|
|
144
|
+
return
|
|
145
|
+
lone_alias = next(iter(sources)) if len(sources) == 1 else None
|
|
146
|
+
starred = _starred_aliases(scope, sources)
|
|
147
|
+
predicates = list(_predicates(scope, sources, lone_alias, dialect))
|
|
148
|
+
|
|
149
|
+
for alias, table in sources.items():
|
|
150
|
+
columns = frozenset(
|
|
151
|
+
column.name.lower()
|
|
152
|
+
for column in scope.columns
|
|
153
|
+
if _owner(column, lone_alias) == alias and column.name.lower() not in PSEUDO_COLUMNS
|
|
154
|
+
)
|
|
155
|
+
yield TableFacts(
|
|
156
|
+
table=TableRef(
|
|
157
|
+
project=table.catalog or None,
|
|
158
|
+
dataset=table.db or None,
|
|
159
|
+
name=table.name,
|
|
160
|
+
alias=alias,
|
|
161
|
+
),
|
|
162
|
+
columns=columns,
|
|
163
|
+
star=alias in starred,
|
|
164
|
+
star_except=starred.get(alias, frozenset()),
|
|
165
|
+
predicates=tuple(p for owner, p in predicates if owner == alias),
|
|
166
|
+
scans=scans,
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _owner(column: exp.Column, lone_alias: str | None) -> str | None:
|
|
171
|
+
"""The alias a column belongs to; unqualified pseudo-columns go to a scope's only table."""
|
|
172
|
+
if column.table:
|
|
173
|
+
return column.table
|
|
174
|
+
if column.name.lower() in PSEUDO_COLUMNS:
|
|
175
|
+
return lone_alias
|
|
176
|
+
return None
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _starred_aliases(scope: Scope, sources: dict[str, exp.Table]) -> dict[str, frozenset[str]]:
|
|
180
|
+
"""Aliases selected with a star, mapped to the columns their ``EXCEPT`` leaves out."""
|
|
181
|
+
select = scope.expression
|
|
182
|
+
assert isinstance(select, exp.Select)
|
|
183
|
+
starred: dict[str, frozenset[str]] = {}
|
|
184
|
+
for projection in select.expressions:
|
|
185
|
+
if isinstance(projection, exp.Star):
|
|
186
|
+
excluded = _star_except(projection)
|
|
187
|
+
starred.update(dict.fromkeys(sources, excluded))
|
|
188
|
+
elif isinstance(projection, exp.Column) and isinstance(projection.this, exp.Star):
|
|
189
|
+
if projection.table in sources:
|
|
190
|
+
starred[projection.table] = _star_except(projection.this)
|
|
191
|
+
return starred
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _star_except(star: exp.Star) -> frozenset[str]:
|
|
195
|
+
return frozenset(column.name.lower() for column in star.args.get(_STAR_EXCEPT_ARG) or [])
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _conjuncts(condition: exp.Expr | None) -> Iterator[exp.Expr]:
|
|
199
|
+
if condition is None:
|
|
200
|
+
return
|
|
201
|
+
if isinstance(condition, exp.Paren):
|
|
202
|
+
yield from _conjuncts(condition.this)
|
|
203
|
+
elif isinstance(condition, exp.And):
|
|
204
|
+
yield from _conjuncts(condition.left)
|
|
205
|
+
yield from _conjuncts(condition.right)
|
|
206
|
+
else:
|
|
207
|
+
yield condition
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _clauses(scope: Scope) -> Iterator[tuple[Clause, exp.Expr]]:
|
|
211
|
+
select = scope.expression
|
|
212
|
+
where = select.args.get("where")
|
|
213
|
+
if where is not None:
|
|
214
|
+
yield from (("where", c) for c in _conjuncts(where.this))
|
|
215
|
+
for join in select.args.get("joins") or []:
|
|
216
|
+
yield from (("on", c) for c in _conjuncts(join.args.get("on")))
|
|
217
|
+
qualify = select.args.get("qualify")
|
|
218
|
+
if qualify is not None:
|
|
219
|
+
yield from (("qualify", c) for c in _conjuncts(qualify.this))
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _local_columns(node: exp.Expr) -> list[exp.Column]:
|
|
223
|
+
"""Columns in ``node`` that belong to this scope, not to a nested subquery."""
|
|
224
|
+
return [
|
|
225
|
+
column
|
|
226
|
+
for column in node.find_all(exp.Column)
|
|
227
|
+
if not isinstance(column.this, exp.Star)
|
|
228
|
+
and column.find_ancestor(exp.Select, exp.Subquery) is node.find_ancestor(exp.Select)
|
|
229
|
+
]
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _has_subquery(node: exp.Expr) -> bool:
|
|
233
|
+
return node.find(exp.Select, exp.Subquery) is not None
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _is_constant(node: exp.Expr) -> bool:
|
|
237
|
+
return not _local_columns(node) and not _has_subquery(node)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _wrapper(side: exp.Expr) -> str | None:
|
|
241
|
+
"""The function around a column, ignoring parentheses and struct field access."""
|
|
242
|
+
while isinstance(side, exp.Paren | exp.Dot):
|
|
243
|
+
side = side.this
|
|
244
|
+
if isinstance(side, exp.Column):
|
|
245
|
+
return None
|
|
246
|
+
if isinstance(side, exp.Func):
|
|
247
|
+
return side.sql_name()
|
|
248
|
+
return side.key.upper()
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _predicates(
|
|
252
|
+
scope: Scope, sources: dict[str, exp.Table], lone_alias: str | None, dialect: str
|
|
253
|
+
) -> Iterator[tuple[str, Predicate]]:
|
|
254
|
+
for clause, condition in _clauses(scope):
|
|
255
|
+
columns = _local_columns(condition)
|
|
256
|
+
owners = {_owner(column, lone_alias) for column in columns}
|
|
257
|
+
if len(owners) != 1:
|
|
258
|
+
continue
|
|
259
|
+
owner = owners.pop()
|
|
260
|
+
if owner not in sources:
|
|
261
|
+
continue
|
|
262
|
+
predicate = _classify(condition, clause, dialect)
|
|
263
|
+
if predicate is not None:
|
|
264
|
+
yield owner, predicate
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _classify(condition: exp.Expr, clause: Clause, dialect: str) -> Predicate | None:
|
|
268
|
+
sql = condition.sql(dialect=dialect)
|
|
269
|
+
|
|
270
|
+
def other() -> Predicate | None:
|
|
271
|
+
columns = _local_columns(condition)
|
|
272
|
+
if not columns:
|
|
273
|
+
return None
|
|
274
|
+
return Predicate(columns[0].name.lower(), "other", (), False, None, clause, sql)
|
|
275
|
+
|
|
276
|
+
def make(side: exp.Expr, op: ComparisonOp, others: list[exp.Expr]) -> Predicate | None:
|
|
277
|
+
columns = _local_columns(side)
|
|
278
|
+
if not columns: # e.g. CURRENT_DATE() BETWEEN valid_from AND valid_to
|
|
279
|
+
return other()
|
|
280
|
+
constant = bool(others) and all(_is_constant(value) for value in others)
|
|
281
|
+
values = tuple(value.sql(dialect=dialect) for value in others) if constant else ()
|
|
282
|
+
return Predicate(columns[0].name.lower(), op, values, constant, _wrapper(side), clause, sql)
|
|
283
|
+
|
|
284
|
+
comparison = _COMPARISONS.get(type(condition))
|
|
285
|
+
if comparison is not None and isinstance(condition, exp.Binary):
|
|
286
|
+
left, right = condition.left, condition.right
|
|
287
|
+
if _local_columns(left) and not _local_columns(right):
|
|
288
|
+
return make(left, comparison, [right])
|
|
289
|
+
if _local_columns(right) and not _local_columns(left):
|
|
290
|
+
return make(right, _FLIPPED.get(comparison, comparison), [left])
|
|
291
|
+
return other()
|
|
292
|
+
if isinstance(condition, exp.Between):
|
|
293
|
+
return make(condition.this, "between", [condition.args["low"], condition.args["high"]])
|
|
294
|
+
if isinstance(condition, exp.In):
|
|
295
|
+
return make(condition.this, "in", _in_values(condition))
|
|
296
|
+
if isinstance(condition, exp.Or):
|
|
297
|
+
disjunction = _equality_disjunction(condition)
|
|
298
|
+
if disjunction is not None:
|
|
299
|
+
side, values = disjunction
|
|
300
|
+
return make(side, "in", values)
|
|
301
|
+
return other()
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _in_values(condition: exp.In) -> list[exp.Expr]:
|
|
305
|
+
"""The right-hand side of IN: a list, a subquery, or UNNEST of an array."""
|
|
306
|
+
query = condition.args.get("query")
|
|
307
|
+
if query is not None:
|
|
308
|
+
return [query]
|
|
309
|
+
unnest = condition.args.get("unnest")
|
|
310
|
+
if unnest is not None:
|
|
311
|
+
arrays = unnest.expressions
|
|
312
|
+
if len(arrays) == 1 and isinstance(arrays[0], exp.Array):
|
|
313
|
+
return list(arrays[0].expressions)
|
|
314
|
+
return list(arrays)
|
|
315
|
+
return list(condition.expressions)
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _disjuncts(condition: exp.Expr) -> Iterator[exp.Expr]:
|
|
319
|
+
if isinstance(condition, exp.Paren):
|
|
320
|
+
yield from _disjuncts(condition.this)
|
|
321
|
+
elif isinstance(condition, exp.Or):
|
|
322
|
+
yield from _disjuncts(condition.left)
|
|
323
|
+
yield from _disjuncts(condition.right)
|
|
324
|
+
else:
|
|
325
|
+
yield condition
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _equality_disjunction(
|
|
329
|
+
condition: exp.Or,
|
|
330
|
+
) -> tuple[exp.Expr, list[exp.Expr]] | None:
|
|
331
|
+
"""Treat ``x = 'a' OR x = 'b'`` like ``x IN ('a', 'b')``, which BigQuery can prune."""
|
|
332
|
+
side: exp.Expr | None = None
|
|
333
|
+
values: list[exp.Expr] = []
|
|
334
|
+
for disjunct in _disjuncts(condition):
|
|
335
|
+
if not isinstance(disjunct, exp.EQ):
|
|
336
|
+
return None
|
|
337
|
+
left, right = disjunct.left, disjunct.right
|
|
338
|
+
if _local_columns(left) and _is_constant(right):
|
|
339
|
+
this, value = left, right
|
|
340
|
+
elif _local_columns(right) and _is_constant(left):
|
|
341
|
+
this, value = right, left
|
|
342
|
+
else:
|
|
343
|
+
return None
|
|
344
|
+
if side is not None and this != side:
|
|
345
|
+
return None
|
|
346
|
+
side = this
|
|
347
|
+
values.append(value)
|
|
348
|
+
return (side, values) if side is not None else None
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def _joins(scope: Scope) -> Iterator[Join]:
|
|
352
|
+
select = scope.expression
|
|
353
|
+
where = select.args.get("where")
|
|
354
|
+
where_conjuncts = list(_conjuncts(where.this)) if where is not None else []
|
|
355
|
+
for join in select.args.get("joins") or []:
|
|
356
|
+
target = join.this
|
|
357
|
+
alias = target.alias_or_name
|
|
358
|
+
kind: Literal["table", "unnest", "derived"]
|
|
359
|
+
if isinstance(target, exp.Unnest):
|
|
360
|
+
kind = "unnest"
|
|
361
|
+
elif isinstance(scope.sources.get(alias), exp.Table):
|
|
362
|
+
kind = "table"
|
|
363
|
+
else:
|
|
364
|
+
kind = "derived"
|
|
365
|
+
on_conjuncts = list(_conjuncts(join.args.get("on")))
|
|
366
|
+
keys = [
|
|
367
|
+
*_equality_keys(on_conjuncts, alias),
|
|
368
|
+
*_equality_keys(where_conjuncts, alias),
|
|
369
|
+
]
|
|
370
|
+
yield Join(
|
|
371
|
+
target=alias,
|
|
372
|
+
target_kind=kind,
|
|
373
|
+
side=join.side or None,
|
|
374
|
+
kind=join.kind or None,
|
|
375
|
+
# ON TRUE, ON 1 = 1 or a filter on one side alone doesn't connect the tables.
|
|
376
|
+
has_condition=bool(keys) or any(_links(c, alias) for c in on_conjuncts),
|
|
377
|
+
keys=tuple(keys),
|
|
378
|
+
)
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def _links(condition: exp.Expr, alias: str) -> bool:
|
|
382
|
+
"""True when a condition relates the join target to some other source."""
|
|
383
|
+
owners = {column.table for column in _local_columns(condition)}
|
|
384
|
+
return alias in owners and len(owners) > 1
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def _equality_keys(
|
|
388
|
+
conditions: Iterator[exp.Expr] | list[exp.Expr], alias: str
|
|
389
|
+
) -> Iterator[tuple[str, str]]:
|
|
390
|
+
for condition in conditions:
|
|
391
|
+
if not isinstance(condition, exp.EQ):
|
|
392
|
+
continue
|
|
393
|
+
left, right = condition.left, condition.right
|
|
394
|
+
if not (isinstance(left, exp.Column) and isinstance(right, exp.Column)):
|
|
395
|
+
continue
|
|
396
|
+
if left.table == right.table or alias not in (left.table, right.table):
|
|
397
|
+
continue
|
|
398
|
+
yield (f"{left.table}.{left.name.lower()}", f"{right.table}.{right.name.lower()}")
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def _effective_root(scope: Scope) -> Scope:
|
|
402
|
+
"""Skip pass-through wrappers such as ``SELECT * FROM (...)`` and pipe-syntax CTEs."""
|
|
403
|
+
while True:
|
|
404
|
+
select = scope.expression
|
|
405
|
+
if not isinstance(select, exp.Select) or len(scope.selected_sources) != 1:
|
|
406
|
+
return scope
|
|
407
|
+
if any(select.args.get(key) for key in ("where", "group", "having", "qualify", "limit")):
|
|
408
|
+
return scope
|
|
409
|
+
if select.args.get("joins") or not all(
|
|
410
|
+
isinstance(p, exp.Star | exp.Column) for p in select.expressions
|
|
411
|
+
):
|
|
412
|
+
return scope
|
|
413
|
+
((_node, source),) = scope.selected_sources.values()
|
|
414
|
+
if not isinstance(source, Scope):
|
|
415
|
+
return scope
|
|
416
|
+
scope = source
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def _outer_shape(expression: exp.Expr) -> tuple[int | None, bool]:
|
|
420
|
+
limit_node = expression.args.get("limit")
|
|
421
|
+
limit: int | None = None
|
|
422
|
+
if limit_node is not None:
|
|
423
|
+
value = limit_node.expression
|
|
424
|
+
if isinstance(value, exp.Literal) and value.is_int:
|
|
425
|
+
limit = int(value.this)
|
|
426
|
+
return limit, _aggregated(expression)
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def _aggregated(expression: exp.Expr) -> bool:
|
|
430
|
+
"""True when the query returns one row per group rather than one per input row."""
|
|
431
|
+
if isinstance(expression, exp.Subquery):
|
|
432
|
+
return _aggregated(expression.this)
|
|
433
|
+
if isinstance(expression, exp.SetOperation):
|
|
434
|
+
return _aggregated(expression.left) and _aggregated(expression.right)
|
|
435
|
+
if not isinstance(expression, exp.Select):
|
|
436
|
+
return False
|
|
437
|
+
if expression.args.get("group"):
|
|
438
|
+
return True
|
|
439
|
+
# Aggregates inside scalar subqueries or window functions don't collapse the rows.
|
|
440
|
+
return any(
|
|
441
|
+
aggregate.find_ancestor(exp.Window) is None
|
|
442
|
+
for projection in expression.expressions
|
|
443
|
+
for aggregate in find_all_in_scope(projection, exp.AggFunc)
|
|
444
|
+
)
|
scanisaur/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: scanisaur
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Schema-aware pre-flight checks for AI-agent SQL, using warehouse metadata only.
|
|
5
|
+
Project-URL: Homepage, https://github.com/tjslezak/Scanisaur
|
|
6
|
+
Project-URL: Issues, https://github.com/tjslezak/Scanisaur/issues
|
|
7
|
+
Author: Scanisaur contributors
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: ai-agents,bigquery,data-warehouse,mcp,query-optimization,sql
|
|
11
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
19
|
+
Classifier: Topic :: Database
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.11
|
|
22
|
+
Requires-Dist: sqlglot<31,>=30.21
|
|
23
|
+
Requires-Dist: typer>=0.15
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# Scanisaur
|
|
27
|
+
The apex predator of agent-generated SQL.
|
|
28
|
+
|
|
29
|
+
Scanisaur is an [MCP](https://modelcontextprotocol.io) server that AI agents call **before** they run SQL. It reads only warehouse metadata (tables, columns, types, partitioning, clustering, row counts and sizes) and uses it to:
|
|
30
|
+
|
|
31
|
+
- **validate** the query: are these tables and columns real?
|
|
32
|
+
- **optimize** it: catch missing partition filters, `SELECT *` on wide tables, joins with no condition and other costly patterns, each with a concrete fix;
|
|
33
|
+
- **quantify** it: estimate bytes scanned and cost before anything runs.
|
|
34
|
+
|
|
35
|
+
Scanisaur never reads table data and never runs the queries it checks. The agent's own SQL tool does that.
|
|
36
|
+
|
|
37
|
+
> **Status: pre-alpha.** Nothing is published yet. BigQuery is the first supported warehouse; Snowflake follows.
|
|
38
|
+
|
|
39
|
+
## Planned MCP tools
|
|
40
|
+
|
|
41
|
+
| Tool | Purpose |
|
|
42
|
+
| --- | --- |
|
|
43
|
+
| `scanisaur_schema_search` | Find relevant tables and columns by keyword |
|
|
44
|
+
| `scanisaur_schema_describe` | Compact, token-efficient table descriptions with partition and cluster keys |
|
|
45
|
+
| `scanisaur_check_sql` | Verdict (`pass`, `warn`, `block`), cost estimate, findings with fixes, and a tracking tag |
|
|
46
|
+
|
|
47
|
+
## Development
|
|
48
|
+
|
|
49
|
+
You need [uv](https://docs.astral.sh/uv/).
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
uv sync
|
|
53
|
+
uv run scanisaur --version
|
|
54
|
+
uv run pytest
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) for the full set of checks, and [docs/adr/](docs/adr/) for the design decisions so far.
|
|
58
|
+
|
|
59
|
+
## License
|
|
60
|
+
|
|
61
|
+
[Apache License 2.0](LICENSE)
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
scanisaur/__init__.py,sha256=3Kc0QOOeotTyGzWJhQc88pBKkQEgzepAnj-6aAzywTw,306
|
|
2
|
+
scanisaur/__main__.py,sha256=OA-_EXWmngoZ8J4HfNrMws_SKxpSFkjbf6gdK99nvHs,58
|
|
3
|
+
scanisaur/cli.py,sha256=Ggcl5glXA0FujSxw3ZwhU9MmF3kmUkzuzhcLmV1-Qik,845
|
|
4
|
+
scanisaur/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
scanisaur/engine/__init__.py,sha256=74zkKSKd_r4YPl0Pmrg2mGDIVrtNBV3NTL7NPMuiyzw,27
|
|
6
|
+
scanisaur/engine/facts.py,sha256=ST6JI94N5QlzOtojwiachBLdr_pIymwbqVRDn14G2QU,16470
|
|
7
|
+
scanisaur-0.0.1.dist-info/METADATA,sha256=iMGCbRAudwO58-4dUS_KOnl_Xu_gQ8ONfMMLBBoZw1A,2449
|
|
8
|
+
scanisaur-0.0.1.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
9
|
+
scanisaur-0.0.1.dist-info/entry_points.txt,sha256=5gdecoK_1hJtd6plzu8ouoveOJQF0BvjNPB480IMNTo,48
|
|
10
|
+
scanisaur-0.0.1.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
11
|
+
scanisaur-0.0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|