supabase-orm
Describe your tables in TypeScript. It compares them with the live database and writes the SQL to close the gap. It also writes typed rows for your Supabase client.
Hand-written migrations drift from the real database. A wrong one can drop data. I wanted the schema in code, the SQL generated from it, and every drop held back until I ask for it.
What it does
From schema to SQL
You change the TypeScript. The migration has only what changed.
- 1
Describe a table
Columns are typed builders.
schema.tstable('app_notes', { id: col.uuid().primaryKey().default('gen_random_uuid()'), name: col.text().notNull(), body: col.text().nullable(), }) - 2
Generate the first migration
A new table becomes
CREATE TABLEwith row level security turned on.001.sqlCREATE TABLE IF NOT EXISTS app_notes ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), name TEXT NOT NULL, body TEXT ); ALTER TABLE app_notes ENABLE ROW LEVEL SECURITY;
- 3
Change it
Rename
namewith.renamedFrom(). Addpinned. Removebody.schema.tstable('app_notes', { id: col.uuid().primaryKey().default('gen_random_uuid()'), title: col.text().notNull().renamedFrom('name'), pinned: col.boolean().notNull().default('false'), }) - 4
Generate again
The rename and the new column are in. The dropped column is held back.
002.sql-- ─── Destructive changes detected but NOT generated ─── -- Re-run with --force-destructive (or set allowDestructive: true) to include: -- drop_column app_notes.body ALTER TABLE app_notes RENAME COLUMN name TO title; ALTER TABLE app_notes ADD COLUMN IF NOT EXISTS pinned BOOLEAN NOT NULL DEFAULT false;
Drops need a flag, twice
Dropping a column or table, or changing a type, is left out by default. --force-destructive writes it into a marked file. apply needs the flag again before it runs that file.
-- supaorm:destructive -- This migration includes DESTRUCTIVE changes. Review carefully before applying: -- drop_column app_notes.body ALTER TABLE app_notes RENAME COLUMN name TO title; ALTER TABLE app_notes ADD COLUMN IF NOT EXISTS pinned BOOLEAN NOT NULL DEFAULT false; ALTER TABLE app_notes DROP COLUMN body;
Typed queries
supaorm types writes Row, Insert and Update types for each table. A repository uses them for every call.
const notes = createRepository<AppTables, 'app_notes'>(client, 'app_notes')
const row = await notes.insert({ title: 'First note' })
await notes.update(row.id, { pinned: true })- 04
No direct database connection
Everything runs through two SQL functions,
exec_sqlandquery_sql. You install them once withsupaorm bootstrap.
Get started
- 1
Install
A dev tool, plus the Supabase client.
$npm install --save-dev @dinesh-gamage/supabase-orm - 2
Set up once
Create the config. Then run the bootstrap SQL in the Supabase SQL editor.
npx supaorm init npx supaorm bootstrap --write
- 3
Migrate
Check the changes, write the migration, then run it.
npx supaorm diff npx supaorm generate npx supaorm apply