import { createClient } from '@supabase/supabase-js'; import { readFileSync } from 'fs'; import * as path from 'path'; import * as dotenv from 'dotenv'; import * as fs from 'fs'; // Load environment variables from .env.local 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 main() { // Check for required environment variables const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY; if (!supabaseUrl || !supabaseServiceKey) { console.error('Error: Missing required environment variables NEXT_PUBLIC_SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY'); process.exit(1); } // Initialize Supabase client const supabase = createClient(supabaseUrl, supabaseServiceKey, { auth: { autoRefreshToken: false, persistSession: false } }); try { console.log('Running SQL script to remove duplicate news items...'); // Read the SQL file const sqlFilePath = path.join(__dirname, 'remove-duplicate-news.sql'); const sqlContent = readFileSync(sqlFilePath, 'utf-8'); // Split the SQL into separate statements const statements = sqlContent .split(';') .map(statement => statement.trim()) .filter(statement => statement.length > 0); // Execute each statement for (const statement of statements) { console.log(`Executing SQL statement: ${statement.substring(0, 100)}...`); const { data, error } = await supabase.rpc('exec_sql', { sql: statement + ';' }); if (error) { console.error('Error executing SQL statement:', error); } else { console.log('SQL statement executed successfully:', data); } } console.log('Duplicate removal completed successfully!'); } catch (error) { console.error('Error removing duplicates:', error); throw error; } } // Run the function main() .then(() => { console.log('Process completed successfully'); process.exit(0); }) .catch((error) => { console.error('Process failed:', error); process.exit(1); });