import { createClient } from '@supabase/supabase-js'; import fs from 'fs'; import path from 'path'; import * as dotenv from 'dotenv'; import { fileURLToPath } from 'url'; // Load environment variables from .env.local const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const envLocalPath = path.resolve(process.cwd(), '.env.local'); if (fs.existsSync(envLocalPath)) { console.log(`Loading environment from: ${envLocalPath}`); dotenv.config({ path: envLocalPath }); } else { console.log(`No .env.local file found at: ${envLocalPath}`); dotenv.config(); // Try loading from default .env } async function applyMigration() { // Validate environment variables const requiredEnvs = ['NEXT_PUBLIC_SUPABASE_URL', 'SUPABASE_SERVICE_ROLE_KEY']; for (const env of requiredEnvs) { if (!process.env[env]) { console.error(`Missing required environment variable: ${env}`); process.exit(1); } } // Create Supabase client with service role key const supabase = createClient( process.env.NEXT_PUBLIC_SUPABASE_URL, process.env.SUPABASE_SERVICE_ROLE_KEY, { auth: { autoRefreshToken: false, persistSession: false } } ); console.log('Creating Supabase client with service role key'); // Read migration SQL const migrationFilePath = path.join(__dirname, '../supabase/migrations/add_image_url_to_tools.sql'); console.log(`Reading migration file from: ${migrationFilePath}`); if (!fs.existsSync(migrationFilePath)) { console.error(`Migration file not found at: ${migrationFilePath}`); process.exit(1); } const migrationSQL = fs.readFileSync(migrationFilePath, 'utf8'); // Apply migration console.log('Applying migration...'); try { const { data, error } = await supabase.rpc('pg_catalog.pg_reload_conf'); if (error) { console.warn('Could not reload configuration, continuing anyway:', error); } const { data: migrationData, error: migrationError } = await supabase.rpc('exec_sql', { sql: migrationSQL }); if (migrationError) { console.error('Error applying migration:', migrationError); process.exit(1); } console.log('Migration applied successfully:', migrationData); // Refresh schema cache console.log('Refreshing schema cache...'); const { error: reloadError } = await supabase.rpc('pg_catalog.pg_reload_conf'); if (reloadError) { console.warn('Could not reload configuration after migration:', reloadError); } else { console.log('Schema cache refreshed successfully'); } } catch (error) { console.error('Unexpected error applying migration:', error); process.exit(1); } } applyMigration() .then(() => { console.log('Migration process completed'); process.exit(0); }) .catch((error) => { console.error('Unhandled error in migration process:', error); process.exit(1); });