AI Resource Pro / website / scripts / run-remove-duplicates.ts
| 1 | import { createClient } from '@supabase/supabase-js'; |
| 2 | import { readFileSync } from 'fs'; |
| 3 | import * as path from 'path'; |
| 4 | import * as dotenv from 'dotenv'; |
| 5 | import * as fs from 'fs'; |
| 6 | |
| 7 | // Load environment variables from .env.local |
| 8 | const envLocalPath = path.resolve(process.cwd(), '.env.local'); |
| 9 | if (fs.existsSync(envLocalPath)) { |
| 10 | console.log(`Loading environment from: ${envLocalPath}`); |
| 11 | dotenv.config({ path: envLocalPath }); |
| 12 | } else { |
| 13 | console.log(`No .env.local file found at: ${envLocalPath}`); |
| 14 | dotenv.config(); // Try loading from default .env |
| 15 | } |
| 16 | |
| 17 | async function main() { |
| 18 | // Check for required environment variables |
| 19 | const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; |
| 20 | const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY; |
| 21 | |
| 22 | if (!supabaseUrl || !supabaseServiceKey) { |
| 23 | console.error('Error: Missing required environment variables NEXT_PUBLIC_SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY'); |
| 24 | process.exit(1); |
| 25 | } |
| 26 | |
| 27 | // Initialize Supabase client |
| 28 | const supabase = createClient(supabaseUrl, supabaseServiceKey, { |
| 29 | auth: { |
| 30 | autoRefreshToken: false, |
| 31 | persistSession: false |
| 32 | } |
| 33 | }); |
| 34 | |
| 35 | try { |
| 36 | console.log('Running SQL script to remove duplicate news items...'); |
| 37 | |
| 38 | // Read the SQL file |
| 39 | const sqlFilePath = path.join(__dirname, 'remove-duplicate-news.sql'); |
| 40 | const sqlContent = readFileSync(sqlFilePath, 'utf-8'); |
| 41 | |
| 42 | // Split the SQL into separate statements |
| 43 | const statements = sqlContent |
| 44 | .split(';') |
| 45 | .map(statement => statement.trim()) |
| 46 | .filter(statement => statement.length > 0); |
| 47 | |
| 48 | // Execute each statement |
| 49 | for (const statement of statements) { |
| 50 | console.log(`Executing SQL statement: ${statement.substring(0, 100)}...`); |
| 51 | const { data, error } = await supabase.rpc('exec_sql', { sql: statement + ';' }); |
| 52 | |
| 53 | if (error) { |
| 54 | console.error('Error executing SQL statement:', error); |
| 55 | } else { |
| 56 | console.log('SQL statement executed successfully:', data); |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | console.log('Duplicate removal completed successfully!'); |
| 61 | } catch (error) { |
| 62 | console.error('Error removing duplicates:', error); |
| 63 | throw error; |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | // Run the function |
| 68 | main() |
| 69 | .then(() => { |
| 70 | console.log('Process completed successfully'); |
| 71 | process.exit(0); |
| 72 | }) |
| 73 | .catch((error) => { |
| 74 | console.error('Process failed:', error); |
| 75 | process.exit(1); |
| 76 | }); |