import { createClient } from '@supabase/supabase-js'; import * as dotenv from 'dotenv'; import * as path from 'path'; import * as fs from 'fs'; // Load environment variables 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(); } // Configuration const AUTO_CLEAN = process.env.AUTO_CLEAN_DB === 'true'; const NOTIFICATION_EMAIL = process.env.ADMIN_EMAIL; const MAX_ORPHANS_BEFORE_ALERT = parseInt(process.env.MAX_ORPHANS_BEFORE_ALERT || '10'); interface OrphanedJunction { table: string; id: number; foreignKey: string; foreignId: number | string; foreignTable: string; } async function scheduledDbMaintenance() { console.log('=== Running Scheduled Database Maintenance ==='); console.log('Started at:', new Date().toISOString()); const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; const supabaseKey = process.env.SUPABASE_SERVICE_ROLE_KEY; if (!supabaseUrl || !supabaseKey) { console.error('Missing Supabase environment variables'); process.exit(1); } const supabase = createClient(supabaseUrl, supabaseKey); // 1. Check for orphaned junction entries const orphanedJunctions: OrphanedJunction[] = []; // Define tables to check const junctionTables = [ { table: 'tools_categories', foreignKey: 'tool_id', foreignTable: 'tools' }, { table: 'news_categories', foreignKey: 'news_id', foreignTable: 'news' }, { table: 'post_categories', foreignKey: 'post_id', foreignTable: 'posts' }, { table: 'learning_categories', foreignKey: 'learning_id', foreignTable: 'learning' } ]; // Check each junction table for (const junction of junctionTables) { console.log(`Checking ${junction.table} for orphaned entries...`); // Fetch all junction entries const { data: junctionEntries, error: junctionError } = await supabase .from(junction.table) .select('*'); if (junctionError) { console.error(`Error fetching ${junction.table}:`, junctionError); continue; } if (!junctionEntries || junctionEntries.length === 0) { console.log(`No entries found in ${junction.table}`); continue; } // Fetch all valid foreign keys const { data: foreignEntries, error: foreignError } = await supabase .from(junction.foreignTable) .select('id'); if (foreignError) { console.error(`Error fetching ${junction.foreignTable}:`, foreignError); continue; } // Create a set of valid foreign IDs const validForeignIds = new Set((foreignEntries || []).map(entry => entry.id)); // Find orphaned entries const orphaned = junctionEntries.filter(entry => !validForeignIds.has(entry[junction.foreignKey])); if (orphaned.length > 0) { console.log(`Found ${orphaned.length} orphaned entries in ${junction.table}`); // Add to our list of orphaned junctions orphanedJunctions.push(...orphaned.map(entry => ({ table: junction.table, id: entry.id, foreignKey: junction.foreignKey, foreignId: entry[junction.foreignKey], foreignTable: junction.foreignTable }))); } else { console.log(`No orphaned entries found in ${junction.table}`); } } // 2. Handle orphaned entries if (orphanedJunctions.length > 0) { console.log(`\nTotal orphaned junction entries found: ${orphanedJunctions.length}`); // Group by table const orphansByTable: Record = {}; for (const orphan of orphanedJunctions) { if (!orphansByTable[orphan.table]) { orphansByTable[orphan.table] = []; } orphansByTable[orphan.table].push(orphan); } // Log summary by table console.log('\nOrphaned entries by table:'); for (const [table, orphans] of Object.entries(orphansByTable)) { console.log(`- ${table}: ${orphans.length} entries`); } // Clean up if auto-clean is enabled if (AUTO_CLEAN) { console.log('\nAuto-cleaning enabled, cleaning up orphaned entries...'); for (const [table, orphans] of Object.entries(orphansByTable)) { console.log(`\nCleaning up ${orphans.length} orphaned entries in ${table}...`); // Process in batches of 100 for (let i = 0; i < orphans.length; i += 100) { const batch = orphans.slice(i, i + 100); const batchIds = batch.map(orphan => orphan.id); console.log(`Deleting batch ${Math.floor(i/100) + 1}/${Math.ceil(orphans.length/100)} (${batch.length} entries)`); const { error: deleteError } = await supabase .from(table) .delete() .in('id', batchIds); if (deleteError) { console.error(`Error deleting batch from ${table}:`, deleteError); } else { console.log(`Successfully deleted batch ${Math.floor(i/100) + 1}`); } } } console.log('\nCleanup completed'); } else { console.log('\nAuto-cleaning disabled, skipping cleanup'); } // Send notification if orphan count exceeds threshold if (orphanedJunctions.length >= MAX_ORPHANS_BEFORE_ALERT) { console.log(`\nOrphaned entries (${orphanedJunctions.length}) exceed threshold (${MAX_ORPHANS_BEFORE_ALERT})`); if (NOTIFICATION_EMAIL) { console.log(`Sending notification to ${NOTIFICATION_EMAIL}`); try { // Here you would implement email notification // This could be using an email service, Supabase Edge Functions, etc. console.log('Email notification would be sent here'); // Example integration point for email service: // await sendEmail({ // to: NOTIFICATION_EMAIL, // subject: `Database Maintenance Alert: ${orphanedJunctions.length} orphaned entries found`, // body: `The scheduled database maintenance job has detected ${orphanedJunctions.length} orphaned junction entries.\n\n` + // `Summary by table:\n` + // Object.entries(orphansByTable).map(([table, orphans]) => `- ${table}: ${orphans.length} entries`).join('\n') // }); } catch (error) { console.error('Error sending notification:', error); } } else { console.log('No notification email configured, skipping notification'); } } } else { console.log('\nNo orphaned junction entries found. Database integrity looks good!'); } // 3. Check for other database issues (optional) // Add additional checks here as needed console.log('\nMaintenance completed at:', new Date().toISOString()); } // Run the maintenance job scheduledDbMaintenance() .catch(error => { console.error('Error in scheduled maintenance job:', error); process.exit(1); }) .finally(() => { console.log('Maintenance job finished'); });