SQLitey
A small, typed wrapper around Python's built-in sqlite3. It keeps you writing plain SQL, and takes care of the repetitive parts: connections, transactions, row shapes, SQL files and migrations.
- No dependencies, standard library only
- Plain SQL, inline or loaded from
.sqlfiles - Rows the way you want them: tuples, dicts, namedtuples or your own dataclasses
- Safe transactions: commit on success, roll back on error, nestable atomic blocks
- Migrations built in, from numbered
.sqlfiles - Fully typed, ships with type hints
Requires Python 3.11 or newer.
Contents
Installation
pip install sqlitey
Quick start
from sqlitey import Db, Sql
with Db("app.db") as db:
db.execute(Sql.raw("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)"))
db.execute(Sql.raw("INSERT INTO users (name) VALUES (?)"), ("Alice",))
user = db.fetchone(Sql.raw("SELECT id, name FROM users WHERE name = ?"), ("Alice",))
print(user) # (1, 'Alice')
That is all there is to it. When the with block ends, your changes are committed and the connection is closed. If an exception is raised inside the block, the changes are rolled back instead.
Guide
Writing queries
Every query is wrapped in a Sql object. Use Sql.raw() for inline SQL:
get_user = Sql.raw("SELECT id, name FROM users WHERE id = ?")
Pass values separately, as parameters. Both positional (?) and named (:name) placeholders work:
db.fetchone(Sql.raw("SELECT * FROM users WHERE id = ?"), (1,))
db.fetchone(Sql.raw("SELECT * FROM users WHERE id = :id"), {"id": 1})
Never build a query by formatting values into the string, that is how SQL injection happens:
# Don't do this
db.fetchone(Sql.raw(f"SELECT * FROM users WHERE name = '{name}'"))
# Do this
db.fetchone(Sql.raw("SELECT * FROM users WHERE name = ?"), (name,))
To help with that, Sql.raw() is typed as LiteralString. Type checkers that enforce it, such as pyright, report the first example above as an error. Note this is a static check only, nothing is verified at runtime.
Reading results
| You want | Use | Returns |
|---|---|---|
| One row | db.fetchone(sql, params) |
A row, or None |
| All rows | db.fetchall(sql, params) |
A list of rows |
| A single value | db.fetchval(sql, params) |
The first column of the first row, or None |
| To loop over many rows | db.execute(sql, params) |
A cursor you can iterate |
total = db.fetchval(Sql.raw("SELECT COUNT(*) FROM users")) # 2
for user_id, name in db.execute(Sql.raw("SELECT id, name FROM users")):
print(user_id, name)
Row factories
By default rows are tuples. Pass a row_factory to get something friendlier.
As dictionaries:
from sqlitey import Db, Sql, dict_factory
with Db("app.db", row_factory=dict_factory) as db:
user = db.fetchone(Sql.raw("SELECT id, name FROM users WHERE id = ?"), (1,))
print(user["name"]) # 'Alice'
As namedtuples:
from sqlitey import Db, Sql, namedtuple_factory
with Db("app.db", row_factory=namedtuple_factory) as db:
user = db.fetchone(Sql.raw("SELECT id, name FROM users WHERE id = ?"), (1,))
print(user.name) # 'Alice'
As your own classes, the column names must match the field names:
from dataclasses import dataclass
from sqlitey import Db, Sql, dataclass_factory
@dataclass
class User:
id: int
name: str
with Db("app.db", row_factory=dataclass_factory(User)) as db:
user = db.fetchone(Sql.raw("SELECT id, name FROM users WHERE id = ?"), (1,))
print(user) # User(id=1, name='Alice')
Tip: with
namedtuple_factory, a column such asCOUNT(*)is not a valid attribute name, so it is renamed to its position (_0,_1, ...). Give it an alias to get a proper name:SELECT COUNT(*) AS total.
SQL files
Longer queries are easier to read, and to syntax-highlight, in their own .sql files. Point Db at the directory and refer to queries by filename:
sql/
get_user_by_id.sql
list_users.sql
from pathlib import Path
from sqlitey import Db, Sql
with Db("app.db", sql_templates_dir=Path("sql")) as db:
user = db.fetchone(Sql.template("get_user_by_id.sql"), (1,))
A single query can also carry its own directory:
sql = Sql.template("get_user_by_id.sql", path=Path("sql"))
If you pass the database and the SQL directory around together, DbPathConfig bundles them:
from sqlitey import Db, DbPathConfig
config = DbPathConfig(database=Path("app.db"), sql_templates_dir=Path("sql"))
with Db.from_config(config) as db:
...
Sql objects are immutable, so you can define them once at the top of a module and reuse them everywhere.
Transactions
Inside a with Db(...) block, your changes form one transaction:
- the block ends normally, everything is committed
- the block raises an exception, everything is rolled back
For finer control, wrap a group of statements in db.transaction(). They succeed or fail together, without affecting the rest of your work:
with Db("app.db") as db:
db.execute(Sql.raw("INSERT INTO users (name) VALUES (?)"), ("Alice",))
try:
with db.transaction():
db.execute(Sql.raw("INSERT INTO users (name) VALUES (?)"), ("Bob",))
raise RuntimeError("something went wrong")
except RuntimeError:
pass # Bob is rolled back, Alice is kept
db.transaction() blocks can be nested. When no transaction is open yet, the outermost block commits as soon as it succeeds.
Other options:
db.commit(sql, params)runs a statement and commits straight awayDb("app.db", autocommit=True)commits every statement as it runs- without a
withblock, calldb.close()yourself when done. Uncommitted changes are discarded, so commit first
Bulk inserts and scripts
Run one statement with many sets of parameters:
users = [("Alice",), ("Bob",), ("Charlie",)]
db.executemany(Sql.raw("INSERT INTO users (name) VALUES (?)"), users)
Run several statements at once:
db.executescript(Sql.raw("""
DELETE FROM users WHERE id = 1;
UPDATE users SET name = 'Robert' WHERE name = 'Bob';
"""))
Pragmas
SQLite's defaults are conservative, most notably foreign keys are not enforced unless you ask. RECOMMENDED_PRAGMAS turns on the settings most applications want: foreign keys, WAL journalling (readers do not block the writer) and synchronous = normal.
from sqlitey import Db, RECOMMENDED_PRAGMAS
with Db("app.db", pragmas=RECOMMENDED_PRAGMAS) as db:
...
Or choose your own:
with Db("app.db", pragmas={"foreign_keys": True, "cache_size": -8000}) as db:
...
Migrations
Keep your schema changes as numbered .sql files, named <version>_<description>.sql:
migrations/
001_create_users.sql
002_add_email.sql
Then call migrate when your application starts:
from pathlib import Path
from sqlitey import Db
with Db("app.db") as db:
applied = db.migrate(Path("migrations"))
print(f"{applied} migration(s) applied")
- Only files newer than the database's current version are run, in order. The version is stored in the database itself (
PRAGMA user_version), so no extra table is needed. - Each file is all-or-nothing. If one fails, the database stays at the previous version and the error is raised.
- It is safe to call from several processes at once, each file is applied only once.
To add a change later, add a new file with the next number. Never edit a migration that has already been applied.
Things to know
- Do not commit inside a
db.transaction()block.db.commit()anddb.executescript()both end the transaction early, and the block then fails on exit. db.migrate()needs a clean slate. It raisesRuntimeErrorif you have uncommitted changes, call it first.- Migration files must not contain
BEGINorCOMMIT. Each file already runs in its own transaction. - SQL files are cached. A file is read once per process, restart to pick up edits.
- Need something not covered here? The underlying
sqlite3connection is available asdb.conn.
API reference
Sql
| Method | Description |
|---|---|
Sql.raw(query) |
A query from an inline string |
Sql.template(filename, path=None) |
A query loaded from a .sql file |
Db
| Method | Description |
|---|---|
Db(database, row_factory=None, sql_templates_dir=None, autocommit=False, pragmas=None) |
Open a database. Extra arguments are passed to sqlite3.connect() |
Db.from_config(config, **kwargs) |
Open a database from a DbPathConfig |
execute(sql, params=()) |
Run a query and return a cursor |
executemany(sql, seq_of_params) |
Run a query once per set of parameters |
executescript(sql) |
Run several statements as a script |
fetchone(sql, params=()) |
Run a query and return the first row, or None |
fetchall(sql, params=()) |
Run a query and return all rows |
fetchval(sql, params=()) |
Run a query and return the first column of the first row, or None |
commit(sql, params=()) |
Run a query and commit |
transaction() |
Context manager, runs a block atomically, nestable |
migrate(directory) |
Apply pending migration files, return how many ran |
close() |
Close the connection, discarding uncommitted changes |
conn |
The underlying sqlite3.Connection |
Row factories
| Factory | Rows are returned as |
|---|---|
| (none) | Tuples |
dict_factory |
Dictionaries |
namedtuple_factory |
Namedtuples |
dataclass_factory(cls) |
Instances of cls |
Other
| Name | Description |
|---|---|
DbPathConfig(database, sql_templates_dir=None) |
Bundles a database path and a SQL directory |
RECOMMENDED_PRAGMAS |
Foreign keys on, WAL journalling, synchronous = normal |
Development
The project uses uv.
make deps # install dependencies
make tests # run the test suite
make ruff # lint
make fmt # format
make mypy # type check
The test suite doubles as a set of runnable examples.
Licence
MIT, see LICENSE.
Metadata
Release files for SQLitey 0.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| sqlitey-0.2.0.tar.gz | 29.7 kB | Without provenance | Details for sqlitey-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| sqlitey-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for sqlitey-0.2.0-py3-none-any.whl |
Total release size: 41.0 kB
Release files / sqlitey-0.2.0.tar.gz
| Download URL | sqlitey-0.2.0.tar.gz |
|---|---|
| Size | 29.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
bcd9592d37d51a441773ca6eee7cadb103fef6f9c41955fb94cc4dc7c63c91c9
|
|
BLAKE2b-256 checksum How to use checksums |
3bc488eb409d13af9206681364afdb4935ae29ff9243065509467f1b393b035d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.9.18 {"installer":{"name":"uv","version":"0.9.18","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Fedora Linux","version":"43","id":"","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Release files / sqlitey-0.2.0-py3-none-any.whl
| Download URL | sqlitey-0.2.0-py3-none-any.whl |
|---|---|
| Size | 11.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
0875f0ad324502961ebb5a027b28e737244a0f01658e2bc3b2e07e32ced49385
|
|
BLAKE2b-256 checksum How to use checksums |
edc96aa769b696dff92a7305a93e09cefe128fbdb510d17adee755697d57d9aa
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.9.18 {"installer":{"name":"uv","version":"0.9.18","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Fedora Linux","version":"43","id":"","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Security for SQLitey 0.2.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.