PostgresLite
Python SQLite library built around asyncpg-style syntax.
No longer do you need to wrestle with raw SQLite. PostgresLite gives you a cleaner, asyncpg-inspired API with everything you'd expect out of the box:
- Automatic type conversion for
DATE,DATETIME,TIMESTAMP, andJSONcolumns - Transactions (and nested savepoints) via context managers
- asyncpg-style placeholders (
$1,$2, …) and status strings ("INSERT 0 1") - Schema dumping and introspection
- Both sync and async connections, using the same API
Installing
You need Python >=3.11 to use this library.
Install by using pip install postgreslite in the terminal.
Quick example
Sync
from postgreslite import PostgresLite
pool = PostgresLite("./hello_world.db").connect()
pool.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE NOT NULL)")
pool.execute("INSERT INTO users (name) VALUES ($1) ON CONFLICT DO NOTHING", "AlexFlipnote")
data = pool.fetch("SELECT * FROM users")
print(data) # [{'id': 1, 'name': 'AlexFlipnote'}]
pool.close()
Async
import asyncio
from postgreslite import PostgresLite
async def main():
async with PostgresLite("./hello_world.db").connect_async() as pool:
data = await pool.fetch("SELECT * FROM users")
asyncio.run(main())
Both connection types support the same API: execute, executemany, fetch, fetchrow, fetchval, transaction, acquire.
Queries run in a worker thread on the async connection, so they don't block the event loop.
PostgresLite(filename, timeout=5.0) accepts a .db, .sqlite, .sqlite3 or .db3 path, a file: URI, or ":memory:".
timeout is how many seconds to wait on another connection's lock before raising database is locked.
Coming from asyncpg
Most asyncpg code works as-is, including async with pool.acquire() as conn, conn.transaction():.
The differences:
| asyncpg | PostgresLite | |
|---|---|---|
| Rows | Record |
dict (so no row[0]; duplicate column names keep the last one) |
pool.acquire() |
Takes a connection from the pool | Yields the same single connection |
| Concurrent use | Raises "another operation is in progress" | Queries are queued; an open transaction blocks other tasks until it finishes |
executemany |
Returns None |
Returns a status, e.g. "INSERT 0 3" |
| Placeholders | $1 only |
$1 or ? |
Type handling
Columns declared as DATE, DATETIME, TIMESTAMP, or JSON are automatically converted on read:
| Column type | Python type |
|---|---|
DATE |
datetime.date |
DATETIME |
datetime.datetime |
TIMESTAMP |
datetime.datetime (converted to UTC) |
JSON |
dict / list |
date, datetime, dict and list arguments are converted on write.
The column converters are registered with Python's
sqlite3module, which is process-wide. They only affect connections opened withdetect_types=sqlite3.PARSE_DECLTYPES.
Transactions
with pool.transaction():
pool.execute("UPDATE accounts SET balance = balance - 100 WHERE id = 1")
pool.execute("UPDATE accounts SET balance = balance + 100 WHERE id = 2")
Rolls back on any error (including cancellation) and re-raises.
Nested transaction() blocks become savepoints, and you can also call start(), commit() and rollback() yourself.
Async pools use async with pool.transaction().
Migrations
Put numbered .sql files in a folder, and apply the new ones on startup:
migrations/
├── 001_init.sql
├── 002_add_bio.sql
└── 003_posts.sql
applied = pool.migrate("migrations") # ['002_add_bio.sql', '003_posts.sql']
- Files run in filename order, each in its own transaction, and are recorded in a
_migrationstable, so each one only ever runs once. - If a file fails, its changes are rolled back and
MigrationErroris raised. Fix it and run again. - Don't edit a migration after it has been applied; add a new one. Edited files raise
MigrationError. - Files must not contain
BEGIN,COMMIT,ROLLBACK,SAVEPOINTorRELEASE. - Foreign keys are checked when each file finishes rather than per statement, so you can rebuild a table
(create the new one, copy the rows, drop the old one, rename) without
ON DELETE CASCADEwiping related rows. - A database that already has tables but no
_migrationstable is assumed to be up to date: every current file is recorded as applied without running it.
Schema utilities
db = PostgresLite("./hello_world.db")
# Dump the current schema as a string, to a file, or to a folder of per-table files
db.dump_schema()
db.dump_schema(output="schema.sql")
db.dump_schema(include_indexes=True, output="schema/")
# For ":memory:" databases, dump from the connection instead
pool.dump_schema()
The output uses IF NOT EXISTS, so it can be run again safely, e.g. with pool.run_sql("schema.sql").
Introspection
pool.tables() # ['users', 'posts']
pool.table_exists("users") # True
pool.table_columns("users") # [<TableColumn name='id' ...>, ...]
pool.lastrowid # ID of the last inserted row
Metadata
Release files for PostgresLite 2.0.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 |
|---|---|---|---|---|
| postgreslite-2.0.0.tar.gz | 22.9 kB | Without provenance | Details for postgreslite-2.0.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| postgreslite-2.0.0-py3-none-any.whl | Python 3 | none | any | Details for postgreslite-2.0.0-py3-none-any.whl |
Total release size: 39.1 kB
Release files / postgreslite-2.0.0.tar.gz
| Download URL | postgreslite-2.0.0.tar.gz |
|---|---|
| Size | 22.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
5b26d312d439d14ec44f0c794111f9234b1d20aedf6a1e29d5b7207ca31e9312
|
|
BLAKE2b-256 checksum How to use checksums |
5f2d4a61bb5487e526ec9138330c27798695925badc80b65cdaa3465dda98878
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.9.9 {"installer":{"name":"uv","version":"0.9.9"},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Release files / postgreslite-2.0.0-py3-none-any.whl
| Download URL | postgreslite-2.0.0-py3-none-any.whl |
|---|---|
| Size | 16.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
405965a39f332fa9dc295e01c4b94b7e81ec2a8a56941c2c8bf7be110d810f67
|
|
BLAKE2b-256 checksum How to use checksums |
1e83a9a53a12bce3c46152be9581f0fb076c853c264312fb695e4992b8146192
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.9.9 {"installer":{"name":"uv","version":"0.9.9"},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Security for PostgresLite 2.0.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.