Skip to content

Field Types

A field’s type is its column type. TypeScript’s own primitives cover the common cases; the rest are named types imported from @supatype/types. Modifiers wrap a type rather than chaining onto it.

import type { Int, MaxLength, Model, Optional, Timestamp, Unique, UUID } from "@supatype/types"
export type Product = Model<{
id: UUID
sku: Unique<string>
name: MaxLength<string, 120>
stock: Int
retired_at: Optional<Timestamp>
}, { tableName: "products" }>

Primitives

TypeScript’s built-ins map straight through:

TypeScriptPostgreSQLNotes
stringTEXT
numberDOUBLE PRECISIONthe type that holds every JavaScript number; reach for Int or Decimal when you want narrower
booleanBOOLEAN
"a" | "b"TEXT + CHECK (col IN ('a','b'))a string-literal union, checked rather than a native ENUM type (see Enums)
T[]T[]array of the element’s column type

A TypeScript type with no column type of its own, such as a single string literal (kind: "outbid") or an object type, is stored as JSONB, and supatype push warns naming the field. Use string for text, a union of two or more literals for an enum, or JSON<T> when JSONB is what you mean.

Text

TypePostgreSQLNotes
stringTEXT
MaxLength<string, 255>TEXT + CHECK (char_length(col) <= 255)a check, not VARCHAR(n), so the limit can change without rewriting the column
MinLength<string, 3>TEXT + CHECK (char_length(col) >= 3)
RichTextJSONBLexical editor state; a plain string is also accepted for seeds and defaults
MarkdownTEXT
Slug<"title">TEXTfilled from the named field by a trigger; wrap in Unique<…> for the constraint
EmailTEXT + CHECK on an email pattern
URLTEXT + CHECK (col ~* '^https?://')
PhoneNumberTEXT
ColorTEXTStudio renders a colour picker

Numbers

TypePostgreSQLNotes
IntINTEGER32-bit
SmallIntSMALLINT16-bit
BigIntBIGINT64-bit; bigint in TypeScript
Float / numberDOUBLE PRECISION
Decimal<10, 2>NUMERIC(10, 2)exact; string in TypeScript so no precision is lost in transit
MoneyNUMERIC(19, 4)not Postgres MONEY, whose behaviour depends on a server locale
Between<Int, 1, 5>the inner type + CHECK on both bounds

Date and time

TypePostgreSQL
Timestamp / DateTime / DateTIMESTAMPTZ
DateOnlyDATE

The three timestamp spellings are aliases; Timestamp reads best on a column and is what the scaffold uses. There is no interval column type exposed today: Duration stores milliseconds as JSON rather than a Postgres INTERVAL.

Identity and keys

TypePostgreSQLNotes
UUIDUUIDPRIMARY KEY DEFAULT gen_random_uuid() when the field is named id
SupatypeAuthUserIdUUIDa user’s id from auth.users, with no foreign key by default; SupatypeAuthUserId<{ onDelete: "cascade" }> adds one ("restrict" and "setNull" are the other choices)
AutoIncrementINTEGER GENERATED BY DEFAULT AS IDENTITYthe database numbers rows and an insert may still give a value; AutoIncrement<bigint> for BIGINT. A SERIAL column made by an older release is left as it is
IdentityINTEGER GENERATED ALWAYS AS IDENTITYIdentity<bigint> for BIGINT; Identity<number, "by-default"> is AutoIncrement. The same as Int<{ identity: "always" }>
PrimaryKey<T>the inner type + PRIMARY KEYfor a key that is not called id. A key you type yourself is fixed forever; see Typed keys
NaturalKey<T>the inner type + PRIMARY KEYa typed key for a value that truly never changes, such as an ISO code. The only typed key a push will create on a new model

Typed keys

A key the database fills (UUID, Identity, AutoIncrement) is safe. A key you type yourself, such as code: PrimaryKey<string>, is fixed forever. It can never be changed, by Studio, the API or anything else: every draft, relation, preview and URL points at it, so a change would orphan them. An update that tries to change one is refused with Cannot change code on "country": it is the record's key. To change a typed key, create a new record and delete the old one.

A push that would create a new model with a typed key is refused. The refusal names the model and the key column, and nothing is applied. A table that already exists in the database you push to is left as it is.

Upgrading a project that already has a typed key. “New” means new to the database being pushed to. An empty database, such as a fresh staging environment, CI or a teammate’s first supatype dev, has none of your tables, so a model declared code: PrimaryKey<string> is refused there. Change it to code: NaturalKey<string>. Nothing in the database changes: the key is already fixed. supatype pull writes NaturalKey<> for a key the database does not fill, so a pulled schema pushes anywhere.

The recommended pattern is the hidden id plus a unique lookup field. The id never changes, and the slug can be renamed:

import type { Model, Slug, UUID, Unique } from "@supatype/types"
export type Category = Model<{
id: UUID
slug: Unique<Slug<"title">>
title: string
}>

If the value truly never changes, such as an ISO country or currency code, say so with NaturalKey<T>. It is a PrimaryKey<T> that tells the push you chose a typed key on purpose:

import type { Model, NaturalKey } from "@supatype/types"
export type Country = Model<{
code: NaturalKey<string>
name: string
}>

Use NaturalKey only when the value is fixed for the life of the record. If it might ever be renamed, use id and Unique<> instead.

Structured

TypePostgreSQLNotes
JSON<T>JSONBT is the shape your client sees
Blocks<A | B>JSONBblock-based content; see the Studio block editor
ButtonJSONB{ label, href, ariaLabel?, target? }
Code<"sql">JSONB{ lang, source }: source text with the language it is written in
Currency<"USD">JSONB{ amount, code }: minor units, with the currency they are denominated in
DurationJSONB{ ms }
ByteaBYTEA
XMLXML

These four are JSONB because each carries more than one value, and the generated client row keeps that shape rather than flattening to an opaque object:

import type { Code, Currency, Model, UUID } from "@supatype/types"
export type Snippet = Model<{
id: UUID
body: Code<"sql"> // { lang: "sql"; source: string }
price: Currency<"USD"> // { amount: string; code: "USD" }
}, { tableName: "snippets" }>

The literal argument narrows the generated type: Code<"sql"> types lang as "sql", and bare Code leaves it string.

amount is a string, like Money and Decimal. The value crosses the wire as JSON, where bigint cannot be serialised at all and number silently loses integers past 2^53, and a rounding error in a currency column is the one place that is least acceptable.

Choosing between Currency and Money: Currency keeps the code with the amount, which is what you want when rows can be denominated differently. Money (or Decimal<p, s>) is a numeric column, which is what you want when the database has to SUM, compare or index it, since SQL arithmetic over JSONB means casting on every row and no usable index.

Enums

A string-literal union is the enum:

import type { Model, UUID } from "@supatype/types"
export type Post = Model<{
id: UUID
status: "draft" | "published" | "archived"
}, { tableName: "posts" }>

This becomes TEXT with CHECK (status IN ('draft','published','archived')), not a native CREATE TYPE … AS ENUM. The reason is migrations: adding a value to a check constraint is one ALTER TABLE, while a native enum type cannot drop a value at all and its ordering is fixed at creation. You keep exhaustive types in TypeScript either way.

Storage

TypePostgreSQLNotes
ImageAsset<Bucket>JSONBstorage reference plus width/height
FileAsset<Bucket>JSONBstorage reference

The bucket is a type too, so the field and the bucket’s access rules stay connected:

import type { Bucket, BucketLoggedIn, BucketPublic, ImageAsset, Model, Optional, UUID } from "@supatype/types"
export type Avatars = Bucket<"avatars", {
accessMode: "public"
accept: ["image/png", "image/jpeg", "image/webp"]
maxSize: "5MB"
access: { read: BucketPublic; create: BucketLoggedIn }
}>
export type Profile = Model<{
id: UUID
avatar: Optional<ImageAsset<Avatars>>
}, { tableName: "profiles" }>

Geographic and vector

TypePostgreSQLNotes
GeoPointGEOGRAPHY(POINT, 4326)GEOGRAPHY, not GEOMETRY, so distances come out in metres on a sphere
GeoGEOGRAPHY(POINT, 4326)
Vector<1536>vector(1536)pgvector

Where the extensions live

The push creates the extensions these types need (postgis for Geo and GeoPoint, vector for Vector<N>, unaccent for Slug, and pgcrypto) in the extensions schema on every tier, as Supabase does, and never in public. The columns read, write and filter through REST and GraphQL as any other column does: the API resolves their types and operators through its extra search path, which is public,extensions (api,extensions when field access uses generated views).

The extensions’ own functions are not API endpoints: POST /rest/v1/rpc/st_distance answers 404, and the OpenAPI document at /rest/v1/ lists none of them. PostGIS and pgvector add about 940 functions, and serving them from public made the OpenAPI root slow enough to time out after a push. To call one from the API, wrap it in a function of your own; see Calling an extension function from the API.

SQL of your own that names one of their objects with a public. prefix (public.vector, public.unaccent(...)) has to drop the prefix or use extensions., and a database role with its own search_path needs extensions on it.

A project pushed by an older release has these extensions in public. The first push after you upgrade moves vector, unaccent and pgcrypto with ALTER EXTENSION ... SET SCHEMA extensions, which leaves columns, indexes and rows untouched. The plan lists the move as a cautious change, so supatype push asks first (--yes agrees up front), supatype dev applies it as it applies other cautious changes, and supatype rollback moves them back. PostGIS cannot be moved that way: the push leaves it in public, where everything keeps working, and prints this warning on every push until you move it:

Extension `postgis` is installed in `public`, where the API serves its functions as /rest/v1/rpc/* endpoints and lists them in the OpenAPI document. A push cannot move it (`ALTER EXTENSION ... SET SCHEMA` is not supported for it), and everything keeps working where it is. To move it to `extensions`, see UPGRADING.md, "Extensions move to the extensions schema".

Moving it means dropping and re-adding every geography and geometry column, so do it in a maintenance window with writes stopped, after a backup (with pg_dump, for example). Run the SQL as the database’s admin role (supatype_admin on supatype/postgres):

  1. List the columns to keep:

    SELECT table_schema, table_name, column_name
    FROM information_schema.columns
    WHERE udt_name IN ('geography', 'geometry');
  2. Copy each column aside with its table’s primary key, as text (the hex form reads back exactly), then replace the extension. Repeat the CREATE TABLE for every column the query listed. The DROP also takes the columns’ indexes, any view or policy that uses them, and the spatial_ref_sys table: copy any rows you added to spatial_ref_sys yourself, and drop postgis_topology or postgis_raster first if you installed them.

    CREATE SCHEMA postgis_move;
    CREATE TABLE postgis_move.places AS SELECT id, point::text AS point FROM public.places;
    DROP EXTENSION postgis CASCADE;
    CREATE EXTENSION postgis WITH SCHEMA extensions;
  3. Push. It adds the columns and their indexes back, empty: supatype push.

  4. Put the values back, and drop the copies:

    UPDATE public.places AS t SET point = m.point::extensions.geography
    FROM postgis_move.places AS m WHERE t.id = m.id;
    DROP SCHEMA postgis_move CASCADE;
  5. Push again. It reports the schema up to date, and the warning is gone.

Calling an extension function from the API

Write a SQL function of your own in public that calls the extension’s function, and call yours with rpc(). Give it SET search_path = public, extensions so its body finds the extension wherever it is installed (PostGIS stays in public on a project that has not moved it), and leave it SECURITY INVOKER, the default, so it runs as the caller and the table’s access rules apply to the rows it reads.

For a model with tableName: "places" and a location: GeoPoint field:

CREATE FUNCTION public.places_within(lat double precision, lng double precision, metres double precision)
RETURNS SETOF public.places
LANGUAGE sql STABLE
SET search_path = public, extensions
AS $$
SELECT *
FROM public.places
WHERE ST_DWithin(location, ST_SetSRID(ST_MakePoint(lng, lat), 4326)::geography, metres)
$$;
NOTIFY pgrst, 'reload schema';

Run it against your database with psql. A push leaves a function it did not make alone (see Server logic in a Postgres function for what is and is not managed), and the NOTIFY makes the API pick the new function up straight away. Then:

import { createClient } from "@supatype/client"
const supatype = createClient({
url: process.env.PUBLIC_SUPATYPE_URL!,
anonKey: process.env.ANON_KEY!,
})
const { data, error } = await supatype.rpc("places_within", { lat: 51.5072, lng: -0.1276, metres: 5000 })

Indexes

Indexed<T> puts a B-tree index on one field. For anything else (several fields, a unique index, or another index method) list the model’s indexes in its options:

import type { GeoPoint, Model, UUID, Vector } from "@supatype/types"
export type Place = Model<{
id: UUID
name: string
category: string
location: GeoPoint
embedding: Vector<1536>
}, {
tableName: "places"
indexes: [
{ fields: ["category", "name"]; unique: true },
{ fields: ["location"]; using: "gist" },
{ fields: ["embedding"]; using: "hnsw" },
]
}>
OptionValuesNotes
fieldsfield namesthe index’s keys, in order
namea stringthe index’s name; generated when omitted
uniquetruea unique index
using"btree", "gin", "gist", "hnsw", "brin"the index method; "btree" when omitted. "gist" for Geo and GeoPoint, "hnsw" for Vector
distance"cosine", "l2", "innerProduct"for an hnsw index only; "cosine" when omitted

An hnsw index is built for one distance, with pgvector’s operator class for it: vector_cosine_ops (<=>, the usual choice for text embeddings), vector_l2_ops (<->) or vector_ip_ops (<#>, for vectors normalised to length one). A query ordered by a different distance than its index’s does not use the index. A push refuses distance on an index that is not hnsw, and an hnsw index on a field that is not a Vector; a using or distance value outside the lists above is refused when the schema is read.

TypePostgreSQL
IPAddressINET
CIDRCIDR
MacAddressMACADDR
TSQueryTSQUERY
TSVectorTSVECTOR

Modifiers

Modifiers wrap a type. They compose, and the order does not matter:

import type { Default, Indexed, MaxLength, Model, Optional, Unique, UUID } from "@supatype/types"
export type Article = Model<{
id: UUID
slug: Unique<Indexed<string>>
title: MaxLength<string, 200>
subtitle: Optional<string>
locale: Default<string, "en">
}, { tableName: "articles" }>
ModifierEffect
Optional<T>nullable, and an optional property on the row type
Unique<T>UNIQUE constraint
Indexed<T>B-tree index; see Indexes for other methods
Default<T, V>DEFAULT V
ServerDefault<T>value the database supplies (now(), a trigger, a sequence); optional on inserts
PrimaryKey<T>PRIMARY KEY. A typed key is fixed forever
NaturalKey<T>PRIMARY KEY for a value that never changes. The only typed key a push creates on a new model
AutoIncrement<T>identity column generated by default
Generated<T, "expr">stored generated column, GENERATED ALWAYS AS (expr) STORED; left out of inserts and updates. Types that take options also accept { generated: "expr" }
MaxLength<T, N> / MinLength<T, N>CHECK on char_length (octets for Bytea)
MaxItems<T, N> / MinItems<T, N>CHECK on the element count of an array, a JSON array or a Blocks field
Between<T, Min, Max>CHECK on both bounds, inclusive; numbers for a numeric column, ISO-8601 strings for a date or time column
Searchable<T>searched by the Studio list view’s search box
Computed<T>maintained by the database (a trigger or default): read-only in Studio, optional on inserts
ComputedFrom<T, "title">prefilled in Studio from other fields until edited
Localized<T>JSONB map of locale to value
NotLocalized<T>opts a field out of LocalizedModel’s automatic localisation
EditorReadOnly<T>writable by the API, read-only in Studio

Everything a field is (nullability, constraints, defaults, its own index) is in its type, so there is nothing outside the declaration to keep in sync. Indexes over several fields, or with another method, are the model’s: see Indexes.

Not every field is a column. Relations are fields too; see Relations.

When a push recreates a column

Some changes cannot be made to a column in place: a type change Postgres cannot convert, a plain column becoming generated, or a generated column’s expression changing. The push drops the column and adds it again. Everything that depends on the column is found from the catalog, dropped first, and made again afterwards from its own definition, so no clause is lost:

  • indexes, including expression and partial indexes, INCLUDE columns and sort order;
  • unique, check and primary key constraints;
  • foreign keys, from this table or another one in the project’s schema, with their ON DELETE, ON UPDATE, MATCH and deferral, and a key to auth.users still pointing there;
  • triggers, including whether each is disabled or fires on replica or always;
  • row-level security policies.

Two kinds of dependent cannot be made again that way: a view that reads the column, and anything in another schema. When one of yours depends on the column, the push stops before it changes anything:

public.posts.score has to be dropped and added again for this change, and view public.top_posts depends on it. Supatype does not drop and make again a view, or anything in another schema, so nothing was changed. Drop it, push again, then make it again.

A function that reads the column only in its body is not a dependent: it stays in place and sees the new column on its next call. Before 0.7.0 a recreate brought back only the foreign keys and plain indexes it recognised, without their extra clauses, and anything else on the column either vanished with it or failed the push halfway.