sqlty 0.1.0__cp315-cp315-win_amd64.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.
- sqlty/__init__.py +99 -0
- sqlty/__main__.py +5 -0
- sqlty/_breaking.py +191 -0
- sqlty/_check.py +880 -0
- sqlty/_cli.py +1219 -0
- sqlty/_config.py +666 -0
- sqlty/_core.cp315-win_amd64.pyd +0 -0
- sqlty/_core.pyi +108 -0
- sqlty/_decode.py +62 -0
- sqlty/_drivers.py +274 -0
- sqlty/_gitignore.py +58 -0
- sqlty/_helpers.py +613 -0
- sqlty/_json_shape.py +299 -0
- sqlty/_json_types.py +225 -0
- sqlty/_lint.py +350 -0
- sqlty/_params.py +177 -0
- sqlty/_psycopg.py +269 -0
- sqlty/_source.py +654 -0
- sqlty/_type_extractor/__init__.py +51 -0
- sqlty/_type_extractor/ast_fields.py +823 -0
- sqlty/_type_extractor/compat.py +252 -0
- sqlty/_type_extractor/extract.py +179 -0
- sqlty/_type_extractor/generic.py +95 -0
- sqlty/_type_extractor/info.py +161 -0
- sqlty/_type_extractor/sandbox.py +385 -0
- sqlty/_type_extractor/subtype.py +156 -0
- sqlty/_widening.py +89 -0
- sqlty/core.py +566 -0
- sqlty/drivers/psycopg.py +104 -0
- sqlty/magic.py +126 -0
- sqlty/py.typed +0 -0
- sqlty/rules/ambiguous-column.md +48 -0
- sqlty/rules/column-count-mismatch.md +30 -0
- sqlty/rules/column-name-mismatch.md +34 -0
- sqlty/rules/column-type-mismatch.md +75 -0
- sqlty/rules/fstring-skipped.md +23 -0
- sqlty/rules/inline-sql-comment.md +27 -0
- sqlty/rules/insert-missing-column.md +58 -0
- sqlty/rules/json-shape-mismatch.md +96 -0
- sqlty/rules/literal-mismatch.md +83 -0
- sqlty/rules/mysql-sql-marker.md +32 -0
- sqlty/rules/nullable-mismatch.md +76 -0
- sqlty/rules/param-count-mismatch.md +66 -0
- sqlty/rules/param-type-mismatch.md +73 -0
- sqlty/rules/redundant-literal.md +68 -0
- sqlty/rules/redundant-optional.md +100 -0
- sqlty/rules/select-star-no-schema.md +24 -0
- sqlty/rules/select-star.md +77 -0
- sqlty/rules/stale-rewrite.md +33 -0
- sqlty/rules/stale-type.md +50 -0
- sqlty/rules/tstring-skipped.md +68 -0
- sqlty/rules/typeddict-inheritance.md +35 -0
- sqlty/rules/typeddict-key-mismatch.md +38 -0
- sqlty/rules/unchecked-query.md +34 -0
- sqlty/rules/ungrouped-column.md +67 -0
- sqlty/rules/unknown-column.md +68 -0
- sqlty/rules/unknown-function.md +49 -0
- sqlty/rules/unknown-table.md +47 -0
- sqlty/rules/unknown-type.md +74 -0
- sqlty/rules/unparsed-query.md +46 -0
- sqlty/rules/unsupported-syntax.md +69 -0
- sqlty/rules/untyped-query.md +39 -0
- sqlty/rules/unused-ignore.md +36 -0
- sqlty/skill/SKILL.md +110 -0
- sqlty-0.1.0.dist-info/METADATA +210 -0
- sqlty-0.1.0.dist-info/RECORD +71 -0
- sqlty-0.1.0.dist-info/WHEEL +4 -0
- sqlty-0.1.0.dist-info/entry_points.txt +2 -0
- sqlty-0.1.0.dist-info/licenses/LICENSE +21 -0
- sqlty-0.1.0.dist-info/sboms/sqlty-core.cyclonedx.json +1891 -0
- sqlty_magic.pth +1 -0
sqlty/_psycopg.py
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
"""Render ``psycopg.sql`` compositions built only from literals.
|
|
2
|
+
|
|
3
|
+
The expression is rebuilt from the AST with the real ``psycopg.sql`` classes
|
|
4
|
+
(no user code runs) and rendered with ``Composable.as_string(None)``, which
|
|
5
|
+
needs no connection since psycopg 3.2. ``sql.Literal(x)`` renders as ``NULL``.
|
|
6
|
+
|
|
7
|
+
Usage:
|
|
8
|
+
scan = ParsedSource(text).psycopg # built from the one walk of the module
|
|
9
|
+
scan.render(expr) # str, UNCHECKED, or None when not a psycopg query
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import ast
|
|
15
|
+
from collections.abc import Callable
|
|
16
|
+
from typing import TYPE_CHECKING, Any, Final
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
from sqlty._source import ParsedSource
|
|
20
|
+
|
|
21
|
+
Resolver = Callable[["ParsedSource", str], "tuple[ParsedSource, ast.expr] | None"]
|
|
22
|
+
|
|
23
|
+
_CLASSES = frozenset({"SQL", "Identifier", "Literal", "Placeholder", "Composed"})
|
|
24
|
+
_METHODS = frozenset({"format", "join"})
|
|
25
|
+
_Pos = tuple[int, int]
|
|
26
|
+
|
|
27
|
+
UNCHECKED: Final = "unchecked"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class _Dynamic(Exception):
|
|
31
|
+
"""A part that is not a literal."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class _Invalid(Exception):
|
|
35
|
+
"""A composition psycopg itself rejects."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _dotted(node: ast.expr) -> str | None:
|
|
39
|
+
if isinstance(node, ast.Name):
|
|
40
|
+
return node.id
|
|
41
|
+
if isinstance(node, ast.Attribute) and (base := _dotted(node.value)):
|
|
42
|
+
return f"{base}.{node.attr}"
|
|
43
|
+
return None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
_Scope = ast.FunctionDef | ast.AsyncFunctionDef | ast.Lambda | ast.ClassDef
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _span(node: _Scope) -> tuple[_Pos, _Pos]:
|
|
50
|
+
return (
|
|
51
|
+
(node.lineno, node.col_offset),
|
|
52
|
+
(node.end_lineno or 0, node.end_col_offset or 0),
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _params(node: ast.FunctionDef | ast.AsyncFunctionDef | ast.Lambda) -> set[str]:
|
|
57
|
+
args = node.args
|
|
58
|
+
names = {a.arg for a in [*args.posonlyargs, *args.args, *args.kwonlyargs]}
|
|
59
|
+
names.update(a.arg for a in (args.vararg, args.kwarg) if a is not None)
|
|
60
|
+
return names
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class PsycopgScan:
|
|
64
|
+
"""What a module walk collects to follow names and imports.
|
|
65
|
+
|
|
66
|
+
Example:
|
|
67
|
+
>>> from sqlty._source import ParsedSource
|
|
68
|
+
>>> parsed = ParsedSource("from psycopg import sql\\nQ = sql.SQL('SELECT {}').format(sql.Identifier('t'))")
|
|
69
|
+
>>> parsed.psycopg.render(parsed.calls[0])
|
|
70
|
+
'SELECT "t"'
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
def __init__(
|
|
74
|
+
self,
|
|
75
|
+
imports: list[ast.Import | ast.ImportFrom],
|
|
76
|
+
scopes: list[_Scope],
|
|
77
|
+
stores: dict[str, list[ast.Name]],
|
|
78
|
+
values: dict[int, ast.expr],
|
|
79
|
+
source: ParsedSource | None = None,
|
|
80
|
+
) -> None:
|
|
81
|
+
self.source = source
|
|
82
|
+
self.imports = imports
|
|
83
|
+
self.scopes = scopes
|
|
84
|
+
self.stores = stores
|
|
85
|
+
self.values = values
|
|
86
|
+
self._table: dict[str, str] | None = None
|
|
87
|
+
self._sql: Any = None
|
|
88
|
+
|
|
89
|
+
def render(self, expr: ast.expr, resolve: Resolver | None = None) -> str | None:
|
|
90
|
+
"""The SQL of a psycopg composition, ``UNCHECKED`` when a part is dynamic.
|
|
91
|
+
|
|
92
|
+
``None`` when ``expr`` is no psycopg composition or psycopg is missing.
|
|
93
|
+
``resolve(source, dotted)`` finds the module-level value of a name imported
|
|
94
|
+
from another module, as ``(its source, expression)``.
|
|
95
|
+
"""
|
|
96
|
+
try:
|
|
97
|
+
from psycopg import sql
|
|
98
|
+
except ImportError:
|
|
99
|
+
return None
|
|
100
|
+
self._sql = sql
|
|
101
|
+
run = _Run(self, sql, resolve)
|
|
102
|
+
try:
|
|
103
|
+
value = run.value(expr)
|
|
104
|
+
if not isinstance(value, sql.Composable):
|
|
105
|
+
return None
|
|
106
|
+
return value.as_string(None)
|
|
107
|
+
except _Dynamic:
|
|
108
|
+
return UNCHECKED if run.seen else None
|
|
109
|
+
except _Invalid, TypeError, ValueError, NotImplementedError, AttributeError:
|
|
110
|
+
return None
|
|
111
|
+
|
|
112
|
+
@property
|
|
113
|
+
def table(self) -> dict[str, str]:
|
|
114
|
+
"""Local names bound by ``psycopg`` imports, to their dotted target."""
|
|
115
|
+
if self._table is None:
|
|
116
|
+
table: dict[str, str] = {}
|
|
117
|
+
for node in self.imports:
|
|
118
|
+
if isinstance(node, ast.Import):
|
|
119
|
+
for alias in node.names:
|
|
120
|
+
if alias.name.split(".")[0] != "psycopg":
|
|
121
|
+
continue
|
|
122
|
+
if alias.asname:
|
|
123
|
+
table[alias.asname] = alias.name
|
|
124
|
+
else:
|
|
125
|
+
table["psycopg"] = "psycopg"
|
|
126
|
+
elif not node.level and (node.module or "").split(".")[0] == "psycopg":
|
|
127
|
+
for alias in node.names:
|
|
128
|
+
table[alias.asname or alias.name] = f"{node.module}.{alias.name}"
|
|
129
|
+
self._table = table
|
|
130
|
+
return self._table
|
|
131
|
+
|
|
132
|
+
def binding(self, name: ast.Name) -> ast.expr | None:
|
|
133
|
+
"""The value of the single assignment ``name`` refers to, if there is one.
|
|
134
|
+
|
|
135
|
+
Looks at the enclosing functions, innermost first, then the module.
|
|
136
|
+
"""
|
|
137
|
+
pos = (name.lineno, name.col_offset)
|
|
138
|
+
enclosing = [scope for scope in self.scopes if (span := _span(scope))[0] <= pos < span[1]]
|
|
139
|
+
enclosing.sort(key=lambda scope: _span(scope)[0], reverse=True)
|
|
140
|
+
functions = [s for s in enclosing if not isinstance(s, ast.ClassDef)]
|
|
141
|
+
for scope in [*functions, None]:
|
|
142
|
+
if isinstance(scope, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)):
|
|
143
|
+
if name.id in _params(scope):
|
|
144
|
+
return None
|
|
145
|
+
found = [s for s in self.stores.get(name.id, []) if self._owner(s) is scope]
|
|
146
|
+
if not found:
|
|
147
|
+
continue
|
|
148
|
+
if len(found) == 1:
|
|
149
|
+
return self.values.get(id(found[0]))
|
|
150
|
+
return None
|
|
151
|
+
return None
|
|
152
|
+
|
|
153
|
+
def is_parameter(self, name: ast.Name) -> bool:
|
|
154
|
+
"""Whether ``name`` is a parameter of an enclosing function."""
|
|
155
|
+
pos = (name.lineno, name.col_offset)
|
|
156
|
+
return any(
|
|
157
|
+
not isinstance(scope, ast.ClassDef)
|
|
158
|
+
and _span(scope)[0] <= pos < _span(scope)[1]
|
|
159
|
+
and name.id in _params(scope)
|
|
160
|
+
for scope in self.scopes
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
def _owner(self, store: ast.Name) -> _Scope | None:
|
|
164
|
+
"""The innermost function or class containing ``store``, ``None`` for the module."""
|
|
165
|
+
pos = (store.lineno, store.col_offset)
|
|
166
|
+
best: _Scope | None = None
|
|
167
|
+
for scope in self.scopes:
|
|
168
|
+
span = _span(scope)
|
|
169
|
+
if span[0] <= pos < span[1] and (best is None or _span(best)[0] <= span[0]):
|
|
170
|
+
best = scope
|
|
171
|
+
return best
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
class _Run:
|
|
175
|
+
"""One evaluation of an expression."""
|
|
176
|
+
|
|
177
|
+
def __init__(self, scan: PsycopgScan, sql: Any, resolve: Resolver | None) -> None:
|
|
178
|
+
self.scan = scan
|
|
179
|
+
self.sql = sql
|
|
180
|
+
self.resolve = resolve
|
|
181
|
+
self.seen = False
|
|
182
|
+
self.depth = 0
|
|
183
|
+
|
|
184
|
+
def _imported(self, node: ast.expr) -> Any:
|
|
185
|
+
"""The value of a name or ``module.NAME`` bound in another checked module."""
|
|
186
|
+
source = self.scan.source
|
|
187
|
+
dotted = _dotted(node)
|
|
188
|
+
if (
|
|
189
|
+
self.resolve is None
|
|
190
|
+
or source is None
|
|
191
|
+
or dotted is None
|
|
192
|
+
or (isinstance(node, ast.Name) and (node.id in self.scan.stores))
|
|
193
|
+
or (isinstance(node, ast.Name) and self.scan.is_parameter(node))
|
|
194
|
+
or (found := self.resolve(source, dotted)) is None
|
|
195
|
+
):
|
|
196
|
+
raise _Dynamic
|
|
197
|
+
parsed, expr = found
|
|
198
|
+
inner = _Run(parsed.psycopg, self.sql, self.resolve)
|
|
199
|
+
inner.depth = self.depth
|
|
200
|
+
try:
|
|
201
|
+
return inner.value(expr)
|
|
202
|
+
finally:
|
|
203
|
+
self.seen = self.seen or inner.seen
|
|
204
|
+
|
|
205
|
+
def value(self, node: ast.expr) -> Any:
|
|
206
|
+
self.depth += 1
|
|
207
|
+
try:
|
|
208
|
+
if self.depth > 64:
|
|
209
|
+
raise _Dynamic
|
|
210
|
+
return self._value(node)
|
|
211
|
+
finally:
|
|
212
|
+
self.depth -= 1
|
|
213
|
+
|
|
214
|
+
def _value(self, node: ast.expr) -> Any:
|
|
215
|
+
if isinstance(node, ast.Constant):
|
|
216
|
+
return node.value
|
|
217
|
+
if isinstance(node, ast.Name):
|
|
218
|
+
if (target := self.scan.binding(node)) is None:
|
|
219
|
+
return self._imported(node)
|
|
220
|
+
return self.value(target)
|
|
221
|
+
if isinstance(node, ast.Attribute):
|
|
222
|
+
return self._imported(node)
|
|
223
|
+
if isinstance(node, (ast.List, ast.Tuple)):
|
|
224
|
+
if any(isinstance(item, ast.Starred) for item in node.elts):
|
|
225
|
+
raise _Dynamic
|
|
226
|
+
return [self.value(item) for item in node.elts]
|
|
227
|
+
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
|
|
228
|
+
return self.value(node.left) + self.value(node.right)
|
|
229
|
+
if isinstance(node, ast.Call):
|
|
230
|
+
return self._call(node)
|
|
231
|
+
raise _Dynamic
|
|
232
|
+
|
|
233
|
+
def _symbol(self, func: ast.expr) -> str | None:
|
|
234
|
+
"""The ``psycopg.sql`` class ``func`` names, through any import form."""
|
|
235
|
+
if (dotted := _dotted(func)) is None:
|
|
236
|
+
return None
|
|
237
|
+
head, _, rest = dotted.partition(".")
|
|
238
|
+
if (target := self.scan.table.get(head)) is None:
|
|
239
|
+
return None
|
|
240
|
+
full = f"{target}.{rest}" if rest else target
|
|
241
|
+
module, _, name = full.rpartition(".")
|
|
242
|
+
return name if module == "psycopg.sql" and name in _CLASSES else None
|
|
243
|
+
|
|
244
|
+
def _call(self, node: ast.Call) -> Any:
|
|
245
|
+
if (name := self._symbol(node.func)) is not None:
|
|
246
|
+
self.seen = True
|
|
247
|
+
if name == "Literal":
|
|
248
|
+
return self.sql.SQL("NULL")
|
|
249
|
+
args, kwargs = self._arguments(node)
|
|
250
|
+
return getattr(self.sql, name)(*args, **kwargs)
|
|
251
|
+
if isinstance(node.func, ast.Attribute) and node.func.attr in _METHODS:
|
|
252
|
+
receiver = self.value(node.func.value)
|
|
253
|
+
if not isinstance(receiver, (str, self.sql.SQL)):
|
|
254
|
+
raise _Invalid
|
|
255
|
+
args, kwargs = self._arguments(node)
|
|
256
|
+
try:
|
|
257
|
+
return getattr(receiver, node.func.attr)(*args, **kwargs)
|
|
258
|
+
except (TypeError, ValueError, IndexError, KeyError) as error:
|
|
259
|
+
raise _Invalid from error
|
|
260
|
+
raise _Dynamic
|
|
261
|
+
|
|
262
|
+
def _arguments(self, node: ast.Call) -> tuple[list[Any], dict[str, Any]]:
|
|
263
|
+
if any(isinstance(arg, ast.Starred) for arg in node.args) or any(
|
|
264
|
+
keyword.arg is None for keyword in node.keywords
|
|
265
|
+
):
|
|
266
|
+
raise _Dynamic
|
|
267
|
+
args = [self.value(arg) for arg in node.args]
|
|
268
|
+
kwargs = {kw.arg: self.value(kw.value) for kw in node.keywords if kw.arg}
|
|
269
|
+
return args, kwargs
|