SQL · Module 14 · Lesson 52 min read

Migrations, Version Control & ORMs

The problem

Schema changes made by hand in production are invisible: nobody knows what changed, when, or how to recreate the database for a new developer, a test run or staging.

Migrations

Numbered SQL files that describe each change, stored in Git and applied in order:

Terminal
supabase/migrations/
  20261101120000_create_expenses.sql
  20261115093000_add_tags_to_expenses.sql
  20261124101500_enable_rls_on_notes.sql
  • The tool records which migrations already ran (a history table)
  • Every environment (local, staging, production) is built the same way
  • Reviewed in pull requests like normal code

Supabase CLI workflow

  1. supabase init + supabase start (local Postgres in Docker)
  2. supabase migration new add_tags → write the SQL
  3. Or change things in the local Studio, then supabase db diff -f add_tags to generate the SQL
  4. supabase db reset → rebuild locally from all migrations + seed.sql
  5. supabase db push → apply to the hosted project (or let CI do it)
  6. supabase gen types typescript → regenerate types

Writing safe migrations

  • Small, focused changes, one purpose per file
  • Never edit a migration that has already run in production → write a new one
  • Make destructive changes in steps (expand → migrate → contract):
    1. add the new column, 2. backfill and deploy code that uses it, 3. later drop the old column
  • Use IF NOT EXISTS / IF EXISTS where sensible
  • Big tables: CREATE INDEX CONCURRENTLY; add NOT NULL after backfilling; avoid long locks
  • Keep a seed file for local/test data

ORMs and query builders

ToolStyle
Prismaschema file → generated client + migrations
DrizzleTypeScript schema, SQL-like queries, lightweight
Kyselytype-safe query builder
Sequelize / TypeORMclassic ORMs
Flyway / Liquibase / Sqitch / dbmatepure migration tools (any language)

ORM trade-offs

✅ Type safety, less boilerplate, migrations built in ❌ Can hide inefficient queries (N+1); complex reports are often easier in raw SQL Knowing SQL makes you much better at using any ORM.

Example

SQL
-- 📄 supabase/migrations/20261124101500_add_expense_tags_and_payment_method.sql
-- Purpose: tag expenses and record how they were paid.
-- Safe to run on a live table: no long locks, idempotent where possible.

BEGIN;

-- 1. EXPAND: add new nullable columns (fast, no table rewrite)
ALTER TABLE expenses ADD COLUMN IF NOT EXISTS payment_method TEXT;

-- 2. Lookup table for allowed values
CREATE TABLE IF NOT EXISTS payment_methods (
  code  TEXT PRIMARY KEY,
  label TEXT NOT NULL
);
INSERT INTO payment_methods (code, label) VALUES
  ('cash', 'Cash'), ('card', 'Card'), ('esewa', 'eSewa'), ('khalti', 'Khalti')
ON CONFLICT (code) DO NOTHING;

-- 3. MIGRATE: backfill existing rows
UPDATE expenses SET payment_method = 'cash' WHERE payment_method IS NULL;

-- 4. CONTRACT: now that every row has a value, enforce the rules
ALTER TABLE expenses ALTER COLUMN payment_method SET DEFAULT 'cash';
ALTER TABLE expenses ALTER COLUMN payment_method SET NOT NULL;
ALTER TABLE expenses
  ADD CONSTRAINT expenses_payment_method_fkey
  FOREIGN KEY (payment_method) REFERENCES payment_methods(code);

COMMIT;

-- Verify
SELECT payment_method, count(*) FROM expenses GROUP BY 1;   -- cash | 31

-- 📄 For big production tables, build indexes outside a transaction:
-- CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_expenses_payment ON expenses (payment_method);

-- 🖥️ Supabase CLI
-- $ supabase migration new add_expense_tags_and_payment_method
-- $ supabase db reset            # rebuild local DB from all migrations + seed.sql
-- $ supabase db push             # apply to the hosted project
-- $ supabase gen types typescript --local > src/types/database.ts

-- 🧩 The same model in Prisma (schema.prisma) for comparison:
-- model Expense {
--   id            BigInt   @id @default(autoincrement())
--   title         String
--   amount        Decimal  @db.Decimal(10, 2)
--   paymentMethod String   @default("cash") @map("payment_method")
--   @@map("expenses")
-- }