import { createClient } from '@supabase/supabase-js'; import * as path from 'path'; import { readFileSync, existsSync } from 'fs'; import * as dotenv from 'dotenv'; import { fileURLToPath } from 'url'; // Get the current file's directory path in ESM const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // Load environment variables from .env.local const envLocalPath = path.resolve(process.cwd(), '.env.local'); if (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 createFaqsTable() { console.log('Starting to create faqs table...'); // Initialize Supabase client const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY; if (!supabaseUrl || !supabaseServiceKey) { console.error('Missing Supabase environment variables. Please set NEXT_PUBLIC_SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY.'); process.exit(1); } console.log(`Using Supabase URL: ${supabaseUrl}`); const supabase = createClient(supabaseUrl, supabaseServiceKey, { auth: { autoRefreshToken: false, persistSession: false } }); try { console.log('Running SQL migration for faqs table...'); // Read the SQL file const sqlFilePath = path.join(process.cwd(), 'create-faqs-table.sql'); if (!existsSync(sqlFilePath)) { console.error(`SQL file not found at: ${sqlFilePath}`); process.exit(1); } const sqlContent = readFileSync(sqlFilePath, 'utf8'); // Split the SQL content into individual statements const statements = sqlContent .replace(/\/\*[\s\S]*?\*\//g, '') // Remove multi-line comments .replace(/--.*?(\r?\n|$)/g, '$1') // Remove single-line comments .split(';') // Split by semicolon .map(stmt => stmt.trim()) .filter(stmt => stmt.length > 0); console.log(`Found ${statements.length} SQL statements to execute`); // Execute each statement sequentially for (let i = 0; i < statements.length; i++) { const statement = statements[i]; console.log(`Executing statement ${i + 1}/${statements.length}:`); console.log(statement.substring(0, 100) + (statement.length > 100 ? '...' : '')); try { // Execute the SQL statement directly using a raw query // We'll use the internal query method which is safer for executing raw SQL const { error } = await supabase.rpc('exec_sql', { command: statement }); if (error) { console.error(`Error executing statement ${i + 1}:`, error); // Continue with other statements rather than failing completely console.log('Continuing with next statement...'); } else { console.log(`Statement ${i + 1} executed successfully`); } } catch (stmtError) { console.error(`Exception executing statement ${i + 1}:`, stmtError); console.log('Continuing with next statement...'); } } // Verify the table was created console.log('Verifying faqs table was created...'); const { error: tableError } = await supabase .from('faqs') .select('id') .limit(1); if (tableError) { console.error('Error verifying faqs table:', tableError); console.log('The table may not have been created successfully.'); // Provide alternative instructions console.log('\nAlternative instructions:'); console.log('1. Go to the Supabase dashboard for your project'); console.log('2. Navigate to the SQL Editor'); console.log('3. Copy and paste the contents of create-faqs-table.sql'); console.log('4. Run the SQL script manually'); } else { console.log('Successfully verified faqs table exists!'); console.log('Table structure has been created.'); } console.log('\nNext steps:'); console.log('Run the following command to seed FAQs data:'); console.log(' npm run supabase:seed-faqs'); } catch (error) { console.error('Unexpected error during table creation:', error); process.exit(1); } } // Run the function createFaqsTable() .then(() => { console.log('Table creation script completed.'); process.exit(0); }) .catch((error) => { console.error('Error in table creation script:', error); process.exit(1); });