import { createClient } from '@supabase/supabase-js'; import fs from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const SUPABASE_URL = process.env.SUPABASE_URL || 'http://127.0.0.1:54321'; const SUPABASE_SERVICE_KEY = process.env.SUPABASE_SERVICE_ROLE_KEY; if (!SUPABASE_SERVICE_KEY) { console.error('❌ SUPABASE_SERVICE_ROLE_KEY is required (set it in backend/.env). Refusing to run with a hardcoded fallback.'); process.exit(1); } const supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_KEY); async function executeSql(sql) { try { const { error } = await supabase.rpc('sql', { query: sql }); if (error) throw error; } catch (err) { // Try with pg_query if available, otherwise use REST fallback console.error('SQL execution fallback:', err.message); } } async function applyMigration() { console.log('🚀 Applying database migration...'); const migrationFile = path.join(__dirname, '../supabase/migrations/20260819064500_create_sessions_messages.sql'); const sql = fs.readFileSync(migrationFile, 'utf-8'); const statements = sql.split(';').map(s => s.trim()).filter(s => s && !s.startsWith('--')); for (const stmt of statements) { try { console.log(`✓ ${stmt.substring(0, 60)}...`); await executeSql(stmt); } catch (err) { console.error(`✗ Failed: ${err.message}`); } } console.log('✅ Migration complete!'); } applyMigration().catch(err => { console.error('❌ Migration failed:', err); process.exit(1); });