sqlty 0.1.0__cp315-cp315-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sqlty/__init__.py +99 -0
- sqlty/__main__.py +5 -0
- sqlty/_breaking.py +191 -0
- sqlty/_check.py +880 -0
- sqlty/_cli.py +1219 -0
- sqlty/_config.py +666 -0
- sqlty/_core.cp315-win_amd64.pyd +0 -0
- sqlty/_core.pyi +108 -0
- sqlty/_decode.py +62 -0
- sqlty/_drivers.py +274 -0
- sqlty/_gitignore.py +58 -0
- sqlty/_helpers.py +613 -0
- sqlty/_json_shape.py +299 -0
- sqlty/_json_types.py +225 -0
- sqlty/_lint.py +350 -0
- sqlty/_params.py +177 -0
- sqlty/_psycopg.py +269 -0
- sqlty/_source.py +654 -0
- sqlty/_type_extractor/__init__.py +51 -0
- sqlty/_type_extractor/ast_fields.py +823 -0
- sqlty/_type_extractor/compat.py +252 -0
- sqlty/_type_extractor/extract.py +179 -0
- sqlty/_type_extractor/generic.py +95 -0
- sqlty/_type_extractor/info.py +161 -0
- sqlty/_type_extractor/sandbox.py +385 -0
- sqlty/_type_extractor/subtype.py +156 -0
- sqlty/_widening.py +89 -0
- sqlty/core.py +566 -0
- sqlty/drivers/psycopg.py +104 -0
- sqlty/magic.py +126 -0
- sqlty/py.typed +0 -0
- sqlty/rules/ambiguous-column.md +48 -0
- sqlty/rules/column-count-mismatch.md +30 -0
- sqlty/rules/column-name-mismatch.md +34 -0
- sqlty/rules/column-type-mismatch.md +75 -0
- sqlty/rules/fstring-skipped.md +23 -0
- sqlty/rules/inline-sql-comment.md +27 -0
- sqlty/rules/insert-missing-column.md +58 -0
- sqlty/rules/json-shape-mismatch.md +96 -0
- sqlty/rules/literal-mismatch.md +83 -0
- sqlty/rules/mysql-sql-marker.md +32 -0
- sqlty/rules/nullable-mismatch.md +76 -0
- sqlty/rules/param-count-mismatch.md +66 -0
- sqlty/rules/param-type-mismatch.md +73 -0
- sqlty/rules/redundant-literal.md +68 -0
- sqlty/rules/redundant-optional.md +100 -0
- sqlty/rules/select-star-no-schema.md +24 -0
- sqlty/rules/select-star.md +77 -0
- sqlty/rules/stale-rewrite.md +33 -0
- sqlty/rules/stale-type.md +50 -0
- sqlty/rules/tstring-skipped.md +68 -0
- sqlty/rules/typeddict-inheritance.md +35 -0
- sqlty/rules/typeddict-key-mismatch.md +38 -0
- sqlty/rules/unchecked-query.md +34 -0
- sqlty/rules/ungrouped-column.md +67 -0
- sqlty/rules/unknown-column.md +68 -0
- sqlty/rules/unknown-function.md +49 -0
- sqlty/rules/unknown-table.md +47 -0
- sqlty/rules/unknown-type.md +74 -0
- sqlty/rules/unparsed-query.md +46 -0
- sqlty/rules/unsupported-syntax.md +69 -0
- sqlty/rules/untyped-query.md +39 -0
- sqlty/rules/unused-ignore.md +36 -0
- sqlty/skill/SKILL.md +110 -0
- sqlty-0.1.0.dist-info/METADATA +210 -0
- sqlty-0.1.0.dist-info/RECORD +71 -0
- sqlty-0.1.0.dist-info/WHEEL +4 -0
- sqlty-0.1.0.dist-info/entry_points.txt +2 -0
- sqlty-0.1.0.dist-info/licenses/LICENSE +21 -0
- sqlty-0.1.0.dist-info/sboms/sqlty-core.cyclonedx.json +1891 -0
- sqlty_magic.pth +1 -0
sqlty/_lint.py
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
"""Lint rule registry — ty-style per-rule severity configuration.
|
|
2
|
+
|
|
3
|
+
Rules use kebab-case names and have three severity levels:
|
|
4
|
+
- "error": hard failure (exit code 1)
|
|
5
|
+
- "warn": warning (exit code 0, shown in output)
|
|
6
|
+
- "ignore": suppressed entirely
|
|
7
|
+
|
|
8
|
+
Configuration via pyproject.toml:
|
|
9
|
+
|
|
10
|
+
[tool.sqlty.rules]
|
|
11
|
+
column-count-mismatch = "error" # default
|
|
12
|
+
column-type-mismatch = "error" # default
|
|
13
|
+
column-name-mismatch = "warn" # default
|
|
14
|
+
nullable-mismatch = "error" # default
|
|
15
|
+
json-shape-mismatch = "error" # default
|
|
16
|
+
redundant-optional = "ignore" # default
|
|
17
|
+
literal-mismatch = "error" # default
|
|
18
|
+
redundant-literal = "ignore" # default
|
|
19
|
+
typeddict-key-mismatch = "error" # default
|
|
20
|
+
typeddict-inheritance = "error" # default
|
|
21
|
+
select-star = "warn" # default
|
|
22
|
+
select-star-no-schema = "error" # default
|
|
23
|
+
stale-rewrite = "warn" # default
|
|
24
|
+
stale-type = "warn" # default
|
|
25
|
+
inline-sql-comment = "warn" # default
|
|
26
|
+
fstring-skipped = "warn" # default
|
|
27
|
+
tstring-skipped = "warn" # default
|
|
28
|
+
unchecked-query = "warn" # default
|
|
29
|
+
untyped-query = "warn" # default
|
|
30
|
+
unparsed-query = "warn" # default
|
|
31
|
+
unknown-table = "error" # default
|
|
32
|
+
unknown-column = "error" # default
|
|
33
|
+
ambiguous-column = "error" # default
|
|
34
|
+
unknown-function = "warn" # default
|
|
35
|
+
unknown-type = "warn" # default
|
|
36
|
+
unsupported-syntax = "warn" # default
|
|
37
|
+
insert-missing-column = "error" # default
|
|
38
|
+
ungrouped-column = "error" # default
|
|
39
|
+
unused-ignore = "warn" # default
|
|
40
|
+
param-count-mismatch = "error" # default
|
|
41
|
+
param-type-mismatch = "error" # default
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
from __future__ import annotations
|
|
45
|
+
|
|
46
|
+
from dataclasses import dataclass
|
|
47
|
+
from enum import Enum
|
|
48
|
+
from typing import TypedDict
|
|
49
|
+
|
|
50
|
+
from sqlty._core import name_rules
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class Severity(Enum):
|
|
54
|
+
"""Lint rule severity level."""
|
|
55
|
+
|
|
56
|
+
ERROR = "error"
|
|
57
|
+
WARN = "warn"
|
|
58
|
+
IGNORE = "ignore"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass(frozen=True)
|
|
62
|
+
class LintRule:
|
|
63
|
+
"""A single lint rule definition."""
|
|
64
|
+
|
|
65
|
+
name: str
|
|
66
|
+
default_severity: Severity
|
|
67
|
+
fixable: bool
|
|
68
|
+
description: str
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
# Rules that explain why a column is untyped, as the engine lists them; the entries in
|
|
72
|
+
# ``RULES`` below must cover them (``tests/test_name_rules.py``).
|
|
73
|
+
NAME_RULES: tuple[str, ...] = tuple(name_rules())
|
|
74
|
+
|
|
75
|
+
# --- Rule definitions ---
|
|
76
|
+
|
|
77
|
+
RULES: dict[str, LintRule] = {
|
|
78
|
+
"column-count-mismatch": LintRule(
|
|
79
|
+
name="column-count-mismatch",
|
|
80
|
+
default_severity=Severity.ERROR,
|
|
81
|
+
fixable=False,
|
|
82
|
+
description="Annotated type has different number of fields than query columns",
|
|
83
|
+
),
|
|
84
|
+
"column-type-mismatch": LintRule(
|
|
85
|
+
name="column-type-mismatch",
|
|
86
|
+
default_severity=Severity.ERROR,
|
|
87
|
+
fixable=False,
|
|
88
|
+
description="Annotated type field has incompatible type with query column",
|
|
89
|
+
),
|
|
90
|
+
"column-name-mismatch": LintRule(
|
|
91
|
+
name="column-name-mismatch",
|
|
92
|
+
default_severity=Severity.WARN,
|
|
93
|
+
fixable=False,
|
|
94
|
+
description="Annotated NamedTuple field name doesn't match query column alias",
|
|
95
|
+
),
|
|
96
|
+
"typeddict-key-mismatch": LintRule(
|
|
97
|
+
name="typeddict-key-mismatch",
|
|
98
|
+
default_severity=Severity.ERROR,
|
|
99
|
+
fixable=False,
|
|
100
|
+
description="Query columns don't fit the fields of a TypedDict, dataclass or Pydantic model",
|
|
101
|
+
),
|
|
102
|
+
"typeddict-inheritance": LintRule(
|
|
103
|
+
name="typeddict-inheritance",
|
|
104
|
+
default_severity=Severity.ERROR,
|
|
105
|
+
fixable=False,
|
|
106
|
+
description=(
|
|
107
|
+
"TypedDict subclass changes openness or adds keys a closed or extra_items base "
|
|
108
|
+
"forbids (PEP 728)"
|
|
109
|
+
),
|
|
110
|
+
),
|
|
111
|
+
"nullable-mismatch": LintRule(
|
|
112
|
+
name="nullable-mismatch",
|
|
113
|
+
default_severity=Severity.ERROR,
|
|
114
|
+
fixable=False,
|
|
115
|
+
description="Row type field is not optional but its query column can be NULL",
|
|
116
|
+
),
|
|
117
|
+
"json-shape-mismatch": LintRule(
|
|
118
|
+
name="json-shape-mismatch",
|
|
119
|
+
default_severity=Severity.ERROR,
|
|
120
|
+
fixable=False,
|
|
121
|
+
description="Row type field cannot hold the JSON a query column builds",
|
|
122
|
+
),
|
|
123
|
+
"redundant-optional": LintRule(
|
|
124
|
+
name="redundant-optional",
|
|
125
|
+
default_severity=Severity.IGNORE,
|
|
126
|
+
fixable=False,
|
|
127
|
+
description="Row type field is optional but its query column cannot be NULL",
|
|
128
|
+
),
|
|
129
|
+
"literal-mismatch": LintRule(
|
|
130
|
+
name="literal-mismatch",
|
|
131
|
+
default_severity=Severity.ERROR,
|
|
132
|
+
fixable=False,
|
|
133
|
+
description="Row type field is a Literal that does not cover the values its column can take",
|
|
134
|
+
),
|
|
135
|
+
"redundant-literal": LintRule(
|
|
136
|
+
name="redundant-literal",
|
|
137
|
+
default_severity=Severity.IGNORE,
|
|
138
|
+
fixable=False,
|
|
139
|
+
description="Row type field is a Literal that lists values its column can never take",
|
|
140
|
+
),
|
|
141
|
+
"select-star": LintRule(
|
|
142
|
+
name="select-star",
|
|
143
|
+
default_severity=Severity.WARN,
|
|
144
|
+
fixable=True,
|
|
145
|
+
description="SELECT * used — expand to explicit column list",
|
|
146
|
+
),
|
|
147
|
+
"select-star-no-schema": LintRule(
|
|
148
|
+
name="select-star-no-schema",
|
|
149
|
+
default_severity=Severity.ERROR,
|
|
150
|
+
fixable=False,
|
|
151
|
+
description="SELECT * used but no schema available to expand",
|
|
152
|
+
),
|
|
153
|
+
"stale-rewrite": LintRule(
|
|
154
|
+
name="stale-rewrite",
|
|
155
|
+
default_severity=Severity.WARN,
|
|
156
|
+
fixable=True,
|
|
157
|
+
description="Source has --sql strings that aren't wrapped in SQL[T]",
|
|
158
|
+
),
|
|
159
|
+
"stale-type": LintRule(
|
|
160
|
+
name="stale-type",
|
|
161
|
+
default_severity=Severity.WARN,
|
|
162
|
+
fixable=True,
|
|
163
|
+
description="SQL[tuple[...]] type doesn't match current schema (drift)",
|
|
164
|
+
),
|
|
165
|
+
"mysql-sql-marker": LintRule(
|
|
166
|
+
name="mysql-sql-marker",
|
|
167
|
+
default_severity=Severity.WARN,
|
|
168
|
+
fixable=True,
|
|
169
|
+
description='MySQL rejects the "--sql" marker; use "-- sql"',
|
|
170
|
+
),
|
|
171
|
+
"inline-sql-comment": LintRule(
|
|
172
|
+
name="inline-sql-comment",
|
|
173
|
+
default_severity=Severity.WARN,
|
|
174
|
+
fixable=True,
|
|
175
|
+
description='--sql followed by space makes entire query a SQL comment; use "--sql\\nSELECT ..." or run sqlty check --fix',
|
|
176
|
+
),
|
|
177
|
+
"fstring-skipped": LintRule(
|
|
178
|
+
name="fstring-skipped",
|
|
179
|
+
default_severity=Severity.WARN,
|
|
180
|
+
fixable=False,
|
|
181
|
+
description="f-string with --sql prefix skipped (cannot be statically rewritten)",
|
|
182
|
+
),
|
|
183
|
+
"tstring-skipped": LintRule(
|
|
184
|
+
name="tstring-skipped",
|
|
185
|
+
default_severity=Severity.WARN,
|
|
186
|
+
fixable=False,
|
|
187
|
+
description="t-string with --sql prefix skipped (a field changes the SQL in a way sqlty cannot follow)",
|
|
188
|
+
),
|
|
189
|
+
"unchecked-query": LintRule(
|
|
190
|
+
name="unchecked-query",
|
|
191
|
+
default_severity=Severity.WARN,
|
|
192
|
+
fixable=False,
|
|
193
|
+
description="--sql query is not plain string literals (raw, bytes, an expression), so it is not checked",
|
|
194
|
+
),
|
|
195
|
+
"untyped-query": LintRule(
|
|
196
|
+
name="untyped-query",
|
|
197
|
+
default_severity=Severity.WARN,
|
|
198
|
+
fixable=True,
|
|
199
|
+
description="SQL[UNTYPED] query has no inferable row type; the message names why",
|
|
200
|
+
),
|
|
201
|
+
"unparsed-query": LintRule(
|
|
202
|
+
name="unparsed-query",
|
|
203
|
+
default_severity=Severity.WARN,
|
|
204
|
+
fixable=False,
|
|
205
|
+
description="--sql query, SQL[T] query or Annotated helper query that does not parse",
|
|
206
|
+
),
|
|
207
|
+
"unknown-table": LintRule(
|
|
208
|
+
name="unknown-table",
|
|
209
|
+
default_severity=Severity.ERROR,
|
|
210
|
+
fixable=False,
|
|
211
|
+
description="Query reads a table that the schema does not define",
|
|
212
|
+
),
|
|
213
|
+
"unknown-column": LintRule(
|
|
214
|
+
name="unknown-column",
|
|
215
|
+
default_severity=Severity.ERROR,
|
|
216
|
+
fixable=False,
|
|
217
|
+
description="Query reads a column that its table does not have",
|
|
218
|
+
),
|
|
219
|
+
"ambiguous-column": LintRule(
|
|
220
|
+
name="ambiguous-column",
|
|
221
|
+
default_severity=Severity.ERROR,
|
|
222
|
+
fixable=False,
|
|
223
|
+
description="Unqualified column exists in more than one table of the query",
|
|
224
|
+
),
|
|
225
|
+
"unknown-function": LintRule(
|
|
226
|
+
name="unknown-function",
|
|
227
|
+
default_severity=Severity.WARN,
|
|
228
|
+
fixable=False,
|
|
229
|
+
description="Function result is untyped because sqlty does not know the function",
|
|
230
|
+
),
|
|
231
|
+
"unknown-type": LintRule(
|
|
232
|
+
name="unknown-type",
|
|
233
|
+
default_severity=Severity.WARN,
|
|
234
|
+
fixable=False,
|
|
235
|
+
description="Cast or column type has no Python type",
|
|
236
|
+
),
|
|
237
|
+
"unsupported-syntax": LintRule(
|
|
238
|
+
name="unsupported-syntax",
|
|
239
|
+
default_severity=Severity.WARN,
|
|
240
|
+
fixable=False,
|
|
241
|
+
description="Query parses, but a construct in it is not typed, so the row type is not trusted",
|
|
242
|
+
),
|
|
243
|
+
"insert-missing-column": LintRule(
|
|
244
|
+
name="insert-missing-column",
|
|
245
|
+
default_severity=Severity.ERROR,
|
|
246
|
+
fixable=False,
|
|
247
|
+
description="INSERT leaves out a NOT NULL column that has no default",
|
|
248
|
+
),
|
|
249
|
+
"ungrouped-column": LintRule(
|
|
250
|
+
name="ungrouped-column",
|
|
251
|
+
default_severity=Severity.ERROR,
|
|
252
|
+
fixable=False,
|
|
253
|
+
description="Grouped query selects a column it neither groups by nor aggregates",
|
|
254
|
+
),
|
|
255
|
+
"param-count-mismatch": LintRule(
|
|
256
|
+
name="param-count-mismatch",
|
|
257
|
+
default_severity=Severity.ERROR,
|
|
258
|
+
fixable=False,
|
|
259
|
+
description="A call passes a different number of parameters, or different names, than its query has placeholders",
|
|
260
|
+
),
|
|
261
|
+
"param-type-mismatch": LintRule(
|
|
262
|
+
name="param-type-mismatch",
|
|
263
|
+
default_severity=Severity.ERROR,
|
|
264
|
+
fixable=False,
|
|
265
|
+
description="A call passes an argument whose type can't be the type its query parameter takes",
|
|
266
|
+
),
|
|
267
|
+
"unused-ignore": LintRule(
|
|
268
|
+
name="unused-ignore",
|
|
269
|
+
default_severity=Severity.WARN,
|
|
270
|
+
fixable=False,
|
|
271
|
+
description="# sqlty: ignore comment, or rule in one, that suppresses no diagnostic",
|
|
272
|
+
),
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
class Diagnostic(TypedDict):
|
|
277
|
+
"""One ``check_source`` result: a plain dict, so ``diag["rule"]`` keeps working.
|
|
278
|
+
|
|
279
|
+
``severity`` is ``"error"`` or ``"warn"``; ``line`` is 1-based.
|
|
280
|
+
"""
|
|
281
|
+
|
|
282
|
+
rule: str
|
|
283
|
+
message: str
|
|
284
|
+
severity: str
|
|
285
|
+
line: int
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
class RuleConfig:
|
|
289
|
+
"""Resolved rule configuration — maps rule names to effective severities.
|
|
290
|
+
|
|
291
|
+
Merges defaults with user overrides from [tool.sqlty.rules].
|
|
292
|
+
"""
|
|
293
|
+
|
|
294
|
+
def __init__(self, overrides: dict[str, str] | None = None) -> None:
|
|
295
|
+
self._severities: dict[str, Severity] = {}
|
|
296
|
+
|
|
297
|
+
# Start with defaults
|
|
298
|
+
for name, rule in RULES.items():
|
|
299
|
+
self._severities[name] = rule.default_severity
|
|
300
|
+
|
|
301
|
+
# Apply user overrides
|
|
302
|
+
if overrides:
|
|
303
|
+
for name, severity_str in overrides.items():
|
|
304
|
+
if name not in RULES:
|
|
305
|
+
continue # ignore unknown rules
|
|
306
|
+
try:
|
|
307
|
+
self._severities[name] = Severity(severity_str)
|
|
308
|
+
except ValueError:
|
|
309
|
+
continue # ignore invalid severity values
|
|
310
|
+
|
|
311
|
+
def severity(self, rule_name: str) -> Severity:
|
|
312
|
+
"""Get the effective severity for a rule."""
|
|
313
|
+
return self._severities.get(rule_name, Severity.WARN)
|
|
314
|
+
|
|
315
|
+
def is_enabled(self, rule_name: str) -> bool:
|
|
316
|
+
"""Check if a rule is enabled (not ignored)."""
|
|
317
|
+
return self.severity(rule_name) != Severity.IGNORE
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
DOCS_URL = "https://jirikuncar.github.io/sqlty/"
|
|
321
|
+
"""The documentation site, which ``rule_doc`` links to."""
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def rule_doc(name: str) -> str:
|
|
325
|
+
"""Markdown documentation of a rule, shipped as ``sqlty/rules/<name>.md``, its links
|
|
326
|
+
to other pages pointing at the documentation site: the repository's relative paths
|
|
327
|
+
mean nothing in a user's terminal.
|
|
328
|
+
|
|
329
|
+
Example:
|
|
330
|
+
>>> rule_doc("stale-type").splitlines()[0]
|
|
331
|
+
'# stale-type'
|
|
332
|
+
>>> "](https://jirikuncar.github.io/sqlty/guide/schema-inference/)" in rule_doc("insert-missing-column")
|
|
333
|
+
True
|
|
334
|
+
"""
|
|
335
|
+
import re
|
|
336
|
+
from importlib.resources import files
|
|
337
|
+
|
|
338
|
+
text = (files("sqlty") / "rules" / f"{name}.md").read_text(encoding="utf-8")
|
|
339
|
+
|
|
340
|
+
def absolute(match: re.Match[str]) -> str:
|
|
341
|
+
path, anchor = match["path"], match["anchor"] or ""
|
|
342
|
+
if path.startswith("../../../docs/"):
|
|
343
|
+
return (
|
|
344
|
+
f"]({DOCS_URL}{path.removeprefix('../../../docs/').removesuffix('.md')}/{anchor})"
|
|
345
|
+
)
|
|
346
|
+
if "/" not in path:
|
|
347
|
+
return f"]({DOCS_URL}reference/rules/#{path.removesuffix('.md')})"
|
|
348
|
+
return match[0]
|
|
349
|
+
|
|
350
|
+
return re.sub(r"\]\((?P<path>[^)\s:]+\.md)(?P<anchor>#[^)\s]*)?\)", absolute, text)
|
sqlty/_params.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
"""Arguments passed to the parameters of a query, judged against the types the query gives them.
|
|
2
|
+
|
|
3
|
+
``arg_type`` reads the type of an argument where the source states it: a literal, a
|
|
4
|
+
variable annotated or assigned a class, a call of a known class. ``mismatches`` compares a
|
|
5
|
+
call's arguments with ``sqlty.core.analyze_params``; an argument of unknown type is never
|
|
6
|
+
reported.
|
|
7
|
+
|
|
8
|
+
Example:
|
|
9
|
+
>>> import ast
|
|
10
|
+
>>> from sqlty._source import ParsedSource
|
|
11
|
+
>>> parsed = ParsedSource("f(1, 'a', None, [1.5], date(2020, 1, 1))\\nfrom datetime import date")
|
|
12
|
+
>>> call = parsed.calls[0]
|
|
13
|
+
>>> [arg_type(a, parsed, parsed.scopes_of(call)) for a in call.args]
|
|
14
|
+
['int', 'str', 'None', 'list[float]', 'datetime.date']
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import ast
|
|
20
|
+
from typing import TYPE_CHECKING, NamedTuple
|
|
21
|
+
|
|
22
|
+
if TYPE_CHECKING:
|
|
23
|
+
from sqlty._source import ParsedSource, _Stack
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ParamArg(NamedTuple):
|
|
27
|
+
"""An argument of a query call: the parameter it binds (1-based position or name) and its type, if known."""
|
|
28
|
+
|
|
29
|
+
key: int | str
|
|
30
|
+
type: str | None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# Classes whose instances have a known type: builtins by name, the rest by the dotted name
|
|
34
|
+
# they are imported as.
|
|
35
|
+
_BUILTINS = frozenset({"int", "str", "float", "bool", "bytes"})
|
|
36
|
+
_IMPORTED = frozenset(
|
|
37
|
+
{
|
|
38
|
+
"datetime.date",
|
|
39
|
+
"datetime.datetime",
|
|
40
|
+
"datetime.time",
|
|
41
|
+
"datetime.timedelta",
|
|
42
|
+
"uuid.UUID",
|
|
43
|
+
"decimal.Decimal",
|
|
44
|
+
}
|
|
45
|
+
)
|
|
46
|
+
_SEQUENCES = frozenset({"list", "tuple", "set", "frozenset"})
|
|
47
|
+
|
|
48
|
+
# What a parameter of a given type takes. Any ``str`` is taken for any type: the server
|
|
49
|
+
# coerces text (psycopg sends it untyped), so only the other types are judged.
|
|
50
|
+
_NUMBERS = frozenset({"int", "float", "bool", "decimal.Decimal"})
|
|
51
|
+
_ACCEPTS: dict[str, frozenset[str]] = {
|
|
52
|
+
"int": _NUMBERS,
|
|
53
|
+
"float": _NUMBERS,
|
|
54
|
+
"decimal.Decimal": _NUMBERS,
|
|
55
|
+
"str": frozenset({"str"}),
|
|
56
|
+
"bool": frozenset({"bool", "int"}),
|
|
57
|
+
"bytes": frozenset({"bytes"}),
|
|
58
|
+
"datetime.date": frozenset({"datetime.date", "datetime.datetime"}),
|
|
59
|
+
"datetime.datetime": frozenset({"datetime.date", "datetime.datetime"}),
|
|
60
|
+
"datetime.time": frozenset({"datetime.time"}),
|
|
61
|
+
"datetime.timedelta": frozenset({"datetime.timedelta"}),
|
|
62
|
+
"uuid.UUID": frozenset({"uuid.UUID"}),
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def arg_type(expr: ast.expr, parsed: ParsedSource, stack: _Stack) -> str | None:
|
|
67
|
+
"""The type ``expr`` has where the source says so, else ``None``.
|
|
68
|
+
|
|
69
|
+
Spelled as the engine spells parameter types: ``int``, ``datetime.date``,
|
|
70
|
+
``list[int]``; ``None`` is ``"None"``. A list, tuple or set is ``list[T]`` when all its
|
|
71
|
+
items have type ``T``, else ``list``.
|
|
72
|
+
"""
|
|
73
|
+
match expr:
|
|
74
|
+
case ast.Constant(value=None):
|
|
75
|
+
return "None"
|
|
76
|
+
case ast.Constant(value=value) if type(value) in (bool, int, float, str, bytes):
|
|
77
|
+
return type(value).__name__
|
|
78
|
+
case ast.UnaryOp(op=ast.USub() | ast.UAdd(), operand=ast.Constant(value=float())):
|
|
79
|
+
return "float"
|
|
80
|
+
case ast.UnaryOp(op=ast.USub() | ast.UAdd(), operand=ast.Constant(value=int())):
|
|
81
|
+
return "int"
|
|
82
|
+
case ast.JoinedStr():
|
|
83
|
+
return "str"
|
|
84
|
+
case ast.List(elts=items) | ast.Tuple(elts=items) | ast.Set(elts=items):
|
|
85
|
+
types = {
|
|
86
|
+
None if isinstance(item, ast.Starred) else arg_type(item, parsed, stack)
|
|
87
|
+
for item in items
|
|
88
|
+
}
|
|
89
|
+
if len(types) == 1 and None not in types and "None" not in types:
|
|
90
|
+
return f"list[{types.pop()}]"
|
|
91
|
+
return "list"
|
|
92
|
+
case ast.Name(id=name):
|
|
93
|
+
return _class(parsed.type_of(stack, name), parsed)
|
|
94
|
+
case ast.Call(func=func):
|
|
95
|
+
return _class(_dotted(func), parsed)
|
|
96
|
+
return None
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _dotted(node: ast.expr) -> str | None:
|
|
100
|
+
parts: list[str] = []
|
|
101
|
+
while isinstance(node, ast.Attribute):
|
|
102
|
+
parts.append(node.attr)
|
|
103
|
+
node = node.value
|
|
104
|
+
return ".".join([node.id, *reversed(parts)]) if isinstance(node, ast.Name) else None
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _class(name: str | None, parsed: ParsedSource) -> str | None:
|
|
108
|
+
"""The type of an instance of the class spelled ``name`` in ``parsed``, when it is a known one."""
|
|
109
|
+
if name is None:
|
|
110
|
+
return None
|
|
111
|
+
head, _, rest = name.partition(".")
|
|
112
|
+
imported = parsed.imported_names.get(head)
|
|
113
|
+
if imported is None:
|
|
114
|
+
return name if name in _BUILTINS else "list" if name in _SEQUENCES else None
|
|
115
|
+
full = f"{imported}.{rest}" if rest else imported
|
|
116
|
+
return full if full in _IMPORTED else None
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def mismatch(
|
|
120
|
+
expected: str | None, nullable: bool | None, actual: str | None, *, postgres: bool = False
|
|
121
|
+
) -> str | None:
|
|
122
|
+
"""Why a value of type ``actual`` can't be passed for a parameter of type ``expected``, else ``None``.
|
|
123
|
+
|
|
124
|
+
PostgreSQL has no implicit cast between ``boolean`` and the number types, and the
|
|
125
|
+
drivers send a ``bool`` as a ``boolean`` and an ``int`` as an integer, so with
|
|
126
|
+
``postgres`` neither is taken for the other.
|
|
127
|
+
|
|
128
|
+
Example:
|
|
129
|
+
>>> mismatch("int", None, "datetime.date")
|
|
130
|
+
'expects int, got datetime.date'
|
|
131
|
+
>>> mismatch("int", False, "None")
|
|
132
|
+
'is not nullable, got None'
|
|
133
|
+
>>> mismatch("list[int]", None, "list[bytes]")
|
|
134
|
+
'expects list[int], got list[bytes]'
|
|
135
|
+
>>> [mismatch("int", None, a) for a in ("bool", "str", "float", None)]
|
|
136
|
+
[None, None, None, None]
|
|
137
|
+
>>> mismatch("int", None, "bool", postgres=True), mismatch("bool", None, "int", postgres=True)
|
|
138
|
+
('expects int, got bool', 'expects bool, got int')
|
|
139
|
+
"""
|
|
140
|
+
if actual is None:
|
|
141
|
+
return None
|
|
142
|
+
if actual == "None":
|
|
143
|
+
return "is not nullable, got None" if nullable is False else None
|
|
144
|
+
if expected is None or actual == "str":
|
|
145
|
+
return None
|
|
146
|
+
if expected.startswith("list["):
|
|
147
|
+
if actual.startswith("list["):
|
|
148
|
+
inner = mismatch(expected[5:-1], None, actual[5:-1], postgres=postgres)
|
|
149
|
+
return None if inner is None else f"expects {expected}, got {actual}"
|
|
150
|
+
return None if actual == "list" else f"expects {expected}, got {actual}"
|
|
151
|
+
accepted = _ACCEPTS.get(expected)
|
|
152
|
+
if postgres and accepted is not None:
|
|
153
|
+
accepted = accepted - ({"int"} if expected == "bool" else {"bool"})
|
|
154
|
+
if accepted is None or actual in accepted:
|
|
155
|
+
return None
|
|
156
|
+
return f"expects {expected}, got {actual}"
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def literal_params(
|
|
160
|
+
arg: ast.expr | None, parsed: ParsedSource, stack: _Stack
|
|
161
|
+
) -> tuple[ParamArg, ...] | None:
|
|
162
|
+
"""The arguments a tuple or list literal, or a dict literal of string keys, passes; else ``None``."""
|
|
163
|
+
if isinstance(arg, (ast.Tuple, ast.List)) and not any(
|
|
164
|
+
isinstance(item, ast.Starred) for item in arg.elts
|
|
165
|
+
):
|
|
166
|
+
return tuple(
|
|
167
|
+
ParamArg(i, arg_type(item, parsed, stack)) for i, item in enumerate(arg.elts, 1)
|
|
168
|
+
)
|
|
169
|
+
if isinstance(arg, ast.Dict) and all(
|
|
170
|
+
isinstance(key, ast.Constant) and isinstance(key.value, str) for key in arg.keys
|
|
171
|
+
):
|
|
172
|
+
return tuple(
|
|
173
|
+
ParamArg(str(key.value), arg_type(value, parsed, stack))
|
|
174
|
+
for key, value in zip(arg.keys, arg.values, strict=True)
|
|
175
|
+
if isinstance(key, ast.Constant)
|
|
176
|
+
)
|
|
177
|
+
return None
|