SQLer
English | 日本語はこちら
sqler stores Python objects as JSON documents in SQLite and lets you query inside them. You write a model class; sqler keeps one table per model, one row per object, and builds the json_extract SQL for you. Sync and async, one file on disk, no server.
Install
pip install 'sqler[pydantic]' # Pydantic models (the examples below)
pip install sqler # dataclass models only; no other dependency
pip install 'sqler[msgspec]' # msgspec models
Python 3.12 or newer. SQLite needs the JSON1 functions, which the SQLite bundled with Python has.
Quick start
from sqler import F, SQLerDB, SQLerModel
class User(SQLerModel):
name: str
age: int
tags: list[str] = []
db = SQLerDB.on_disk("app.db") # or SQLerDB.in_memory()
User(name="Alice", age=30, tags=["admin"]).save(db=db)
User(name="Bob", age=25, tags=["user"]).save(db=db)
admins = User.using(db).filter(F("tags").contains("admin")).all()
assert [u.name for u in admins] == ["Alice"]
young = User.using(db).filter(F("age") < 28).order_by("name").all()
assert [u.name for u in young] == ["Bob"]
db.close()
save(db=db) writes one object. User.using(db) starts a query. Nothing is bound to the class.
With more than one database, User.beside(row) queries the database row was read from:
from sqler import SQLerDB, SQLerModel
class User(SQLerModel):
name: str
kyoto, osaka = SQLerDB.in_memory(), SQLerDB.in_memory()
User(name="Aiko").save(db=kyoto)
User(name="Ren").save(db=osaka)
ren = User.using(osaka).first()
assert [u.name for u in User.beside(ren).all()] == ["Ren"]
A query names its database: User.beside(ren).db() is osaka, as User.db() names the one a class is bound to.
What is in the file
The quick start leaves this in app.db, readable with any SQLite tool:
CREATE TABLE users (
_id INTEGER PRIMARY KEY AUTOINCREMENT,
data JSON NOT NULL
);
-- 1 | {"name":"Alice","age":30,"tags":["admin"]}
-- 2 | {"name":"Bob","age":25,"tags":["user"]}
The table name is the lowercase plural of the class name, or __tablename__ if you set it. _id is the object's _id attribute after a save. Safe models (below) add a _version column. A reference to another model is stored as {"_table": "...", "_id": ...}.
Queries
from sqler import F, SQLerDB, SQLerModel
class Order(SQLerModel):
customer: dict
items: list[dict] = []
db = SQLerDB.in_memory()
Order(customer={"name": "Ada", "city": "Kyoto"}, items=[{"sku": "A1", "qty": 2}]).save(db=db)
Order(customer={"name": "Bob", "city": "Osaka"}, items=[{"sku": "B7", "qty": 1}]).save(db=db)
# a nested field
kyoto = Order.using(db).filter(F("customer")["city"] == "Kyoto").all()
assert [o.customer["name"] for o in kyoto] == ["Ada"]
# any element of an array
bulk = Order.using(db).filter(F(["items"]).any().where(F("qty") > 1)).all()
assert [o.customer["name"] for o in bulk] == ["Ada"]
Also: exclude, order_by, paginate, count, first, isin, between, contains. debug() and explain_query_plan() show the SQL and how SQLite runs it. A query on a JSON field scans the table unless you create an index for that field with db.create_index(...).
Async
The async classes mirror the sync ones.
import asyncio
from sqler import AsyncSQLerDB, AsyncSQLerModel, F
class Job(AsyncSQLerModel):
name: str
done: bool = False
async def main():
db = AsyncSQLerDB.on_disk("app.db")
await db.connect()
await Job(name="resize").save(db=db)
await Job(name="email", done=True).save(db=db)
pending = await Job.using(db).filter(F("done") == False).all()
assert [j.name for j in pending] == ["resize"]
await db.close()
asyncio.run(main())
Three kinds of model
| Base class | Install | Use it when |
|---|---|---|
SQLerModel |
sqler[pydantic] |
you want validation and Pydantic's serialization |
SQLerLiteModel (a dataclass) |
sqler |
you want no dependency, or you run in Pyodide |
SQLerMsgspecModel |
sqler[msgspec] |
decoding speed matters more than validation features |
from dataclasses import dataclass
from sqler import SQLerDB
from sqler.models.lite import SQLerLiteModel
@dataclass
class User(SQLerLiteModel):
__tablename__ = "users"
name: str = ""
age: int = 0
db = SQLerDB.in_memory()
User(name="Alice", age=30).save(db=db)
assert User.using(db).count() == 1
The query API is the same for all three.
Safe models: two writers, one row
SQLerSafeModel keeps a version number per row. A save that started from an old version fails instead of overwriting.
from sqler import SQLerDB, SQLerSafeModel, StaleVersionError
class Account(SQLerSafeModel):
owner: str
balance: int
db = SQLerDB.in_memory()
mine = Account(owner="Ada", balance=100).save(db=db)
theirs = Account.using(db).first() # someone else loads the same row
theirs.balance = 50
theirs.save(db=db)
mine.balance = 120
try:
mine.save(db=db)
except StaleVersionError:
pass # reload, then decide
Transactions
with db.transaction():
Account(owner="Bob", balance=50).save(db=db)
raise RuntimeError("abort") # the row is not written
Relationships
A field typed as another model is stored as a reference and loaded as that model.
from sqler import ReferentialIntegrityError, SQLerDB, SQLerModel
class Address(SQLerModel):
city: str
class User(SQLerModel):
name: str
address: Address | None = None
db = SQLerDB.in_memory()
home = Address(city="Kyoto").save(db=db)
user = User(name="Alice", address=home).save(db=db)
assert User.from_id(user._id, db=db).address.city == "Kyoto" # the reference is loaded
in_kyoto = User.using(db).filter(User.ref("address").field("city") == "Kyoto").all()
assert [u.name for u in in_kyoto] == ["Alice"]
try:
home.delete(db=db) # Alice still refers to it
except ReferentialIntegrityError:
pass
A delete is refused while another row refers to the object. delete_with_policy(on_delete="cascade") deletes the referring rows too; on_delete="set_null" clears their field.
Full-text search
from sqler import FTSIndex, SQLerDB, SQLerModel
class Note(SQLerModel):
text: str
db = SQLerDB.in_memory()
Note(text="buy rice").save(db=db)
index = FTSIndex(Note, fields=["text"]) # SQLite FTS5
index.create(db) # indexes the rows already there
Note(text="cook rice").save(db=db) # and follows every later write
assert sorted(n.text for n in index.search("rice")) == ["buy rice", "cook rice"]
What sqler does not do
- One writer at a time. That is SQLite. Batch writes with
save_many(),bulk_upsert()and transactions. - No JOINs. A reference is loaded with a second query, not joined.
- Fields are not columns. Every field read goes through
json_extract; an index on the field closes most of the gap. - Results are loaded into memory. Use
paginate()andcount()on large tables. - One database engine. For PostgreSQL or several engines, use SQLAlchemy. For plain relational SQLite work, use sqlite-utils.
More
- Mixins for timestamps, soft delete and audit fields; lifecycle hooks; change tracking.
- Export and import: CSV, JSON, JSONL.
- Query caching, schema migrations, metrics.
- API reference · Examples · Changelog
Interactive tour
Eleven marimo notebooks: open the tour. The dataclass versions run in the browser with nothing installed.
| Tour | Topics |
|---|---|
| 01. Fundamentals | Models, CRUD, queries, aggregations |
| 02. Relationships | References, loading, cross-model queries |
| 03. Safe Models | Optimistic locking, conflicts |
| 04. Transactions | Atomic operations, rollback |
| 05. Mixins | Timestamps, soft delete, hooks |
| 06. Advanced | Bulk operations, indexes, integrity, raw SQL |
| 07. Export/Import | CSV, JSON, JSONL |
| 08. Full-Text Search | FTS5, boolean queries, ranking |
| 09. Change Tracking | Dirty checking, change detection |
| 10. Database Ops | Health checks, stats, vacuum, logging |
| 11. Metrics & Caching | Metrics, query caching |
To run the Pydantic versions locally: uv sync --dev, then uv run marimo edit examples/tour_01_fundamentals.py.
The -ler family
| Package | What it is |
|---|---|
| sqler | This package: JSON documents in SQLite |
| qler | A background job queue that stores its jobs with sqler |
| logler | Log investigation; its --db option reads a sqler database file |
Development
uv sync --dev
uv run ruff check .
uv run ruff format --check .
uv run pytest -m "not perf" # the whole suite; over twenty minutes
uv run python -m benchmarks run --scale medium --storage both # benchmarks, with SQLite baselines
License
MIT
Metadata
Release files for sqler 1.2026.11.3
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 |
|---|---|---|---|---|
| sqler-1.2026.11.3.tar.gz | 261.2 kB | With provenance | Details for sqler-1.2026.11.3.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| sqler-1.2026.11.3-py3-none-any.whl | Python 3 | none | any | Details for sqler-1.2026.11.3-py3-none-any.whl |
Total release size: 561.6 kB
Release files / sqler-1.2026.11.3.tar.gz
| Download URL | sqler-1.2026.11.3.tar.gz |
|---|---|
| Size | 261.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
9f1c5051a367edbdbca102346af8babef7619ca62ad9df8408b8e10b141c3b4d
|
|
BLAKE2b-256 checksum How to use checksums |
d5cbc45b738f3bfd31bbd9ef3644303067aa1901a08a91e5191b9b9559256af7
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 22, 2026.
Transparency logRelease files / sqler-1.2026.11.3-py3-none-any.whl
| Download URL | sqler-1.2026.11.3-py3-none-any.whl |
|---|---|
| Size | 300.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
52fd171e11393287452aad5fa936955c13051461e407cc17ddc16033bf595715
|
|
BLAKE2b-256 checksum How to use checksums |
bdef130f2db8f710b6e7b36a6c2c061206bcfc827e630f5c423b9089d2cb05be
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 22, 2026.
Transparency logSecurity for sqler 1.2026.11.3
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.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for sqler-1.2026.11.3.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 22, 2026.
Transparency logA 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.