aiosql – Simple SQL in Python
raw JSON → 15.0 verified Fri May 01 auth: no python
aiosql allows you to write SQL queries in separate .sql files and call them directly from Python as async or sync functions. It supports multiple database drivers (sqlite3, aiosqlite, psycopg2, asyncpg, etc.) and provides a clean separation of SQL and Python. Current version 15.0, requires Python ≥3.10. Release cadence is irregular but actively maintained.
pip install aiosql Common errors
error ModuleNotFoundError: No module named 'aiosql' ↓
cause aiosql is not installed.
fix
pip install aiosql
error aiosql.exceptions.AioSQLQueryNotFoundError: No query named 'get_user' ↓
cause The query name in the SQL file does not match the Python call, or the file was not loaded properly.
fix
Check that the SQL file contains
-- name: get_user (case-sensitive, exact match) and that the file is in the directory passed to from_path. error TypeError: from_path() got an unexpected keyword argument 'driver' ↓
cause Using old keyword argument name; `driver` was renamed to `driver_name` or changed to positional.
fix
Use
aiosql.from_path('queries', 'sqlite3') or aiosql.from_path('queries', driver_name='sqlite3'). Warnings
breaking In version 11.0, the `from_path` and `from_str` signatures changed: the driver name changed from a string like 'sqlite' to the actual driver module or string (e.g., 'sqlite3'). Old code using `aiosql.from_path('queries', 'sqlite')` will break. ↓
fix Change to `aiosql.from_path('queries', 'sqlite3')` or pass the module object: `aiosql.from_path('queries', aiosql.adapters.sqlite)`.
gotcha Query names must be unique across all .sql files loaded; duplicates cause silent overwrite of the earlier one. ↓
fix Ensure each SQL file has unique `-- name:` tags. Use a single directory or namespace with subdirectories.
deprecated The `from_sql` function was removed in version 10.0. Use `from_path` or `from_str` instead. ↓
fix Replace `aiosql.from_sql(...)` with `aiosql.from_str(...)` or `aiosql.from_path(...)`.
Imports
- aiosql wrong
from aiosql import aiosqlcorrectimport aiosql - from_query wrong
from aiosql import from_querycorrectfrom aiosql import from_path
Quickstart
import aiosql
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)")
conn.execute("INSERT INTO users VALUES (1, 'Alice')")
conn.commit()
# Write a SQL file: queries/users.sql
# -- name: get_user
# SELECT * FROM users WHERE id = ?
queries = aiosql.from_path("queries", "sqlite3")
user = queries.get_user(conn, user_id=1)
print(user)