# Supabase Migration Guide

**Last Updated**: 2025-10-24

## ⚠️ CRITICAL: Read This First

This project has experienced **migration tracking issues** where the Supabase CLI lost sync with the remote database. This guide documents the proper workflow to prevent future issues.

---

## The Problem We Had

### What Went Wrong (Oct 2024)
1. **Manual SQL Changes**: Some schema changes were applied directly via Supabase Dashboard SQL Editor instead of through migration files
2. **CLI Lost Sync**: The `supabase_migrations.schema_migrations` table didn't have all migration versions registered
3. **CLI Confusion**: `supabase db push` reported "Remote database is up to date" even though new migrations existed
4. **Manual Application Required**: Migration had to be applied manually via Dashboard

### Root Cause
When you run SQL directly in Supabase Dashboard (instead of through migrations), the migration tracking table (`supabase_migrations.schema_migrations`) doesn't get updated. The CLI then thinks the database is at a different state than it actually is.

---

## The Correct Workflow

### Option A: Using Supabase CLI (PREFERRED)

This is the **proper way** to handle migrations. Always use this when possible.

#### 1. Create a Migration File

```bash
# Using Nx (recommended)
pnpm nx run supabase-backend:migration:new add_some_feature

# Or directly with Supabase CLI
cd apps/supabase-backend
pnpm supabase migration new add_some_feature

# This creates: supabase/migrations/YYYYMMDDHHMMSS_add_some_feature.sql
```

#### 2. Write Your Migration SQL

Edit the generated file and add your SQL:

```sql
-- Migration: Add some feature
-- Date: YYYY-MM-DD
-- Purpose: Description of what this does

CREATE TABLE IF NOT EXISTS my_new_table (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  name TEXT NOT NULL,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

-- Always include verification queries at the end
-- Verify table created
SELECT table_name FROM information_schema.tables
WHERE table_schema = 'public' AND table_name = 'my_new_table';
```

#### 3. Test Locally First (Optional but Recommended)

```bash
# Start local Supabase (if not already running)
pnpm supabase start

# Apply migration locally
pnpm supabase db reset

# Verify it works
pnpm supabase db diff
```

#### 4. Apply to Production

```bash
# Dry run first to see what will happen
pnpm supabase db push --dry-run

# If dry run looks good, apply for real
pnpm supabase db push

# Verify migration was registered
pnpm supabase migration list
```

#### 5. Commit the Migration File

```bash
git add supabase/migrations/YYYYMMDDHHMMSS_add_some_feature.sql
git commit -m "feat: Add some feature migration"
git push
```

---

### Option B: Manual Application via Dashboard (USE ONLY WHEN CLI FAILS)

If the CLI is not working (like in our Oct 2024 incident), use this fallback:

#### 1. Create Migration File First

Even if applying manually, **always create a migration file** for version control:

```bash
cd apps/supabase-backend
pnpm supabase migration new add_some_feature
```

#### 2. Write SQL in Migration File

Write your SQL in the migration file (NOT directly in Dashboard).

#### 3. Apply via Supabase Dashboard

1. Log in to [Supabase Dashboard](https://supabase.com/dashboard/project/dwdytxxqcvlrmyemonxz)
2. Navigate to: **SQL Editor**
3. Copy the **entire contents** of your migration file
4. Paste into SQL Editor
5. Click **Run**

#### 4. Register the Migration Manually

This is **CRITICAL** - you must register the migration so CLI knows it was applied:

```sql
-- Get the migration version from filename: YYYYMMDDHHMMSS_add_some_feature.sql
-- Use just the timestamp part: YYYYMMDDHHMMSS

INSERT INTO supabase_migrations.schema_migrations (version)
VALUES ('YYYYMMDDHHMMSS')
ON CONFLICT (version) DO NOTHING;
```

Example:
```sql
-- For file: 20251024000000_add_customer_registry.sql
INSERT INTO supabase_migrations.schema_migrations (version)
VALUES ('20251024000000')
ON CONFLICT (version) DO NOTHING;
```

#### 5. Verify Registration

```bash
pnpm supabase migration list
# Should show your migration as applied
```

#### 6. Commit the Migration File

```bash
git add supabase/migrations/YYYYMMDDHHMMSS_add_some_feature.sql
git commit -m "feat: Add some feature migration (applied manually)"
git push
```

---

## Migration File Best Practices

### File Naming Convention

```
YYYYMMDDHHMMSS_descriptive_name.sql

Examples:
20251024000000_add_customer_registry.sql
20251022230600_add_session_metrics.sql
20251015165400_baseline_existing_schema.sql
```

### Migration File Structure

Every migration file should follow this structure:

```sql
-- ============================================================================
-- Migration: [Descriptive Name]
-- Date: YYYY-MM-DD
-- Purpose: [What this migration does and why]
-- Related PRD: [Path to PRD if applicable]
-- ============================================================================

-- ============================================================================
-- 1. CREATE TABLES
-- ============================================================================

CREATE TABLE IF NOT EXISTS my_table (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  -- columns...
);

COMMENT ON TABLE my_table IS 'Description of what this table stores';

-- ============================================================================
-- 2. ALTER EXISTING TABLES
-- ============================================================================

ALTER TABLE existing_table
ADD COLUMN IF NOT EXISTS new_column TEXT;

-- ============================================================================
-- 3. CREATE INDEXES
-- ============================================================================

CREATE INDEX IF NOT EXISTS idx_my_table_column ON my_table(column);

-- ============================================================================
-- 4. ROW LEVEL SECURITY
-- ============================================================================

ALTER TABLE my_table ENABLE ROW LEVEL SECURITY;

DROP POLICY IF EXISTS "policy_name" ON my_table;
CREATE POLICY "policy_name"
ON my_table FOR SELECT
USING (true);

-- ============================================================================
-- 5. TEST DATA (Optional - only for development)
-- ============================================================================

INSERT INTO my_table (name)
VALUES ('test')
ON CONFLICT (id) DO NOTHING;

-- ============================================================================
-- 6. VERIFICATION QUERIES
-- ============================================================================

-- These queries should be run after migration to verify success

-- Verify table created
SELECT table_name FROM information_schema.tables
WHERE table_schema = 'public' AND table_name = 'my_table';

-- Verify columns exist
SELECT column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_schema = 'public' AND table_name = 'my_table'
ORDER BY column_name;

-- ============================================================================
-- 7. ROLLBACK PROCEDURE
-- ============================================================================

-- If migration fails, rollback with these commands:
-- WARNING: This will delete data!
--
-- DROP TABLE IF EXISTS my_table CASCADE;
```

---

## Common Migration Patterns

### Adding a New Table

```sql
CREATE TABLE IF NOT EXISTS my_table (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  name VARCHAR(255) NOT NULL,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_my_table_name ON my_table(name);

COMMENT ON TABLE my_table IS 'Description';
```

### Adding Columns to Existing Table

```sql
-- Always use IF NOT EXISTS to make migration idempotent
ALTER TABLE existing_table
ADD COLUMN IF NOT EXISTS new_column UUID REFERENCES other_table(id) ON DELETE SET NULL;

-- Add index if it's a foreign key
CREATE INDEX IF NOT EXISTS idx_existing_table_new_column ON existing_table(new_column);

-- Add comment explaining the column
COMMENT ON COLUMN existing_table.new_column IS 'Description of what this stores';
```

### Creating Policies (PostgreSQL RLS)

```sql
-- Enable RLS on table
ALTER TABLE my_table ENABLE ROW LEVEL SECURITY;

-- Drop existing policy first (PostgreSQL doesn't support IF NOT EXISTS for policies)
DROP POLICY IF EXISTS "policy_name" ON my_table;

-- Create the policy
CREATE POLICY "policy_name"
ON my_table FOR SELECT
USING (status = 'active');
```

### Creating Views

```sql
CREATE OR REPLACE VIEW v_my_view AS
SELECT
  t1.id,
  t1.name,
  COUNT(t2.id) AS count
FROM table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.table1_id
GROUP BY t1.id, t1.name;

COMMENT ON VIEW v_my_view IS 'Aggregated view for reporting';
```

---

## Troubleshooting

### "Remote database is up to date" but migration not applied

**Cause**: CLI migration tracking is out of sync

**Solution**:
1. Check what's registered: `pnpm supabase migration list`
2. If your migration is missing, apply it manually via Dashboard (Option B above)
3. **Don't forget** to register it in `supabase_migrations.schema_migrations`

### "Tenant or user not found" when using psql

**Cause**: Incorrect connection string or pooler vs direct connection

**Solution**:
- Use Supabase Dashboard SQL Editor instead
- Or get the correct connection string from: Dashboard → Settings → Database → Connection String

### Migration file exists locally but not in production

**Cause**: Migration file created but never applied

**Solution**:
1. Run `pnpm supabase db push` to apply it
2. Or apply manually via Dashboard + register in migration table

### Want to see what's in the migration tracking table

```bash
cd apps/supabase-backend
pnpm supabase migration list

# This queries: supabase_migrations.schema_migrations
```

---

## PostgreSQL Syntax Gotchas

### IF NOT EXISTS Support

✅ **Supported**:
```sql
CREATE TABLE IF NOT EXISTS my_table (...);
ALTER TABLE my_table ADD COLUMN IF NOT EXISTS my_column TEXT;
CREATE INDEX IF NOT EXISTS idx_name ON my_table(column);
DROP POLICY IF EXISTS "policy_name" ON my_table;
```

❌ **NOT Supported**:
```sql
-- This will ERROR!
CREATE POLICY IF NOT EXISTS "policy_name" ON my_table ...;

-- Use this instead:
DROP POLICY IF EXISTS "policy_name" ON my_table;
CREATE POLICY "policy_name" ON my_table ...;
```

### Always Use Transactions

Migrations are automatically wrapped in transactions by Supabase CLI, but if applying manually:

```sql
BEGIN;

-- Your migration SQL here

COMMIT;
-- or ROLLBACK; if something fails
```

---

## Checklist Before Applying Migration

- [ ] Migration file created with proper naming: `YYYYMMDDHHMMSS_descriptive_name.sql`
- [ ] Migration includes header comment with date, purpose, related PRD
- [ ] All CREATE/ALTER statements use `IF NOT EXISTS` / `IF EXISTS` (except policies)
- [ ] Policies use `DROP POLICY IF EXISTS` + `CREATE POLICY` pattern
- [ ] Verification queries included at end of file
- [ ] Rollback procedure documented (commented out)
- [ ] Tested locally if possible (`pnpm supabase db reset`)
- [ ] Dry run successful (`pnpm supabase db push --dry-run`)
- [ ] Migration applied to production
- [ ] If applied manually, registered in `supabase_migrations.schema_migrations`
- [ ] Verification queries run and passed
- [ ] Migration file committed to git

---

## Migration History

This section tracks all applied migrations and any issues encountered.

### Applied Migrations

| Version | Name | Applied Date | Method | Issues |
|---------|------|--------------|--------|--------|
| 20251012000000 | create_active_bots | 2025-10-12 | CLI | None |
| 20251015000000 | baseline_existing_schema | 2025-10-15 | Manual | Initial setup |
| 20251015000001 | add_livekit_support | 2025-10-15 | Manual | Not registered initially |
| 20251015000002 | make_all_daily_columns_nullable | 2025-10-15 | Manual | Not registered initially |
| 20251016000000 | add_screenshare_livekit_bot_type | 2025-10-16 | Manual | Not registered initially |
| 20251022230600 | add_session_metrics | 2025-10-22 | Manual | Not registered initially |
| 20251024000000 | add_customer_registry | 2025-10-24 | Manual | Fixed policy syntax, column reference |

### Known Issues

**Issue #1: CLI Migration Tracking Out of Sync (Oct 2024)**
- **Problem**: Early migrations not registered in `supabase_migrations.schema_migrations`
- **Cause**: Manual SQL changes applied via Dashboard
- **Impact**: CLI reported incorrect migration status
- **Resolution**: Applied new migrations manually via Dashboard + registered in tracking table
- **Prevention**: Always use CLI workflow (Option A) or register manually (Option B step 4)

---

## Getting Help

If you encounter migration issues:

1. Check this guide first
2. Check Supabase Dashboard → SQL Editor → Query History (shows recent manual changes)
3. Check migration tracking: `pnpm supabase migration list`
4. Check the actual database schema via: Dashboard → Database → Tables
5. If all else fails, apply manually via Dashboard (don't forget to register!)

## Related Documentation

- [Supabase CLI Reference](https://supabase.com/docs/reference/cli)
- [Supabase Migrations Guide](https://supabase.com/docs/guides/cli/managing-migrations)
- Project PRDs: `.claude/prds/`
