import { createClient } from '@supabase/supabase-js'; import fs from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; import dotenv from 'dotenv'; // Get the directory name const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // Load environment variables dotenv.config({ path: '.env.local' }); // Validate required environment variables if (!process.env.NEXT_PUBLIC_SUPABASE_URL || !process.env.SUPABASE_SERVICE_ROLE_KEY) { console.error('Error: Missing Supabase environment variables.'); console.error('Make sure NEXT_PUBLIC_SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY are set in .env.local'); process.exit(1); } // Create Supabase client const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; const supabaseKey = process.env.SUPABASE_SERVICE_ROLE_KEY; const supabase = createClient(supabaseUrl, supabaseKey, { auth: { autoRefreshToken: false, persistSession: false } }); // Function to execute SQL directly (fallback) async function executeSQL(sql) { try { // First try the exec_sql RPC function const { error } = await supabase.rpc('exec_sql', { sql }); if (error) { // If the RPC function fails, try direct SQL execution console.log('Falling back to direct SQL execution...'); const { error: directError } = await supabase.from('_exec_sql').select('*').eq('sql', sql).maybeSingle(); if (directError) { throw new Error(`Failed to execute SQL: ${directError.message}`); } } return { success: true }; } catch (error) { return { success: false, error }; } } // Read and execute the migration SQL async function runMigration() { try { // Import the file path const sqlFilePath = path.join(__dirname, 'add-slug-to-learning-simple.sql'); // Inside the runMigration function, replace the file path console.log('Reading migration SQL file...'); const migrationSql = fs.readFileSync(sqlFilePath, 'utf8'); // Split the SQL into individual statements const statements = migrationSql .replace(/\/\*.*?\*\//g, '') // Remove block comments .replace(/--.*?$/gm, '') // Remove line comments .split(';') .map(s => s.trim()) .filter(s => s.length > 0); // Filter out empty statements console.log(`Found ${statements.length} SQL statements to execute.`); // Execute each statement for (let i = 0; i < statements.length; i++) { const statement = statements[i]; console.log(`Executing statement ${i + 1}/${statements.length}...`); // Try executing the SQL statement const { success, error } = await executeSQL(statement); if (!success) { console.error(`Error executing statement ${i + 1}:`, error.message); console.error('SQL Statement:', statement); // Continue with other statements console.log('Continuing with remaining statements...'); } } console.log('Migration completed!'); // Verify the migration by checking if slug column exists const { data, error: verifyError } = await supabase .from('learning') .select('slug') .limit(1); if (verifyError) { console.warn('Warning: Could not verify migration:', verifyError.message); } else if (data && data.length > 0) { console.log('Verification successful: slug column exists and contains data.'); } else { console.log('Slug column exists but may not contain data yet.'); } } catch (error) { console.error('Error executing migration:', error.message); process.exit(1); } } runMigration();