import { createClient } from '@supabase/supabase-js'; import { readFileSync, existsSync } from 'fs'; import * as path from 'path'; import * as dotenv from 'dotenv'; // 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 } // Get Supabase credentials from environment variables 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'); process.exit(1); } // Create a service role client const supabase = createClient(supabaseUrl, supabaseServiceKey, { auth: { persistSession: false, }, }); async function runSQL(sqlContent: string, description: string) { console.log(`Executing SQL: ${description}`); try { // Execute SQL directly using REST API const { data, error } = await supabase.rpc('exec_sql', { sql: sqlContent }); if (error) { console.log(`Error executing ${description}:`, error); return false; } console.log(`Successfully executed ${description}:`, data); return true; } catch (error) { console.error(`Error executing ${description}:`, error); return false; } } async function createExecSQLFunction() { console.log('Creating exec_sql function...'); try { // Read the SQL file const sqlPath = path.join(process.cwd(), 'scripts', 'create-exec-sql-function.sql'); const sqlContent = readFileSync(sqlPath, 'utf8'); // Try to execute exec_sql to test if it exists try { const { data, error } = await supabase.rpc('exec_sql', { sql: 'SELECT 1 as test' }); if (!error) { console.log('exec_sql function already exists:', data); return true; } } catch (err) { console.log('exec_sql function does not exist yet. Creating it...'); } // Try executing the SQL directly via raw query try { const response = await fetch(`${supabaseUrl}/rest/v1/rpc/postgres`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${supabaseServiceKey}`, 'apikey': `${supabaseServiceKey}` }, body: JSON.stringify({ query: sqlContent }) }); if (!response.ok) { const errorData = await response.json(); console.log('Error creating exec_sql function via postgres RPC:', errorData); } else { console.log('Successfully created exec_sql function via postgres RPC'); return true; } } catch (err) { console.log('Error executing postgres RPC:', err); } // As a fallback, try direct HTTP request to the SQL endpoint try { const response = await fetch(`${supabaseUrl}/rest/v1/sql`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${supabaseServiceKey}`, 'apikey': `${supabaseServiceKey}`, 'Prefer': 'return=representation' }, body: JSON.stringify({ query: sqlContent }) }); if (!response.ok) { const errorData = await response.json(); console.error('Error creating exec_sql function via SQL endpoint:', errorData); return false; } console.log('Successfully created exec_sql function via SQL endpoint'); return true; } catch (error) { console.error('Error accessing SQL endpoint:', error); return false; } } catch (error) { console.error('Error creating exec_sql function:', error); return false; } } async function fixRecursivePolicies() { console.log('Applying fix for recursive policies...'); try { // Read the SQL file const sqlPath = path.join(process.cwd(), 'scripts', 'fix-recursive-policies.sql'); const sqlContent = readFileSync(sqlPath, 'utf8'); // Execute the SQL using our runSQL helper const success = await runSQL(sqlContent, 'fix for recursive policies'); if (!success) { throw new Error('Failed to apply recursive policy fixes'); } console.log('Successfully applied fix for recursive policies'); console.log('Please restart your application for the changes to take effect.'); return true; } catch (error) { console.error('Error applying fix:', error); return false; } } async function main() { // First, try to create the exec_sql function const execSqlCreated = await createExecSQLFunction(); if (!execSqlCreated) { console.error('Failed to create exec_sql function. Cannot proceed with policy fixes.'); process.exit(1); } // Then, apply the recursive policy fixes const policiesFixed = await fixRecursivePolicies(); if (!policiesFixed) { console.error('Failed to apply recursive policy fixes.'); process.exit(1); } console.log('All operations completed successfully!'); } main();