Schema
Your schema is a set of TypeScript types in schema/index.ts. Supatype builds the tables, access rules, APIs and the typed client from it.
Pre-1.0: APIs and config may change between releases.
Models
Each exported Model<> type is a table. Import the types from @supatype/types.
Nothing in schema/index.ts runs. The CLI reads it as type declarations, so a model is an export type, never an export const, and there is no builder function to call.
import type { Model, UUID, Optional, Public, LoggedIn } from "@supatype/types"
export type Post = Model<{ id: UUID title: string published: boolean published_at: Optional<string>}, { access: { read: Public; create: LoggedIn; update: LoggedIn; delete: LoggedIn }}>The table name is the type name in snake case: Post becomes post, BlogPost becomes blog_post. Set tableName in the second argument to choose another.
An id: UUID field becomes the primary key, and the database fills it in. A model with no id field and no PrimaryKey<> gets one anyway: an id UUID primary key filled by gen_random_uuid(). Wrap another field in PrimaryKey<> to key the model by it instead.
A key you type yourself, such as slug: PrimaryKey<string>, is fixed forever. It can never be changed, by Studio, the API or anything else, because drafts, relations and URLs all point at it. To let editors rename a record, keep the hidden id and add a unique lookup field: id: UUID and slug: Unique<Slug<"title">>. A push that would create a new model with a typed key is refused, with a message naming the model, unless the key is wrapped in NaturalKey<>. Use NaturalKey<> only for a value that truly never changes, such as an ISO country code. A model already in the database is left as it is. On an empty database, such as a fresh environment or CI, an existing model with PrimaryKey<string> counts as new: change it to NaturalKey<string>, which changes nothing in the database.
The second argument also takes these options:
| Option | Does |
|---|---|
label, labelPlural | Names the model in Studio |
indexes | Adds indexes, see below |
versions | Keeps drafts and history, see below |
singleton: true | Keeps one row, such as site settings. The table is _global_ plus the snake case name, unless you set tableName |
constraints | Checks the database runs on every write, in the access rule language, such as Lte<"starts_at", "ends_at">. They cannot name the caller or the clock |
searchable | The fields the search box in Studio’s list looks in |
timestamps, softDelete | Adds created_at and updated_at columns, or a deleted_at column. Left out, they follow the fields the model declares |
autoLocalize: true | Makes copy fields localized by default. Wrap one in NotLocalized<> to opt out |
hooks, validate | Runs an edge function before or after an API write, or to check one field. They do not run for direct SQL or seeds |
cache | Says how reads of the model may be cached |
mcp | Opts the model in to the app MCP, so the people who use your app can reach it through their agent: a description, the exposed operations, an optional toolPrefix and fields. A model with no mcp block has no MCP tools |
An index is { fields: ["a", "b"] }, with unique: true and name if you need them. using picks the method: "btree" (the default), "gin", "gist", "hnsw" or "brin". An "hnsw" index is for Vector fields only. Its distance is "cosine" (the default), "l2" or "innerProduct". A distance on any other index is refused.
supatype dev applies each save. supatype push applies the schema to another database. supatype diff shows the change without applying it.
Field types
Every field is required (NOT NULL) unless you wrap it in Optional<>. Use Optional<>, not ?.
| Write | Stores |
|---|---|
string | text |
number, Float | a floating point number |
Int, SmallInt, BigInt, Decimal<10, 2>, Money | exact numbers |
boolean | true or false |
Timestamp, DateTime, DateOnly | a time with zone, or a date |
UUID | a Postgres uuid |
Email, URL, Color, PhoneNumber, Markdown | text. The database checks the format of Email and URL |
"news" | "guide" | text limited to those values by a check |
string[] | an array |
JSON<T> | JSONB, typed as T in the client |
Code, Currency, Duration, Button | JSONB with a typed shape, such as { amount, code } for Currency |
Vector<1536> | a pgvector embedding with that many dimensions |
GeoPoint, Geo | a PostGIS geography point |
IPAddress, CIDR, MacAddress, Bytea, XML, TSVector, TSQuery | the matching Postgres type: inet, cidr, macaddr, bytea, xml, tsvector, tsquery |
RichText, Blocks<T>, Slug<"title"> | content fields, see below |
ImageAsset<Bucket>, FileAsset | a file in a storage bucket |
SupatypeAuthUserId | the id of a sign-in user, see below |
Wrap a field to add more:
| Wrap | Does |
|---|---|
Unique<T>, Indexed<T> | Adds a unique constraint, or an index |
Default<T, value> | Sets the column’s default |
ServerDefault<T> | Says the database fills the column, by a trigger or default. Inserts may leave it out |
MinLength<T, n>, MaxLength<T, n> | Bounds the length of text |
MinItems<T, n>, MaxItems<T, n> | Bounds how many items an array, JSON array or Blocks field holds |
Between<T, min, max> | Bounds a number or a date |
Searchable<T> | Adds the field to the search box in Studio’s list |
Localized<T> | Stores one value per locale, such as { "en": "Hello", "de": "Hallo" } |
Three wrappers shape a field in Studio. EditorReadOnly<T> is shown but not editable there, and the API can still write it. Computed<T> is filled by the database and read-only in Studio. ComputedFrom<string, "title"> is prefilled from the fields it names on a new record, until the editor changes it.
For translated content, declare the locales once, such as export type Locales = LocaleConfig<["en", "fr"], "en">, and wrap a field in Localized<T>. It is stored as JSONB keyed by locale: { "en": "Hello", "fr": "Bonjour" }. LocalizedModel<> localizes a model’s text fields for you, and NotLocalized<T> opts one back out. There is no locale setting in supatype.config.ts.
Wrap the fields in WithTimestamps<{ ... }> to add created_at and updated_at, which the database fills in.
With the Native provider, supatype dev stores Vector<> and Geo fields as JSONB, because its Postgres has no pgvector or PostGIS. Use Docker to work with them locally.
Identity and generated columns
An integer field can be an identity column. Int<{ identity: "always" }>, or Identity<number>, is GENERATED ALWAYS AS IDENTITY. An insert cannot give it a value. BigInt<{ identity: "by-default" }>, or Identity<bigint, "by-default">, takes a value when an insert gives one.
AutoIncrement<number> is Identity<number, "by-default">. Before 0.7.0 it was a SERIAL. A serial column pushed then is left as it is.
Generated<T, "sql"> is a stored generated column, such as Generated<string, "lower(name)">. Most types also take it as an option: Float<{ generated: "price * quantity" }>.
import type { Model, PrimaryKey, Int, Float, Generated } from "@supatype/types"
export type LineItem = Model<{ id: PrimaryKey<Int<{ identity: "always" }>> price: Float quantity: Int total: Generated<Float, "price * quantity">}>A column cannot be both. Neither takes a Default<>. The generated client leaves generated columns and "always" identities out of inserts and updates. A "by-default" identity is optional on insert. Removing either is destructive, so the push asks first or needs --yes.
Relations
RelatedTo<Model> adds a foreign key column named after the field plus _id. The field author becomes the column author_id. The column can be null unless you pass { required: true }.
onDelete takes "cascade", "setNull", "restrict" or "noAction". It defaults to "restrict": deleting an author with posts is refused. onUpdate takes the same values and defaults to "cascade".
HasMany<Model> and HasOne<Model> are the other side of a RelatedTo. They add no column. They let the client and seeds reach the related rows.
ManyToMany<Model> makes one junction table for the pair, whichever side declares it. It is named from both tables in alphabetical order, so posts and tags share post_tag. Pass { through: "name" } to choose the name.
import type { Model, UUID, SupatypeAuthUserId, Timestamp, RichText, Slug, Unique, Optional, Int, RelatedTo, HasMany, ManyToMany, Owner, Role, LoggedIn, Public, Any, Lte, Now, Bucket, BucketPublic, BucketLoggedIn, BucketOwner, ImageAsset, Block, Blocks, Default,} from "@supatype/types"
export type Author = Model<{ id: SupatypeAuthUserId name: string bio: Optional<string> posts: HasMany<Post>}, { access: { read: Public; create: Owner<"id">; update: Owner<"id">; delete: Owner<"id"> }}>
export type Tag = Model<{ id: UUID name: Unique<string>}, { access: { read: Public; create: Role<"admin">; update: Role<"admin">; delete: Role<"admin"> }}>
export type Post = Model<{ id: UUID title: string slug: Unique<Slug<"title">> body: RichText sections: Optional<Blocks<HeroBlock | ProseBlock>> kind: "news" | "guide" cover: Optional<ImageAsset<Covers>> author: RelatedTo<Author, { required: true; onDelete: "cascade" }> tags: ManyToMany<Tag> comments: HasMany<Comment> views: Default<Int, 0> published_at: Optional<Timestamp>}, { versions: { drafts: true } access: { read: Any<[Lte<"published_at", Now>, Owner<"author_id">]> create: Owner<"author_id"> update: Owner<"author_id"> delete: Any<[Owner<"author_id">, Role<"admin">]> }}>
export type Comment = Model<{ id: UUID post: RelatedTo<Post, { required: true; onDelete: "cascade" }> user_id: SupatypeAuthUserId<{ onDelete: "cascade" }> body: string}, { access: { read: Public; create: Owner<"user_id">; update: Owner<"user_id">; delete: Owner<"user_id"> }}>The other pages use this schema in their examples. HeroBlock, ProseBlock and Covers are defined further down.
Access rules
Each model has a rule for read, create, update and delete. The rules become Postgres row level security, so they hold for REST, GraphQL, realtime and the client alike.
An operation with no rule is denied. A model with no access at all is not reachable through the API.
| Rule | Who passes |
|---|---|
Public | Everyone, signed in or not |
LoggedIn | Any signed-in user |
Private | Nobody through the API |
Owner<"author_id"> | The user whose id is in that column. Use "id", a SupatypeAuthUserId field, or a relation’s _id column. Owner<Post, "author_id"> also names the model, so the editor checks the field |
OwnerFrom<"post"> | The owner of the related row, one relation deep |
Role<"admin"> | A user whose app_metadata.role is admin |
Any<[A, B]>, All<[A, B]>, Not<A> | Either rule, both rules, or the opposite |
Eq, Neq, Gt, Gte, Lt, Lte, Like | A comparison, such as Lte<"published_at", Now> |
In<"site_id", Rows<"user_sites", "site_id", Eq<"user_id", AuthUid>>> | The column’s value is in the set: rows of another table, Values<["draft", "review"]>, or a claim holding an array |
Exists<Rows<...>> | The set is not empty, whatever the row holds |
In a comparison, a plain string names a column. Wrap a constant in Literal<>. Now, AuthUid and Claim<"app_metadata.plan"> are also available. IsNull<"col"> and NotNull<"col"> test for null.
A time can be relative to now. Ago<30, "days"> and FromNow<7, "days"> take one amount and one unit. StartOf<"day"> is the start of the day, week, month or year. After<Now, { days: 30 }> and Before<StartOf<"day">, { hours: 9 }> add or take away several units at once. So Gte<"created_at", Ago<30, "days">> passes rows from the last 30 days.
Since 0.7.0 a push refuses an owner rule that could never match. An Owner on a relation must reach, through one relation at most, a model keyed by a SupatypeAuthUserId or one with its own Owner rule. On a plain UUID field it still works, with a warning.
Role<> reads the user’s app_metadata.role, which only the auth admin API can set. It is not the Studio role.
Field rules and masking
A field rule limits who can read or write one column. Declare it under access.fields.
export type Profile = Model<{ id: SupatypeAuthUserId display_name: string email: string}, { access: { read: Public create: Owner<"id"> update: Owner<"id"> delete: Owner<"id"> fields: { email: { read: Any<[Owner<"id">, Role<"moderator">]>; write: Owner<"id"> } } }}>A caller who may not read the column still gets the row, with the value masked as null. A write the rule refuses fails with error 42501.
A field’s write rule applies together with its read rule: only callers who can also read a column can write it. If the write rule is wider than the read rule, supatype push and supatype diff warn and say so. For example, with read: Role<"admin"> and write: Owner<"owner_id">, only admins who own the row can write the column. A hook that sets it on another caller’s write is refused.
Name a relation by its column, such as author_id.
Auth user ids
SupatypeAuthUserId holds the id of a sign-in user. Use it for owner columns.
When the create rule is Owner<"col"> and the column has no default, the column defaults to the caller’s own user id. So a client can leave it out on insert.
By default there is no foreign key to the user. Deleting a user leaves their rows as they were. Add onDelete to get one:
onDelete | When the user is deleted |
|---|---|
"cascade" | Their rows are deleted too |
"restrict" | Deleting the user is refused while they own rows |
"setNull" | The column is set to null. The field must be Optional<> |
The push that adds the key refuses if existing rows name a user that does not exist. Its message says how many rows and how to remove them. It also refuses if the database has no auth.users table, which Supatype’s auth server creates. Start the auth server against the database once, or remove onDelete so the field holds an id with no foreign key.
Drafts and versions
versions: { drafts: true } keeps drafts and a history of each record. versions: true is short for the same. keep sets how many versions to keep (default 20).
The model’s own table holds the published record. That is what read rules and the public API see. Drafts and old versions live in post_versions.
Publishing copies a draft into the live table. It also sets published_at if it is empty. The update rule decides who may publish.
A direct API update of the live row is refused with error 42501. Save a draft with the client’s update, then publish, or pass { publish: true } to do both. See Client.
versions: { drafts: false } keeps history only. Writes go straight to the live row.
The read rule does not decide who sees a draft. The record’s creator sees it. So do the Studio roles in publishing.draft_visibility in supatype.config.ts (default admin, developer and editor), and anyone with a signed preview link.
Slugs, rich text and blocks
Slug<"title"> fills itself from title when you leave it empty. While it still holds the generated value, it follows the title when the title changes. Set it yourself to keep a URL fixed. Add Unique<> if it must be unique.
RichText stores a rich text document. When you write, a plain string is accepted and becomes one paragraph. A read always returns the document.
Blocks<T> is a list of sections an editor arranges in Studio. Each block is Block<"name", { fields }>:
export type HeroBlock = Block<"hero", { heading: string; image: Optional<ImageAsset<Covers>> }>export type ProseBlock = Block<"prose", { body: RichText }>Each entry is stored as { "type": "hero", "data": { "heading": "Hi" } }. A renderer switches on type and reads data. Rich text inside a block is not converted from a string, so write the full document there.
A third argument, { label, icon }, sets how Studio shows the block, such as Block<"hero", { heading: string }, { label: "Hero banner" }>. Both are optional.
Before 0.7.0 a block’s fields sat beside type. supatype push moves entries stored that way under data, and supatype diff shows how many are pending. Push before anyone opens those records in Studio. See Upgrading.
Storage buckets
export type Covers = Bucket<"covers", { accessMode: "public" accept: ["image/png", "image/jpeg", "image/webp"] maxSize: "5MB" access: { read: BucketPublic; create: BucketLoggedIn; update: BucketOwner; delete: BucketOwner }}>A bucket has the same four rules as a model. update means overwriting a file. The rules are BucketPublic, BucketLoggedIn, BucketOwner (the uploader), BucketRole<"name"> and BucketPrivate.
A rule you leave out is refused for everyone but the service role, and the push warns about it. accessMode: "public" serves files on a public URL whatever read says.
ImageAsset<Covers> on a model stores a reference to a file in that bucket.
Renames
A push never guesses a rename. Renaming a field in the schema looks like a drop and an add.
In a terminal, supatype push and supatype dev ask, for example “Was post.title renamed to post.headline? (recorded in supatype/renames.json)”. Answer yes and it records the rename. Without a terminal the push stops and prints the supatype rename command to run.
$ supatype rename post.title post.headline # a column$ supatype rename post article # a tableRenames are recorded in supatype/renames.json. Commit it. Every push replays it, so each database gets the same rename. supatype rename --prune removes entries the target database has already applied. Point it at a database with --connection, --env or --direct, as for a push.
What a push refuses
| Push stops when | To go on |
|---|---|
| A change can lose data, such as a drop | Answer yes in a terminal, or pass --yes in CI |
| A table the schema names exists but Supatype did not create it | supatype adopt, or give the model another tableName. The push offers to adopt in a terminal |
| A change rewrites or scans a table of more than 100,000 rows, which locks it while it runs | Answer yes in a terminal, or pass --yes |
| Policies, grants, labels or row level security were changed outside Supatype | --overwrite-drift puts Supatype’s back. To keep the hand edits, run supatype doctor --rebaseline --accept-access-drift |
| A versioned model has field rules | Remove one of the two |
An onDelete key would point at missing users | Delete or fix those rows |
An onDelete key needs auth.users and the database has none | Start the auth server against the database once, or remove onDelete |
| The schema has identity or generated columns and the engine is older than 0.7.0 | Run supatype update |
A JSON field changed to Blocks holds values that are not objects | Change or remove those values, then push again |
--yes does not override hand-edited access rules. Only --overwrite-drift does. Objects that Supatype did not create are never dropped or taken over.
Server logic in a Postgres function
The schema declares tables and access rules. It has no place for your own SQL, so logic that must run as one step in the database, such as checking a price and raising it in one transaction, is a Postgres function that you create yourself and call with supatype.rpc(). “No raw SQL” means the access rules are typed, not that the database is closed to you.
CREATE FUNCTION public.place_bid(lot_id uuid, amount numeric)RETURNS public.lotLANGUAGE plpgsqlSECURITY INVOKERSET search_path = ''AS $$DECLARE current_lot public.lot;BEGIN -- Lock the row, so two bids at once are checked one after the other. SELECT * INTO current_lot FROM public.lot WHERE id = lot_id FOR UPDATE; IF NOT FOUND THEN RAISE EXCEPTION 'no such lot'; END IF; IF amount <= current_lot.price THEN RAISE EXCEPTION 'bid must be above %', current_lot.price; END IF; UPDATE public.lot SET price = amount WHERE id = lot_id RETURNING * INTO current_lot; RETURN current_lot;END;$$;
GRANT EXECUTE ON FUNCTION public.place_bid(uuid, numeric) TO authenticated;NOTIFY pgrst, 'reload schema';- Lock what you check.
SELECT ... FOR UPDATEmakes a second caller wait until the first transaction ends, so the check and the update cannot interleave. SECURITY INVOKERorDEFINER. An invoker function runs as the caller, so the row rules and field masking on every table it touches apply as they would for a request. That is the default, and the one to use. A definer function runs as the role that created it, which skips both, so it must do its own checks (for example againstauth.uid()) and should be written with great care.SET search_path = ''. It stops a caller shadowing a table or function with one of their own. Name every object with its schema, as above. It matters most for a definer function.- Grant it. The API roles can call only what you grant:
GRANT EXECUTE ... TO authenticated, oranonfor a signed-out caller. - Create it. Run the SQL with
psqlagainst your database, or in Studio’s SQL runner.NOTIFY pgrst, 'reload schema'makes the API pick the function up straight away. - Call it.
rpcsends the named arguments, and aRAISE EXCEPTIONcomes back aserror.
const { data: lot, error } = await supatype.rpc("place_bid", { lot_id: lotId, amount: 120 })Run a function on a schedule
The image ships pg_cron, so a Postgres function can run on a timer. Write the function as above (here, one that closes every lot whose end time has passed), then schedule it by hand.
$ psql "$DATABASE_URL"
SELECT cron.schedule('close-lots', '* * * * *', $$SELECT public.close_ended_lots()$$);SELECT jobid, jobname, schedule, command, username, database FROM cron.job;SELECT status, return_message, start_time FROM cron.job_run_details ORDER BY runid DESC LIMIT 5;SELECT cron.unschedule('close-lots');- Where it runs. In your project’s database, the one named by
POSTGRES_DB, as the role that calledcron.schedule. With the admin URL that role issupatype_admin, a superuser, so the job is not held to row rules and field masking, and the function should do its own checks. - Who can schedule. The admin role can, and so can Studio’s SQL runner on
supatype/postgres17.2.17 or later. The runner connects assupatype_sql_editor, so its jobs run as that role, with the runner’s rights. It can remove its own jobs but not the admin’s. On an older image the runner fails withpermission denied for schema cron: usepsqlwith the admin URL. - List and remove.
cron.joblists the jobs,cron.job_run_detailssays whether each run succeeded, andcron.unschedule('name')removes one.
The same pattern serves a query the REST filters cannot express. The geography example adds a places_within function the same way.