AI Resource Pro / website / scripts / scheduled-db-maintenance.ts
| 1 | import { createClient } from '@supabase/supabase-js'; |
| 2 | import * as dotenv from 'dotenv'; |
| 3 | import * as path from 'path'; |
| 4 | import * as fs from 'fs'; |
| 5 | |
| 6 | // Load environment variables |
| 7 | const envLocalPath = path.resolve(process.cwd(), '../.env.local'); |
| 8 | if (fs.existsSync(envLocalPath)) { |
| 9 | console.log(`Loading environment from: ${envLocalPath}`); |
| 10 | dotenv.config({ path: envLocalPath }); |
| 11 | } else { |
| 12 | console.log(`No .env.local file found at: ${envLocalPath}`); |
| 13 | dotenv.config(); |
| 14 | } |
| 15 | |
| 16 | // Configuration |
| 17 | const AUTO_CLEAN = process.env.AUTO_CLEAN_DB === 'true'; |
| 18 | const NOTIFICATION_EMAIL = process.env.ADMIN_EMAIL; |
| 19 | const MAX_ORPHANS_BEFORE_ALERT = parseInt(process.env.MAX_ORPHANS_BEFORE_ALERT || '10'); |
| 20 | |
| 21 | interface OrphanedJunction { |
| 22 | table: string; |
| 23 | id: number; |
| 24 | foreignKey: string; |
| 25 | foreignId: number | string; |
| 26 | foreignTable: string; |
| 27 | } |
| 28 | |
| 29 | async function scheduledDbMaintenance() { |
| 30 | console.log('=== Running Scheduled Database Maintenance ==='); |
| 31 | console.log('Started at:', new Date().toISOString()); |
| 32 | |
| 33 | const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; |
| 34 | const supabaseKey = process.env.SUPABASE_SERVICE_ROLE_KEY; |
| 35 | |
| 36 | if (!supabaseUrl || !supabaseKey) { |
| 37 | console.error('Missing Supabase environment variables'); |
| 38 | process.exit(1); |
| 39 | } |
| 40 | |
| 41 | const supabase = createClient(supabaseUrl, supabaseKey); |
| 42 | |
| 43 | // 1. Check for orphaned junction entries |
| 44 | const orphanedJunctions: OrphanedJunction[] = []; |
| 45 | |
| 46 | // Define tables to check |
| 47 | const junctionTables = [ |
| 48 | { table: 'tools_categories', foreignKey: 'tool_id', foreignTable: 'tools' }, |
| 49 | { table: 'news_categories', foreignKey: 'news_id', foreignTable: 'news' }, |
| 50 | { table: 'post_categories', foreignKey: 'post_id', foreignTable: 'posts' }, |
| 51 | { table: 'learning_categories', foreignKey: 'learning_id', foreignTable: 'learning' } |
| 52 | ]; |
| 53 | |
| 54 | // Check each junction table |
| 55 | for (const junction of junctionTables) { |
| 56 | console.log(`Checking ${junction.table} for orphaned entries...`); |
| 57 | |
| 58 | // Fetch all junction entries |
| 59 | const { data: junctionEntries, error: junctionError } = await supabase |
| 60 | .from(junction.table) |
| 61 | .select('*'); |
| 62 | |
| 63 | if (junctionError) { |
| 64 | console.error(`Error fetching ${junction.table}:`, junctionError); |
| 65 | continue; |
| 66 | } |
| 67 | |
| 68 | if (!junctionEntries || junctionEntries.length === 0) { |
| 69 | console.log(`No entries found in ${junction.table}`); |
| 70 | continue; |
| 71 | } |
| 72 | |
| 73 | // Fetch all valid foreign keys |
| 74 | const { data: foreignEntries, error: foreignError } = await supabase |
| 75 | .from(junction.foreignTable) |
| 76 | .select('id'); |
| 77 | |
| 78 | if (foreignError) { |
| 79 | console.error(`Error fetching ${junction.foreignTable}:`, foreignError); |
| 80 | continue; |
| 81 | } |
| 82 | |
| 83 | // Create a set of valid foreign IDs |
| 84 | const validForeignIds = new Set((foreignEntries || []).map(entry => entry.id)); |
| 85 | |
| 86 | // Find orphaned entries |
| 87 | const orphaned = junctionEntries.filter(entry => !validForeignIds.has(entry[junction.foreignKey])); |
| 88 | |
| 89 | if (orphaned.length > 0) { |
| 90 | console.log(`Found ${orphaned.length} orphaned entries in ${junction.table}`); |
| 91 | |
| 92 | // Add to our list of orphaned junctions |
| 93 | orphanedJunctions.push(...orphaned.map(entry => ({ |
| 94 | table: junction.table, |
| 95 | id: entry.id, |
| 96 | foreignKey: junction.foreignKey, |
| 97 | foreignId: entry[junction.foreignKey], |
| 98 | foreignTable: junction.foreignTable |
| 99 | }))); |
| 100 | } else { |
| 101 | console.log(`No orphaned entries found in ${junction.table}`); |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | // 2. Handle orphaned entries |
| 106 | if (orphanedJunctions.length > 0) { |
| 107 | console.log(`\nTotal orphaned junction entries found: ${orphanedJunctions.length}`); |
| 108 | |
| 109 | // Group by table |
| 110 | const orphansByTable: Record<string, OrphanedJunction[]> = {}; |
| 111 | for (const orphan of orphanedJunctions) { |
| 112 | if (!orphansByTable[orphan.table]) { |
| 113 | orphansByTable[orphan.table] = []; |
| 114 | } |
| 115 | orphansByTable[orphan.table].push(orphan); |
| 116 | } |
| 117 | |
| 118 | // Log summary by table |
| 119 | console.log('\nOrphaned entries by table:'); |
| 120 | for (const [table, orphans] of Object.entries(orphansByTable)) { |
| 121 | console.log(`- ${table}: ${orphans.length} entries`); |
| 122 | } |
| 123 | |
| 124 | // Clean up if auto-clean is enabled |
| 125 | if (AUTO_CLEAN) { |
| 126 | console.log('\nAuto-cleaning enabled, cleaning up orphaned entries...'); |
| 127 | |
| 128 | for (const [table, orphans] of Object.entries(orphansByTable)) { |
| 129 | console.log(`\nCleaning up ${orphans.length} orphaned entries in ${table}...`); |
| 130 | |
| 131 | // Process in batches of 100 |
| 132 | for (let i = 0; i < orphans.length; i += 100) { |
| 133 | const batch = orphans.slice(i, i + 100); |
| 134 | const batchIds = batch.map(orphan => orphan.id); |
| 135 | |
| 136 | console.log(`Deleting batch ${Math.floor(i/100) + 1}/${Math.ceil(orphans.length/100)} (${batch.length} entries)`); |
| 137 | |
| 138 | const { error: deleteError } = await supabase |
| 139 | .from(table) |
| 140 | .delete() |
| 141 | .in('id', batchIds); |
| 142 | |
| 143 | if (deleteError) { |
| 144 | console.error(`Error deleting batch from ${table}:`, deleteError); |
| 145 | } else { |
| 146 | console.log(`Successfully deleted batch ${Math.floor(i/100) + 1}`); |
| 147 | } |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | console.log('\nCleanup completed'); |
| 152 | } else { |
| 153 | console.log('\nAuto-cleaning disabled, skipping cleanup'); |
| 154 | } |
| 155 | |
| 156 | // Send notification if orphan count exceeds threshold |
| 157 | if (orphanedJunctions.length >= MAX_ORPHANS_BEFORE_ALERT) { |
| 158 | console.log(`\nOrphaned entries (${orphanedJunctions.length}) exceed threshold (${MAX_ORPHANS_BEFORE_ALERT})`); |
| 159 | |
| 160 | if (NOTIFICATION_EMAIL) { |
| 161 | console.log(`Sending notification to ${NOTIFICATION_EMAIL}`); |
| 162 | |
| 163 | try { |
| 164 | // Here you would implement email notification |
| 165 | // This could be using an email service, Supabase Edge Functions, etc. |
| 166 | console.log('Email notification would be sent here'); |
| 167 | |
| 168 | // Example integration point for email service: |
| 169 | // await sendEmail({ |
| 170 | // to: NOTIFICATION_EMAIL, |
| 171 | // subject: `Database Maintenance Alert: ${orphanedJunctions.length} orphaned entries found`, |
| 172 | // body: `The scheduled database maintenance job has detected ${orphanedJunctions.length} orphaned junction entries.\n\n` + |
| 173 | // `Summary by table:\n` + |
| 174 | // Object.entries(orphansByTable).map(([table, orphans]) => `- ${table}: ${orphans.length} entries`).join('\n') |
| 175 | // }); |
| 176 | } catch (error) { |
| 177 | console.error('Error sending notification:', error); |
| 178 | } |
| 179 | } else { |
| 180 | console.log('No notification email configured, skipping notification'); |
| 181 | } |
| 182 | } |
| 183 | } else { |
| 184 | console.log('\nNo orphaned junction entries found. Database integrity looks good!'); |
| 185 | } |
| 186 | |
| 187 | // 3. Check for other database issues (optional) |
| 188 | // Add additional checks here as needed |
| 189 | |
| 190 | console.log('\nMaintenance completed at:', new Date().toISOString()); |
| 191 | } |
| 192 | |
| 193 | // Run the maintenance job |
| 194 | scheduledDbMaintenance() |
| 195 | .catch(error => { |
| 196 | console.error('Error in scheduled maintenance job:', error); |
| 197 | process.exit(1); |
| 198 | }) |
| 199 | .finally(() => { |
| 200 | console.log('Maintenance job finished'); |
| 201 | }); |