tuple-rows¶
Default severity: error
What it does¶
Reports a query whose row type is a class (SQL[UserRow]) run by a driver method that
returns rows of its own: execute of a psycopg, sqlite3 or aiosqlite connection or cursor
returns tuples, and asyncpg's fetch, fetchrow and fetchmany return asyncpg.Records.
A module that mentions row_factory or record_class is not checked, since it may build
other rows.
from typing import NamedTuple
import psycopg
from sqlty import SQL
class UserRow(NamedTuple):
id: int
users = SQL[UserRow]("--sql\nSELECT 1::INTEGER AS id")
conn = psycopg.connect()
# error: [tuple-rows] "psycopg returns tuples here, not `UserRow` rows: run the query with `sqlty.drivers.psycopg.execute`"
rows = conn.execute(users).fetchall()
Open in playgroundWhy is this bad?¶
The type checker reads row.id as an int, but the row is a tuple, so it raises
AttributeError at runtime. A TypedDict row fails on row["id"], and a dataclass or
Pydantic row is never built.
Fix¶
Run the query with the sqlty.drivers helper, which builds each row as the class:
from typing import NamedTuple
import psycopg
from sqlty import SQL
from sqlty.drivers.psycopg import execute
class UserRow(NamedTuple):
id: int
users = SQL[UserRow]("--sql\nSELECT 1::INTEGER AS id")
conn = psycopg.connect()
rows = execute(conn, users).fetchall()
Open in playgroundOr give the query a tuple[...] row type, which is what the driver returns.