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
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
"""Compatibility of a resolved row type with SQL column types."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ast
|
|
6
|
+
import typing
|
|
7
|
+
|
|
8
|
+
if typing.TYPE_CHECKING:
|
|
9
|
+
pass
|
|
10
|
+
|
|
11
|
+
from sqlty._type_extractor.ast_fields import _annotation_type, _split_type_args
|
|
12
|
+
from sqlty._type_extractor.info import TypeInfo, _column_type
|
|
13
|
+
from sqlty._type_extractor.subtype import (
|
|
14
|
+
_LAX_FROM,
|
|
15
|
+
_PROMOTED_FROM,
|
|
16
|
+
_erase,
|
|
17
|
+
_is_subtype,
|
|
18
|
+
_union_members,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def check_type_compatibility(
|
|
23
|
+
user_type: TypeInfo,
|
|
24
|
+
column_name: str,
|
|
25
|
+
column_python_type: str | None,
|
|
26
|
+
) -> bool:
|
|
27
|
+
"""Check if a user type's field can hold values of a SQL column type.
|
|
28
|
+
|
|
29
|
+
Uses runtime type objects when available (``resolved_hints``), else the
|
|
30
|
+
types resolved from source (``field_types``). ``Any``, unions and the
|
|
31
|
+
``int`` -> ``float`` promotion are accepted; narrower fields (``bool`` for
|
|
32
|
+
an ``int`` column) are not, unless the field is ``lax`` (see `_LAX_FROM`).
|
|
33
|
+
Annotations neither path can resolve or decide count as compatible.
|
|
34
|
+
|
|
35
|
+
Args:
|
|
36
|
+
user_type: The user-defined type info.
|
|
37
|
+
column_name: Name of the SQL column / field to check.
|
|
38
|
+
column_python_type: The inferred Python type string from SQL
|
|
39
|
+
(e.g. ``"int"``, ``"datetime.datetime"``).
|
|
40
|
+
|
|
41
|
+
Returns:
|
|
42
|
+
True if types are compatible, False if they mismatch.
|
|
43
|
+
|
|
44
|
+
Example:
|
|
45
|
+
>>> from sqlty._type_extractor import extract_type_definitions
|
|
46
|
+
>>> src = "import typing as t, not_installed\\nclass Row(t.NamedTuple):\\n id: int | t.Any\\n flag: bool"
|
|
47
|
+
>>> info = extract_type_definitions(src)["Row"]
|
|
48
|
+
>>> check_type_compatibility(info, "id", "str"), check_type_compatibility(info, "flag", "int")
|
|
49
|
+
(True, False)
|
|
50
|
+
"""
|
|
51
|
+
declared = dict(user_type.fields)
|
|
52
|
+
if column_name in declared:
|
|
53
|
+
annotation = declared[column_name]
|
|
54
|
+
hints = user_type.resolved_hints or {}
|
|
55
|
+
field = (
|
|
56
|
+
hints[column_name] if column_name in hints else user_type.field_types.get(column_name)
|
|
57
|
+
)
|
|
58
|
+
elif user_type.extra_items is not None:
|
|
59
|
+
annotation = user_type.extra_items
|
|
60
|
+
field = user_type.extra_items_hint or user_type.extra_items_type
|
|
61
|
+
else:
|
|
62
|
+
return column_python_type is None
|
|
63
|
+
lax = column_name in user_type.lax
|
|
64
|
+
return _accepts(field, annotation, column_python_type, _LAX_FROM if lax else _PROMOTED_FROM)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def admits_none(tp: typing.Any) -> bool | None:
|
|
68
|
+
"""Whether a resolved annotation admits ``None``; ``None`` when it can't be told.
|
|
69
|
+
|
|
70
|
+
``Optional[X]``, ``X | None``, ``Any``, ``object`` and ``Literal[None]`` admit it;
|
|
71
|
+
plain classes, generics and ``NewType`` of those don't. A forward reference or a
|
|
72
|
+
name that failed to resolve is undecided.
|
|
73
|
+
|
|
74
|
+
Example:
|
|
75
|
+
>>> admits_none(int), admits_none(int | None), admits_none(typing.Any), admits_none(None)
|
|
76
|
+
(False, True, True, None)
|
|
77
|
+
"""
|
|
78
|
+
if tp is None:
|
|
79
|
+
return None
|
|
80
|
+
verdicts = [_member_admits_none(member) for member in _union_members(tp)]
|
|
81
|
+
if True in verdicts:
|
|
82
|
+
return True
|
|
83
|
+
return None if None in verdicts else False
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _member_admits_none(member: typing.Any) -> bool | None:
|
|
87
|
+
if member is type(None) or member is None or member is typing.Any or member is object:
|
|
88
|
+
return True
|
|
89
|
+
if isinstance(member, typing.NewType):
|
|
90
|
+
return admits_none(member.__supertype__)
|
|
91
|
+
origin = typing.get_origin(member)
|
|
92
|
+
if origin is typing.Literal:
|
|
93
|
+
return None in typing.get_args(member)
|
|
94
|
+
if isinstance(member, type) or isinstance(origin, type):
|
|
95
|
+
return False
|
|
96
|
+
return None
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def column_literal_values(python_type: str) -> list[str | int] | None:
|
|
100
|
+
"""The values of an inferred ``Literal`` column type, ``None`` when it is not one.
|
|
101
|
+
|
|
102
|
+
``None`` members (a nullable column) are left out; nullability is checked separately.
|
|
103
|
+
|
|
104
|
+
Example:
|
|
105
|
+
>>> column_literal_values("typing.Literal['a', 'b'] | None")
|
|
106
|
+
['a', 'b']
|
|
107
|
+
>>> column_literal_values("typing.Literal[1, 2]")
|
|
108
|
+
[1, 2]
|
|
109
|
+
>>> column_literal_values("str") is None
|
|
110
|
+
True
|
|
111
|
+
"""
|
|
112
|
+
try:
|
|
113
|
+
tree = ast.parse(python_type, mode="eval").body
|
|
114
|
+
except SyntaxError:
|
|
115
|
+
return None
|
|
116
|
+
members = [tree]
|
|
117
|
+
while any(isinstance(m, ast.BinOp) and isinstance(m.op, ast.BitOr) for m in members):
|
|
118
|
+
members = [
|
|
119
|
+
part
|
|
120
|
+
for m in members
|
|
121
|
+
for part in ((m.left, m.right) if isinstance(m, ast.BinOp) else (m,))
|
|
122
|
+
]
|
|
123
|
+
values: list[str | int] = []
|
|
124
|
+
for member in members:
|
|
125
|
+
if isinstance(member, ast.Constant) and member.value is None:
|
|
126
|
+
continue
|
|
127
|
+
if not (
|
|
128
|
+
isinstance(member, ast.Subscript)
|
|
129
|
+
and isinstance(member.value, ast.Attribute)
|
|
130
|
+
and ast.unparse(member.value) == "typing.Literal"
|
|
131
|
+
):
|
|
132
|
+
return None
|
|
133
|
+
items = member.slice.elts if isinstance(member.slice, ast.Tuple) else [member.slice]
|
|
134
|
+
for item in items:
|
|
135
|
+
if not (isinstance(item, ast.Constant) and isinstance(item.value, (str, int))):
|
|
136
|
+
return None
|
|
137
|
+
values.append(item.value)
|
|
138
|
+
return values or None
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def declared_literal_values(tp: typing.Any, inferred: list[str | int]) -> set[str | int] | None:
|
|
142
|
+
"""The values a resolved annotation admits for a column that takes ``inferred``.
|
|
143
|
+
|
|
144
|
+
``None`` when the annotation also takes values by class (``str`` for string values,
|
|
145
|
+
``int`` for integers, ``Any``), or when it can't be told (an enum or other user class,
|
|
146
|
+
an unresolved name): only an annotation made of ``Literal`` members and ``None`` is a set.
|
|
147
|
+
|
|
148
|
+
Example:
|
|
149
|
+
>>> declared_literal_values(typing.Literal["a", "b"] | None, ["a"]) == {"a", "b"}
|
|
150
|
+
True
|
|
151
|
+
>>> declared_literal_values(str, ["a"]) is None
|
|
152
|
+
True
|
|
153
|
+
>>> declared_literal_values(typing.Literal[1], ["a"]) == {1}
|
|
154
|
+
True
|
|
155
|
+
"""
|
|
156
|
+
covering: tuple[type, ...] = (str,) if isinstance(inferred[0], str) else (int, float, complex)
|
|
157
|
+
admitted: set[str | int] = set()
|
|
158
|
+
for member in _union_members(tp):
|
|
159
|
+
while isinstance(member, typing.NewType):
|
|
160
|
+
member = member.__supertype__
|
|
161
|
+
if member is type(None) or member is None:
|
|
162
|
+
continue
|
|
163
|
+
if typing.get_origin(member) is typing.Literal:
|
|
164
|
+
admitted.update(a for a in typing.get_args(member) if isinstance(a, (str, int)))
|
|
165
|
+
elif (
|
|
166
|
+
member is typing.Any
|
|
167
|
+
or member is object
|
|
168
|
+
or member in covering
|
|
169
|
+
or not (isinstance(member, type) and member.__module__ == "builtins")
|
|
170
|
+
):
|
|
171
|
+
return None
|
|
172
|
+
return admitted
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def is_optional(tp: typing.Any) -> bool:
|
|
176
|
+
"""Whether a resolved annotation spells ``None`` out: ``Optional[X]`` or ``X | None``.
|
|
177
|
+
|
|
178
|
+
``Any`` and ``object`` admit ``None`` but are not optional in this sense.
|
|
179
|
+
|
|
180
|
+
Example:
|
|
181
|
+
>>> is_optional(int | None), is_optional(typing.Optional[str]), is_optional(typing.Any)
|
|
182
|
+
(True, True, False)
|
|
183
|
+
"""
|
|
184
|
+
members = _union_members(tp)
|
|
185
|
+
return len(members) > 1 and any(m is type(None) for m in members)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def field_type(user_type: TypeInfo, column_name: str) -> typing.Any:
|
|
189
|
+
"""The resolved annotation of the field of ``user_type`` that holds ``column_name``.
|
|
190
|
+
|
|
191
|
+
Resolved as `check_type_compatibility` resolves it, but with ``| None`` kept (type
|
|
192
|
+
compatibility ignores it, since every column may be NULL); ``None`` when the field is
|
|
193
|
+
unknown or its annotation can't be resolved.
|
|
194
|
+
"""
|
|
195
|
+
declared = dict(user_type.fields)
|
|
196
|
+
if column_name in declared:
|
|
197
|
+
hints = user_type.declared_hints
|
|
198
|
+
return (
|
|
199
|
+
hints[column_name] if column_name in hints else user_type.field_types.get(column_name)
|
|
200
|
+
)
|
|
201
|
+
if user_type.extra_items is not None:
|
|
202
|
+
return user_type.extra_items_type
|
|
203
|
+
return None
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def field_accepts(annotation: str, column_python_type: str | None) -> bool:
|
|
207
|
+
"""Check if a field annotated ``annotation`` can hold values of a SQL column type.
|
|
208
|
+
|
|
209
|
+
For annotations known only as strings, such as ``SQL[tuple[...]]`` items;
|
|
210
|
+
see `check_type_compatibility`.
|
|
211
|
+
|
|
212
|
+
Example:
|
|
213
|
+
>>> field_accepts("float", "int"), field_accepts("bool", "int"), field_accepts("Any", "str")
|
|
214
|
+
(True, False, True)
|
|
215
|
+
"""
|
|
216
|
+
return _accepts(_annotation_type(annotation), annotation, column_python_type)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _accepts(
|
|
220
|
+
field: typing.Any,
|
|
221
|
+
annotation: str,
|
|
222
|
+
column_python_type: str | None,
|
|
223
|
+
promotions: dict[type, tuple[type, ...]] | None = None,
|
|
224
|
+
) -> bool:
|
|
225
|
+
if not column_python_type:
|
|
226
|
+
return True
|
|
227
|
+
fits = _is_subtype(_column_type(column_python_type), _erase(field), promotions)
|
|
228
|
+
return fits is not False
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def parse_tuple_annotation(annotation: str) -> list[tuple[str, str]] | None:
|
|
232
|
+
"""Parse a tuple type annotation into a field list.
|
|
233
|
+
|
|
234
|
+
Args:
|
|
235
|
+
annotation: Type annotation string like ``"tuple[int, str]"``.
|
|
236
|
+
|
|
237
|
+
Returns:
|
|
238
|
+
List of (positional_name, type) pairs, or None if not a tuple.
|
|
239
|
+
Positional names are ``"_0"``, ``"_1"``, etc.
|
|
240
|
+
|
|
241
|
+
Examples:
|
|
242
|
+
>>> parse_tuple_annotation("tuple[int, str]")
|
|
243
|
+
[('_0', 'int'), ('_1', 'str')]
|
|
244
|
+
>>> parse_tuple_annotation("tuple[int]")
|
|
245
|
+
[('_0', 'int')]
|
|
246
|
+
>>> parse_tuple_annotation("User")
|
|
247
|
+
"""
|
|
248
|
+
if not annotation.startswith("tuple[") or not annotation.endswith("]"):
|
|
249
|
+
return None
|
|
250
|
+
inner = annotation[6:-1]
|
|
251
|
+
parts = _split_type_args(inner)
|
|
252
|
+
return [(f"_{i}", t.strip()) for i, t in enumerate(parts)]
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""Find the user-defined row types of a source: AST scan, then sandboxed resolution."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ast
|
|
6
|
+
import typing
|
|
7
|
+
|
|
8
|
+
from sqlty._source import ParsedSource
|
|
9
|
+
|
|
10
|
+
if typing.TYPE_CHECKING:
|
|
11
|
+
from sqlty._helpers import HelperIndex
|
|
12
|
+
|
|
13
|
+
from sqlty._type_extractor.ast_fields import (
|
|
14
|
+
_ast_annotations,
|
|
15
|
+
_ast_key_types,
|
|
16
|
+
_ast_type,
|
|
17
|
+
_base_names,
|
|
18
|
+
_classify_class,
|
|
19
|
+
_extract_fields_from_ast,
|
|
20
|
+
_functional_classes,
|
|
21
|
+
_header_errors,
|
|
22
|
+
_key_errors,
|
|
23
|
+
_lax_fields,
|
|
24
|
+
_lineage,
|
|
25
|
+
_metadata_defaults,
|
|
26
|
+
_newtype_assignments,
|
|
27
|
+
_own_openness,
|
|
28
|
+
_pydantic_config,
|
|
29
|
+
_set_openness,
|
|
30
|
+
_set_pydantic_names,
|
|
31
|
+
)
|
|
32
|
+
from sqlty._type_extractor.info import TypeInfo
|
|
33
|
+
from sqlty._type_extractor.sandbox import (
|
|
34
|
+
_Import,
|
|
35
|
+
_import_value,
|
|
36
|
+
_namespace_statements,
|
|
37
|
+
_own_extra_type,
|
|
38
|
+
_resolve_class,
|
|
39
|
+
_type_hints,
|
|
40
|
+
)
|
|
41
|
+
from sqlty._type_extractor.subtype import _unwrap_optional
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def extract_type_definitions(
|
|
45
|
+
source: str | ParsedSource,
|
|
46
|
+
helpers: HelperIndex | None = None,
|
|
47
|
+
module: str | None = None,
|
|
48
|
+
type_modules: typing.Iterable[str] | None = None,
|
|
49
|
+
) -> dict[str, TypeInfo]:
|
|
50
|
+
"""Extract type definitions from Python source code.
|
|
51
|
+
|
|
52
|
+
Finds class definitions that are:
|
|
53
|
+
- ``TypedDict`` subclasses
|
|
54
|
+
- ``NamedTuple`` subclasses
|
|
55
|
+
- ``@dataclass``-decorated classes
|
|
56
|
+
- Pydantic ``BaseModel`` subclasses
|
|
57
|
+
- ``Protocol`` classes, whose attributes a row must have
|
|
58
|
+
|
|
59
|
+
For each recognized class, attempts runtime resolution of field types
|
|
60
|
+
using ``typing.get_type_hints()``. Falls back to AST string extraction
|
|
61
|
+
if runtime resolution fails (e.g. missing dependencies).
|
|
62
|
+
|
|
63
|
+
Names imported from modules of ``helpers`` (a ``HelperIndex``) are read
|
|
64
|
+
from those modules' source, never imported; ``module`` is the name of
|
|
65
|
+
``source``, for relative imports. Imports are executed only for the
|
|
66
|
+
standard library, `_TRUSTED_MODULES` and ``type_modules``; any other name
|
|
67
|
+
is read from the source of ``helpers`` or is unknown.
|
|
68
|
+
|
|
69
|
+
Args:
|
|
70
|
+
source: Python source code, or a ``ParsedSource`` whose tree is reused.
|
|
71
|
+
helpers: modules of the checked paths.
|
|
72
|
+
module: dotted name of ``source``.
|
|
73
|
+
type_modules: extra modules (and their submodules) whose imports may be executed.
|
|
74
|
+
|
|
75
|
+
Returns:
|
|
76
|
+
Dictionary mapping type name to TypeInfo.
|
|
77
|
+
"""
|
|
78
|
+
parsed = ParsedSource.of(source)
|
|
79
|
+
if (tree := parsed.tree) is None:
|
|
80
|
+
return {}
|
|
81
|
+
|
|
82
|
+
aliases = parsed.typing_aliases
|
|
83
|
+
imports = parsed.imported_names
|
|
84
|
+
newtypes: dict[str, ast.Assign | typing.Any] = dict(_newtype_assignments(tree, aliases))
|
|
85
|
+
|
|
86
|
+
# Phase 1: AST scan — find recognized classes; TypedDict subclasses
|
|
87
|
+
# are recognized when their base is a TypedDict defined earlier
|
|
88
|
+
recognized: list[tuple[ast.ClassDef, str]] = [] # (node, kind)
|
|
89
|
+
typeddict_nodes: dict[str, ast.ClassDef] = {}
|
|
90
|
+
classes = parsed.classes
|
|
91
|
+
if functional := _functional_classes(tree, aliases):
|
|
92
|
+
classes = sorted([*classes, *functional], key=lambda node: node.lineno)
|
|
93
|
+
for node in classes:
|
|
94
|
+
kind = _classify_class(node, aliases, typeddict_nodes)
|
|
95
|
+
if kind == "TypedDict":
|
|
96
|
+
typeddict_nodes[node.name] = node
|
|
97
|
+
if kind:
|
|
98
|
+
recognized.append((node, kind))
|
|
99
|
+
|
|
100
|
+
if not recognized:
|
|
101
|
+
return {}
|
|
102
|
+
|
|
103
|
+
# Phase 2: Collect the guarded imports and aliases needed for the namespace
|
|
104
|
+
extra = frozenset(type_modules or ())
|
|
105
|
+
if helpers is not None and helpers.type_modules != extra:
|
|
106
|
+
helpers.type_modules = extra
|
|
107
|
+
helpers.namespaces.clear()
|
|
108
|
+
import_stmts = _namespace_statements(tree, set(newtypes), helpers, module, extra)
|
|
109
|
+
if helpers is not None:
|
|
110
|
+
# A NewType imported from a checked module, read from its source, for the AST
|
|
111
|
+
# fallback (a BaseModel without pydantic installed).
|
|
112
|
+
used = {n.id for node, _ in recognized for n in ast.walk(node) if isinstance(n, ast.Name)}
|
|
113
|
+
for stmt in import_stmts:
|
|
114
|
+
if isinstance(stmt, _Import) and stmt.module and stmt.name and stmt.local in used:
|
|
115
|
+
if isinstance(tp := _import_value(helpers, stmt), typing.NewType):
|
|
116
|
+
newtypes.setdefault(stmt.local, tp)
|
|
117
|
+
|
|
118
|
+
# Phase 3: For each class, try runtime resolution then fall back to AST
|
|
119
|
+
result: dict[str, TypeInfo] = {}
|
|
120
|
+
typeddicts: dict[str, TypeInfo] = {}
|
|
121
|
+
for node, kind in recognized:
|
|
122
|
+
keywords = {k.arg: k.value for k in node.keywords if k.arg}
|
|
123
|
+
total = not (isinstance(t := keywords.get("total"), ast.Constant) and t.value is False)
|
|
124
|
+
own_fields, own_required = _extract_fields_from_ast(
|
|
125
|
+
node, aliases, total=total, defaults_optional=kind in ("dataclass", "BaseModel")
|
|
126
|
+
)
|
|
127
|
+
parents = [typeddicts[n] for n in _base_names(node) if n in typeddicts]
|
|
128
|
+
inherited = {k: v for p in parents for k, v in p.fields}
|
|
129
|
+
fields = list((inherited | dict(own_fields)).items())
|
|
130
|
+
required = frozenset(
|
|
131
|
+
{k for p in parents for k in p.required} - dict(own_fields).keys() | own_required
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
is_typeddict = kind == "TypedDict"
|
|
135
|
+
nodes = list(_lineage(node, typeddict_nodes).values()) if is_typeddict else [node]
|
|
136
|
+
defaulted = {name for n in nodes for name in _metadata_defaults(n, aliases)}
|
|
137
|
+
required -= defaulted
|
|
138
|
+
info = TypeInfo(name=node.name, fields=fields, kind=kind, required=required)
|
|
139
|
+
info.lineno = node.lineno
|
|
140
|
+
# A row that has a Protocol's attributes may have more.
|
|
141
|
+
info.allows_extra = kind == "Protocol"
|
|
142
|
+
info.module = module
|
|
143
|
+
if kind == "BaseModel":
|
|
144
|
+
_set_pydantic_names(info, node)
|
|
145
|
+
if (config := _pydantic_config(node, kind, imports)) is not None:
|
|
146
|
+
info.lax = _lax_fields(node, config, aliases, imports)
|
|
147
|
+
info.field_types = _ast_key_types(nodes, aliases, newtypes, imports)
|
|
148
|
+
info.annotations = _ast_annotations(nodes, aliases)
|
|
149
|
+
info.aliases = aliases
|
|
150
|
+
hints = None
|
|
151
|
+
if (fields or is_typeddict) and (
|
|
152
|
+
resolved := _resolve_class(nodes, import_stmts, parsed.text, helpers)
|
|
153
|
+
):
|
|
154
|
+
cls, namespace = resolved
|
|
155
|
+
hints = _type_hints(cls, namespace)
|
|
156
|
+
info.declared_hints = hints
|
|
157
|
+
info.resolved_hints = {name: _unwrap_optional(tp) for name, tp in hints.items()}
|
|
158
|
+
if is_typeddict:
|
|
159
|
+
info.bases = [p.name for p in parents]
|
|
160
|
+
own = _own_openness(keywords, aliases)
|
|
161
|
+
if hints is not None:
|
|
162
|
+
info.required = frozenset(getattr(cls, "__required_keys__", info.required))
|
|
163
|
+
info.required -= defaulted
|
|
164
|
+
own_type = _own_extra_type(cls, namespace) if own and own.extra_items else None
|
|
165
|
+
else:
|
|
166
|
+
hints = info.field_types
|
|
167
|
+
own_type = (
|
|
168
|
+
_ast_type(own.extra_node, aliases, newtypes) if own and own.extra_node else None
|
|
169
|
+
)
|
|
170
|
+
header = _header_errors(info.name, keywords, own, own_type, parents)
|
|
171
|
+
info.errors = list(dict.fromkeys(header + _key_errors(info, hints, parents)))
|
|
172
|
+
_set_openness(info, None if header else own, own_type, parents)
|
|
173
|
+
if info.resolved_hints is not None and info.extra_items_type is not None:
|
|
174
|
+
info.extra_items_hint = _unwrap_optional(info.extra_items_type)
|
|
175
|
+
typeddicts[node.name] = info
|
|
176
|
+
if fields:
|
|
177
|
+
result[node.name] = info
|
|
178
|
+
|
|
179
|
+
return result
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Generic row types with their type arguments applied: ``SQL[Row[int]]`` for ``class Row[T]``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ast
|
|
6
|
+
import copy
|
|
7
|
+
import re
|
|
8
|
+
import typing
|
|
9
|
+
|
|
10
|
+
from sqlty._type_extractor.ast_fields import _ast_type
|
|
11
|
+
from sqlty._type_extractor.info import TypeInfo
|
|
12
|
+
from sqlty._type_extractor.subtype import _unwrap_optional
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def specialize(
|
|
16
|
+
info: TypeInfo, node: ast.ClassDef, args: list[ast.expr], aliases: dict[str, str]
|
|
17
|
+
) -> TypeInfo | None:
|
|
18
|
+
"""``info`` with the type parameters of its class ``node`` replaced by ``args``.
|
|
19
|
+
|
|
20
|
+
The parameters are those of ``class Row[T]`` or of a ``Generic[T]`` base. ``None`` when
|
|
21
|
+
the class takes a different number of arguments. An argument sqlty cannot resolve leaves
|
|
22
|
+
the fields it fills unknown, as an unresolved annotation does.
|
|
23
|
+
|
|
24
|
+
Example:
|
|
25
|
+
>>> from sqlty._source import ParsedSource
|
|
26
|
+
>>> from sqlty._type_extractor import extract_type_definitions
|
|
27
|
+
>>> parsed = ParsedSource("from typing import TypedDict\\nclass Row[T](TypedDict):\\n ids: list[T]")
|
|
28
|
+
>>> row = extract_type_definitions(parsed, None, None, None)["Row"]
|
|
29
|
+
>>> specialize(row, parsed.classes[0], [ast.parse("int", mode="eval").body], {}).resolved_hints
|
|
30
|
+
{'ids': list[int]}
|
|
31
|
+
"""
|
|
32
|
+
params = _type_params(node)
|
|
33
|
+
if not params or len(params) != len(args):
|
|
34
|
+
return None
|
|
35
|
+
texts = dict(zip(params, (ast.unparse(arg) for arg in args), strict=True))
|
|
36
|
+
nodes = dict(zip(params, args, strict=True))
|
|
37
|
+
runtime = {name: _ast_type(arg, aliases) for name, arg in nodes.items()}
|
|
38
|
+
words = re.compile(r"\b(" + "|".join(map(re.escape, params)) + r")\b")
|
|
39
|
+
|
|
40
|
+
def text(annotation: str) -> str:
|
|
41
|
+
return words.sub(lambda match: texts[match[0]], annotation)
|
|
42
|
+
|
|
43
|
+
def hint(tp: typing.Any) -> typing.Any:
|
|
44
|
+
if isinstance(tp, typing.TypeVar):
|
|
45
|
+
return runtime.get(tp.__name__)
|
|
46
|
+
free = [p for p in getattr(tp, "__parameters__", ()) if isinstance(p, typing.TypeVar)]
|
|
47
|
+
if not free:
|
|
48
|
+
return tp
|
|
49
|
+
values = [runtime.get(p.__name__) for p in free]
|
|
50
|
+
if any(value is None for value in values):
|
|
51
|
+
return None
|
|
52
|
+
try:
|
|
53
|
+
return tp[tuple(values)] if len(values) > 1 else tp[values[0]]
|
|
54
|
+
except TypeError:
|
|
55
|
+
return None
|
|
56
|
+
|
|
57
|
+
out = copy.copy(info)
|
|
58
|
+
out.fields = [(name, text(annotation)) for name, annotation in info.fields]
|
|
59
|
+
out.annotations = {
|
|
60
|
+
name: _Substitute(nodes).visit(copy.deepcopy(annotation))
|
|
61
|
+
for name, annotation in info.annotations.items()
|
|
62
|
+
}
|
|
63
|
+
out.field_types = {
|
|
64
|
+
name: _ast_type(out.annotations[name], aliases) if name in out.annotations else tp
|
|
65
|
+
for name, tp in info.field_types.items()
|
|
66
|
+
}
|
|
67
|
+
if info.declared_hints:
|
|
68
|
+
out.declared_hints = {name: hint(tp) for name, tp in info.declared_hints.items()}
|
|
69
|
+
out.declared_hints = {k: v for k, v in out.declared_hints.items() if v is not None}
|
|
70
|
+
if info.resolved_hints is not None:
|
|
71
|
+
out.resolved_hints = {
|
|
72
|
+
name: _unwrap_optional(tp)
|
|
73
|
+
for name, tp in ((name, hint(tp)) for name, tp in info.resolved_hints.items())
|
|
74
|
+
if tp is not None
|
|
75
|
+
}
|
|
76
|
+
return out
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _type_params(node: ast.ClassDef) -> list[str]:
|
|
80
|
+
"""``T`` of ``class Row[T]``, or of a ``Generic[T]`` base."""
|
|
81
|
+
if node.type_params:
|
|
82
|
+
return [param.name for param in node.type_params if isinstance(param, ast.TypeVar)]
|
|
83
|
+
for base in node.bases:
|
|
84
|
+
if isinstance(base, ast.Subscript) and ast.unparse(base.value).endswith("Generic"):
|
|
85
|
+
items = base.slice.elts if isinstance(base.slice, ast.Tuple) else [base.slice]
|
|
86
|
+
return [item.id for item in items if isinstance(item, ast.Name)]
|
|
87
|
+
return []
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class _Substitute(ast.NodeTransformer):
|
|
91
|
+
def __init__(self, nodes: dict[str, ast.expr]) -> None:
|
|
92
|
+
self.nodes = nodes
|
|
93
|
+
|
|
94
|
+
def visit_Name(self, node: ast.Name) -> ast.expr:
|
|
95
|
+
return copy.deepcopy(self.nodes[node.id]) if node.id in self.nodes else node
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""Row-type description (``TypeInfo``) and the SQL-to-Python type map."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ast
|
|
6
|
+
import datetime
|
|
7
|
+
import decimal
|
|
8
|
+
import functools
|
|
9
|
+
import ipaddress
|
|
10
|
+
import operator
|
|
11
|
+
import typing
|
|
12
|
+
import uuid
|
|
13
|
+
|
|
14
|
+
if typing.TYPE_CHECKING:
|
|
15
|
+
pass
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class TypeInfo:
|
|
19
|
+
"""Information about a user-defined type extracted from source.
|
|
20
|
+
|
|
21
|
+
``required``, ``closed`` and ``extra_items`` describe TypedDict keys
|
|
22
|
+
(PEP 655, PEP 728); other kinds have every field required and are open.
|
|
23
|
+
For TypedDicts, ``extra_items_readonly`` and ``extra_items_type`` (the
|
|
24
|
+
resolved type, or None when unknown) complete ``extra_items``. ``field_types``
|
|
25
|
+
holds each field's type resolved from source (None when unknown), ``owner``
|
|
26
|
+
names the class whose header set the openness, ``lineno`` is the class
|
|
27
|
+
line, ``bases`` names its TypedDict bases defined in the same source and
|
|
28
|
+
``errors`` lists its PEP 728 inheritance violations. For Pydantic models,
|
|
29
|
+
``columns`` maps each accepted column name (field name or validation alias)
|
|
30
|
+
to its field, ``opaque`` names the fields whose validation names are not
|
|
31
|
+
statically known (``AliasChoices``, ``alias_generator``) and ``allows_extra``
|
|
32
|
+
whether it keeps undeclared columns (``extra="allow"``, or a config not read from source). ``lax`` names the fields of a Pydantic model or
|
|
33
|
+
dataclass that accept lax-mode conversions (not strict). ``annotations`` holds
|
|
34
|
+
each field's annotation from source, qualifiers stripped and ``| None`` kept, and
|
|
35
|
+
``aliases`` the typing names of the source it was read from (see
|
|
36
|
+
``ParsedSource.typing_aliases``); JSON shapes are checked against them.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
__slots__ = (
|
|
40
|
+
"name",
|
|
41
|
+
"fields",
|
|
42
|
+
"kind",
|
|
43
|
+
"resolved_hints",
|
|
44
|
+
"declared_hints",
|
|
45
|
+
"required",
|
|
46
|
+
"closed",
|
|
47
|
+
"extra_items",
|
|
48
|
+
"extra_items_hint",
|
|
49
|
+
"extra_items_readonly",
|
|
50
|
+
"extra_items_type",
|
|
51
|
+
"field_types",
|
|
52
|
+
"owner",
|
|
53
|
+
"lineno",
|
|
54
|
+
"bases",
|
|
55
|
+
"errors",
|
|
56
|
+
"columns",
|
|
57
|
+
"opaque",
|
|
58
|
+
"allows_extra",
|
|
59
|
+
"lax",
|
|
60
|
+
"annotations",
|
|
61
|
+
"aliases",
|
|
62
|
+
"module",
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
def __init__(
|
|
66
|
+
self,
|
|
67
|
+
name: str,
|
|
68
|
+
fields: list[tuple[str, str]],
|
|
69
|
+
kind: str,
|
|
70
|
+
resolved_hints: dict[str, type] | None = None,
|
|
71
|
+
*,
|
|
72
|
+
required: frozenset[str] | None = None,
|
|
73
|
+
closed: bool = False,
|
|
74
|
+
extra_items: str | None = None,
|
|
75
|
+
extra_items_hint: type | None = None,
|
|
76
|
+
) -> None:
|
|
77
|
+
self.name = name
|
|
78
|
+
self.fields = fields # [(field_name, field_type_str), ...] — AST fallback
|
|
79
|
+
self.kind = kind # "TypedDict", "NamedTuple", "dataclass", "BaseModel", "Protocol"
|
|
80
|
+
self.resolved_hints = resolved_hints # {field_name: type_object} — runtime
|
|
81
|
+
self.required = frozenset(n for n, _ in fields) if required is None else required
|
|
82
|
+
self.closed = closed
|
|
83
|
+
self.extra_items = extra_items
|
|
84
|
+
self.extra_items_hint = extra_items_hint
|
|
85
|
+
self.extra_items_readonly = False
|
|
86
|
+
self.extra_items_type: typing.Any = None
|
|
87
|
+
self.field_types: dict[str, typing.Any] = {}
|
|
88
|
+
self.declared_hints: dict[str, typing.Any] = {} # runtime hints, ``| None`` kept
|
|
89
|
+
self.owner = name
|
|
90
|
+
self.lineno = 0
|
|
91
|
+
self.bases: list[str] = []
|
|
92
|
+
self.errors: list[str] = []
|
|
93
|
+
self.columns: dict[str, str] = {}
|
|
94
|
+
self.opaque: frozenset[str] = frozenset()
|
|
95
|
+
self.allows_extra = False
|
|
96
|
+
self.lax: frozenset[str] = frozenset()
|
|
97
|
+
self.annotations: dict[str, ast.expr] = {}
|
|
98
|
+
self.aliases: dict[str, str] = {}
|
|
99
|
+
self.module: str | None = None # the module that defines it, when known
|
|
100
|
+
|
|
101
|
+
def field_for(self, column: str) -> str | None:
|
|
102
|
+
"""The field a query column fills, by name (a Pydantic alias counts); None if none does."""
|
|
103
|
+
if self.kind == "BaseModel":
|
|
104
|
+
return self.columns.get(column)
|
|
105
|
+
return column if column in dict(self.fields) else None
|
|
106
|
+
|
|
107
|
+
def column_names(self, field: str) -> list[str]:
|
|
108
|
+
"""The query column names that fill ``field``, the Pydantic alias first."""
|
|
109
|
+
if self.kind == "BaseModel":
|
|
110
|
+
return [c for c, f in self.columns.items() if f == field]
|
|
111
|
+
return [field]
|
|
112
|
+
|
|
113
|
+
@property
|
|
114
|
+
def keyed(self) -> bool:
|
|
115
|
+
"""Whether columns match keys by name (closed or ``extra_items`` TypedDict)."""
|
|
116
|
+
return self.closed or self.extra_items is not None
|
|
117
|
+
|
|
118
|
+
def __repr__(self) -> str:
|
|
119
|
+
return f"TypeInfo({self.name!r}, fields={self.fields!r}, kind={self.kind!r})"
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
PYTHON_TYPE_MAP: dict[str, type] = {
|
|
123
|
+
"int": int,
|
|
124
|
+
"str": str,
|
|
125
|
+
"float": float,
|
|
126
|
+
"bool": bool,
|
|
127
|
+
"bytes": bytes,
|
|
128
|
+
"list": list,
|
|
129
|
+
"dict": dict,
|
|
130
|
+
"datetime.date": datetime.date,
|
|
131
|
+
"datetime.datetime": datetime.datetime,
|
|
132
|
+
"datetime.time": datetime.time,
|
|
133
|
+
"datetime.timedelta": datetime.timedelta,
|
|
134
|
+
"uuid.UUID": uuid.UUID,
|
|
135
|
+
"decimal.Decimal": decimal.Decimal,
|
|
136
|
+
"typing.Any": typing.Any,
|
|
137
|
+
"None": type(None),
|
|
138
|
+
"ipaddress.IPv4Address": ipaddress.IPv4Address,
|
|
139
|
+
"ipaddress.IPv6Address": ipaddress.IPv6Address,
|
|
140
|
+
"ipaddress.IPv4Interface": ipaddress.IPv4Interface,
|
|
141
|
+
"ipaddress.IPv6Interface": ipaddress.IPv6Interface,
|
|
142
|
+
"ipaddress.IPv4Network": ipaddress.IPv4Network,
|
|
143
|
+
"ipaddress.IPv6Network": ipaddress.IPv6Network,
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _column_type(python_type: str) -> typing.Any:
|
|
148
|
+
"""The type object of an inferred column type; ``list[T]`` is ``list``, ``A | B`` a union, unknown is None.
|
|
149
|
+
|
|
150
|
+
Example:
|
|
151
|
+
>>> _column_type("list[decimal.Decimal]"), _column_type("int | str"), _column_type("nope")
|
|
152
|
+
(<class 'list'>, int | str, None)
|
|
153
|
+
>>> _column_type("None") # a VOID result
|
|
154
|
+
<class 'NoneType'>
|
|
155
|
+
"""
|
|
156
|
+
if python_type.startswith("list["):
|
|
157
|
+
return list
|
|
158
|
+
members = [PYTHON_TYPE_MAP.get(name.strip()) for name in python_type.split(" | ")]
|
|
159
|
+
if None in members:
|
|
160
|
+
return None
|
|
161
|
+
return functools.reduce(operator.or_, members)
|