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.
Files changed (71) hide show
  1. sqlty/__init__.py +99 -0
  2. sqlty/__main__.py +5 -0
  3. sqlty/_breaking.py +191 -0
  4. sqlty/_check.py +880 -0
  5. sqlty/_cli.py +1219 -0
  6. sqlty/_config.py +666 -0
  7. sqlty/_core.cp315-win_amd64.pyd +0 -0
  8. sqlty/_core.pyi +108 -0
  9. sqlty/_decode.py +62 -0
  10. sqlty/_drivers.py +274 -0
  11. sqlty/_gitignore.py +58 -0
  12. sqlty/_helpers.py +613 -0
  13. sqlty/_json_shape.py +299 -0
  14. sqlty/_json_types.py +225 -0
  15. sqlty/_lint.py +350 -0
  16. sqlty/_params.py +177 -0
  17. sqlty/_psycopg.py +269 -0
  18. sqlty/_source.py +654 -0
  19. sqlty/_type_extractor/__init__.py +51 -0
  20. sqlty/_type_extractor/ast_fields.py +823 -0
  21. sqlty/_type_extractor/compat.py +252 -0
  22. sqlty/_type_extractor/extract.py +179 -0
  23. sqlty/_type_extractor/generic.py +95 -0
  24. sqlty/_type_extractor/info.py +161 -0
  25. sqlty/_type_extractor/sandbox.py +385 -0
  26. sqlty/_type_extractor/subtype.py +156 -0
  27. sqlty/_widening.py +89 -0
  28. sqlty/core.py +566 -0
  29. sqlty/drivers/psycopg.py +104 -0
  30. sqlty/magic.py +126 -0
  31. sqlty/py.typed +0 -0
  32. sqlty/rules/ambiguous-column.md +48 -0
  33. sqlty/rules/column-count-mismatch.md +30 -0
  34. sqlty/rules/column-name-mismatch.md +34 -0
  35. sqlty/rules/column-type-mismatch.md +75 -0
  36. sqlty/rules/fstring-skipped.md +23 -0
  37. sqlty/rules/inline-sql-comment.md +27 -0
  38. sqlty/rules/insert-missing-column.md +58 -0
  39. sqlty/rules/json-shape-mismatch.md +96 -0
  40. sqlty/rules/literal-mismatch.md +83 -0
  41. sqlty/rules/mysql-sql-marker.md +32 -0
  42. sqlty/rules/nullable-mismatch.md +76 -0
  43. sqlty/rules/param-count-mismatch.md +66 -0
  44. sqlty/rules/param-type-mismatch.md +73 -0
  45. sqlty/rules/redundant-literal.md +68 -0
  46. sqlty/rules/redundant-optional.md +100 -0
  47. sqlty/rules/select-star-no-schema.md +24 -0
  48. sqlty/rules/select-star.md +77 -0
  49. sqlty/rules/stale-rewrite.md +33 -0
  50. sqlty/rules/stale-type.md +50 -0
  51. sqlty/rules/tstring-skipped.md +68 -0
  52. sqlty/rules/typeddict-inheritance.md +35 -0
  53. sqlty/rules/typeddict-key-mismatch.md +38 -0
  54. sqlty/rules/unchecked-query.md +34 -0
  55. sqlty/rules/ungrouped-column.md +67 -0
  56. sqlty/rules/unknown-column.md +68 -0
  57. sqlty/rules/unknown-function.md +49 -0
  58. sqlty/rules/unknown-table.md +47 -0
  59. sqlty/rules/unknown-type.md +74 -0
  60. sqlty/rules/unparsed-query.md +46 -0
  61. sqlty/rules/unsupported-syntax.md +69 -0
  62. sqlty/rules/untyped-query.md +39 -0
  63. sqlty/rules/unused-ignore.md +36 -0
  64. sqlty/skill/SKILL.md +110 -0
  65. sqlty-0.1.0.dist-info/METADATA +210 -0
  66. sqlty-0.1.0.dist-info/RECORD +71 -0
  67. sqlty-0.1.0.dist-info/WHEEL +4 -0
  68. sqlty-0.1.0.dist-info/entry_points.txt +2 -0
  69. sqlty-0.1.0.dist-info/licenses/LICENSE +21 -0
  70. sqlty-0.1.0.dist-info/sboms/sqlty-core.cyclonedx.json +1891 -0
  71. sqlty_magic.pth +1 -0
sqlty/_source.py ADDED
@@ -0,0 +1,654 @@
1
+ """One Python source file, parsed and walked at most once.
2
+
3
+ Every check that needs the syntax tree of a file (helper indexing, helper
4
+ call sites, user-defined row types, ``# sqlty: ignore`` comments) reads it from
5
+ a ``ParsedSource`` instead of calling ``ast.parse`` / ``tokenize`` itself, so a
6
+ file costs one parse and one walk however many checks look at it.
7
+
8
+ Usage:
9
+ parsed = ParsedSource(text, module="pkg.mod")
10
+ parsed.tree # ast.Module, parsed on first access; None on a syntax error
11
+ parsed.imports # every Import / ImportFrom node
12
+ parsed.classes # every ClassDef node
13
+ parsed.calls # every Call node
14
+ parsed.calls_to(names) # Call nodes, skipping bodies whose source never matches ``names``
15
+ parsed.typing_aliases # local names of typing members: {'t': 'typing', 'A': 'Any'}
16
+ parsed.imported_names # absolute imports, local name to dotted name: {'D': 'decimal.Decimal'}
17
+ parsed.ignores # {line: _Ignore} for "# sqlty: ignore" comments
18
+
19
+ Pass the object wherever a function takes ``source: str | ParsedSource``
20
+ (``check_source``, ``HelperIndex.add``, ``find_helper_calls``,
21
+ ``extract_type_definitions``); a plain ``str`` is wrapped with
22
+ ``ParsedSource.of``. Build one per file and reuse it; never call
23
+ ``ast.parse(parsed.text)``. Nothing is parsed until a property that needs the
24
+ tree is read: guard with the cheap ``text`` checks (``may_define_helpers``,
25
+ ``has_ignore_comments``) first. ``imports``, ``classes`` and ``calls`` come
26
+ from one walk, in ``ast.walk`` order (breadth first): statements first, and the
27
+ expressions of a body once ``calls_to`` needs them.
28
+ Module-level statements are ``tree.body``; ``functions`` lists the module-level
29
+ function definitions.
30
+
31
+ Example:
32
+ >>> parsed = ParsedSource("import typing as t\\nclass A: ...\\nf(A)")
33
+ >>> parsed.typing_aliases, [c.name for c in parsed.classes], len(parsed.calls)
34
+ ({'t': 'typing'}, ['A'], 1)
35
+ >>> ParsedSource("x = 1").may_define_helpers
36
+ False
37
+ """
38
+
39
+ from __future__ import annotations
40
+
41
+ import ast
42
+ import functools
43
+ import io
44
+ import itertools
45
+ import re
46
+ import tokenize
47
+ import typing
48
+ from dataclasses import dataclass
49
+
50
+ from sqlty._psycopg import PsycopgScan
51
+
52
+ _TYPING_MODULES = frozenset({"typing", "typing_extensions"})
53
+ # A comment runs to the end of its line, so the gap can split text only one way.
54
+ _GAP = r"(?:[\s\"'rRuU]|#[^\n]*(?![^\n]))*"
55
+ _MARKER_RE = re.compile(rf"-{_GAP}-{_GAP}s{_GAP}q{_GAP}l", re.IGNORECASE)
56
+ _IGNORE_RE = re.compile(r"#\s*sqlty:\s*ignore\b(?:\[([^\]]*)\])?")
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class _Ignore:
61
+ """A ``# sqlty: ignore`` comment; ``rules`` is ``None`` for a bare one."""
62
+
63
+ line: int
64
+ rules: tuple[str, ...] | None
65
+
66
+
67
+ def is_any(node: ast.expr, aliases: dict[str, str]) -> bool:
68
+ """Whether ``node`` is ``typing.Any``, quoted or in ``Annotated`` too.
69
+
70
+ ``aliases`` is ``ParsedSource.typing_aliases``, so a bare ``Any`` that was
71
+ not imported from ``typing`` is not one.
72
+
73
+ Example:
74
+ >>> aliases = ParsedSource("import typing as t\\nfrom typing import Any as A").typing_aliases
75
+ >>> [is_any(ast.parse(s, mode="eval").body, aliases) for s in ("A", "t.Any", "'A'", "t.Annotated[A, 1]", "Any")]
76
+ [True, True, True, True, False]
77
+ """
78
+ if isinstance(node, ast.Constant) and isinstance(node.value, str):
79
+ try:
80
+ node = ast.parse(node.value, mode="eval").body
81
+ except SyntaxError, ValueError:
82
+ return False
83
+ if (
84
+ isinstance(node, ast.Subscript)
85
+ and _typing_name(node.value, aliases) == "Annotated"
86
+ and isinstance(node.slice, ast.Tuple)
87
+ ):
88
+ return is_any(node.slice.elts[0], aliases)
89
+ return _typing_name(node, aliases) == "Any"
90
+
91
+
92
+ def _typing_name(node: ast.expr, aliases: dict[str, str]) -> str | None:
93
+ """The ``typing`` member ``node`` names, if any."""
94
+ if isinstance(node, ast.Name):
95
+ return aliases.get(node.id)
96
+ if (
97
+ isinstance(node, ast.Attribute)
98
+ and isinstance(node.value, ast.Name)
99
+ and aliases.get(node.value.id) in _TYPING_MODULES
100
+ ):
101
+ return node.attr
102
+ return None
103
+
104
+
105
+ def _wrapper_name(import_style: str | None) -> str | None:
106
+ """How the engine spells the wrapper for ``import_style``; ``None`` when it rejects it."""
107
+ style = (import_style or "").strip()
108
+ if style in ("", "from sqlty import SQL"):
109
+ return "SQL"
110
+ if style == "import sqlty":
111
+ return "sqlty.SQL"
112
+ for prefix, suffix in (("from sqlty import SQL as ", ""), ("import sqlty as ", ".SQL")):
113
+ if style.startswith(prefix):
114
+ return style[len(prefix) :].strip() + suffix
115
+ return None
116
+
117
+
118
+ _LEAVES = (ast.expr_context, ast.operator, ast.unaryop, ast.cmpop, ast.boolop)
119
+ _STATEMENTS = (ast.mod, ast.stmt, ast.excepthandler, ast.match_case)
120
+ _SCOPE_TYPES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)
121
+ _FIELDS: dict[type, tuple[str, ...]] = {}
122
+
123
+
124
+ def _holds_nodes(kind: object) -> bool:
125
+ """Whether a field annotated ``kind`` can hold a node worth visiting."""
126
+ if isinstance(kind, type):
127
+ return issubclass(kind, ast.AST) and not issubclass(kind, _LEAVES)
128
+ return any(_holds_nodes(arg) for arg in typing.get_args(kind))
129
+
130
+
131
+ def _fields(cls: type) -> tuple[str, ...]:
132
+ """The fields of node type ``cls`` that can hold child nodes; ``ctx`` and operators never do."""
133
+ found = _FIELDS.get(cls)
134
+ if found is None:
135
+ types = getattr(cls, "_field_types", {})
136
+ found = _FIELDS[cls] = tuple(name for name, kind in types.items() if _holds_nodes(kind))
137
+ return found
138
+
139
+
140
+ class _Scan:
141
+ """Collects the nodes consumers need in one traversal, in depth-first pre-order with depths.
142
+
143
+ Children are pushed on an explicit stack; leaf nodes that cannot hold or be one of the
144
+ collected nodes (names, constants, ``ctx``, operators) are never visited. ``visit`` walks
145
+ statements only and leaves their expressions in ``deferred`` for ``expand``, which walks
146
+ those of the bodies that may hold a wanted call; with ``bindings`` it walks everything.
147
+ """
148
+
149
+ def __init__(self, bindings: bool = False) -> None:
150
+ self.imports: list[tuple[int, ast.Import | ast.ImportFrom]] = []
151
+ self.classes: list[tuple[int, ast.ClassDef]] = []
152
+ self.calls: list[tuple[int, ast.Call]] = []
153
+ self.bindings = bindings
154
+ self.scopes: list[ast.FunctionDef | ast.AsyncFunctionDef | ast.Lambda | ast.ClassDef] = []
155
+ self.stores: dict[str, list[ast.Name]] = {}
156
+ self.values: dict[int, ast.expr] = {}
157
+ self.stacks: dict[int, _Stack] = {}
158
+ self.types: dict[tuple[int | None, str], str | None] = {}
159
+ self.deferred: list[tuple[ast.AST, int, _Stack]] = []
160
+ self.visited = 0
161
+ self._stack: _Stack = ()
162
+
163
+ def visit(self, tree: ast.AST) -> None:
164
+ self._walk([(tree, 0, ())], defer=not self.bindings)
165
+
166
+ def expand(self, wanted: typing.Callable[[_Stack], bool]) -> None:
167
+ """Walk the deferred expressions whose enclosing scopes are ``wanted``."""
168
+ roots: list[tuple[ast.AST, int, _Stack]] = []
169
+ rest: list[tuple[ast.AST, int, _Stack]] = []
170
+ known: dict[int, bool] = {}
171
+ for root in self.deferred:
172
+ stack = root[2]
173
+ if (found := known.get(id(stack))) is None:
174
+ found = known[id(stack)] = wanted(stack)
175
+ (roots if found else rest).append(root)
176
+ self.deferred = rest
177
+ self._walk(roots[::-1], defer=False)
178
+
179
+ def _walk(self, todo: list[tuple[ast.AST, int, _Stack]], defer: bool) -> None:
180
+ pop, push = todo.pop, todo.append
181
+ bindings = self.bindings
182
+ while todo:
183
+ node, depth, stack = pop()
184
+ if defer and not isinstance(node, _STATEMENTS):
185
+ self.deferred.append((node, depth, stack))
186
+ continue
187
+ self.visited += 1
188
+ self._stack = stack
189
+ if isinstance(node, _SCOPE_TYPES):
190
+ if isinstance(node, ast.ClassDef):
191
+ self.classes.append((depth, node))
192
+ else:
193
+ self._parameters(node)
194
+ if bindings:
195
+ self.scopes.append(node)
196
+ stack = (*stack, node)
197
+ elif isinstance(node, ast.Call):
198
+ self.calls.append((depth, node))
199
+ self.stacks[id(node)] = stack
200
+ elif isinstance(node, (ast.Assign, ast.AnnAssign)):
201
+ self._typed(node)
202
+ if bindings:
203
+ self._bind(node)
204
+ elif isinstance(node, (ast.Import, ast.ImportFrom)):
205
+ self.imports.append((depth, node))
206
+ continue
207
+ elif bindings:
208
+ self._bind(node)
209
+ children: list[ast.AST] = []
210
+ for name in _FIELDS.get(type(node)) or _fields(type(node)):
211
+ value = getattr(node, name)
212
+ if type(value) is list:
213
+ children += value
214
+ elif value is not None:
215
+ children.append(value)
216
+ depth += 1
217
+ for child in reversed(children):
218
+ if child is not None and (bindings or _FIELDS.get(type(child)) != ()):
219
+ push((child, depth, stack))
220
+
221
+ def _note(self, key: tuple[int | None, str], type_name: str | None) -> None:
222
+ """Remember the class a name or ``self`` attribute holds; ``None`` once it is ambiguous."""
223
+ known = self.types.get(key, type_name)
224
+ self.types[key] = type_name if known == type_name else None
225
+
226
+ def _parameters(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None:
227
+ args = node.args
228
+ for arg in [*args.posonlyargs, *args.args, *args.kwonlyargs]:
229
+ self._note((id(node), arg.arg), _class_name(arg.annotation))
230
+
231
+ def _typed(self, node: ast.Assign | ast.AnnAssign) -> None:
232
+ """Record ``name = Cls(...)`` and ``name: Cls`` in the current scope.
233
+
234
+ Also ``self.attr`` the same way inside a method, keyed by the class.
235
+ """
236
+ if isinstance(node, ast.Assign):
237
+ targets = node.targets
238
+ type_name = _class_name(node.value.func) if isinstance(node.value, ast.Call) else None
239
+ else:
240
+ targets = [node.target]
241
+ type_name = _class_name(node.annotation)
242
+ if type_name is None and isinstance(node.value, ast.Call):
243
+ type_name = _class_name(node.value.func)
244
+ scope = self._stack[-1] if self._stack else None
245
+ for target in targets:
246
+ if isinstance(target, ast.Name):
247
+ self._note((id(scope) if scope is not None else None, target.id), type_name)
248
+ elif (
249
+ isinstance(target, ast.Attribute)
250
+ and isinstance(target.value, ast.Name)
251
+ and len(self._stack) > 1
252
+ and isinstance(self._stack[-2], ast.ClassDef)
253
+ and isinstance(scope, (ast.FunctionDef, ast.AsyncFunctionDef))
254
+ and scope.args.args
255
+ and scope.args.args[0].arg == target.value.id
256
+ ):
257
+ self._note((id(self._stack[-2]), f".{target.attr}"), type_name)
258
+
259
+ def _bind(self, node: ast.AST) -> None:
260
+ """Record what binds a name or opens a scope, for the psycopg composition scan."""
261
+ if isinstance(node, ast.Name):
262
+ if isinstance(node.ctx, ast.Store):
263
+ self.stores.setdefault(node.id, []).append(node)
264
+ elif isinstance(node, ast.Assign):
265
+ if len(node.targets) == 1 and isinstance(node.targets[0], ast.Name):
266
+ self.values[id(node.targets[0])] = node.value
267
+ elif isinstance(node, ast.AnnAssign):
268
+ if isinstance(node.target, ast.Name) and node.value is not None:
269
+ self.values[id(node.target)] = node.value
270
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda, ast.ClassDef)):
271
+ self.scopes.append(node)
272
+
273
+
274
+ _Stack = tuple[ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef, ...]
275
+
276
+
277
+ def _class_name(node: ast.expr | None) -> str | None:
278
+ """The dotted name an annotation or a called expression spells, if it is a plain one.
279
+
280
+ Example:
281
+ >>> _class_name(ast.parse("m.Db", mode="eval").body)
282
+ 'm.Db'
283
+ >>> _class_name(ast.Constant("Db"))
284
+ 'Db'
285
+ """
286
+ if isinstance(node, ast.Constant) and isinstance(node.value, str):
287
+ text = node.value.strip()
288
+ return text if re.fullmatch(r"[A-Za-z_]\w*(\.[A-Za-z_]\w*)*", text) else None
289
+ parts: list[str] = []
290
+ while isinstance(node, ast.Attribute):
291
+ parts.append(node.attr)
292
+ node = node.value
293
+ if isinstance(node, ast.Name):
294
+ return ".".join([node.id, *reversed(parts)])
295
+ return None
296
+
297
+
298
+ def _breadth_first[T](found: list[tuple[int, T]]) -> list[T]:
299
+ """Depth-first pre-order nodes in breadth-first order (stable per depth)."""
300
+ return [node for _, node in sorted(found, key=lambda item: item[0])]
301
+
302
+
303
+ class ParsedSource:
304
+ """Source text with its lazily parsed, cached syntax tree and facts.
305
+
306
+ ``module`` is the dotted name of the file, used to resolve relative imports.
307
+ """
308
+
309
+ def __init__(self, text: str, module: str | None = None) -> None:
310
+ self.text = text
311
+ self.module = module
312
+
313
+ @classmethod
314
+ def of(cls, source: str | ParsedSource, module: str | None = None) -> ParsedSource:
315
+ """``source`` itself when it is already parsed, else a new ``ParsedSource``."""
316
+ return source if isinstance(source, ParsedSource) else cls(source, module)
317
+
318
+ @functools.cached_property
319
+ def tree(self) -> ast.Module | None:
320
+ """The module, or ``None`` when the text is not valid Python."""
321
+ try:
322
+ return ast.parse(self.text)
323
+ except SyntaxError, ValueError:
324
+ return None
325
+
326
+ @functools.cached_property
327
+ def _scan(self) -> _Scan:
328
+ scan = _Scan(bindings="psycopg" in self.text)
329
+ if self.tree is not None:
330
+ scan.visit(self.tree)
331
+ return scan
332
+
333
+ @functools.cached_property
334
+ def imports(self) -> list[ast.Import | ast.ImportFrom]:
335
+ """Every import statement, at any depth."""
336
+ return _breadth_first(self._scan.imports)
337
+
338
+ @functools.cached_property
339
+ def classes(self) -> list[ast.ClassDef]:
340
+ """Every class definition, at any depth."""
341
+ return _breadth_first(self._scan.classes)
342
+
343
+ @property
344
+ def calls(self) -> list[ast.Call]:
345
+ """Every call expression."""
346
+ return self.calls_to(None)
347
+
348
+ def calls_to(self, names: re.Pattern[str] | None) -> list[ast.Call]:
349
+ """Every call, except in function and class bodies whose source never matches ``names``.
350
+
351
+ Example:
352
+ >>> parsed = ParsedSource("def f():\\n g(1)\\ndef h():\\n k(2)\\nk(3)")
353
+ >>> [ast.unparse(c) for c in parsed.calls_to(re.compile(r"\\bg\\b"))]
354
+ ['k(3)', 'g(1)']
355
+ """
356
+ scan = self._scan
357
+ if scan.deferred:
358
+ scan.expand(lambda stack: names is None or self._mentions(stack, names))
359
+ return _breadth_first(scan.calls)
360
+
361
+ def _mentions(self, stack: _Stack, names: re.Pattern[str]) -> bool:
362
+ """Whether the source of the innermost scope of ``stack`` (decorators included) matches."""
363
+ if not stack:
364
+ return True
365
+ scope = stack[-1]
366
+ lines = self._lines
367
+ first = scope.decorator_list[0].lineno if scope.decorator_list else scope.lineno
368
+ end = lines[scope.end_lineno] if scope.end_lineno is not None else len(self.text)
369
+ return names.search(self.text, lines[first - 1], end) is not None
370
+
371
+ def segment(self, node: ast.expr) -> str | None:
372
+ """The source of ``node``; ``None`` unless the text is ASCII (offsets count UTF-8 bytes).
373
+
374
+ Example:
375
+ >>> parsed = ParsedSource("f(tuple[int, str])")
376
+ >>> parsed.segment(parsed.calls[0].args[0])
377
+ 'tuple[int, str]'
378
+ """
379
+ if not self._ascii or node.end_lineno is None or node.end_col_offset is None:
380
+ return None
381
+ lines = self._lines
382
+ start = lines[node.lineno - 1] + node.col_offset
383
+ return self.text[start : lines[node.end_lineno - 1] + node.end_col_offset]
384
+
385
+ @functools.cached_property
386
+ def _ascii(self) -> bool:
387
+ return self.text.isascii()
388
+
389
+ @functools.cached_property
390
+ def _lines(self) -> list[int]:
391
+ """Offset of each line start, and the text length after the last line."""
392
+ return [0, *(m.end() for m in re.finditer(r"\r\n?|\n", self.text)), len(self.text)]
393
+
394
+ @functools.cached_property
395
+ def psycopg(self) -> PsycopgScan:
396
+ """What ``psycopg.sql`` compositions need: imports, scopes and single assignments.
397
+
398
+ Collected in the same pass as ``imports``, and only when the text mentions ``psycopg``.
399
+ """
400
+ scan = self._scan
401
+ return PsycopgScan(self.imports, scan.scopes, scan.stores, scan.values, self)
402
+
403
+ @functools.cached_property
404
+ def constants(self) -> dict[str, ast.expr | None]:
405
+ """Module-level names to the value of their one assignment.
406
+
407
+ A name bound more than once, or by an import, ``def``, ``class`` or augmented
408
+ assignment, maps to ``None``. Only top-level statements are read.
409
+
410
+ Example:
411
+ >>> sorted(ParsedSource("A = 'x'\\nB = 1\\nB = 2\\ndef C(): ...").constants)
412
+ ['A', 'B', 'C']
413
+ >>> ParsedSource("A = 'x'\\nB = 1\\nB = 2").constants['B'] is None
414
+ True
415
+ """
416
+ found: dict[str, ast.expr | None] = {}
417
+ for node in self.tree.body if self.tree is not None else []:
418
+ bound: dict[str, ast.expr | None] = {}
419
+ if isinstance(node, ast.Assign) and all(isinstance(t, ast.Name) for t in node.targets):
420
+ bound = {t.id: node.value for t in node.targets if isinstance(t, ast.Name)}
421
+ elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
422
+ bound = {node.target.id: node.value}
423
+ elif isinstance(node, ast.AugAssign) and isinstance(node.target, ast.Name):
424
+ bound = {node.target.id: None}
425
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
426
+ bound = {node.name: None}
427
+ elif isinstance(node, (ast.Import, ast.ImportFrom)):
428
+ bound = {(a.asname or a.name).partition(".")[0]: None for a in node.names}
429
+ for name, value in bound.items():
430
+ found[name] = None if name in found else value
431
+ return found
432
+
433
+ @functools.cached_property
434
+ def functions(self) -> list[ast.FunctionDef | ast.AsyncFunctionDef]:
435
+ """Module-level function definitions."""
436
+ body = self.tree.body if self.tree is not None else []
437
+ return [n for n in body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))]
438
+
439
+ @functools.cached_property
440
+ def methods(self) -> list[tuple[ast.ClassDef, ast.FunctionDef | ast.AsyncFunctionDef]]:
441
+ """Functions defined directly in a class body, with their class."""
442
+ return [
443
+ (cls, node)
444
+ for cls in self.classes
445
+ for node in cls.body
446
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
447
+ ]
448
+
449
+ def scopes_of(self, call: ast.Call) -> _Stack:
450
+ """The functions and classes enclosing ``call``, outermost first."""
451
+ return self._scan.stacks.get(id(call), ())
452
+
453
+ def type_of(self, stack: _Stack, name: str, attribute: bool = False) -> str | None:
454
+ """The class a variable holds, from ``name = Cls(...)`` or ``name: Cls`` in scope.
455
+
456
+ ``stack`` is ``scopes_of(call)``. With ``attribute``, ``name`` is an attribute of
457
+ ``self`` and the class of the innermost enclosing method is searched instead.
458
+ """
459
+ types = self._scan.types
460
+ if attribute:
461
+ cls = next((s for s in reversed(stack) if isinstance(s, ast.ClassDef)), None)
462
+ return types.get((id(cls), f".{name}")) if cls is not None else None
463
+ for scope in [*(s for s in reversed(stack) if not isinstance(s, ast.ClassDef)), None]:
464
+ key = (id(scope) if scope is not None else None, name)
465
+ if key in types:
466
+ return types[key]
467
+ return None
468
+
469
+ @functools.cached_property
470
+ def typing_aliases(self) -> dict[str, str]:
471
+ """Local names for ``typing`` / ``typing_extensions`` and their members, to originals."""
472
+ aliases: dict[str, str] = {}
473
+ for node in self.imports:
474
+ if isinstance(node, ast.ImportFrom):
475
+ if node.module in _TYPING_MODULES:
476
+ aliases |= {a.asname or a.name: a.name for a in node.names}
477
+ else:
478
+ aliases |= {
479
+ a.asname or a.name: a.name for a in node.names if a.name in _TYPING_MODULES
480
+ }
481
+ return aliases
482
+
483
+ @functools.cached_property
484
+ def type_aliases(self) -> dict[str, ast.expr]:
485
+ """Module-level aliases of row types: ``type Row = ...``, ``Row: TypeAlias = ...``, and
486
+ ``Row = tuple[...]`` or ``Row = OtherRow``; a generic alias is left out.
487
+
488
+ Example:
489
+ >>> aliases = ParsedSource("type A = tuple[int]\\nB = A\\nC = 1").type_aliases
490
+ >>> {name: ast.unparse(value) for name, value in aliases.items()}
491
+ {'A': 'tuple[int]', 'B': 'A'}
492
+ """
493
+ if self.tree is None:
494
+ return {}
495
+ aliases: dict[str, ast.expr] = {}
496
+ for node in self.tree.body:
497
+ match node:
498
+ case ast.TypeAlias(name=ast.Name(id=name), type_params=[], value=value):
499
+ aliases[name] = value
500
+ case ast.AnnAssign(target=ast.Name(id=name), annotation=hint, value=value) if (
501
+ value is not None and _typing_name(hint, self.typing_aliases) == "TypeAlias"
502
+ ):
503
+ aliases[name] = value
504
+ case ast.Assign(targets=[ast.Name(id=name)], value=value) if isinstance(
505
+ value, ast.Subscript | ast.Name | ast.Attribute
506
+ ) and (
507
+ not isinstance(value, ast.Subscript)
508
+ or ast.unparse(value.value) in ("tuple", "typing.Tuple", "Tuple")
509
+ ):
510
+ aliases[name] = value
511
+ return aliases
512
+
513
+ @functools.cached_property
514
+ def imported_names(self) -> dict[str, str]:
515
+ """Local names bound by absolute imports, to the dotted names they stand for; the outermost binding wins.
516
+
517
+ Example:
518
+ >>> ParsedSource("import a.b, c as d\\nfrom e.f import g as h").imported_names
519
+ {'a': 'a', 'd': 'c', 'h': 'e.f.g'}
520
+ """
521
+ names: dict[str, str] = {}
522
+ for node in self.imports:
523
+ if isinstance(node, ast.ImportFrom):
524
+ if node.module and not node.level:
525
+ for a in node.names:
526
+ names.setdefault(a.asname or a.name, f"{node.module}.{a.name}")
527
+ else:
528
+ for a in node.names:
529
+ root = a.name.partition(".")[0]
530
+ names.setdefault(a.asname or root, a.name if a.asname else root)
531
+ return names
532
+
533
+ @functools.cached_property
534
+ def marker_names(self) -> tuple[set[str], set[str]]:
535
+ """Local spellings of ``Annotated`` and of the ``sqlty.SQL`` marker.
536
+
537
+ Example:
538
+ >>> ParsedSource("import typing as t\\nfrom sqlty import SQL as Q").marker_names
539
+ ({'t.Annotated'}, {'Q'})
540
+ """
541
+ annotated: set[str] = set()
542
+ marker: set[str] = set()
543
+ for node in self.imports:
544
+ if isinstance(node, ast.ImportFrom):
545
+ if node.level:
546
+ continue
547
+ for alias in node.names:
548
+ local = alias.asname or alias.name
549
+ if node.module in _TYPING_MODULES and alias.name == "Annotated":
550
+ annotated.add(local)
551
+ elif node.module == "sqlty" and alias.name == "SQL":
552
+ marker.add(local)
553
+ else:
554
+ for alias in node.names:
555
+ local = alias.asname or alias.name
556
+ if alias.name in _TYPING_MODULES:
557
+ annotated.add(f"{local}.Annotated")
558
+ elif alias.name == "sqlty":
559
+ marker.add(f"{local}.SQL")
560
+ return annotated, marker
561
+
562
+ @functools.cached_property
563
+ def may_define_helpers(self) -> bool:
564
+ """Whether the text can define a marked helper (needs ``Annotated`` and ``sqlty``)."""
565
+ return "Annotated" in self.text and "sqlty" in self.text and "SQL" in self.text
566
+
567
+ def may_wrap(self, import_style: str | None = None) -> bool:
568
+ """Whether the text can hold a ``SQL[T](...)`` call, spelled as ``import_style`` says."""
569
+ prefix = "from sqlty import SQL as "
570
+ style = (import_style or "").strip()
571
+ return (style[len(prefix) :].strip() if style.startswith(prefix) else "SQL") in self.text
572
+
573
+ def any_calls(self, import_style: str | None = None) -> list[int]:
574
+ """Byte offset of each ``SQL[T](...)`` call whose ``T`` is ``typing.Any`` (see ``is_any``).
575
+
576
+ Example:
577
+ >>> ParsedSource("import typing as t\\nq = SQL[t.Any](x)\\nr = SQL[int](y)").any_calls()
578
+ [23]
579
+ """
580
+ wrapper = _wrapper_name(import_style)
581
+ if wrapper is None or "Any" not in self.text or not self.may_wrap(import_style):
582
+ return []
583
+ aliases = self.typing_aliases
584
+ lines = self.text.encode().splitlines(keepends=True)
585
+ starts = list(itertools.accumulate(map(len, lines), initial=0))
586
+ offsets = []
587
+ for call in self.calls:
588
+ func = call.func
589
+ if not isinstance(func, ast.Subscript) or not is_any(func.slice, aliases):
590
+ continue
591
+ name = ast.unparse(func.value)
592
+ if name == wrapper or name.endswith(f".{wrapper}"):
593
+ offsets.append(starts[func.value.lineno - 1] + func.value.col_offset)
594
+ return sorted(offsets)
595
+
596
+ def may_need_rust_check(self, import_style: str | None = None) -> bool:
597
+ """Whether the Rust checker can report anything for the text.
598
+
599
+ Every Rust rule starts from a ``--sql`` / ``-- sql`` marker at the start of a
600
+ string (``mysql-sql-marker``, ``stale-rewrite``, ``inline-sql-comment``,
601
+ ``unparsed-query``, ``fstring-skipped``, ``tstring-skipped``,
602
+ ``unchecked-query``, ``select-star*``, ``stale-type``, ``untyped-query``); the
603
+ wrapper call (``SQL[``, spelled as ``import_style`` says) and ``UNTYPED`` count
604
+ too, which also covers a marker split over concatenated literals in a call. A marker
605
+ split over implicit concatenation anywhere else (``"--" "sql\\n..."``) matches
606
+ with quotes, prefixes, whitespace and comments allowed between its characters.
607
+ An ``import_style`` the engine rejects always needs the call, so that it raises.
608
+
609
+ Example:
610
+ >>> ParsedSource("x = 'SELECT 1'").may_need_rust_check()
611
+ False
612
+ >>> ParsedSource("x = '--sql\\nSELECT 1'").may_need_rust_check()
613
+ True
614
+ >>> ParsedSource("q = Q[UNTYPED]").may_need_rust_check("from sqlty import SQL as Q")
615
+ True
616
+ """
617
+ wrapper = _wrapper_name(import_style)
618
+ text = self.text
619
+ return (
620
+ wrapper is None
621
+ or f"{wrapper}[" in text
622
+ or "UNTYPED" in text
623
+ or _MARKER_RE.search(text) is not None
624
+ )
625
+
626
+ @property
627
+ def has_ignore_comments(self) -> bool:
628
+ """Whether the text can hold a ``# sqlty: ignore`` comment."""
629
+ return "sqlty:" in self.text
630
+
631
+ @functools.cached_property
632
+ def ignores(self) -> dict[int, _Ignore]:
633
+ """``# sqlty: ignore`` comments by line, read from COMMENT tokens only.
634
+
635
+ Tokenizes only when the text contains ``sqlty:``.
636
+ """
637
+ found: dict[int, _Ignore] = {}
638
+ if not self.has_ignore_comments:
639
+ return found
640
+ tokens = tokenize.generate_tokens(io.StringIO(self.text).readline)
641
+ try:
642
+ for tok in tokens:
643
+ if tok.type != tokenize.COMMENT or (match := _IGNORE_RE.match(tok.string)) is None:
644
+ continue
645
+ names = match.group(1)
646
+ rules = (
647
+ None
648
+ if names is None
649
+ else tuple(n.strip() for n in names.split(",") if n.strip())
650
+ )
651
+ found[tok.start[0]] = _Ignore(tok.start[0], rules)
652
+ except tokenize.TokenError, SyntaxError:
653
+ pass
654
+ return found