#!/usr/bin/env node /** * Apply LiveKit support migrations to Supabase * * This script reads the migration SQL files and executes them against * the Supabase database using the Postgres connection. */ import { createClient } from '@supabase/supabase-js'; import * as fs from 'fs'; import * as path from 'path'; // ANSI color codes const colors = { reset: '\x1b[0m', bright: '\x1b[1m', green: '\x1b[32m', yellow: '\x1b[33m', red: '\x1b[31m', cyan: '\x1b[36m', }; function log(msg: string, color = colors.reset) { console.log(`${color}${msg}${colors.reset}`); } async function executeMigration(sql: string, migrationName: string): Promise { const supabaseUrl = process.env.SUPABASE_URL; const supabaseKey = process.env.SUPABASE_SERVICE_KEY; if (!supabaseUrl || !supabaseKey) { throw new Error('SUPABASE_URL and SUPABASE_SERVICE_KEY must be set'); } log(`\n${'='.repeat(60)}`, colors.cyan); log(`Applying migration: ${migrationName}`, colors.bright); log('='.repeat(60), colors.cyan); const supabase = createClient(supabaseUrl, supabaseKey); // Split SQL into individual statements // Remove comments and split by semicolon const statements = sql .split('\n') .filter(line => !line.trim().startsWith('--')) .join('\n') .split(';') .map(s => s.trim()) .filter(s => s.length > 0); log(`\nFound ${statements.length} SQL statements to execute\n`, colors.cyan); // Execute each statement for (let i = 0; i < statements.length; i++) { const stmt = statements[i]; // Skip empty or comment-only statements if (!stmt || stmt.startsWith('--')) continue; // Get first line for logging const firstLine = stmt.split('\n')[0].substring(0, 60); log(`[${i + 1}/${statements.length}] ${firstLine}...`, colors.yellow); try { // Use raw SQL execution via rpc if available, otherwise try PostgREST const { error } = await supabase.rpc('exec', { sql: stmt }); if (error) { // If RPC doesn't work, we'll need to execute via raw connection // For now, log warning and continue if (error.message.includes('function') || error.message.includes('not found')) { log(`⚠️ RPC method not available - statement skipped`, colors.yellow); log(` Statement: ${firstLine}`, colors.yellow); continue; } throw error; } log(`✅ Success`, colors.green); } catch (err: any) { log(`❌ Failed: ${err.message}`, colors.red); // Continue for idempotent operations (IF NOT EXISTS, IF EXISTS) if (stmt.includes('IF NOT EXISTS') || stmt.includes('IF EXISTS')) { log(` (Continuing - statement is idempotent)`, colors.yellow); continue; } throw err; } } log(`\n✅ Migration ${migrationName} completed\n`, colors.green); } async function applyAllMigrations() { log('\n' + '='.repeat(60), colors.bright); log(' Supabase Migration Application', colors.bright); log('='.repeat(60) + '\n', colors.bright); const migrations = [ { name: 'Baseline Existing Schema', file: '../supabase/migrations/20251015_baseline_existing_schema.sql' }, { name: 'Add LiveKit Support', file: '../supabase/migrations/20251015_add_livekit_support.sql' } ]; let allSuccess = true; for (const migration of migrations) { try { const migrationPath = path.join(__dirname, migration.file); const sql = fs.readFileSync(migrationPath, 'utf8'); await executeMigration(sql, migration.name); } catch (err: any) { log(`\n❌ Migration ${migration.name} failed: ${err.message}\n`, colors.red); allSuccess = false; } } log('\n' + '='.repeat(60), colors.cyan); if (!allSuccess) { log('⚠️ Some migrations failed. Please apply manually:', colors.yellow); log(' 1. Go to Supabase Dashboard → SQL Editor', colors.yellow); log(' 2. Run: /tmp/apply_migrations.sql', colors.yellow); log(' 3. Or view migration files in: supabase/migrations/', colors.yellow); process.exit(1); } log('✅ All migrations applied successfully!', colors.green); log('='.repeat(60) + '\n', colors.cyan); // Print summary log('Summary of changes:', colors.bright); log(' • conversation_sessions: Added LiveKit columns', colors.green); log(' - livekit_room_id', colors.cyan); log(' - livekit_room_name', colors.cyan); log(' - livekit_recording_url', colors.cyan); log(' - voice_agent_session_id', colors.cyan); log(' • active_bots: Added bot_type column', colors.green); log(' • Indexes: Added performance indexes', colors.green); log(''); } // Main execution if (require.main === module) { applyAllMigrations().catch(err => { log(`\n❌ Fatal error: ${err.message}\n`, colors.red); log('Please apply migrations manually via Supabase Dashboard', colors.yellow); process.exit(1); }); }