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/magic.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""The ``sqlty`` source codec: ``--sql`` strings become ``SQL[T](...)`` when imported or run.
|
|
2
|
+
|
|
3
|
+
Modules opt in with a coding declaration on their first or second line::
|
|
4
|
+
|
|
5
|
+
# coding: sqlty
|
|
6
|
+
q = "--sql\\nSELECT 1::INTEGER" # Python sees SQL[tuple[int]]("--sql\\nSELECT 1::INTEGER")
|
|
7
|
+
|
|
8
|
+
Importing this module registers the codec. The ``sqlty_magic.pth`` file that a
|
|
9
|
+
non-editable install puts in ``site-packages`` registers a lookup at interpreter startup
|
|
10
|
+
that imports this module only when a file declares the codec.
|
|
11
|
+
``SQLTY_NO_MAGIC=1`` skips the registration. Other files, UTF-8 ones included,
|
|
12
|
+
are never transformed.
|
|
13
|
+
|
|
14
|
+
``sqlty._decode.decode`` transforms bytes without registering anything, and
|
|
15
|
+
``python -m sqlty.magic FILE`` prints a module as the codec decodes it.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import codecs
|
|
21
|
+
import encodings
|
|
22
|
+
import io
|
|
23
|
+
import os
|
|
24
|
+
import sys
|
|
25
|
+
from collections.abc import Buffer
|
|
26
|
+
from encodings.utf_8 import StreamReader as _Utf8StreamReader
|
|
27
|
+
from typing import TYPE_CHECKING, Any
|
|
28
|
+
|
|
29
|
+
# Import decode from _decode module to avoid circular imports
|
|
30
|
+
from sqlty._decode import decode
|
|
31
|
+
|
|
32
|
+
# Re-export decode for backward compatibility
|
|
33
|
+
__all__ = ["decode", "register"]
|
|
34
|
+
|
|
35
|
+
if TYPE_CHECKING:
|
|
36
|
+
from codecs import CodecInfo
|
|
37
|
+
|
|
38
|
+
# Get the standard UTF-8 codec
|
|
39
|
+
utf_8_codec = encodings.search_function("utf8")
|
|
40
|
+
assert utf_8_codec is not None, "UTF-8 codec not found"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class IncrementalDecoder(codecs.BufferedIncrementalDecoder):
|
|
44
|
+
"""Incremental decoder for the sqlty-magic codec."""
|
|
45
|
+
|
|
46
|
+
def _buffer_decode(
|
|
47
|
+
self, input: Buffer, errors: str, final: bool
|
|
48
|
+
) -> tuple[str, int]: # pragma: no cover
|
|
49
|
+
if final:
|
|
50
|
+
return decode(input, errors)
|
|
51
|
+
else:
|
|
52
|
+
return "", 0
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class StreamReader(_Utf8StreamReader):
|
|
56
|
+
"""Stream reader for the sqlty-magic codec.
|
|
57
|
+
|
|
58
|
+
Decode is deferred to support better error messages.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
_stream: Any = None
|
|
62
|
+
_decoded: bool = False
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def stream(self) -> Any:
|
|
66
|
+
"""Get the decoded stream."""
|
|
67
|
+
if not self._decoded:
|
|
68
|
+
text, _ = decode(self._stream.read())
|
|
69
|
+
self._stream = io.BytesIO(text.encode("UTF-8"))
|
|
70
|
+
self._decoded = True
|
|
71
|
+
return self._stream
|
|
72
|
+
|
|
73
|
+
@stream.setter
|
|
74
|
+
def stream(self, stream: Any) -> None:
|
|
75
|
+
"""Set the stream to decode."""
|
|
76
|
+
self._stream = stream
|
|
77
|
+
self._decoded = False
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
_sqlty_codec_info = codecs.CodecInfo(
|
|
81
|
+
name="sqlty",
|
|
82
|
+
encode=utf_8_codec.encode,
|
|
83
|
+
decode=decode,
|
|
84
|
+
incrementalencoder=utf_8_codec.incrementalencoder,
|
|
85
|
+
incrementaldecoder=IncrementalDecoder,
|
|
86
|
+
streamreader=StreamReader,
|
|
87
|
+
streamwriter=utf_8_codec.streamwriter,
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _codec_search(encoding: str) -> CodecInfo | None:
|
|
92
|
+
return _sqlty_codec_info if encoding == "sqlty" else None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def register() -> None:
|
|
96
|
+
"""Register the ``sqlty`` codec; registering twice is harmless."""
|
|
97
|
+
codecs.unregister(_codec_search)
|
|
98
|
+
codecs.register(_codec_search)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
if not os.environ.get("SQLTY_NO_MAGIC"):
|
|
102
|
+
register()
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def main(argv: list[str]) -> int:
|
|
106
|
+
import argparse
|
|
107
|
+
|
|
108
|
+
parser = argparse.ArgumentParser(description="Prints transformed source.")
|
|
109
|
+
parser.add_argument("filename")
|
|
110
|
+
args = parser.parse_args(argv)
|
|
111
|
+
|
|
112
|
+
with open(args.filename, "rb") as f:
|
|
113
|
+
text, _ = decode(f.read())
|
|
114
|
+
|
|
115
|
+
# Write to stdout buffer if available, otherwise stdout
|
|
116
|
+
stdout_buffer = getattr(sys.stdout, "buffer", None)
|
|
117
|
+
if stdout_buffer is not None:
|
|
118
|
+
stdout_buffer.write(text.encode("UTF-8"))
|
|
119
|
+
else:
|
|
120
|
+
sys.stdout.write(text)
|
|
121
|
+
|
|
122
|
+
return 0
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
if __name__ == "__main__":
|
|
126
|
+
raise SystemExit(main(sys.argv[1:]))
|
sqlty/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# ambiguous-column
|
|
2
|
+
|
|
3
|
+
Default severity: **error**
|
|
4
|
+
|
|
5
|
+
## What it does
|
|
6
|
+
|
|
7
|
+
Reports an unqualified column that more than one table of the query has.
|
|
8
|
+
|
|
9
|
+
```toml
|
|
10
|
+
[tool.sqlty]
|
|
11
|
+
schema = "schema.sql"
|
|
12
|
+
|
|
13
|
+
[tool.sqlty.rules]
|
|
14
|
+
ambiguous-column = "warn"
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
`schema.sql`:
|
|
18
|
+
|
|
19
|
+
```sql
|
|
20
|
+
CREATE TABLE users (id INTEGER, name TEXT);
|
|
21
|
+
CREATE TABLE orders (id INTEGER, user_id INTEGER);
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
from sqlty import SQL
|
|
26
|
+
|
|
27
|
+
# error: [ambiguous-column] "column reference `id` is ambiguous"
|
|
28
|
+
q = SQL[tuple[int]]("--sql\nSELECT id FROM users u JOIN orders o ON o.user_id = u.id")
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Why is this bad?
|
|
32
|
+
|
|
33
|
+
The database rejects the query. sqlty types the column from the first table that has it, so the annotation can look right while the query fails.
|
|
34
|
+
|
|
35
|
+
## How to fix
|
|
36
|
+
|
|
37
|
+
Qualify the column: `u.id`. A column merged by `USING (id)` or any column of a `NATURAL` join is single and not reported; a subquery's own tables shadow the outer query. To accept one case, put `# sqlty: ignore[ambiguous-column]` on its line.
|
|
38
|
+
|
|
39
|
+
## Configuration
|
|
40
|
+
|
|
41
|
+
An error by default: the database rejects such SQL. Lower or turn it off:
|
|
42
|
+
|
|
43
|
+
```toml
|
|
44
|
+
[tool.sqlty.rules]
|
|
45
|
+
ambiguous-column = "warn"
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Only checked when a schema with tables is configured. Applies to the `postgres`, `mysql` and `sqlite` dialects.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# column-count-mismatch
|
|
2
|
+
|
|
3
|
+
Default severity: **error**
|
|
4
|
+
|
|
5
|
+
## What it does
|
|
6
|
+
|
|
7
|
+
Checks that a user-defined row type (`TypedDict`, `NamedTuple`, dataclass,
|
|
8
|
+
Pydantic model) has as many fields as the query returns columns. A TypedDict, dataclass or
|
|
9
|
+
Pydantic model may omit fields with a default (`NotRequired` keys).
|
|
10
|
+
|
|
11
|
+
## Why is this bad?
|
|
12
|
+
|
|
13
|
+
Drivers build each row from the columns in order. A missing or extra field
|
|
14
|
+
fails at runtime, or silently drops data.
|
|
15
|
+
|
|
16
|
+
## Example
|
|
17
|
+
|
|
18
|
+
```python
|
|
19
|
+
from typing import TypedDict
|
|
20
|
+
|
|
21
|
+
from sqlty import SQL
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class User(TypedDict):
|
|
25
|
+
id: int
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
# error: [column-count-mismatch] "User has 1 fields but query returns 2 columns"
|
|
29
|
+
q = SQL[User]("--sql\nSELECT id::INTEGER, name::TEXT FROM users")
|
|
30
|
+
```
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# column-name-mismatch
|
|
2
|
+
|
|
3
|
+
Default severity: **warn**
|
|
4
|
+
|
|
5
|
+
## What it does
|
|
6
|
+
|
|
7
|
+
Checks that the fields of a `NamedTuple` are named like the query columns,
|
|
8
|
+
in order. `NamedTuple` is matched by position; TypedDicts, dataclasses and
|
|
9
|
+
Pydantic models are matched by name (see
|
|
10
|
+
[`typeddict-key-mismatch`](typeddict-key-mismatch.md)).
|
|
11
|
+
|
|
12
|
+
## Why is this bad?
|
|
13
|
+
|
|
14
|
+
Name-based row factories (`dict_row`, `class_row`) need matching names, and a
|
|
15
|
+
positional mismatch usually means two columns were swapped.
|
|
16
|
+
|
|
17
|
+
## Example
|
|
18
|
+
|
|
19
|
+
```python
|
|
20
|
+
from typing import NamedTuple
|
|
21
|
+
|
|
22
|
+
from sqlty import SQL
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class User(NamedTuple):
|
|
26
|
+
name: str
|
|
27
|
+
email: str
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
# error: [column-name-mismatch] "User.email doesn't match query column 'login'"
|
|
31
|
+
q = SQL[User]("--sql\nSELECT name::TEXT, login::TEXT FROM users")
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Alias the column (`login AS email`) or rename the field.
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# column-type-mismatch
|
|
2
|
+
|
|
3
|
+
Default severity: **error**
|
|
4
|
+
|
|
5
|
+
## What it does
|
|
6
|
+
|
|
7
|
+
Checks each field type of a user-defined row type against the type inferred
|
|
8
|
+
for the matching query column.
|
|
9
|
+
|
|
10
|
+
## Why is this bad?
|
|
11
|
+
|
|
12
|
+
The annotation promises a type the database won't return, so type checkers
|
|
13
|
+
validate code against the wrong row.
|
|
14
|
+
|
|
15
|
+
## Example
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
from datetime import datetime
|
|
19
|
+
from typing import NamedTuple
|
|
20
|
+
|
|
21
|
+
from sqlty import SQL
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Event(NamedTuple):
|
|
25
|
+
id: int
|
|
26
|
+
created_at: str
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
# error: [column-type-mismatch] "Event.created_at is str but query column 'created_at' infers datetime.datetime"
|
|
30
|
+
q = SQL[Event]("--sql\nSELECT id::INTEGER, created_at::TIMESTAMP FROM events")
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
`from datetime import datetime` and `datetime.datetime` are equivalent: types
|
|
34
|
+
are resolved, not compared by spelling.
|
|
35
|
+
|
|
36
|
+
A field passes when it can hold every value of its column: `Any`, a union
|
|
37
|
+
containing `Any` or the column type, and `float` for an `int` column are
|
|
38
|
+
accepted. A narrower field, such as `bool` for an `INTEGER` column, is not.
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
from typing import Any, NamedTuple
|
|
42
|
+
|
|
43
|
+
from sqlty import SQL
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class Row(NamedTuple):
|
|
47
|
+
id: Any
|
|
48
|
+
total: float | None
|
|
49
|
+
active: bool
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
# error: [column-type-mismatch] "Row.active is bool but query column 'active' infers int"
|
|
53
|
+
q = SQL[Row]("--sql\nSELECT id::INTEGER, total::INTEGER, active::INTEGER FROM orders")
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
A `NewType` field is accepted wherever its supertype is, and a parametrised
|
|
57
|
+
generic such as `list[str]` for a column that infers `list` (array element
|
|
58
|
+
types are inferred but not compared):
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
from typing import NamedTuple, NewType
|
|
62
|
+
|
|
63
|
+
from sqlty import SQL
|
|
64
|
+
|
|
65
|
+
UserId = NewType("UserId", int)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class User(NamedTuple):
|
|
69
|
+
id: UserId
|
|
70
|
+
tags: list[str]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
q = SQL[User]("--sql\nSELECT id::INTEGER, tags::TEXT[] FROM users")
|
|
74
|
+
# error:
|
|
75
|
+
```
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# fstring-skipped
|
|
2
|
+
|
|
3
|
+
Default severity: **warn**
|
|
4
|
+
|
|
5
|
+
## What it does
|
|
6
|
+
|
|
7
|
+
Flags f-strings starting with `--sql`, alone or in a concatenation, which
|
|
8
|
+
rewrite leaves alone.
|
|
9
|
+
|
|
10
|
+
## Why is this bad?
|
|
11
|
+
|
|
12
|
+
Interpolated SQL can't be analyzed statically, and string formatting is the
|
|
13
|
+
classic route to SQL injection.
|
|
14
|
+
|
|
15
|
+
## Example
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
# error: [fstring-skipped] "f-string with --sql prefix skipped (f-strings cannot be statically rewritten)"
|
|
19
|
+
q = f"--sql\nSELECT {column}::INTEGER FROM users"
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Pass values as query parameters; build identifiers with your driver's SQL
|
|
23
|
+
composition (`psycopg.sql`).
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# inline-sql-comment
|
|
2
|
+
|
|
3
|
+
Default severity: **warn**
|
|
4
|
+
|
|
5
|
+
## What it does
|
|
6
|
+
|
|
7
|
+
Flags `"--sql SELECT ..."`, where a space instead of a newline follows the
|
|
8
|
+
marker and a SQL statement follows the space.
|
|
9
|
+
|
|
10
|
+
## Why is this bad?
|
|
11
|
+
|
|
12
|
+
`--sql` starts a SQL comment that runs to the end of the line, so the whole
|
|
13
|
+
query is a comment: nothing is inferred and the database receives an empty
|
|
14
|
+
statement.
|
|
15
|
+
|
|
16
|
+
## Example
|
|
17
|
+
|
|
18
|
+
```python
|
|
19
|
+
# error: [inline-sql-comment] ""--sql SELECT ..." treats the query as a SQL comment; use "--sql\nSELECT ..." or run sqlty check --fix"
|
|
20
|
+
q = "--sql SELECT id::INTEGER FROM users"
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Use `"--sql\nSELECT ..."`. Only a statement after the space is reported
|
|
24
|
+
(`SELECT` with a column, `DELETE FROM`, `UPDATE t SET`, `CREATE TABLE`, ...),
|
|
25
|
+
so text such as `"--sql flag enables it"` is not. `sqlty check --fix` makes
|
|
26
|
+
the change when the string is a plain literal (not raw, f- or t-) that this
|
|
27
|
+
rule reports.
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# insert-missing-column
|
|
2
|
+
|
|
3
|
+
Default severity: **error**
|
|
4
|
+
|
|
5
|
+
## What it does
|
|
6
|
+
|
|
7
|
+
Reports an `INSERT` with a column list, or MySQL's `INSERT ... SET`, that leaves
|
|
8
|
+
out a schema column declared `NOT NULL` without a default. A `DEFAULT`,
|
|
9
|
+
`serial`, identity, generated or auto-increment column, and SQLite's
|
|
10
|
+
`INTEGER PRIMARY KEY`, get a value anyway.
|
|
11
|
+
|
|
12
|
+
```toml
|
|
13
|
+
[tool.sqlty]
|
|
14
|
+
schema = "schema.sql"
|
|
15
|
+
|
|
16
|
+
[tool.sqlty.rules]
|
|
17
|
+
insert-missing-column = "warn"
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
`schema.sql`:
|
|
21
|
+
|
|
22
|
+
```sql
|
|
23
|
+
CREATE TABLE users (
|
|
24
|
+
id SERIAL PRIMARY KEY,
|
|
25
|
+
email TEXT NOT NULL,
|
|
26
|
+
name TEXT NOT NULL,
|
|
27
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
28
|
+
bio TEXT
|
|
29
|
+
);
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
# error: [insert-missing-column] "INSERT into `users` leaves out `name`, which is NOT NULL and has no default"
|
|
34
|
+
q = "--sql\nINSERT INTO users (email) VALUES (%s)"
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Why is this bad?
|
|
38
|
+
|
|
39
|
+
The database rejects the row: the column has no value and may not be NULL. A
|
|
40
|
+
migration that adds such a column breaks every `INSERT` written before it, which
|
|
41
|
+
`sqlty breaking` reports.
|
|
42
|
+
|
|
43
|
+
## How to fix
|
|
44
|
+
|
|
45
|
+
Set the column in the `INSERT`, or give it a `DEFAULT` in the schema.
|
|
46
|
+
|
|
47
|
+
## Configuration
|
|
48
|
+
|
|
49
|
+
An error by default: the database rejects such SQL. Lower or turn it off:
|
|
50
|
+
|
|
51
|
+
```toml
|
|
52
|
+
[tool.sqlty.rules]
|
|
53
|
+
insert-missing-column = "warn"
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Needs a [schema](../../../docs/guide/schema-inference.md), and is judged in the
|
|
57
|
+
`postgres`, `mysql` and `sqlite` dialects. An `INSERT` without a column list
|
|
58
|
+
is not checked.
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
# json-shape-mismatch
|
|
2
|
+
|
|
3
|
+
Default severity: **error**
|
|
4
|
+
|
|
5
|
+
## What it does
|
|
6
|
+
|
|
7
|
+
Reports a field of a user-defined row type (or an item of a helper's `tuple[...]` row
|
|
8
|
+
type) that cannot hold the JSON its query column builds. The column must be built in the
|
|
9
|
+
query, with `jsonb_build_object()`, `jsonb_agg()`, `to_jsonb()` and the like (PostgreSQL) or
|
|
10
|
+
`JSON_OBJECT()`, `JSON_ARRAY()`, `JSON_ARRAYAGG()` and `JSON_OBJECTAGG()` (MySQL),
|
|
11
|
+
so that sqlty knows its shape; the annotation is followed through nested `TypedDict`s,
|
|
12
|
+
`list[...]` and `dict[str, ...]`. A scalar of the wrong type, a member that can be `null`
|
|
13
|
+
while the annotation is not optional, a required key the query may omit or never builds,
|
|
14
|
+
and a key the `TypedDict` does not declare are all reported, each with its path. A nested
|
|
15
|
+
Pydantic model is checked for its keys only (by alias, extra keys allowed by
|
|
16
|
+
`extra="allow"`), not for the types of its fields.
|
|
17
|
+
|
|
18
|
+
```toml
|
|
19
|
+
[tool.sqlty]
|
|
20
|
+
schema = "schema.sql"
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
`schema.sql`:
|
|
24
|
+
|
|
25
|
+
```sql
|
|
26
|
+
CREATE TABLE orders (id INTEGER PRIMARY KEY);
|
|
27
|
+
CREATE TABLE lines (id INTEGER PRIMARY KEY, order_id INTEGER NOT NULL, sku TEXT NOT NULL, qty INTEGER NOT NULL);
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
from typing import TypedDict
|
|
32
|
+
|
|
33
|
+
from sqlty import SQL
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Line(TypedDict):
|
|
37
|
+
sku: str
|
|
38
|
+
qty: str
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class Order(TypedDict):
|
|
42
|
+
id: int
|
|
43
|
+
lines: list[Line]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
# error: [json-shape-mismatch] "Order.lines is list[Line] but query column 'lines' builds JSON that does not fit: lines[].qty is str but the query builds an integer"
|
|
47
|
+
q = SQL[Order]("""--sql
|
|
48
|
+
SELECT o.id, (SELECT coalesce(jsonb_agg(jsonb_build_object('sku', l.sku, 'qty', l.qty)), '[]') FROM lines l WHERE l.order_id = o.id) AS lines
|
|
49
|
+
FROM orders o""")
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Why is this bad?
|
|
53
|
+
|
|
54
|
+
The JSON column is `Any` to a type checker, so nothing connects the query that builds the
|
|
55
|
+
document to the `TypedDict` that describes it. The annotation promises `qty: str`; the
|
|
56
|
+
database sends an integer.
|
|
57
|
+
|
|
58
|
+
## How to fix
|
|
59
|
+
|
|
60
|
+
Change the annotation to what the query builds (`qty: int`), or change the query. Where a
|
|
61
|
+
member is optional, use `NotRequired[...]`; where it can be `null`, use `... | None`.
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
from typing import TypedDict
|
|
65
|
+
|
|
66
|
+
from sqlty import SQL
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class Line(TypedDict):
|
|
70
|
+
sku: str
|
|
71
|
+
qty: int
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class Order(TypedDict):
|
|
75
|
+
id: int
|
|
76
|
+
lines: list[Line]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
q = SQL[Order]("""--sql
|
|
80
|
+
SELECT o.id, (SELECT coalesce(jsonb_agg(jsonb_build_object('sku', l.sku, 'qty', l.qty)), '[]') FROM lines l WHERE l.order_id = o.id) AS lines
|
|
81
|
+
FROM orders o""")
|
|
82
|
+
# error:
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
A column of unknown shape (JSON read from a table, `||`, `jsonb_set()`), and a field
|
|
86
|
+
annotated `Any`, `object`, or with a class sqlty cannot see into, are never reported. The
|
|
87
|
+
JSON shapes guide lists the shapes sqlty infers.
|
|
88
|
+
|
|
89
|
+
## Configuration
|
|
90
|
+
|
|
91
|
+
To lower the severity or turn the rule off:
|
|
92
|
+
|
|
93
|
+
```toml
|
|
94
|
+
[tool.sqlty.rules]
|
|
95
|
+
json-shape-mismatch = "warn"
|
|
96
|
+
```
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# literal-mismatch
|
|
2
|
+
|
|
3
|
+
Default severity: **error**
|
|
4
|
+
|
|
5
|
+
## What it does
|
|
6
|
+
|
|
7
|
+
Reports a field of a user-defined row type (or an item of a helper's `tuple[...]` row
|
|
8
|
+
type) annotated with a `Literal` that does not cover every value its query column can
|
|
9
|
+
take. sqlty knows the values of a column from an enum, a `CHECK (col IN (...))` or
|
|
10
|
+
`CHECK (col = ANY (ARRAY[...]))` constraint (also through a domain), a `CASE` or
|
|
11
|
+
`COALESCE` over constants, a `UNION` of such columns, and a constant itself.
|
|
12
|
+
|
|
13
|
+
```toml
|
|
14
|
+
[tool.sqlty]
|
|
15
|
+
schema = "schema.sql"
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
`schema.sql`:
|
|
19
|
+
|
|
20
|
+
```sql
|
|
21
|
+
CREATE TABLE orders (
|
|
22
|
+
id INTEGER PRIMARY KEY,
|
|
23
|
+
status TEXT NOT NULL CHECK (status IN ('pending', 'paid', 'refunded'))
|
|
24
|
+
);
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
from typing import Literal, TypedDict
|
|
29
|
+
|
|
30
|
+
from sqlty import SQL
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Order(TypedDict):
|
|
34
|
+
id: int
|
|
35
|
+
status: Literal["pending", "paid"]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
# error: [literal-mismatch] "Order.status is Literal['pending', 'paid'] but query column 'status' can be 'refunded'"
|
|
39
|
+
q = SQL[Order]("--sql\nSELECT id, status FROM orders")
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Why is this bad?
|
|
43
|
+
|
|
44
|
+
The annotation promises values the database may not return. A type checker narrows on
|
|
45
|
+
`status == "paid"` and treats a `"refunded"` row as impossible.
|
|
46
|
+
|
|
47
|
+
## How to fix
|
|
48
|
+
|
|
49
|
+
Add the missing values to the `Literal`, or narrow the query so it cannot return them
|
|
50
|
+
(`WHERE status IN ('pending', 'paid')` does not narrow the inferred values yet, so list
|
|
51
|
+
them in the annotation or use `str`).
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from typing import Literal, TypedDict
|
|
55
|
+
|
|
56
|
+
from sqlty import SQL
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class Order(TypedDict):
|
|
60
|
+
id: int
|
|
61
|
+
status: Literal["pending", "paid", "refunded"]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
q = SQL[Order]("--sql\nSELECT id, status FROM orders")
|
|
65
|
+
# error:
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
An annotation that takes values by class is never reported: `str` (or `int` for an
|
|
69
|
+
integer column), `Any`, `object`, or an enum class. A column whose values are unknown,
|
|
70
|
+
such as `name::TEXT` or any column without a schema, is never reported either: sqlty
|
|
71
|
+
only reports what the schema or the query proves. A set larger than 32 values is not
|
|
72
|
+
tracked and the column is plain `str` or `int`.
|
|
73
|
+
|
|
74
|
+
## Configuration
|
|
75
|
+
|
|
76
|
+
The rule that finds the opposite, `Literal` values the column can never take, is
|
|
77
|
+
[`redundant-literal`](redundant-literal.md); it is off by default. To lower the severity
|
|
78
|
+
of this rule or turn it off:
|
|
79
|
+
|
|
80
|
+
```toml
|
|
81
|
+
[tool.sqlty.rules]
|
|
82
|
+
literal-mismatch = "warn"
|
|
83
|
+
```
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# mysql-sql-marker
|
|
2
|
+
|
|
3
|
+
Default severity: **warn**
|
|
4
|
+
|
|
5
|
+
## What it does
|
|
6
|
+
|
|
7
|
+
With `dialect = "mysql"`, flags plain string literals that open with the `--sql`
|
|
8
|
+
marker (f-, t- and raw strings are not checked).
|
|
9
|
+
|
|
10
|
+
## Why is this bad?
|
|
11
|
+
|
|
12
|
+
MySQL and MariaDB read `--` as a comment only when whitespace follows it.
|
|
13
|
+
`--sql` is read as two minus signs and a name, so the server rejects the query
|
|
14
|
+
with a syntax error (1064), although sqlty types it.
|
|
15
|
+
|
|
16
|
+
## Example
|
|
17
|
+
|
|
18
|
+
```toml
|
|
19
|
+
[tool.sqlty]
|
|
20
|
+
dialect = "mysql"
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
from sqlty import SQL
|
|
25
|
+
|
|
26
|
+
# error: [mysql-sql-marker] "MySQL reads "--sql" as an expression, not a comment; use "-- sql""
|
|
27
|
+
q = SQL[tuple[int]]("--sql\nSELECT CAST(id AS SIGNED) FROM users")
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Use `"-- sql\nSELECT ..."`, a comment in every dialect, which sqlty also
|
|
31
|
+
reads as the marker. `sqlty check --fix` makes the change in plain string
|
|
32
|
+
literals, wrapped or not.
|