Python API for libsyntaqlite: parse, format, and statically analyze SQLite SQL
Actively maintained. Last release 4 weeks ago, commits in 15 of the last 26 weeks. A safe choice.
pip install syntaqlitelibsyntaqlite for Python
libsyntaqlite is a fast, embeddable parser, formatter, and static analyzer for SQLite SQL. The syntaqlite package provides its Python API.
Docs · Playground · GitHub
pip install syntaqlite
The package requires Python 3.10 or later. Wheels are available for Linux (x86_64, aarch64), macOS (x86_64, arm64), and Windows (x86_64).
API
Everything goes through a Syntaqlite instance. Create one and reuse it across many calls:
import syntaqlite
with syntaqlite.Syntaqlite() as sq:
print(sq.format_sql("select 1"))
Formatting
sql = "select u.id, u.name, p.title from users u join posts p on u.id = p.user_id where u.active = 1 and p.published = true order by p.created_at desc limit 10"
print(sq.format_sql(sql))
SELECT u.id, u.name, p.title
FROM users u
JOIN posts p ON u.id = p.user_id
WHERE
u.active = 1
AND p.published = true
ORDER BY
p.created_at DESC
LIMIT 10;
Raises syntaqlite.FormatError on invalid input.
Parsing
sq.parse() returns a full AST as typed Python objects, one per statement:
stmts = sq.parse("SELECT 1 + 2 FROM foo")
stmt = stmts[0] # SelectStmt
print(type(stmt).__name__) # SelectStmt
print(stmt.columns[0].expr) # BinaryExpr(...)
print(stmt.from_clause) # TableRef(...)
print(stmt.where_clause) # None
Every node type is a __slots__ class with typed attributes, which supports
IDE completion and isinstance checks:
from syntaqlite.nodes import SelectStmt, BinaryExpr
assert isinstance(stmt, SelectStmt)
assert isinstance(stmt.columns[0].expr, BinaryExpr)
Enum and flag fields are IntEnum/IntFlag from syntaqlite.enums:
from syntaqlite.enums import BinaryOp
expr = stmt.columns[0].expr
print(expr.op.name) # PLUS
For performance-sensitive code, use sq.parse_raw() to get plain dicts
instead of typed objects.