Your SQL already knows its types. SQLTy tells Python.
Type-safe raw SQL without an ORM or a database connection. sqlty reads row and
parameter types from your SQL and schema, and checks them on every commit, so a
migration that changes a column is caught in review, not in production.
A migration makes email nullable. sqlty and mypy find the code that would crash.
(view source)
Fits if you write SQL as string literals on Python 3.14+, against
PostgreSQL, SQLite or MySQL, with a schema dump or SQL migrations in the
repository. Rows are typed end to end with psycopg 3; with other drivers sqlty
checks the query and its parameters, and you annotate what the cursor returns
(Drivers).
Beta. APIs and configuration may change before 1.0. Feedback welcome in
GitHub Issues.
How it works
Drivers return rows of Any, so nothing ties a query's columns to the code
that reads them. Start a query with --sql and a newline, and
sqlty rewrite . adds the row type inferred from your CREATE TABLE
statements:
SQL[T] is a str subclass, so the query still runs anywhere a string does,
and mypy, pyright and ty see T. Without a schema, casts such as id::INTEGER
type the columns; a query with neither stays as it is. With a space instead of
the newline, "--sql SELECT ..." is a SQL comment, and sqlty check warns.
What it catches
A migration changes a column
[tool.sqlty]
schema = "schema.sql"
A migration dropped NOT NULL from email.
schema.sql:
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT);
from sqlty import SQL
# error: [narrow-type] "SQL[tuple[int, str]] should be SQL[tuple[int, str | None]]"
query = SQL[tuple[int, str]]("--sql\nSELECT id, email FROM users")
sqlty check --fix . updates the type, and your type checker finds every
caller that now needs a None check. narrow-type is an error, so CI fails on
it; an annotation that is only wider than the rows, such as str | None for a
column made NOT NULL, is a stale-type warning
(CI). For rolling deploys,
sqlty breaking --against origin/main exits 1 when old code breaks on the new
schema or new code on the old one
(Breaking schema changes).
A row type that doesn't match its query
from typing import TypedDict
from sqlty import SQL
class User(TypedDict):
id: str
name: str