Repository navigation
Pydantic Supabase Studio
This page mirrors the docs. Edit
docs/guide/integrations.mdin the repo.
Pydantic models from your tables, Supabase row-level security helpers, the Studio data browser, and typed dicts for inserts and updates. The examples use this table, with Supabase-style policies:
from typing import final, override
from mizzle import Constraint, Table, eq, rls, sql
from mizzle.pg import integer, text, timestamp, uuid
from mizzle.supabase import ANON, AUTHENTICATED, auth_uid, crud_policy
@final
class Notes(Table, name="notes"):
id = integer().primary_key().generated_always_as_identity()
owner_id = uuid().not_null().default(sql("auth.uid()"))
body = text().not_null()
public = text().not_null().default("no")
created_at = timestamp(tz=True).not_null().default(sql("now()"))
@classmethod
@override
def config(cls) -> list[Constraint]:
return [
rls(),
*crud_policy(
"notes_owner",
to=[AUTHENTICATED],
read=eq(cls.owner_id, auth_uid()),
modify=eq(cls.owner_id, auth_uid()),
),
*crud_policy("notes_public", to=[ANON], read=eq(cls.public, "yes")),
]pip install "mizzle[pydantic]"mizzle.pydantic builds Pydantic models from a table:
class NoteIn(insert_model(Notes, include=["body", "public"])):
pass
class NotePatch(update_model(Notes, include=["body", "public"])):
pass
class NoteOut(select_model(Notes, exclude=["owner_id"])):
pass| Function | Model of | Fields |
|---|---|---|
select_model(T) |
a stored row | every column, as stored |
insert_model(T) |
a new row | columns with a default or generated by the database are optional; serial, identity and generated columns are left out |
update_model(T) |
a partial update | every field optional; primary keys and generated columns left out |
Each takes include= (an allowlist), exclude=, refine= (replace a field's type) and
name=. Subclass the result, as above, so type checkers and FastAPI see a normal class.
Field types follow the columns: varchar(255) gets max_length=255, numeric(10, 2)
gets max_digits and decimal_places, vector(3) exactly 3 floats, enums the enum.
Pass a model straight to values() or set(), and validate rows into a response model:
async with as_user(db, ANN) as tx:
body = NoteIn.model_validate({"body": "hello"}) # what a client sent
[note] = await tx.insert(Notes).values(body).returning()
out = NoteOut.model_validate(note) # rows validate directly (from_attributes)
print(out.model_dump_json()) #
patch = NotePatch.model_validate({"public": "yes"})
await tx.update(Notes).set(patch).where(eq(Notes.id, note.id)) # only "public" changes
try:
NoteIn.model_validate({"body": "hi", "owner_id": str(BOB)})
except pydantic.ValidationError:
pass # owner_id is not in include=: extra fields are rejectedvalues(model) and set(model) use only the fields the client sent
(model_fields_set), so the others keep their database defaults or current values. Each
value is the dumped one: serializers run, and a nested model keeps its defaults. (as_user is defined below.)
!!! warning "Use include= for client input"
A model accepts every field it contains. Without include=, a client could send a
field you never meant to expose, such as "role": "admin". Models reject unknown
fields (extra="forbid").
refine replaces a field's type:
Strict = insert_model(Notes, include=["body"], refine={"body": pydantic.constr(min_length=3)})examples/social uses these models in a FastAPI app.
mizzle.supabase has what Supabase projects need for row-level security:
-
ANON,AUTHENTICATED,SERVICE_ROLE,POSTGRES,SUPABASE_AUTH_ADMIN: Supabase's roles, asrole(..., existing=True). Migrations use them in policies but never create or change them. -
auth_uid(),auth_jwt(),auth_role():(select auth.uid())and friends, for policy conditions. The subquery makes PostgreSQL evaluate them once per statement instead of once per row, as Supabase recommends. -
crud_policy(name, to=[...], read=..., modify=...): the usual policies.readcontrols SELECT;modifycontrols INSERT, UPDATE and DELETE.Trueallows every row,Falsenone, a condition the matching rows, andNoneadds no policy. They are named{name}_select,{name}_insert,{name}_updateand{name}_delete.
The Notes table above makes this migration (shortened):
CREATE POLICY "notes_owner_select" ON "notes" AS PERMISSIVE FOR SELECT TO "authenticated" USING ("owner_id" = (select auth.uid()));
CREATE POLICY "notes_owner_insert" ON "notes" AS PERMISSIVE FOR INSERT TO "authenticated" WITH CHECK ("owner_id" = (select auth.uid()));
CREATE POLICY "notes_owner_update" ON "notes" AS PERMISSIVE FOR UPDATE TO "authenticated" USING ("owner_id" = (select auth.uid())) WITH CHECK ("owner_id" = (select auth.uid()));
CREATE POLICY "notes_owner_delete" ON "notes" AS PERMISSIVE FOR DELETE TO "authenticated" USING ("owner_id" = (select auth.uid()));
CREATE POLICY "notes_public_select" ON "notes" AS PERMISSIVE FOR SELECT TO "anon" USING ("public" = 'yes');Grants are not managed by mizzle (Supabase grants its roles on new tables by default); add
any others in a custom migration (GRANT SELECT ON notes TO anon;).
Your server connects as a role that bypasses RLS (postgres, or the table owner). To run
queries as a signed-in user, do what Supabase's API does: set the JWT claims and the role
for one transaction:
@asynccontextmanager
async def as_user(db: Database, user_id: uuid.UUID) -> AsyncGenerator[Session]:
"""A transaction as Supabase runs it for a signed-in user."""
claims = json.dumps({"sub": str(user_id), "role": "authenticated"})
async with db.transaction() as tx:
await tx.execute(sql("SELECT set_config('request.jwt.claims', {}, true)", claims))
await tx.execute(sql("SET LOCAL ROLE authenticated"))
yield txasync with as_user(db, ANN) as tx:
await tx.insert(Notes).values(body="ann's note") # owner_id defaults to auth.uid()
mine = await tx.select().from_(Notes) # only Ann's notesA row the policies refuse raises DatabaseError with sqlstate "42501":
try:
async with as_user(db, ANN) as tx:
await tx.insert(Notes).values(body="forged", owner_id=BOB)
except DatabaseError as exc:
print(exc.sqlstate) # 42501: the policy's WITH CHECK refused the rowSupabase keeps its own tables in the auth and storage schemas. mizzle only reads the
schemas in schema_filter (default ["public"]), so migrations leave those alone. More on
policies and roles: Migrations.
pip install "mizzle[studio]"
mizzle studio # opens the browser
mizzle studio --read-only --port 4983 --no-openmizzle studio (read-only) running at http://127.0.0.1:4983/#token=...
Press Ctrl+C to stop.
Studio browses, filters and edits rows, runs SQL and shows each table's structure. It
uses the same mizzle.toml and database URL as the other commands.
- It listens on
127.0.0.1only, and every API call needs the one-time token in the printed link. Other websites cannot call it. -
--read-onlyblocks every write; SQL runs in a read-only transaction. It needs a non-privileged database role and refuses to start as a superuser (see the CLI reference). - The UI (about 250 KB) downloads on first run into your virtual environment, checked by
SHA-256. On offline machines pass
--ui-pathwith a local build.
mizzle typegen writes three TypedDicts per table, next to your schema module
(db/schema_types.py): <Table>Row for a full selected row (including generated
columns), <Table>Insert for the values of a new row, and <Table>Update for a partial
update.
class NotesInsert(TypedDict):
owner_id: NotRequired[uuid.UUID]
body: str
public: NotRequired[str]
created_at: NotRequired[datetime.datetime]NotesUpdate has the same fields, all optional. Use them to type rows you build before
inserting:
rows: list[NotesInsert] = [{"body": "one"}, {"body": "two"}]
async with as_user(db, ANN) as tx:
await tx.insert(Notes).values(rows) # a misspelled key is a type error<Table>Row names the shape a projection returns; as_rows() checks the field names and
re-types the result:
rows = (
await db.select({"id": Notes.id, "body": Notes.body})
.from_(Notes)
.as_rows(NotesRow) # list[NotesRow]
)Once the file exists, mizzle generate rewrites it each time it writes a migration.
--out writes it elsewhere.