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,823 @@
|
|
|
1
|
+
"""AST-level extraction of fields for TypedDict, dataclass, NamedTuple and Pydantic classes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ast
|
|
6
|
+
import datetime
|
|
7
|
+
import decimal
|
|
8
|
+
import functools
|
|
9
|
+
import operator
|
|
10
|
+
import types
|
|
11
|
+
import typing
|
|
12
|
+
import uuid
|
|
13
|
+
|
|
14
|
+
if typing.TYPE_CHECKING:
|
|
15
|
+
pass
|
|
16
|
+
|
|
17
|
+
from sqlty._type_extractor.info import TypeInfo
|
|
18
|
+
from sqlty._type_extractor.subtype import _QUALIFIERS, _consistent, _is_subtype, _type_repr
|
|
19
|
+
|
|
20
|
+
_TYPING_MODULES = frozenset({"typing", "typing_extensions"})
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
_TYPE_EXPR_NODES = (
|
|
24
|
+
ast.Name,
|
|
25
|
+
ast.Attribute,
|
|
26
|
+
ast.Subscript,
|
|
27
|
+
ast.Tuple,
|
|
28
|
+
ast.Constant,
|
|
29
|
+
ast.BinOp,
|
|
30
|
+
ast.BitOr,
|
|
31
|
+
ast.expr_context,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _newtype_assignments(tree: ast.Module, aliases: dict[str, str]) -> dict[str, ast.Assign]:
|
|
36
|
+
"""Module-level ``X = NewType("X", T)`` with ``T`` a type expression, by name.
|
|
37
|
+
|
|
38
|
+
Example:
|
|
39
|
+
>>> list(_newtype_assignments(ast.parse("U = NewType('U', int)\\nV = NewType('V', f())"), {}))
|
|
40
|
+
['U']
|
|
41
|
+
"""
|
|
42
|
+
return {
|
|
43
|
+
node.targets[0].id: node
|
|
44
|
+
for node in tree.body
|
|
45
|
+
if isinstance(node, ast.Assign)
|
|
46
|
+
and len(node.targets) == 1
|
|
47
|
+
and isinstance(node.targets[0], ast.Name)
|
|
48
|
+
and isinstance(node.value, ast.Call)
|
|
49
|
+
and _is_name(node.value.func, "NewType", aliases)
|
|
50
|
+
and len(node.value.args) == 2
|
|
51
|
+
and not node.value.keywords
|
|
52
|
+
and isinstance(name := node.value.args[0], ast.Constant)
|
|
53
|
+
and name.value == node.targets[0].id
|
|
54
|
+
and all(isinstance(n, _TYPE_EXPR_NODES) for n in ast.walk(node.value.args[1]))
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _classify_class(
|
|
59
|
+
node: ast.ClassDef,
|
|
60
|
+
aliases: dict[str, str] | None = None,
|
|
61
|
+
typeddicts: typing.Container[str] = (),
|
|
62
|
+
) -> str | None:
|
|
63
|
+
"""Classify a class as TypedDict, NamedTuple, dataclass, BaseModel or Protocol.
|
|
64
|
+
|
|
65
|
+
Subclasses of the names in ``typeddicts`` are TypedDicts too.
|
|
66
|
+
"""
|
|
67
|
+
aliases = aliases or {}
|
|
68
|
+
for base in node.bases:
|
|
69
|
+
base_name = _get_name(base)
|
|
70
|
+
base_name = aliases.get(base_name, base_name) if base_name else None
|
|
71
|
+
if base_name == "TypedDict" or (isinstance(base, ast.Name) and base.id in typeddicts):
|
|
72
|
+
return "TypedDict"
|
|
73
|
+
if base_name == "NamedTuple":
|
|
74
|
+
return "NamedTuple"
|
|
75
|
+
if base_name == "BaseModel":
|
|
76
|
+
return "BaseModel"
|
|
77
|
+
if base_name == "Protocol":
|
|
78
|
+
return "Protocol"
|
|
79
|
+
|
|
80
|
+
for decorator in node.decorator_list:
|
|
81
|
+
dec_name = _get_name(decorator)
|
|
82
|
+
if dec_name == "dataclass":
|
|
83
|
+
return "dataclass"
|
|
84
|
+
|
|
85
|
+
return None
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _functional_classes(tree: ast.Module, aliases: dict[str, str]) -> list[ast.ClassDef]:
|
|
89
|
+
"""``R = TypedDict("R", {...})`` and ``N = NamedTuple("N", [(...), ...])`` at module level, as classes.
|
|
90
|
+
|
|
91
|
+
Each class keeps the position of its assignment, whose source builds it at runtime.
|
|
92
|
+
|
|
93
|
+
Example:
|
|
94
|
+
>>> tree = ast.parse('R = TypedDict("R", {"a": int}, total=False)')
|
|
95
|
+
>>> [ast.unparse(c) for c in _functional_classes(tree, {"TypedDict": "TypedDict"})]
|
|
96
|
+
['class R(TypedDict, total=False):\\n a: int']
|
|
97
|
+
"""
|
|
98
|
+
classes: list[ast.ClassDef] = []
|
|
99
|
+
for stmt in tree.body:
|
|
100
|
+
if not (
|
|
101
|
+
isinstance(stmt, ast.Assign)
|
|
102
|
+
and len(stmt.targets) == 1
|
|
103
|
+
and isinstance(target := stmt.targets[0], ast.Name)
|
|
104
|
+
and isinstance(call := stmt.value, ast.Call)
|
|
105
|
+
and len(call.args) == 2
|
|
106
|
+
):
|
|
107
|
+
continue
|
|
108
|
+
name = _get_name(call.func) or ""
|
|
109
|
+
kind, spec = aliases.get(name, name), call.args[1]
|
|
110
|
+
if kind == "TypedDict" and isinstance(spec, ast.Dict):
|
|
111
|
+
pairs = list(zip(spec.keys, spec.values, strict=True))
|
|
112
|
+
elif kind == "NamedTuple" and isinstance(spec, (ast.List, ast.Tuple)):
|
|
113
|
+
pairs = [
|
|
114
|
+
(item.elts[0], item.elts[1])
|
|
115
|
+
for item in spec.elts
|
|
116
|
+
if isinstance(item, ast.Tuple) and len(item.elts) == 2
|
|
117
|
+
]
|
|
118
|
+
if len(pairs) != len(spec.elts):
|
|
119
|
+
continue
|
|
120
|
+
else:
|
|
121
|
+
continue
|
|
122
|
+
fields = [
|
|
123
|
+
(key.value, value)
|
|
124
|
+
for key, value in pairs
|
|
125
|
+
if isinstance(key, ast.Constant) and isinstance(key.value, str)
|
|
126
|
+
]
|
|
127
|
+
if len(fields) != len(pairs):
|
|
128
|
+
continue
|
|
129
|
+
body: list[ast.stmt] = [
|
|
130
|
+
ast.copy_location(
|
|
131
|
+
ast.AnnAssign(target=ast.Name(field, ast.Store()), annotation=value, simple=1),
|
|
132
|
+
value,
|
|
133
|
+
)
|
|
134
|
+
for field, value in fields
|
|
135
|
+
]
|
|
136
|
+
node = ast.ClassDef(
|
|
137
|
+
name=target.id,
|
|
138
|
+
bases=[call.func],
|
|
139
|
+
keywords=call.keywords,
|
|
140
|
+
body=body or [ast.Pass()],
|
|
141
|
+
decorator_list=[],
|
|
142
|
+
type_params=[],
|
|
143
|
+
)
|
|
144
|
+
classes.append(ast.copy_location(node, stmt))
|
|
145
|
+
return classes
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _base_names(node: ast.ClassDef) -> list[str]:
|
|
149
|
+
"""Names of bases spelled as bare names."""
|
|
150
|
+
return [base.id for base in node.bases if isinstance(base, ast.Name)]
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _lineage(node: ast.ClassDef, classes: dict[str, ast.ClassDef]) -> dict[str, ast.ClassDef]:
|
|
154
|
+
"""``node`` and its earlier-defined bases among ``classes``, bases first."""
|
|
155
|
+
lineage: dict[str, ast.ClassDef] = {}
|
|
156
|
+
for name in _base_names(node):
|
|
157
|
+
if (base := classes.get(name)) is not None and base.lineno < node.lineno:
|
|
158
|
+
lineage |= _lineage(base, classes)
|
|
159
|
+
return lineage | {node.name: node}
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
class _Openness(typing.NamedTuple):
|
|
163
|
+
"""``closed`` / ``extra_items`` as written in a TypedDict header."""
|
|
164
|
+
|
|
165
|
+
spelling: str # e.g. "closed=True", "extra_items=ReadOnly[int]"
|
|
166
|
+
closed: bool
|
|
167
|
+
extra_items: str | None = None
|
|
168
|
+
readonly: bool = False
|
|
169
|
+
extra_node: ast.expr | None = None
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _own_openness(keywords: dict[str, ast.expr], aliases: dict[str, str]) -> _Openness | None:
|
|
173
|
+
"""The openness a class header declares; ``extra_items=Never`` is ``closed=True``."""
|
|
174
|
+
if (kw := keywords.get("extra_items")) is not None:
|
|
175
|
+
spelling = f"extra_items={ast.unparse(kw)}"
|
|
176
|
+
extra = _unwrap_qualifiers_ast(kw, aliases)[0]
|
|
177
|
+
if _is_name(extra, "Never", aliases) or _is_name(extra, "NoReturn", aliases):
|
|
178
|
+
return _Openness(spelling, closed=True)
|
|
179
|
+
readonly = isinstance(kw, ast.Subscript) and _is_name(kw.value, "ReadOnly", aliases)
|
|
180
|
+
return _Openness(spelling, False, _normalize_type_str(ast.unparse(extra)), readonly, extra)
|
|
181
|
+
if isinstance(kw := keywords.get("closed"), ast.Constant) and isinstance(kw.value, bool):
|
|
182
|
+
return _Openness(f"closed={kw.value}", kw.value)
|
|
183
|
+
return None
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _extra_repr(info: TypeInfo) -> str:
|
|
187
|
+
if info.extra_items_type is None:
|
|
188
|
+
return str(info.extra_items)
|
|
189
|
+
return _type_repr(info.extra_items_type)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _header_errors(
|
|
193
|
+
name: str,
|
|
194
|
+
keywords: dict[str, ast.expr],
|
|
195
|
+
own: _Openness | None,
|
|
196
|
+
own_type: typing.Any,
|
|
197
|
+
parents: list[TypeInfo],
|
|
198
|
+
) -> list[str]:
|
|
199
|
+
"""PEP 728 violations of a subclass header against its closed / ``extra_items`` bases.
|
|
200
|
+
|
|
201
|
+
``closed=False`` cannot reopen them, a closed base admits no ``extra_items``,
|
|
202
|
+
a mutable base ``extra_items`` must be kept as is, and a read-only one may
|
|
203
|
+
only be narrowed or closed.
|
|
204
|
+
"""
|
|
205
|
+
closed_kw = keywords.get("closed")
|
|
206
|
+
reopen = isinstance(closed_kw, ast.Constant) and closed_kw.value is False
|
|
207
|
+
errors: list[str] = []
|
|
208
|
+
for p in parents:
|
|
209
|
+
if not p.keyed or own is None:
|
|
210
|
+
continue
|
|
211
|
+
base = f"base {p.owner}"
|
|
212
|
+
if reopen:
|
|
213
|
+
what = "is closed" if p.closed else "has extra_items"
|
|
214
|
+
errors.append(f"{name} cannot set closed=False: {base} {what}")
|
|
215
|
+
elif p.closed and not own.closed:
|
|
216
|
+
errors.append(f"{name} cannot set {own.spelling}: {base} is closed")
|
|
217
|
+
elif p.extra_items is not None and not p.extra_items_readonly:
|
|
218
|
+
if own.closed or own.readonly or _consistent(own_type, p.extra_items_type) is False:
|
|
219
|
+
errors.append(
|
|
220
|
+
f"{name} cannot set {own.spelling}: {base} has mutable extra_items "
|
|
221
|
+
f"{_extra_repr(p)}"
|
|
222
|
+
)
|
|
223
|
+
elif p.extra_items_readonly and _is_subtype(own_type, p.extra_items_type) is False:
|
|
224
|
+
errors.append(
|
|
225
|
+
f"{name} cannot set {own.spelling}: {base} has read-only extra_items "
|
|
226
|
+
f"{_extra_repr(p)}"
|
|
227
|
+
)
|
|
228
|
+
return errors
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _key_errors(
|
|
232
|
+
info: TypeInfo, key_types: dict[str, typing.Any], parents: list[TypeInfo]
|
|
233
|
+
) -> list[str]:
|
|
234
|
+
"""PEP 728 violations of the keys ``info`` has beyond each closed / ``extra_items`` base.
|
|
235
|
+
|
|
236
|
+
Keys brought in by a sibling base count. A closed base admits no new keys;
|
|
237
|
+
under a read-only ``extra_items`` they must be assignable to it, under a
|
|
238
|
+
mutable one ``NotRequired`` and consistent with it.
|
|
239
|
+
"""
|
|
240
|
+
errors: list[str] = []
|
|
241
|
+
for p in parents:
|
|
242
|
+
if not p.keyed:
|
|
243
|
+
continue
|
|
244
|
+
base_keys = dict(p.fields)
|
|
245
|
+
for key in (k for k, _ in info.fields if k not in base_keys):
|
|
246
|
+
tp = key_types.get(key)
|
|
247
|
+
if p.closed:
|
|
248
|
+
errors.append(f"{info.name} cannot add key '{key}' to closed base {p.owner}")
|
|
249
|
+
continue
|
|
250
|
+
what = f"extra_items {_extra_repr(p)}"
|
|
251
|
+
if p.extra_items_readonly:
|
|
252
|
+
fits = _is_subtype(tp, p.extra_items_type)
|
|
253
|
+
what = f"read-only {what}"
|
|
254
|
+
else:
|
|
255
|
+
fits = _consistent(tp, p.extra_items_type)
|
|
256
|
+
if key in info.required:
|
|
257
|
+
errors.append(
|
|
258
|
+
f"{info.name}.{key} must be NotRequired: base {p.owner} has {what}"
|
|
259
|
+
)
|
|
260
|
+
if fits is False:
|
|
261
|
+
errors.append(
|
|
262
|
+
f"{info.name}.{key} is {_type_repr(tp)} but base {p.owner} has {what}"
|
|
263
|
+
)
|
|
264
|
+
return errors
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _set_openness(
|
|
268
|
+
info: TypeInfo, own: _Openness | None, own_type: typing.Any, parents: list[TypeInfo]
|
|
269
|
+
) -> None:
|
|
270
|
+
"""Take a valid header's openness, else the first closed / ``extra_items`` base's."""
|
|
271
|
+
if own is not None:
|
|
272
|
+
info.closed, info.extra_items, info.extra_items_readonly = (
|
|
273
|
+
own.closed,
|
|
274
|
+
own.extra_items,
|
|
275
|
+
own.readonly,
|
|
276
|
+
)
|
|
277
|
+
info.extra_items_type = own_type if own.extra_items is not None else None
|
|
278
|
+
elif keyed := [p for p in parents if p.keyed]:
|
|
279
|
+
base = keyed[0]
|
|
280
|
+
info.closed, info.extra_items = base.closed, base.extra_items
|
|
281
|
+
info.extra_items_readonly, info.extra_items_type = (
|
|
282
|
+
base.extra_items_readonly,
|
|
283
|
+
base.extra_items_type,
|
|
284
|
+
)
|
|
285
|
+
info.owner = base.owner
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
_GENERICS = (list, dict, set, frozenset, tuple)
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
_AST_TYPES: dict[str, typing.Any] = {
|
|
292
|
+
"int": int,
|
|
293
|
+
"float": float,
|
|
294
|
+
"complex": complex,
|
|
295
|
+
"str": str,
|
|
296
|
+
"bytes": bytes,
|
|
297
|
+
"bool": bool,
|
|
298
|
+
"object": object,
|
|
299
|
+
"list": list,
|
|
300
|
+
"dict": dict,
|
|
301
|
+
"set": set,
|
|
302
|
+
"frozenset": frozenset,
|
|
303
|
+
"tuple": tuple,
|
|
304
|
+
"Any": typing.Any,
|
|
305
|
+
"Never": typing.Never,
|
|
306
|
+
"NoReturn": typing.Never,
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
_TYPING_GENERICS: dict[str, typing.Any] = {
|
|
311
|
+
"List": list,
|
|
312
|
+
"Dict": dict,
|
|
313
|
+
"Set": set,
|
|
314
|
+
"FrozenSet": frozenset,
|
|
315
|
+
"Tuple": tuple,
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
_STRICT_TYPES: dict[str, type] = {
|
|
320
|
+
"StrictInt": int,
|
|
321
|
+
"StrictFloat": float,
|
|
322
|
+
"StrictBool": bool,
|
|
323
|
+
"StrictStr": str,
|
|
324
|
+
"StrictBytes": bytes,
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
_STRICT_NAMES = {
|
|
329
|
+
f"{m}.{n}": t for m in ("pydantic", "pydantic.types") for n, t in _STRICT_TYPES.items()
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
_IMPORTED_TYPES: dict[str, typing.Any] = {
|
|
334
|
+
"decimal.Decimal": decimal.Decimal,
|
|
335
|
+
"datetime.date": datetime.date,
|
|
336
|
+
"datetime.datetime": datetime.datetime,
|
|
337
|
+
"datetime.time": datetime.time,
|
|
338
|
+
"datetime.timedelta": datetime.timedelta,
|
|
339
|
+
"uuid.UUID": uuid.UUID,
|
|
340
|
+
**_STRICT_NAMES,
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def _ast_type(
|
|
345
|
+
node: ast.expr,
|
|
346
|
+
aliases: dict[str, str],
|
|
347
|
+
newtypes: dict[str, ast.Assign | typing.Any] | None = None,
|
|
348
|
+
imports: dict[str, str] | None = None,
|
|
349
|
+
) -> typing.Any:
|
|
350
|
+
"""Builtin scalars and generics, ``Any``, ``Never``, NewTypes and their unions from source; None if unknown.
|
|
351
|
+
|
|
352
|
+
``aliases`` maps local names to ``typing`` names (see ``ParsedSource.typing_aliases``), so
|
|
353
|
+
``A`` for ``from typing import Any as A`` and ``t.Any`` for
|
|
354
|
+
``import typing as t`` resolve; ``Annotated`` metadata is dropped.
|
|
355
|
+
``typing`` generic aliases (``List``, ``Dict``, ``Set``, ``FrozenSet``,
|
|
356
|
+
``Tuple``) resolve to their builtins only when imported from ``typing``
|
|
357
|
+
or ``typing_extensions``.
|
|
358
|
+
``newtypes`` maps names to their ``NewType`` assignments (see `_newtype_assignments`), or to
|
|
359
|
+
a ``NewType`` already resolved, such as one imported from a checked module.
|
|
360
|
+
With ``imports`` (see ``ParsedSource.imported_names``), the ``decimal``,
|
|
361
|
+
``datetime`` and ``uuid`` types and Pydantic's ``Strict*`` aliases resolve too.
|
|
362
|
+
"""
|
|
363
|
+
newtypes = newtypes or {}
|
|
364
|
+
if isinstance(node, ast.Constant) and node.value is None:
|
|
365
|
+
return type(None)
|
|
366
|
+
if imports and (tp := _IMPORTED_TYPES.get(_qualname(node, imports) or "")):
|
|
367
|
+
return tp
|
|
368
|
+
if isinstance(node, ast.Name) and isinstance(resolved := newtypes.get(node.id), typing.NewType):
|
|
369
|
+
return resolved
|
|
370
|
+
if isinstance(node, ast.Name) and (assign := newtypes.get(node.id)):
|
|
371
|
+
others = {k: v for k, v in newtypes.items() if k != node.id}
|
|
372
|
+
supertype = _ast_type(typing.cast(ast.Call, assign.value).args[1], aliases, others, imports)
|
|
373
|
+
return None if supertype is None else typing.NewType(node.id, supertype) # ty: ignore[invalid-newtype]
|
|
374
|
+
if isinstance(node, ast.Name):
|
|
375
|
+
known = _AST_TYPES | _TYPING_GENERICS if node.id in aliases else _AST_TYPES
|
|
376
|
+
return known.get(aliases.get(node.id, node.id))
|
|
377
|
+
if isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name):
|
|
378
|
+
module = aliases.get(node.value.id, node.value.id)
|
|
379
|
+
return (_AST_TYPES | _TYPING_GENERICS).get(node.attr) if module in _TYPING_MODULES else None
|
|
380
|
+
if isinstance(node, ast.Subscript) and _is_name(node.value, "Annotated", aliases):
|
|
381
|
+
return _ast_type(
|
|
382
|
+
node.slice.elts[0] if isinstance(node.slice, ast.Tuple) else node.slice,
|
|
383
|
+
aliases,
|
|
384
|
+
newtypes,
|
|
385
|
+
imports,
|
|
386
|
+
)
|
|
387
|
+
if isinstance(node, ast.Subscript) and _is_name(node.value, "Literal", aliases):
|
|
388
|
+
items = node.slice.elts if isinstance(node.slice, ast.Tuple) else [node.slice]
|
|
389
|
+
if all(isinstance(i, ast.Constant) and isinstance(i.value, (str, int)) for i in items):
|
|
390
|
+
literal: typing.Any = typing.Literal
|
|
391
|
+
return literal[tuple(typing.cast(ast.Constant, i).value for i in items)]
|
|
392
|
+
return None
|
|
393
|
+
if (
|
|
394
|
+
isinstance(node, ast.Subscript)
|
|
395
|
+
and (origin := _ast_type(node.value, aliases, newtypes, imports)) in _GENERICS
|
|
396
|
+
):
|
|
397
|
+
args = node.slice.elts if isinstance(node.slice, ast.Tuple) else [node.slice]
|
|
398
|
+
return types.GenericAlias(
|
|
399
|
+
origin, tuple(_ast_type(a, aliases, newtypes, imports) or typing.Any for a in args)
|
|
400
|
+
)
|
|
401
|
+
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.BitOr):
|
|
402
|
+
members = [node.left, node.right]
|
|
403
|
+
elif isinstance(node, ast.Subscript) and _is_name(node.value, "Optional", aliases):
|
|
404
|
+
members = [node.slice, ast.Constant(None)]
|
|
405
|
+
elif isinstance(node, ast.Subscript) and _is_name(node.value, "Union", aliases):
|
|
406
|
+
members = list(node.slice.elts) if isinstance(node.slice, ast.Tuple) else [node.slice]
|
|
407
|
+
else:
|
|
408
|
+
return None
|
|
409
|
+
resolved = [_ast_type(m, aliases, newtypes, imports) for m in members]
|
|
410
|
+
return None if None in resolved else functools.reduce(operator.or_, resolved)
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def _annotation_type(annotation: str) -> typing.Any:
|
|
414
|
+
"""Parse an annotation string into a type as `_ast_type` does; None if it can't be resolved.
|
|
415
|
+
|
|
416
|
+
Only for annotations without their module's imports; ``typing.X`` resolves.
|
|
417
|
+
"""
|
|
418
|
+
try:
|
|
419
|
+
return _ast_type(ast.parse(annotation, mode="eval").body, {n: n for n in _TYPING_GENERICS})
|
|
420
|
+
except SyntaxError:
|
|
421
|
+
return None
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def _ast_key_types(
|
|
425
|
+
nodes: list[ast.ClassDef],
|
|
426
|
+
aliases: dict[str, str],
|
|
427
|
+
newtypes: dict[str, ast.Assign | typing.Any],
|
|
428
|
+
imports: dict[str, str] | None = None,
|
|
429
|
+
) -> dict[str, typing.Any]:
|
|
430
|
+
"""Key types of a TypedDict lineage (bases first) from source, as by ``_ast_type``."""
|
|
431
|
+
return {
|
|
432
|
+
item.target.id: _ast_type(
|
|
433
|
+
_unwrap_qualifiers_ast(item.annotation, aliases)[0], aliases, newtypes, imports
|
|
434
|
+
)
|
|
435
|
+
for node in nodes
|
|
436
|
+
for item in node.body
|
|
437
|
+
if isinstance(item, ast.AnnAssign) and isinstance(item.target, ast.Name)
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def _ast_annotations(nodes: list[ast.ClassDef], aliases: dict[str, str]) -> dict[str, ast.expr]:
|
|
442
|
+
"""Field annotations of a class lineage (bases first), qualifiers stripped, ``| None`` kept."""
|
|
443
|
+
return {
|
|
444
|
+
item.target.id: _unwrap_qualifiers_ast(item.annotation, aliases)[0]
|
|
445
|
+
for node in nodes
|
|
446
|
+
for item in node.body
|
|
447
|
+
if isinstance(item, ast.AnnAssign) and isinstance(item.target, ast.Name)
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def _is_name(node: ast.expr, name: str, aliases: dict[str, str]) -> bool:
|
|
452
|
+
return (n := _get_name(node)) is not None and aliases.get(n, n) == name
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def _qualname(node: ast.expr, imports: dict[str, str]) -> str | None:
|
|
456
|
+
"""The dotted name ``node`` spells, its first part resolved through ``imports``.
|
|
457
|
+
|
|
458
|
+
Example:
|
|
459
|
+
>>> _qualname(ast.parse("dt.date", mode="eval").body, {"dt": "datetime"})
|
|
460
|
+
'datetime.date'
|
|
461
|
+
"""
|
|
462
|
+
if isinstance(node, ast.Name):
|
|
463
|
+
return imports.get(node.id, node.id)
|
|
464
|
+
if isinstance(node, ast.Attribute) and (base := _qualname(node.value, imports)):
|
|
465
|
+
return f"{base}.{node.attr}"
|
|
466
|
+
return None
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def _get_name(node: ast.expr) -> str | None:
|
|
470
|
+
"""Get the simple name from an AST expression."""
|
|
471
|
+
if isinstance(node, ast.Name):
|
|
472
|
+
return node.id
|
|
473
|
+
if isinstance(node, ast.Attribute):
|
|
474
|
+
return node.attr
|
|
475
|
+
if isinstance(node, ast.Call):
|
|
476
|
+
return _get_name(node.func)
|
|
477
|
+
return None
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def _extract_fields_from_ast(
|
|
481
|
+
node: ast.ClassDef,
|
|
482
|
+
aliases: dict[str, str] | None = None,
|
|
483
|
+
*,
|
|
484
|
+
total: bool = True,
|
|
485
|
+
defaults_optional: bool = False,
|
|
486
|
+
) -> tuple[list[tuple[str, str]], frozenset[str]]:
|
|
487
|
+
"""Extract annotated fields as (name, type_str) pairs plus required names.
|
|
488
|
+
|
|
489
|
+
Qualifiers are stripped from the type strings. This is the fallback
|
|
490
|
+
when runtime resolution is not available. With ``defaults_optional``
|
|
491
|
+
(dataclasses, Pydantic models) a field with a default is not required.
|
|
492
|
+
"""
|
|
493
|
+
fields: list[tuple[str, str]] = []
|
|
494
|
+
required: set[str] = set()
|
|
495
|
+
for item in node.body:
|
|
496
|
+
if isinstance(item, ast.AnnAssign) and isinstance(item.target, ast.Name):
|
|
497
|
+
annotation, is_required = _unwrap_qualifiers_ast(item.annotation, aliases or {})
|
|
498
|
+
fields.append((item.target.id, _normalize_type_str(ast.unparse(annotation))))
|
|
499
|
+
if _metadata_has_default(item.annotation, aliases or {}):
|
|
500
|
+
continue
|
|
501
|
+
if defaults_optional:
|
|
502
|
+
if not _has_default(item.value):
|
|
503
|
+
required.add(item.target.id)
|
|
504
|
+
elif total if is_required is None else is_required:
|
|
505
|
+
required.add(item.target.id)
|
|
506
|
+
return fields, frozenset(required)
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def _has_default(value: ast.expr | None) -> bool:
|
|
510
|
+
"""Whether a dataclass / Pydantic field assigned ``value`` has a default.
|
|
511
|
+
|
|
512
|
+
Example:
|
|
513
|
+
>>> [_has_default(ast.parse(s, mode="eval").body) for s in ("1", "field(default_factory=list)", "Field(...)", "field()", "Field(0)")]
|
|
514
|
+
[True, True, False, False, True]
|
|
515
|
+
"""
|
|
516
|
+
if value is None:
|
|
517
|
+
return False
|
|
518
|
+
if isinstance(value, ast.Call) and _get_name(value.func) in ("field", "Field"):
|
|
519
|
+
defaults = {"default", "default_factory", "factory"}
|
|
520
|
+
if any(k.arg in defaults for k in value.keywords):
|
|
521
|
+
return True
|
|
522
|
+
first = value.args[0] if value.args else None
|
|
523
|
+
return first is not None and not (isinstance(first, ast.Constant) and first.value is ...)
|
|
524
|
+
return True
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def _field_calls(annotation: ast.expr, aliases: dict[str, str]) -> list[ast.Call]:
|
|
528
|
+
"""``Field(...)`` / ``field(...)`` calls in the ``Annotated`` metadata of ``annotation``.
|
|
529
|
+
|
|
530
|
+
Example:
|
|
531
|
+
>>> a = ast.parse("NotRequired[Annotated[list[str], Field(default_factory=list), 1]]", mode="eval").body
|
|
532
|
+
>>> [ast.unparse(c) for c in _field_calls(a, {})]
|
|
533
|
+
['Field(default_factory=list)']
|
|
534
|
+
"""
|
|
535
|
+
calls: list[ast.Call] = []
|
|
536
|
+
while isinstance(annotation, ast.Subscript):
|
|
537
|
+
name = _get_name(annotation.value)
|
|
538
|
+
name = aliases.get(name, name) if name else None
|
|
539
|
+
if name == "Annotated" and isinstance(annotation.slice, ast.Tuple):
|
|
540
|
+
elts = annotation.slice.elts
|
|
541
|
+
calls += [
|
|
542
|
+
m
|
|
543
|
+
for m in elts[1:]
|
|
544
|
+
if isinstance(m, ast.Call) and _get_name(m.func) in ("field", "Field")
|
|
545
|
+
]
|
|
546
|
+
annotation = elts[0]
|
|
547
|
+
elif name in _QUALIFIERS:
|
|
548
|
+
annotation = annotation.slice
|
|
549
|
+
else:
|
|
550
|
+
break
|
|
551
|
+
return calls
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
def _metadata_has_default(annotation: ast.expr, aliases: dict[str, str]) -> bool:
|
|
555
|
+
"""Whether ``Annotated`` metadata of ``annotation`` declares a default (any row kind)."""
|
|
556
|
+
return any(_has_default(call) for call in _field_calls(annotation, aliases))
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
def _metadata_defaults(node: ast.ClassDef, aliases: dict[str, str]) -> list[str]:
|
|
560
|
+
"""Names of the fields of ``node`` whose ``Annotated`` metadata declares a default."""
|
|
561
|
+
return [
|
|
562
|
+
item.target.id
|
|
563
|
+
for item in node.body
|
|
564
|
+
if isinstance(item, ast.AnnAssign)
|
|
565
|
+
and isinstance(item.target, ast.Name)
|
|
566
|
+
and _metadata_has_default(item.annotation, aliases)
|
|
567
|
+
]
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def _config_options(node: ast.ClassDef, config: ast.expr | None = None) -> dict[str, ast.expr]:
|
|
571
|
+
"""Pydantic config of ``node``: ``model_config`` / ``__pydantic_config__ = ConfigDict(...)`` / ``{...}``, ``class Config`` or ``config``."""
|
|
572
|
+
options: dict[str, ast.expr] = {}
|
|
573
|
+
|
|
574
|
+
def read(value: ast.expr | None) -> None:
|
|
575
|
+
if isinstance(value, ast.Call):
|
|
576
|
+
options.update({k.arg: k.value for k in value.keywords if k.arg})
|
|
577
|
+
elif isinstance(value, ast.Dict):
|
|
578
|
+
options.update(
|
|
579
|
+
{
|
|
580
|
+
k.value: v
|
|
581
|
+
for k, v in zip(value.keys, value.values, strict=True)
|
|
582
|
+
if isinstance(k, ast.Constant) and isinstance(k.value, str)
|
|
583
|
+
}
|
|
584
|
+
)
|
|
585
|
+
|
|
586
|
+
options.update({k.arg: k.value for k in node.keywords if k.arg})
|
|
587
|
+
read(config)
|
|
588
|
+
names = ("model_config", "__pydantic_config__")
|
|
589
|
+
for item in node.body:
|
|
590
|
+
if (
|
|
591
|
+
isinstance(item, ast.Assign)
|
|
592
|
+
and any(isinstance(t, ast.Name) and t.id in names for t in item.targets)
|
|
593
|
+
or (
|
|
594
|
+
isinstance(item, ast.AnnAssign)
|
|
595
|
+
and isinstance(item.target, ast.Name)
|
|
596
|
+
and item.target.id in names
|
|
597
|
+
)
|
|
598
|
+
):
|
|
599
|
+
read(item.value)
|
|
600
|
+
elif isinstance(item, ast.ClassDef) and item.name == "Config":
|
|
601
|
+
for stmt in item.body:
|
|
602
|
+
if isinstance(stmt, ast.Assign):
|
|
603
|
+
options.update(
|
|
604
|
+
{t.id: stmt.value for t in stmt.targets if isinstance(t, ast.Name)}
|
|
605
|
+
)
|
|
606
|
+
return options
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
def _is_true(node: ast.expr | None) -> bool:
|
|
610
|
+
return isinstance(node, ast.Constant) and node.value is True
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
def _pydantic_config(
|
|
614
|
+
node: ast.ClassDef, kind: str, imports: dict[str, str]
|
|
615
|
+
) -> dict[str, ast.expr] | None:
|
|
616
|
+
"""Config of a Pydantic model or ``pydantic.dataclasses.dataclass``; None for other rows."""
|
|
617
|
+
if kind == "BaseModel":
|
|
618
|
+
return _config_options(node)
|
|
619
|
+
for decorator in node.decorator_list:
|
|
620
|
+
call = decorator if isinstance(decorator, ast.Call) else None
|
|
621
|
+
if _qualname(call.func if call else decorator, imports) == "pydantic.dataclasses.dataclass":
|
|
622
|
+
keywords = call.keywords if call else []
|
|
623
|
+
return _config_options(
|
|
624
|
+
node, next((k.value for k in keywords if k.arg == "config"), None)
|
|
625
|
+
)
|
|
626
|
+
return None
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
def _strict(call: ast.Call) -> bool | None:
|
|
630
|
+
"""``strict`` set by ``Field(strict=...)`` or ``Strict(...)``; None if unset."""
|
|
631
|
+
name = _get_name(call.func)
|
|
632
|
+
if name not in ("Field", "Strict"):
|
|
633
|
+
return None
|
|
634
|
+
value = next((k.value for k in call.keywords if k.arg == "strict"), None)
|
|
635
|
+
if name == "Strict":
|
|
636
|
+
value = call.args[0] if call.args else value or ast.Constant(True)
|
|
637
|
+
return (
|
|
638
|
+
value.value if isinstance(value, ast.Constant) and isinstance(value.value, bool) else None
|
|
639
|
+
)
|
|
640
|
+
|
|
641
|
+
|
|
642
|
+
def _lax_fields(
|
|
643
|
+
node: ast.ClassDef,
|
|
644
|
+
config: dict[str, ast.expr],
|
|
645
|
+
aliases: dict[str, str],
|
|
646
|
+
imports: dict[str, str],
|
|
647
|
+
) -> frozenset[str]:
|
|
648
|
+
"""Fields of a Pydantic row that are not strict, by ``config``, ``Field``, ``Strict()`` or ``Strict*`` types."""
|
|
649
|
+
model = _is_true(config.get("strict"))
|
|
650
|
+
lax: set[str] = set()
|
|
651
|
+
for item in node.body:
|
|
652
|
+
if not (isinstance(item, ast.AnnAssign) and isinstance(item.target, ast.Name)):
|
|
653
|
+
continue
|
|
654
|
+
pending, members = [item.annotation], []
|
|
655
|
+
metadata: list[ast.expr | None] = []
|
|
656
|
+
while pending:
|
|
657
|
+
annotation = pending.pop()
|
|
658
|
+
name = _get_name(annotation.value) if isinstance(annotation, ast.Subscript) else None
|
|
659
|
+
name = aliases.get(name, name) if name else None
|
|
660
|
+
if isinstance(annotation, ast.BinOp) and isinstance(annotation.op, ast.BitOr):
|
|
661
|
+
pending += [annotation.left, annotation.right]
|
|
662
|
+
elif not isinstance(annotation, ast.Subscript):
|
|
663
|
+
members.append(annotation)
|
|
664
|
+
elif name == "Annotated" and isinstance(annotation.slice, ast.Tuple):
|
|
665
|
+
metadata[:0] = annotation.slice.elts[1:]
|
|
666
|
+
pending.append(annotation.slice.elts[0])
|
|
667
|
+
elif name in (*_QUALIFIERS, "Optional"):
|
|
668
|
+
pending.append(annotation.slice)
|
|
669
|
+
elif name == "Union" and isinstance(annotation.slice, ast.Tuple):
|
|
670
|
+
pending += annotation.slice.elts
|
|
671
|
+
else:
|
|
672
|
+
members.append(annotation)
|
|
673
|
+
metadata.append(item.value)
|
|
674
|
+
found = [s for m in metadata if isinstance(m, ast.Call) and (s := _strict(m)) is not None]
|
|
675
|
+
typed = any(_qualname(m, imports) in _STRICT_NAMES for m in members)
|
|
676
|
+
if not (typed or (found[-1] if found else model)):
|
|
677
|
+
lax.add(item.target.id)
|
|
678
|
+
return frozenset(lax)
|
|
679
|
+
|
|
680
|
+
|
|
681
|
+
def _allows_extra(node: ast.ClassDef, options: dict[str, ast.expr]) -> bool:
|
|
682
|
+
"""Whether a Pydantic model keeps undeclared columns: ``extra="allow"``, or a config not read.
|
|
683
|
+
|
|
684
|
+
``extra="ignore"`` (the default) drops them and ``extra="forbid"`` rejects them. A config
|
|
685
|
+
sqlty cannot read from source (a ``model_config`` that is not a literal, ``**`` options, a
|
|
686
|
+
base other than ``BaseModel`` and ``Generic``) may allow them.
|
|
687
|
+
|
|
688
|
+
Example:
|
|
689
|
+
>>> cls = lambda src: ast.parse(src).body[0]
|
|
690
|
+
>>> _allows_extra(cls("class A(BaseModel): x: int"), {})
|
|
691
|
+
False
|
|
692
|
+
>>> _allows_extra(cls("class A(BaseModel): model_config = CONFIG"), {})
|
|
693
|
+
True
|
|
694
|
+
"""
|
|
695
|
+
if (extra := options.get("extra")) is not None:
|
|
696
|
+
value = (
|
|
697
|
+
extra.value
|
|
698
|
+
if isinstance(extra, ast.Constant)
|
|
699
|
+
else extra.attr
|
|
700
|
+
if isinstance(extra, ast.Attribute)
|
|
701
|
+
else None
|
|
702
|
+
)
|
|
703
|
+
return value not in ("ignore", "forbid")
|
|
704
|
+
if any(k.arg is None for k in node.keywords):
|
|
705
|
+
return True
|
|
706
|
+
for base in node.bases:
|
|
707
|
+
root = base.value if isinstance(base, ast.Subscript) else base
|
|
708
|
+
if _get_name(root) not in ("BaseModel", "Generic"):
|
|
709
|
+
return True
|
|
710
|
+
names = ("model_config", "__pydantic_config__")
|
|
711
|
+
for item in node.body:
|
|
712
|
+
targets = (
|
|
713
|
+
item.targets
|
|
714
|
+
if isinstance(item, ast.Assign)
|
|
715
|
+
else [item.target]
|
|
716
|
+
if isinstance(item, ast.AnnAssign)
|
|
717
|
+
else []
|
|
718
|
+
)
|
|
719
|
+
if not any(isinstance(t, ast.Name) and t.id in names for t in targets):
|
|
720
|
+
continue
|
|
721
|
+
config = typing.cast(ast.Assign | ast.AnnAssign, item).value
|
|
722
|
+
if isinstance(config, ast.Call):
|
|
723
|
+
if any(k.arg is None for k in config.keywords) or config.args:
|
|
724
|
+
return True
|
|
725
|
+
elif isinstance(config, ast.Dict):
|
|
726
|
+
if None in config.keys:
|
|
727
|
+
return True
|
|
728
|
+
else:
|
|
729
|
+
return True
|
|
730
|
+
return False
|
|
731
|
+
|
|
732
|
+
|
|
733
|
+
def _set_pydantic_names(info: TypeInfo, node: ast.ClassDef) -> None:
|
|
734
|
+
"""Read validation aliases and the ``extra`` setting from the class source.
|
|
735
|
+
|
|
736
|
+
A field is matched by its ``alias`` / ``validation_alias`` string (either
|
|
737
|
+
that or its name with ``populate_by_name=True``). ``AliasChoices``,
|
|
738
|
+
``AliasPath``, non-literal aliases and ``alias_generator`` leave the
|
|
739
|
+
field's names unknown (``opaque``).
|
|
740
|
+
"""
|
|
741
|
+
options = _config_options(node)
|
|
742
|
+
info.allows_extra = _allows_extra(node, options)
|
|
743
|
+
by_name = _is_true(options.get("populate_by_name")) or _is_true(options.get("validate_by_name"))
|
|
744
|
+
generated = "alias_generator" in options and not (
|
|
745
|
+
isinstance(options["alias_generator"], ast.Constant)
|
|
746
|
+
and options["alias_generator"].value is None
|
|
747
|
+
)
|
|
748
|
+
columns: dict[str, str] = {}
|
|
749
|
+
opaque: set[str] = set()
|
|
750
|
+
for item in node.body:
|
|
751
|
+
if not (isinstance(item, ast.AnnAssign) and isinstance(item.target, ast.Name)):
|
|
752
|
+
continue
|
|
753
|
+
name = item.target.id
|
|
754
|
+
calls = _field_calls(item.annotation, {})
|
|
755
|
+
if isinstance(item.value, ast.Call) and _get_name(item.value.func) == "Field":
|
|
756
|
+
calls.append(item.value)
|
|
757
|
+
keywords = {k.arg: k.value for call in calls for k in call.keywords if k.arg}
|
|
758
|
+
spec = keywords.get("validation_alias", keywords.get("alias"))
|
|
759
|
+
if spec is None:
|
|
760
|
+
if generated:
|
|
761
|
+
opaque.add(name)
|
|
762
|
+
else:
|
|
763
|
+
columns[name] = name
|
|
764
|
+
elif isinstance(spec, ast.Constant) and isinstance(spec.value, str):
|
|
765
|
+
columns[spec.value] = name
|
|
766
|
+
if by_name:
|
|
767
|
+
columns.setdefault(name, name)
|
|
768
|
+
else:
|
|
769
|
+
opaque.add(name)
|
|
770
|
+
info.columns = columns
|
|
771
|
+
info.opaque = frozenset(opaque)
|
|
772
|
+
|
|
773
|
+
|
|
774
|
+
def _unwrap_qualifiers_ast(
|
|
775
|
+
annotation: ast.expr, aliases: dict[str, str]
|
|
776
|
+
) -> tuple[ast.expr, bool | None]:
|
|
777
|
+
"""Strip qualifier subscripts; report ``Required`` (True) / ``NotRequired`` (False)."""
|
|
778
|
+
required: bool | None = None
|
|
779
|
+
while isinstance(annotation, ast.Subscript):
|
|
780
|
+
name = _get_name(annotation.value)
|
|
781
|
+
name = aliases.get(name, name) if name else None
|
|
782
|
+
if name not in _QUALIFIERS:
|
|
783
|
+
break
|
|
784
|
+
if name != "ReadOnly":
|
|
785
|
+
required = name == "Required"
|
|
786
|
+
annotation = annotation.slice
|
|
787
|
+
return annotation, required
|
|
788
|
+
|
|
789
|
+
|
|
790
|
+
def _split_type_args(s: str) -> list[str]:
|
|
791
|
+
"""Split comma-separated type arguments, respecting nested brackets."""
|
|
792
|
+
parts: list[str] = []
|
|
793
|
+
depth = 0
|
|
794
|
+
current: list[str] = []
|
|
795
|
+
for ch in s:
|
|
796
|
+
if ch == "[":
|
|
797
|
+
depth += 1
|
|
798
|
+
current.append(ch)
|
|
799
|
+
elif ch == "]":
|
|
800
|
+
depth -= 1
|
|
801
|
+
current.append(ch)
|
|
802
|
+
elif ch == "," and depth == 0:
|
|
803
|
+
parts.append("".join(current).strip())
|
|
804
|
+
current = []
|
|
805
|
+
else:
|
|
806
|
+
current.append(ch)
|
|
807
|
+
if current:
|
|
808
|
+
parts.append("".join(current).strip())
|
|
809
|
+
return parts
|
|
810
|
+
|
|
811
|
+
|
|
812
|
+
def _normalize_type_str(type_str: str) -> str:
|
|
813
|
+
"""Normalize a type string — strips Optional/None wrappers.
|
|
814
|
+
|
|
815
|
+
Used as fallback when runtime resolution is not available.
|
|
816
|
+
"""
|
|
817
|
+
if " | None" in type_str:
|
|
818
|
+
type_str = type_str.replace(" | None", "")
|
|
819
|
+
if "None | " in type_str:
|
|
820
|
+
type_str = type_str.replace("None | ", "")
|
|
821
|
+
if type_str.startswith("Optional[") and type_str.endswith("]"):
|
|
822
|
+
type_str = type_str[9:-1]
|
|
823
|
+
return type_str.strip()
|