Repository navigation
All features
This page mirrors the docs. Edit
docs/features.mdin the repo.
Every feature in one page, each with a short example. The links go to the full guide. The
examples use Users and Posts from Getting started.
Tables and columns. A table is a class; columns come from mizzle.pg.
More
@final
class Users(Table, name="users"):
id = serial().primary_key()
email = varchar(255).not_null().unique()
bio = text()Defaults and on_update. Database defaults, Python defaults, and values set on every update. More
views = integer().not_null().default(0)
updated_at = timestamp(tz=True).not_null().default(sql("now()")).on_update_now()Keys, unique and check constraints. More
weight = integer().not_null().check(sql("weight > 0"))
# in config(): primary_key(cls.a, cls.b), unique(cls.x, cls.y), check("name", sql(...))Foreign keys. Single or composite, with actions and deferrable. More
author_id = integer().not_null().references(lambda: Users.id, on_delete="cascade")Indexes. Expression, partial, unique, gin/gist/hnsw with opclasses, storage options. More
index("users_lower_email").on(lower(cls.email)).where(eq(cls.deleted, False))Enums. A Python Enum becomes a PostgreSQL enum. More
status = pg_enum(Status).not_null().default(Status.DRAFT)Columns of other types. Domains, composites, ranges, citext and any extension type,
with decode= / encode=. More
nights = custom("int4range")
qty = custom("posint", py_type=int)Identity and generated columns. More
id = integer().primary_key().generated_always_as_identity()
total = numeric(12, 2).generated_always_as(sql("qty * unit_price"))Schemas. Tables in any PostgreSQL schema. More
class AuditLog(Table, name="audit_log", schema="archive"): ...Relations. one and many, for relational queries. More
posts = many(lambda: Posts)
author = one(lambda: Users, fields=lambda: [Posts.author_id], references=lambda: [Users.id])Views and materialized views. More
class PostCounts(View, name="post_counts"): ... # columns + a query
await db.refresh(DailyPosts, concurrently=True)Row-level security, policies and roles. More
rls(), policy("own_posts", using=eq(cls.author_id, sql("current_setting('app.user_id')::int")))Table options. Comments, unlogged tables, storage parameters.
class Org(Table, name="org", comment="customers", unlogged=False, storage={"fillfactor": 70}): ...Select. Whole rows, chosen columns as tuples, or named columns as dicts. More
users = await db.select().from_(Users)
pairs = await db.select(Users.id, Users.email).from_(Users)Where. eq, ne, gt, in_, between, like, ilike, is_null, and_, or_,
not_... More
await db.select().from_(Posts).where(and_(gt(Posts.views, 10), ilike(Posts.title, "%hi%")))Joins. Inner, left, right, full; the optional side is typed | None.
More
await db.select(Users, Posts).from_(Users).left_join(Posts, eq(Posts.author_id, Users.id))Order, limit, offset. More
await db.select().from_(Posts).order_by(desc(Posts.views, nulls="last")).limit(20).offset(40)Group by and aggregates. count, sum_, avg, min_, max_, having.
More
await db.select(Posts.author_id, count()).from_(Posts).group_by(Posts.author_id)Expressions and functions. Arithmetic, string functions, coalesce, cast, any SQL
function with func. More
await db.select(lower(Users.email), coalesce(Users.bio, "")).from_(Users)CASE. More
case_().when(gt(Posts.views, 100), "hot").else_("cold")Dates and times. now, date_trunc, extract, timedelta arithmetic.
More
await db.select(date_trunc("month", Events.starts_at)).from_(Events)Subqueries. in_, exists, and subqueries in FROM. More
await db.select().from_(Users).where(in_(Users.id, db.select(Posts.author_id).from_(Posts)))CTEs, also recursive. More
ranked = db.select({"id": Posts.id}).from_(Posts).cte("ranked")
await db.with_(ranked).select(ranked.c("id", int)).from_(ranked)Window functions. row_number, rank, lag, lead, running totals.
More
row_number().over(partition_by=Posts.author_id, order_by=desc(Posts.views))Union, intersect, except. More
await staff.union(writers).order_by(Users.id)Aliases. The same table twice in one query. More
manager = alias(Users, "manager")Full-text search. More
doc = to_tsvector(Posts.title, config="english")
await db.select().from_(Posts).where(matches(doc, websearch_to_tsquery("cats -dogs")))Raw SQL. Values are always parameters. More
await db.execute(sql("SELECT id FROM users WHERE id = {}", user_id))Explain, prepared queries, SQL text. More
by_role = db.select().from_(Users).where(eq(Users.role, placeholder("role"))).prepare()
await by_role.execute(role=Role.ADMIN)Insert, with returning. More
[ann] = await db.insert(Users).values(email="ann@example.com").returning()Upserts. on_conflict_do_nothing and on_conflict_do_update with excluded().
More
await db.insert(Users).values(email="a@x.io", name="A").on_conflict_do_update(
target=Users.email, set_=
)Update and delete. A where is required; .all_rows() to touch every row. Also
UPDATE ... FROM and DELETE ... USING. More
await db.update(Users).set(name="Ann").where(eq(Users.id, 1))MERGE. when_matched_then_update, when_not_matched_then_insert...
await db.merge(Users).using(Imports).on(eq(Users.email, Imports.email)).when_matched_then_update(
).when_not_matched_then_insert({"email": Imports.email, "name": Imports.name})Bulk insert. Many rows in batches, one transaction. More
await db.insert_many(Users, rows, batch_size=1000)Streaming. Large results from a server-side cursor. More
async for user in db.select().from_(Users).stream(batch_size=1000): ...find_many / find_first with nested relations. Filters, order, limit and columns at every level, in one SQL statement. More
users = await db.query(Users).find_many(
with_={"posts": {"where": gt(Posts.views, 10), "order_by": desc(Posts.views), "limit": 5}}
)Transactions and savepoints. More
async with db.transaction() as tx:
async with tx.transaction() as sp: # SAVEPOINT
...Isolation levels, read-only, after-commit hooks. More
async with db.transaction("serializable", readonly=True) as tx: ...Retry on serialization failure. More
await db.retry(transfer, attempts=5)Row locks. for_update, skip_locked, nowait. More
jobs = await tx.select().from_(Jobs).limit(10).for_update(skip_locked=True)Timeouts. Per database or per query. More
await db.with_timeout(0.5).execute(sql("SELECT pg_sleep(2)")) # raises QueryTimeoutTyped errors. UniqueViolation, ForeignKeyViolation, CheckViolation,
QueryTimeout... More
try:
await db.insert(Users).values(email="ann@example.com")
except UniqueViolation:
...generate and migrate. SQL migrations from your schema, applied once even with many servers starting at the same time. More
mizzle generate --name init
mizzle migrateRenames and data-loss checks. More
mizzle generate --rename users.name=full_name
mizzle generate --allow-data-lossCustom migrations. Your own SQL, in the same history. More
mizzle generate --custom --name backfillpush for development databases. More
mizzle push --dry-runpull from an existing database. Writes the schema module and a baseline. More
mizzle pullcheck, status, doctor, drop, reset, squash, seed. More
mizzle check # in CI: folder and journal agree
mizzle doctor # drift between the database and the migrationsPydantic models from tables. Insert, update and select models. More
UserIn, UserOut = insert_model(Users), select_model(Users)
await db.insert(Users).values(UserIn.model_validate_json(body))Supabase. auth.uid(), roles and ready-made policies. More
*crud_policy("notes_owner", to=[AUTHENTICATED], read=eq(cls.owner_id, auth_uid()),
modify=eq(cls.owner_id, auth_uid()))pgvector. vector, halfvec, sparsevec, distances and hnsw / ivfflat indexes.
More
await db.select().from_(Items).order_by(cosine_distance(Items.embedding, query)).limit(5)mizzle studio. A data browser in the browser, with a read-only mode. More
mizzle studio --read-onlytypegen. TypedDicts for rows, inserts and updates. More
mizzle typegen --out app/types.pyRead replicas, pooling, PgBouncer, timeouts. More
db = await Database.connect(url, replicas=[replica_url], pool_size=20, query_timeout=5)
await db.primary.select().from_(Users) # read your own writeFor what mizzle does not do, see Known gaps.