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/_helpers.py
ADDED
|
@@ -0,0 +1,613 @@
|
|
|
1
|
+
"""Helpers whose query parameter is marked ``Annotated[LiteralString, SQL]``.
|
|
2
|
+
|
|
3
|
+
A call passing a string literal to such a parameter is a checked query, with
|
|
4
|
+
no ``--sql`` marker or ``SQL[T]`` wrapper. The row type is the argument bound
|
|
5
|
+
to the parameter annotated ``type[T]`` / ``TypeForm[T]`` where ``T`` also
|
|
6
|
+
appears in the return annotation.
|
|
7
|
+
|
|
8
|
+
Usage:
|
|
9
|
+
index = HelperIndex()
|
|
10
|
+
index.add("pkg.queries", source_of_pkg_queries)
|
|
11
|
+
find_helper_calls(source, index, "pkg.app")
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import ast
|
|
17
|
+
import re
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from typing import TYPE_CHECKING, Any, NamedTuple
|
|
20
|
+
|
|
21
|
+
from sqlty._params import ParamArg, arg_type, literal_params
|
|
22
|
+
from sqlty._psycopg import UNCHECKED
|
|
23
|
+
from sqlty._source import ParsedSource
|
|
24
|
+
|
|
25
|
+
if TYPE_CHECKING:
|
|
26
|
+
from sqlty._type_extractor import TypeInfo
|
|
27
|
+
|
|
28
|
+
_TYPE_FORMS = frozenset({"type", "Type", "TypeForm"})
|
|
29
|
+
# Names that mark where a helper takes the query's parameters: a ``params`` argument holding
|
|
30
|
+
# a sequence or mapping, ``*args`` (asyncpg), or ``**params``.
|
|
31
|
+
_PARAMS_ARGUMENT = frozenset({"params", "parameters", "args"})
|
|
32
|
+
_PARAMS_VARIADIC = frozenset({"args", "params", "parameters"})
|
|
33
|
+
_PARAMS_KEYWORDS = frozenset({"params", "parameters"})
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class Helper:
|
|
38
|
+
"""A function with a marked query parameter.
|
|
39
|
+
|
|
40
|
+
``positional`` lists the parameters a call may bind by position, ``keywords``
|
|
41
|
+
those it may bind by name. ``row`` is ``None`` when no ``type[T]`` parameter
|
|
42
|
+
shares ``T`` with the return type. A method is named ``Class.method`` and its
|
|
43
|
+
``self`` / ``cls`` is not listed; ``kind`` is ``instance`` for a method that is
|
|
44
|
+
only callable on an instance (a call through the class would shift the arguments).
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
name: str
|
|
48
|
+
positional: tuple[str, ...]
|
|
49
|
+
keywords: frozenset[str]
|
|
50
|
+
query: str
|
|
51
|
+
row: str | None
|
|
52
|
+
kind: str = "function"
|
|
53
|
+
params: str | None = None
|
|
54
|
+
rest: str | None = None
|
|
55
|
+
named: str | None = None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class HelperCall(NamedTuple):
|
|
59
|
+
"""A call passing a query to a helper's query parameter.
|
|
60
|
+
|
|
61
|
+
``query`` is ``None`` for a psycopg composition with a part that is not a literal.
|
|
62
|
+
``params`` holds the arguments the call passes for the query's placeholders, with the
|
|
63
|
+
type of each where the source states it, or ``None`` when the helper takes no parameters
|
|
64
|
+
or the call does not spell them out.
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
line: int
|
|
68
|
+
query: str | None
|
|
69
|
+
row: ast.expr | None
|
|
70
|
+
typing_aliases: dict[str, str]
|
|
71
|
+
params: tuple[ParamArg, ...] | None = None
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _dotted(node: ast.expr) -> str | None:
|
|
75
|
+
if isinstance(node, ast.Name):
|
|
76
|
+
return node.id
|
|
77
|
+
if isinstance(node, ast.Attribute) and (base := _dotted(node.value)):
|
|
78
|
+
return f"{base}.{node.attr}"
|
|
79
|
+
return None
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _expr(annotation: ast.expr | None) -> ast.expr | None:
|
|
83
|
+
"""The annotation, with a quoted one parsed."""
|
|
84
|
+
if isinstance(annotation, ast.Constant) and isinstance(annotation.value, str):
|
|
85
|
+
try:
|
|
86
|
+
return ast.parse(annotation.value, mode="eval").body
|
|
87
|
+
except SyntaxError:
|
|
88
|
+
return None
|
|
89
|
+
return annotation
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _is_marked(annotation: ast.expr | None, annotated: set[str], marker: set[str]) -> bool:
|
|
93
|
+
if (annotation := _expr(annotation)) is None:
|
|
94
|
+
return False
|
|
95
|
+
for node in ast.walk(annotation):
|
|
96
|
+
if (
|
|
97
|
+
isinstance(node, ast.Subscript)
|
|
98
|
+
and _dotted(node.value) in annotated
|
|
99
|
+
and isinstance(node.slice, ast.Tuple)
|
|
100
|
+
):
|
|
101
|
+
if any(_dotted(meta) in marker for meta in node.slice.elts[1:]):
|
|
102
|
+
return True
|
|
103
|
+
return False
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _row_param(args: ast.arguments, returns: ast.expr | None) -> str | None:
|
|
107
|
+
"""The first parameter annotated ``type[T]`` / ``TypeForm[T]`` with ``T`` in ``returns``."""
|
|
108
|
+
if (returns := _expr(returns)) is None:
|
|
109
|
+
return None
|
|
110
|
+
returned = {n.id for n in ast.walk(returns) if isinstance(n, ast.Name)}
|
|
111
|
+
for arg in [*args.posonlyargs, *args.args, *args.kwonlyargs]:
|
|
112
|
+
if (annotation := _expr(arg.annotation)) is None:
|
|
113
|
+
continue
|
|
114
|
+
for node in ast.walk(annotation):
|
|
115
|
+
if (
|
|
116
|
+
isinstance(node, ast.Subscript)
|
|
117
|
+
and (name := _dotted(node.value))
|
|
118
|
+
and name.rpartition(".")[2] in _TYPE_FORMS
|
|
119
|
+
and isinstance(node.slice, ast.Name)
|
|
120
|
+
and node.slice.id in returned
|
|
121
|
+
):
|
|
122
|
+
return arg.arg
|
|
123
|
+
return None
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _parameters(args: ast.arguments) -> set[str]:
|
|
127
|
+
return {a.arg for a in [*args.posonlyargs, *args.args, *args.kwonlyargs]}
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _kind(node: ast.FunctionDef | ast.AsyncFunctionDef) -> str:
|
|
131
|
+
"""``static``, ``class`` or ``instance`` for a method, by its decorators."""
|
|
132
|
+
names = {_dotted(d) for d in node.decorator_list}
|
|
133
|
+
if "staticmethod" in names:
|
|
134
|
+
return "static"
|
|
135
|
+
return "class" if "classmethod" in names else "instance"
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _rank(node: ast.FunctionDef | ast.AsyncFunctionDef, complete: bool) -> tuple[bool, bool]:
|
|
139
|
+
"""Sort key among definitions of one name: complete first, then non-``@overload``."""
|
|
140
|
+
overload = any((_dotted(d) or "").rpartition(".")[2] == "overload" for d in node.decorator_list)
|
|
141
|
+
return not complete, overload
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _definitions(
|
|
145
|
+
parsed: ParsedSource,
|
|
146
|
+
) -> list[tuple[str, ast.FunctionDef | ast.AsyncFunctionDef, str]]:
|
|
147
|
+
"""Module-level functions and methods as ``(name, node, kind)``; methods are ``Class.name``."""
|
|
148
|
+
return [
|
|
149
|
+
*((node.name, node, "function") for node in parsed.functions),
|
|
150
|
+
*((f"{cls.name}.{node.name}", node, _kind(node)) for cls, node in parsed.methods),
|
|
151
|
+
]
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _helper(
|
|
155
|
+
name: str,
|
|
156
|
+
node: ast.FunctionDef | ast.AsyncFunctionDef,
|
|
157
|
+
kind: str,
|
|
158
|
+
query: str,
|
|
159
|
+
row: str | None,
|
|
160
|
+
) -> Helper:
|
|
161
|
+
args = node.args
|
|
162
|
+
positional = [*args.posonlyargs, *args.args]
|
|
163
|
+
keywords = [*args.args, *args.kwonlyargs]
|
|
164
|
+
names = [a.arg for a in [*positional, *args.kwonlyargs]]
|
|
165
|
+
if kind in ("instance", "class") and positional:
|
|
166
|
+
keywords = [a for a in keywords if a is not positional[0]]
|
|
167
|
+
positional = positional[1:]
|
|
168
|
+
return Helper(
|
|
169
|
+
name=name,
|
|
170
|
+
positional=tuple(a.arg for a in positional),
|
|
171
|
+
keywords=frozenset(a.arg for a in keywords),
|
|
172
|
+
query=query,
|
|
173
|
+
row=row,
|
|
174
|
+
kind=kind,
|
|
175
|
+
params=next((n for n in names if n in _PARAMS_ARGUMENT and n not in (query, row)), None),
|
|
176
|
+
rest=args.vararg.arg if args.vararg and args.vararg.arg in _PARAMS_VARIADIC else None,
|
|
177
|
+
named=args.kwarg.arg if args.kwarg and args.kwarg.arg in _PARAMS_KEYWORDS else None,
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def index_functions(source: str | ParsedSource) -> dict[str, Helper]:
|
|
182
|
+
"""Functions and methods with a marked query parameter, by name (``Class.method``).
|
|
183
|
+
|
|
184
|
+
Example:
|
|
185
|
+
>>> src = "from typing import Annotated\\nfrom sqlty import SQL\\ndef f[T](q: Annotated[str, SQL], t: type[T], /) -> T: ..."
|
|
186
|
+
>>> index_functions(src)["f"]
|
|
187
|
+
Helper(name='f', positional=('q', 't'), keywords=frozenset(), query='q', row='t', kind='function', params=None, rest=None, named=None)
|
|
188
|
+
"""
|
|
189
|
+
parsed = ParsedSource.of(source)
|
|
190
|
+
annotated, marker = parsed.marker_names
|
|
191
|
+
if not annotated or not marker:
|
|
192
|
+
return {}
|
|
193
|
+
found: dict[str, tuple[tuple[bool, bool], Helper]] = {}
|
|
194
|
+
for name, node, kind in _definitions(parsed):
|
|
195
|
+
args = node.args
|
|
196
|
+
query = next(
|
|
197
|
+
(
|
|
198
|
+
a.arg
|
|
199
|
+
for a in [*args.posonlyargs, *args.args, *args.kwonlyargs]
|
|
200
|
+
if _is_marked(a.annotation, annotated, marker)
|
|
201
|
+
),
|
|
202
|
+
None,
|
|
203
|
+
)
|
|
204
|
+
if query is not None:
|
|
205
|
+
row = _row_param(args, node.returns)
|
|
206
|
+
rank = _rank(node, row is not None)
|
|
207
|
+
if name not in found or rank < found[name][0]:
|
|
208
|
+
found[name] = rank, _helper(name, node, kind, query, row)
|
|
209
|
+
return {name: helper for name, (_, helper) in found.items()}
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
class HelperIndex:
|
|
213
|
+
"""Helpers of the modules of a checked tree, by module name.
|
|
214
|
+
|
|
215
|
+
Example:
|
|
216
|
+
>>> index = HelperIndex()
|
|
217
|
+
>>> index.add("pkg.db", "from typing import Annotated\\nfrom sqlty import SQL\\ndef run(q: Annotated[str, SQL]): ...")
|
|
218
|
+
True
|
|
219
|
+
>>> sorted(index.modules["pkg.db"])
|
|
220
|
+
['run']
|
|
221
|
+
"""
|
|
222
|
+
|
|
223
|
+
def __init__(self) -> None:
|
|
224
|
+
self.modules: dict[str, dict[str, Helper]] = {}
|
|
225
|
+
self.sources: dict[str, ParsedSource] = {}
|
|
226
|
+
self.packages: set[str] = set()
|
|
227
|
+
self.prefixes: set[str] = set()
|
|
228
|
+
self.namespaces: dict[str, tuple[dict[str, object], dict[str, Any]]] = {}
|
|
229
|
+
self.type_modules: frozenset[str] = frozenset()
|
|
230
|
+
self._pattern: re.Pattern[str] | None = None
|
|
231
|
+
self._names: frozenset[str] | None = None
|
|
232
|
+
self._exports: dict[str, dict[str, tuple[str, str]]] = {}
|
|
233
|
+
self._row_types: dict[tuple[str, frozenset[str]], dict[str, TypeInfo]] = {}
|
|
234
|
+
|
|
235
|
+
def fork(self) -> HelperIndex:
|
|
236
|
+
"""A copy whose later ``register`` calls do not reach this index; sources are shared."""
|
|
237
|
+
other = HelperIndex()
|
|
238
|
+
other.modules = {module: dict(found) for module, found in self.modules.items()}
|
|
239
|
+
other.sources = self.sources
|
|
240
|
+
other.packages = set(self.packages)
|
|
241
|
+
other.prefixes = set(self.prefixes)
|
|
242
|
+
other.type_modules = self.type_modules
|
|
243
|
+
other._exports = self._exports
|
|
244
|
+
other._row_types = self._row_types
|
|
245
|
+
return other
|
|
246
|
+
|
|
247
|
+
def add(self, module: str, source: str | ParsedSource) -> bool:
|
|
248
|
+
"""Index the helpers of ``source`` as module ``module``; whether it has any.
|
|
249
|
+
|
|
250
|
+
The parsed source is kept, so annotations naming types of ``module`` can be
|
|
251
|
+
resolved without importing it or parsing it again.
|
|
252
|
+
"""
|
|
253
|
+
parsed = ParsedSource.of(source)
|
|
254
|
+
if parsed.module is None:
|
|
255
|
+
parsed.module = module
|
|
256
|
+
self.sources[module] = parsed
|
|
257
|
+
if parsed.module is not None and parsed.module.endswith(".__init__"):
|
|
258
|
+
self.packages.add(module)
|
|
259
|
+
parts = module.split(".")
|
|
260
|
+
self.prefixes.update(".".join(parts[:i]) for i in range(1, len(parts) + 1))
|
|
261
|
+
self.namespaces.pop(module, None)
|
|
262
|
+
self._exports.pop(module, None)
|
|
263
|
+
for key in [key for key in self._row_types if key[0] == module]:
|
|
264
|
+
del self._row_types[key]
|
|
265
|
+
if not parsed.may_define_helpers or not (found := index_functions(parsed)):
|
|
266
|
+
return False
|
|
267
|
+
self.modules.setdefault(module, {}).update(found)
|
|
268
|
+
self._pattern = None
|
|
269
|
+
self._names = None
|
|
270
|
+
return True
|
|
271
|
+
|
|
272
|
+
def register(self, import_path: str, query: str, row: str | None = None) -> None:
|
|
273
|
+
"""Register ``import_path`` (``pkg.mod.func`` or ``pkg.mod.Class.method``) as a helper.
|
|
274
|
+
|
|
275
|
+
Used for ``[[tool.sqlty.functions]]``: the function needs no marked parameter. Its
|
|
276
|
+
positional parameters are read from the definition when ``pkg.mod`` is indexed;
|
|
277
|
+
otherwise ``query`` and ``row`` can only be passed by keyword. Of ``@overload``
|
|
278
|
+
definitions, the first naming both is used unless the implementation names them.
|
|
279
|
+
|
|
280
|
+
Example:
|
|
281
|
+
>>> index = HelperIndex()
|
|
282
|
+
>>> index.register("db.run", "sql", "form")
|
|
283
|
+
>>> index.modules["db"]["run"].keywords == {"sql", "form"}
|
|
284
|
+
True
|
|
285
|
+
"""
|
|
286
|
+
parts = import_path.split(".")
|
|
287
|
+
known = [i for i in range(len(parts) - 1, 0, -1) if ".".join(parts[:i]) in self.sources]
|
|
288
|
+
for i in known[:1] or [i for i in (len(parts) - 1, len(parts) - 2) if i > 0]:
|
|
289
|
+
module, name = ".".join(parts[:i]), ".".join(parts[i:])
|
|
290
|
+
parsed = self.sources.get(module)
|
|
291
|
+
definition = min(
|
|
292
|
+
(d for d in (_definitions(parsed) if parsed else []) if d[0] == name),
|
|
293
|
+
key=lambda d: _rank(d[1], {query, row} - {None} <= _parameters(d[1].args)),
|
|
294
|
+
default=None,
|
|
295
|
+
)
|
|
296
|
+
if definition is not None:
|
|
297
|
+
helper = _helper(name, definition[1], definition[2], query, row)
|
|
298
|
+
else:
|
|
299
|
+
helper = Helper(name, (), frozenset(filter(None, [query, row])), query, row)
|
|
300
|
+
self.modules.setdefault(module, {})[name] = helper
|
|
301
|
+
self._pattern = None
|
|
302
|
+
self._names = None
|
|
303
|
+
|
|
304
|
+
def _reexports(self, module: str, parsed: ParsedSource) -> dict[str, tuple[str, str]]:
|
|
305
|
+
if (exports := self._exports.get(module)) is None:
|
|
306
|
+
exports = self._exports[module] = _imports(parsed, parsed.module or module)[0]
|
|
307
|
+
return exports
|
|
308
|
+
|
|
309
|
+
def get(self, module: str, name: str, _depth: int = 0) -> Helper | None:
|
|
310
|
+
"""The helper ``name`` of ``module``, following names the module re-exports.
|
|
311
|
+
|
|
312
|
+
``name`` may be ``Class.method``; a package ``__init__`` doing
|
|
313
|
+
``from .db import fetch_all`` exposes ``fetch_all`` as ``module.fetch_all``.
|
|
314
|
+
"""
|
|
315
|
+
if (found := self.modules.get(module, {}).get(name)) is not None:
|
|
316
|
+
return found
|
|
317
|
+
if _depth > 8 or (parsed := self.sources.get(module)) is None:
|
|
318
|
+
return None
|
|
319
|
+
exports = self._reexports(module, parsed)
|
|
320
|
+
head, dot, rest = name.partition(".")
|
|
321
|
+
if (target := exports.get(head)) is None:
|
|
322
|
+
return None
|
|
323
|
+
return self.get(target[0], target[1] + dot + rest, _depth + 1)
|
|
324
|
+
|
|
325
|
+
def fragment(self, parsed: ParsedSource, dotted: str) -> tuple[ParsedSource, ast.expr] | None:
|
|
326
|
+
"""The value of ``NAME`` or ``module.NAME`` imported by ``parsed`` from a checked module.
|
|
327
|
+
|
|
328
|
+
Only a module-level name assigned once counts; re-exports are followed.
|
|
329
|
+
"""
|
|
330
|
+
functions, modules = _imports(parsed, parsed.module)
|
|
331
|
+
prefix, _, name = dotted.rpartition(".")
|
|
332
|
+
if not prefix:
|
|
333
|
+
return self._constant(*functions[name]) if name in functions else None
|
|
334
|
+
head, _, rest = prefix.partition(".")
|
|
335
|
+
mod = modules.get(head)
|
|
336
|
+
return self._constant(
|
|
337
|
+
(f"{mod}.{rest}" if rest else mod) if mod is not None else prefix, name
|
|
338
|
+
)
|
|
339
|
+
|
|
340
|
+
def row_type(
|
|
341
|
+
self, parsed: ParsedSource, dotted: str, type_modules: frozenset[str]
|
|
342
|
+
) -> tuple[TypeInfo, dict[str, TypeInfo]] | None:
|
|
343
|
+
"""The row type ``NAME`` or ``module.NAME`` that ``parsed`` imports from a checked module.
|
|
344
|
+
|
|
345
|
+
Returns it with the row types of its module, which its nested types refer to.
|
|
346
|
+
Re-exports are followed; the module is read from its source, never imported.
|
|
347
|
+
"""
|
|
348
|
+
functions, modules = _imports(parsed, parsed.module)
|
|
349
|
+
prefix, _, name = dotted.rpartition(".")
|
|
350
|
+
if not prefix:
|
|
351
|
+
if name not in functions:
|
|
352
|
+
return None
|
|
353
|
+
module, name = functions[name]
|
|
354
|
+
else:
|
|
355
|
+
head, _, rest = prefix.partition(".")
|
|
356
|
+
mod = modules.get(head)
|
|
357
|
+
module = (f"{mod}.{rest}" if rest else mod) if mod is not None else prefix
|
|
358
|
+
return self._row_type(module, name, type_modules)
|
|
359
|
+
|
|
360
|
+
def _row_type(
|
|
361
|
+
self, module: str, name: str, type_modules: frozenset[str], _depth: int = 0
|
|
362
|
+
) -> tuple[TypeInfo, dict[str, TypeInfo]] | None:
|
|
363
|
+
if _depth > 8 or (parsed := self.sources.get(module)) is None:
|
|
364
|
+
return None
|
|
365
|
+
if (defs := self._row_types.get((module, type_modules))) is None:
|
|
366
|
+
from sqlty._type_extractor import extract_type_definitions
|
|
367
|
+
|
|
368
|
+
defs = extract_type_definitions(parsed, self, module, type_modules)
|
|
369
|
+
self._row_types[module, type_modules] = defs
|
|
370
|
+
if name in defs:
|
|
371
|
+
return defs[name], defs
|
|
372
|
+
exports = self._reexports(module, parsed)
|
|
373
|
+
return self._row_type(*exports[name], type_modules, _depth + 1) if name in exports else None
|
|
374
|
+
|
|
375
|
+
def _constant(
|
|
376
|
+
self, module: str, name: str, _depth: int = 0
|
|
377
|
+
) -> tuple[ParsedSource, ast.expr] | None:
|
|
378
|
+
if _depth > 8 or (parsed := self.sources.get(module)) is None:
|
|
379
|
+
return None
|
|
380
|
+
if (value := parsed.constants.get(name)) is not None:
|
|
381
|
+
return parsed, value
|
|
382
|
+
exports = self._reexports(module, parsed)
|
|
383
|
+
return self._constant(*exports[name], _depth + 1) if name in exports else None
|
|
384
|
+
|
|
385
|
+
@property
|
|
386
|
+
def names(self) -> frozenset[str]:
|
|
387
|
+
"""Unqualified names of the indexed helpers, methods included."""
|
|
388
|
+
if self._names is None:
|
|
389
|
+
self._names = frozenset(
|
|
390
|
+
name.rpartition(".")[2] for helpers in self.modules.values() for name in helpers
|
|
391
|
+
)
|
|
392
|
+
return self._names
|
|
393
|
+
|
|
394
|
+
def mentions(self, source: str) -> bool:
|
|
395
|
+
"""Whether ``source`` contains the name of some helper, so it may call one."""
|
|
396
|
+
if self._pattern is None:
|
|
397
|
+
self._pattern = re.compile("|".join(map(re.escape, sorted(self.names))) or r"(?!)")
|
|
398
|
+
return self._pattern.search(source) is not None
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def _imports(
|
|
402
|
+
parsed: ParsedSource, module: str | None
|
|
403
|
+
) -> tuple[dict[str, tuple[str, str]], dict[str, str]]:
|
|
404
|
+
"""Local names bound to imported functions ``(module, name)`` and to modules.
|
|
405
|
+
|
|
406
|
+
Example:
|
|
407
|
+
>>> _imports(ParsedSource("from a.b import f as g\\nimport a.c as m"), None)
|
|
408
|
+
({'g': ('a.b', 'f')}, {'g': 'a.b.f', 'm': 'a.c'})
|
|
409
|
+
"""
|
|
410
|
+
functions: dict[str, tuple[str, str]] = {}
|
|
411
|
+
modules: dict[str, str] = {}
|
|
412
|
+
package = module.rpartition(".")[0] if module else ""
|
|
413
|
+
for node in parsed.imports:
|
|
414
|
+
if isinstance(node, ast.Import):
|
|
415
|
+
for alias in node.names:
|
|
416
|
+
modules[alias.asname or alias.name] = alias.name
|
|
417
|
+
elif isinstance(node, ast.ImportFrom):
|
|
418
|
+
base = node.module or ""
|
|
419
|
+
if node.level:
|
|
420
|
+
if module is None:
|
|
421
|
+
continue
|
|
422
|
+
parts = package.split(".") if package else []
|
|
423
|
+
if node.level - 1 > len(parts):
|
|
424
|
+
continue
|
|
425
|
+
parts = parts[: len(parts) - (node.level - 1)]
|
|
426
|
+
base = ".".join([*parts, *([node.module] if node.module else [])])
|
|
427
|
+
for alias in node.names:
|
|
428
|
+
local = alias.asname or alias.name
|
|
429
|
+
functions[local] = (base, alias.name)
|
|
430
|
+
modules[local] = f"{base}.{alias.name}" if base else alias.name
|
|
431
|
+
return functions, modules
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def _argument(helper: Helper, call: ast.Call, param: str | None) -> ast.expr | None:
|
|
435
|
+
"""The argument of ``call`` bound to ``param``."""
|
|
436
|
+
if param is None:
|
|
437
|
+
return None
|
|
438
|
+
if param in helper.keywords:
|
|
439
|
+
for keyword in call.keywords:
|
|
440
|
+
if keyword.arg == param:
|
|
441
|
+
return keyword.value
|
|
442
|
+
if param in helper.positional:
|
|
443
|
+
index = helper.positional.index(param)
|
|
444
|
+
if any(isinstance(arg, ast.Starred) for arg in call.args[: index + 1]):
|
|
445
|
+
return None
|
|
446
|
+
if index < len(call.args):
|
|
447
|
+
return call.args[index]
|
|
448
|
+
return None
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def _call_params(
|
|
452
|
+
helper: Helper, call: ast.Call, parsed: ParsedSource
|
|
453
|
+
) -> tuple[ParamArg, ...] | None:
|
|
454
|
+
"""The arguments ``call`` passes for the placeholders of its query, or ``None`` when not spelled out.
|
|
455
|
+
|
|
456
|
+
A helper takes them as a ``params`` argument (a tuple or list literal, or a dict literal
|
|
457
|
+
of string keys), as ``*args``, or as ``**params``.
|
|
458
|
+
"""
|
|
459
|
+
stack = parsed.scopes_of(call)
|
|
460
|
+
|
|
461
|
+
def typed(key: int | str, value: ast.expr) -> ParamArg:
|
|
462
|
+
return ParamArg(key, arg_type(value, parsed, stack))
|
|
463
|
+
|
|
464
|
+
if helper.params is not None:
|
|
465
|
+
arg = _argument(helper, call, helper.params)
|
|
466
|
+
return literal_params(arg, parsed, stack)
|
|
467
|
+
if helper.rest is not None:
|
|
468
|
+
if any(isinstance(arg, ast.Starred) for arg in call.args):
|
|
469
|
+
return None
|
|
470
|
+
return tuple(typed(i, arg) for i, arg in enumerate(call.args[len(helper.positional) :], 1))
|
|
471
|
+
if helper.named is not None:
|
|
472
|
+
if any(keyword.arg is None for keyword in call.keywords):
|
|
473
|
+
return None
|
|
474
|
+
return tuple(
|
|
475
|
+
typed(keyword.arg, keyword.value)
|
|
476
|
+
for keyword in call.keywords
|
|
477
|
+
if keyword.arg is not None and keyword.arg not in helper.keywords
|
|
478
|
+
)
|
|
479
|
+
return None
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def find_helper_calls(
|
|
483
|
+
source: str | ParsedSource, helpers: HelperIndex | None = None, module: str | None = None
|
|
484
|
+
) -> list[HelperCall]:
|
|
485
|
+
"""Calls passing a string literal to a marked query parameter.
|
|
486
|
+
|
|
487
|
+
Helpers defined in ``source`` count, and so do those of ``helpers`` that
|
|
488
|
+
``source`` imports (``module`` is its name, for relative imports).
|
|
489
|
+
|
|
490
|
+
Example:
|
|
491
|
+
>>> src = '''
|
|
492
|
+
... from typing import Annotated
|
|
493
|
+
... from sqlty import SQL
|
|
494
|
+
... def run[T](q: Annotated[str, SQL], t: type[T]) -> T: ...
|
|
495
|
+
... run("SELECT 1", int)
|
|
496
|
+
... '''
|
|
497
|
+
>>> [(c.line, c.query) for c in find_helper_calls(src)]
|
|
498
|
+
[(5, 'SELECT 1')]
|
|
499
|
+
"""
|
|
500
|
+
parsed = ParsedSource.of(source, module)
|
|
501
|
+
local = parsed.may_define_helpers
|
|
502
|
+
imported = helpers is not None and bool(helpers.modules) and helpers.mentions(parsed.text)
|
|
503
|
+
composed = "psycopg" in parsed.text
|
|
504
|
+
if not (local or imported):
|
|
505
|
+
return []
|
|
506
|
+
own = index_functions(parsed) if local else {}
|
|
507
|
+
if not own and not imported:
|
|
508
|
+
return []
|
|
509
|
+
functions, modules = (
|
|
510
|
+
_imports(parsed, module if module is not None else parsed.module) if imported else ({}, {})
|
|
511
|
+
)
|
|
512
|
+
|
|
513
|
+
def lookup(module_name: str, name: str) -> Helper | None:
|
|
514
|
+
return helpers.get(module_name, name) if helpers is not None else None
|
|
515
|
+
|
|
516
|
+
def module_of(prefix: str) -> str:
|
|
517
|
+
head, _, rest = prefix.partition(".")
|
|
518
|
+
mod = modules.get(head)
|
|
519
|
+
return (f"{mod}.{rest}" if rest else mod) if mod is not None else prefix
|
|
520
|
+
|
|
521
|
+
def method_of(cls: str, name: str) -> Helper | None:
|
|
522
|
+
"""The method ``name`` of the class spelled ``cls`` in this file."""
|
|
523
|
+
prefix, _, cls_name = cls.rpartition(".")
|
|
524
|
+
if prefix:
|
|
525
|
+
return lookup(module_of(prefix), f"{cls_name}.{name}")
|
|
526
|
+
if (found := own.get(f"{cls}.{name}")) is not None:
|
|
527
|
+
return found
|
|
528
|
+
if cls in functions:
|
|
529
|
+
module_name, original = functions[cls]
|
|
530
|
+
return lookup(module_name, f"{original}.{name}")
|
|
531
|
+
return None
|
|
532
|
+
|
|
533
|
+
def resolve(call: ast.Call) -> Helper | None:
|
|
534
|
+
func = call.func
|
|
535
|
+
if isinstance(func, ast.Name):
|
|
536
|
+
if func.id in own:
|
|
537
|
+
return own[func.id]
|
|
538
|
+
if func.id in functions:
|
|
539
|
+
return lookup(*functions[func.id])
|
|
540
|
+
elif isinstance(func, ast.Attribute) and (prefix := _dotted(func.value)):
|
|
541
|
+
if (found := lookup(module_of(prefix), func.attr)) is not None:
|
|
542
|
+
return found
|
|
543
|
+
if (found := method_of(prefix, func.attr)) is not None:
|
|
544
|
+
return found if found.kind != "instance" else None
|
|
545
|
+
if (cls := receiver_class(call, func.value)) is not None:
|
|
546
|
+
return method_of(cls, func.attr)
|
|
547
|
+
return None
|
|
548
|
+
|
|
549
|
+
def receiver_class(call: ast.Call, receiver: ast.expr) -> str | None:
|
|
550
|
+
"""The class of ``self``, or of a variable or ``self`` attribute with an evident type."""
|
|
551
|
+
stack = parsed.scopes_of(call)
|
|
552
|
+
base = receiver.value if isinstance(receiver, ast.Attribute) else receiver
|
|
553
|
+
if not isinstance(base, ast.Name):
|
|
554
|
+
return None
|
|
555
|
+
for outer, inner in zip(reversed(stack[:-1]), reversed(stack[1:]), strict=True):
|
|
556
|
+
if (
|
|
557
|
+
isinstance(outer, ast.ClassDef)
|
|
558
|
+
and not isinstance(inner, ast.ClassDef)
|
|
559
|
+
and inner.args.args
|
|
560
|
+
and inner.args.args[0].arg == base.id
|
|
561
|
+
and _kind(inner) != "static"
|
|
562
|
+
):
|
|
563
|
+
if isinstance(receiver, ast.Attribute):
|
|
564
|
+
return parsed.type_of(stack, receiver.attr, attribute=True)
|
|
565
|
+
return outer.name
|
|
566
|
+
return parsed.type_of(stack, base.id) if base is receiver else None
|
|
567
|
+
|
|
568
|
+
def resolve_fragment(source: ParsedSource, dotted: str) -> tuple[ParsedSource, ast.expr] | None:
|
|
569
|
+
if helpers is None:
|
|
570
|
+
return None
|
|
571
|
+
if source.module is None:
|
|
572
|
+
source.module = module
|
|
573
|
+
return helpers.fragment(source, dotted)
|
|
574
|
+
|
|
575
|
+
aliases = parsed.typing_aliases
|
|
576
|
+
calls = []
|
|
577
|
+
scan = parsed.psycopg if composed else None
|
|
578
|
+
pending: list[tuple[ast.Call, Helper, ast.expr]] = []
|
|
579
|
+
names = {name.rpartition(".")[2] for name in own}
|
|
580
|
+
if helpers is not None and imported:
|
|
581
|
+
names |= helpers.names
|
|
582
|
+
names |= {local for local, (_, original) in functions.items() if original in names}
|
|
583
|
+
pattern = re.compile(rf"\b(?:{'|'.join(map(re.escape, sorted(names)))})\b")
|
|
584
|
+
for node in parsed.calls_to(pattern):
|
|
585
|
+
if (helper := resolve(node)) is None:
|
|
586
|
+
continue
|
|
587
|
+
query = _argument(helper, node, helper.query)
|
|
588
|
+
if isinstance(query, ast.Constant) and isinstance(query.value, str):
|
|
589
|
+
calls.append(
|
|
590
|
+
HelperCall(
|
|
591
|
+
node.lineno,
|
|
592
|
+
query.value,
|
|
593
|
+
_argument(helper, node, helper.row),
|
|
594
|
+
aliases,
|
|
595
|
+
_call_params(helper, node, parsed),
|
|
596
|
+
)
|
|
597
|
+
)
|
|
598
|
+
elif scan is not None and query is not None:
|
|
599
|
+
pending.append((node, helper, query))
|
|
600
|
+
for node, helper, query in pending:
|
|
601
|
+
assert scan is not None
|
|
602
|
+
if (text := scan.render(query, resolve_fragment)) is not None:
|
|
603
|
+
row = _argument(helper, node, helper.row)
|
|
604
|
+
calls.append(
|
|
605
|
+
HelperCall(
|
|
606
|
+
node.lineno,
|
|
607
|
+
None if text == UNCHECKED else text,
|
|
608
|
+
row,
|
|
609
|
+
aliases,
|
|
610
|
+
_call_params(helper, node, parsed),
|
|
611
|
+
)
|
|
612
|
+
)
|
|
613
|
+
return sorted(calls, key=lambda call: call.line)
|