AI Resource Pro / website / scripts / fix-database-integrity.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 | interface OrphanedJunction { |
| 17 | table: string; |
| 18 | id: number; |
| 19 | foreignId: number | string; |
| 20 | foreignTable: string; |
| 21 | foreignKey: string; |
| 22 | } |
| 23 | |
| 24 | async function fixDatabaseIntegrity() { |
| 25 | const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; |
| 26 | const supabaseKey = process.env.SUPABASE_SERVICE_ROLE_KEY; |
| 27 | |
| 28 | if (!supabaseUrl || !supabaseKey) { |
| 29 | console.error('Missing Supabase environment variables'); |
| 30 | process.exit(1); |
| 31 | } |
| 32 | |
| 33 | const supabase = createClient(supabaseUrl, supabaseKey); |
| 34 | |
| 35 | // Part 1: Validate Foreign Key Constraints |
| 36 | console.log('Checking if foreign key constraints are enabled...'); |
| 37 | |
| 38 | const { data: fkData, error: fkError } = await supabase.rpc('check_foreign_keys_enabled'); |
| 39 | |
| 40 | if (fkError) { |
| 41 | console.error('Error checking foreign key constraints:', fkError); |
| 42 | // Create the function if it doesn't exist |
| 43 | console.log('Creating check_foreign_keys_enabled function...'); |
| 44 | |
| 45 | const { error: createFunctionError } = await supabase.rpc('create_check_foreign_keys_function'); |
| 46 | |
| 47 | if (createFunctionError) { |
| 48 | console.error('Error creating function:', createFunctionError); |
| 49 | console.log(` |
| 50 | To enable checking foreign key constraints, run this SQL in the Supabase SQL editor: |
| 51 | |
| 52 | CREATE OR REPLACE FUNCTION check_foreign_keys_enabled() |
| 53 | RETURNS BOOLEAN AS $$ |
| 54 | DECLARE |
| 55 | result BOOLEAN; |
| 56 | BEGIN |
| 57 | SELECT current_setting('session.force_foreign_key_checks')::BOOLEAN INTO result; |
| 58 | RETURN result; |
| 59 | EXCEPTION |
| 60 | WHEN OTHERS THEN |
| 61 | RETURN TRUE; -- Default to assuming enabled if we can't check |
| 62 | END; |
| 63 | $$ LANGUAGE plpgsql SECURITY DEFINER; |
| 64 | `); |
| 65 | } |
| 66 | } else { |
| 67 | console.log(`Foreign key constraints are ${fkData ? 'enabled' : 'disabled'}`); |
| 68 | |
| 69 | if (!fkData) { |
| 70 | console.log(` |
| 71 | To enable foreign key constraints, run this SQL in the Supabase SQL editor: |
| 72 | |
| 73 | ALTER SYSTEM SET session.force_foreign_key_checks = on; |
| 74 | SELECT pg_reload_conf(); |
| 75 | `); |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | // Part 2: Find Orphaned Junction Entries |
| 80 | console.log('\nFinding orphaned junction entries...'); |
| 81 | |
| 82 | // Check tools_categories |
| 83 | const orphanedJunctions: OrphanedJunction[] = []; |
| 84 | |
| 85 | const { data: toolsJunctions, error: toolsJunctionsError } = await supabase |
| 86 | .from('tools_categories') |
| 87 | .select('*'); |
| 88 | |
| 89 | if (toolsJunctionsError) { |
| 90 | console.error('Error fetching tools_categories:', toolsJunctionsError); |
| 91 | } else if (toolsJunctions) { |
| 92 | // Get all valid tool IDs |
| 93 | const { data: tools } = await supabase.from('tools').select('id'); |
| 94 | const validToolIds = new Set((tools || []).map(t => t.id)); |
| 95 | |
| 96 | // Find orphaned entries |
| 97 | for (const junction of toolsJunctions) { |
| 98 | if (!validToolIds.has(junction.tool_id)) { |
| 99 | orphanedJunctions.push({ |
| 100 | table: 'tools_categories', |
| 101 | id: junction.id, |
| 102 | foreignId: junction.tool_id, |
| 103 | foreignTable: 'tools', |
| 104 | foreignKey: 'tool_id' |
| 105 | }); |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | console.log(`Found ${orphanedJunctions.length} orphaned entries in tools_categories`); |
| 110 | } |
| 111 | |
| 112 | // Check news_categories |
| 113 | const { data: newsJunctions, error: newsJunctionsError } = await supabase |
| 114 | .from('news_categories') |
| 115 | .select('*'); |
| 116 | |
| 117 | if (newsJunctionsError) { |
| 118 | console.error('Error fetching news_categories:', newsJunctionsError); |
| 119 | } else if (newsJunctions) { |
| 120 | // Get all valid news IDs |
| 121 | const { data: news } = await supabase.from('news').select('id'); |
| 122 | const validNewsIds = new Set((news || []).map(n => n.id)); |
| 123 | |
| 124 | // Find orphaned entries |
| 125 | for (const junction of newsJunctions) { |
| 126 | if (!validNewsIds.has(junction.news_id)) { |
| 127 | orphanedJunctions.push({ |
| 128 | table: 'news_categories', |
| 129 | id: junction.id, |
| 130 | foreignId: junction.news_id, |
| 131 | foreignTable: 'news', |
| 132 | foreignKey: 'news_id' |
| 133 | }); |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | console.log(`Found ${orphanedJunctions.filter(j => j.table === 'news_categories').length} orphaned entries in news_categories`); |
| 138 | } |
| 139 | |
| 140 | // Check post_categories |
| 141 | const { data: postJunctions, error: postJunctionsError } = await supabase |
| 142 | .from('post_categories') |
| 143 | .select('*'); |
| 144 | |
| 145 | if (postJunctionsError) { |
| 146 | console.error('Error fetching post_categories:', postJunctionsError); |
| 147 | } else if (postJunctions) { |
| 148 | // Get all valid post IDs |
| 149 | const { data: posts } = await supabase.from('posts').select('id'); |
| 150 | const validPostIds = new Set((posts || []).map(p => p.id)); |
| 151 | |
| 152 | // Find orphaned entries |
| 153 | for (const junction of postJunctions) { |
| 154 | if (!validPostIds.has(junction.post_id)) { |
| 155 | orphanedJunctions.push({ |
| 156 | table: 'post_categories', |
| 157 | id: junction.id, |
| 158 | foreignId: junction.post_id, |
| 159 | foreignTable: 'posts', |
| 160 | foreignKey: 'post_id' |
| 161 | }); |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | console.log(`Found ${orphanedJunctions.filter(j => j.table === 'post_categories').length} orphaned entries in post_categories`); |
| 166 | } |
| 167 | |
| 168 | // Check learning_categories |
| 169 | const { data: learningJunctions, error: learningJunctionsError } = await supabase |
| 170 | .from('learning_categories') |
| 171 | .select('*'); |
| 172 | |
| 173 | if (learningJunctionsError) { |
| 174 | console.error('Error fetching learning_categories:', learningJunctionsError); |
| 175 | } else if (learningJunctions) { |
| 176 | // Get all valid learning IDs |
| 177 | const { data: learning } = await supabase.from('learning').select('id'); |
| 178 | const validLearningIds = new Set((learning || []).map(l => l.id)); |
| 179 | |
| 180 | // Find orphaned entries |
| 181 | for (const junction of learningJunctions) { |
| 182 | if (!validLearningIds.has(junction.learning_id)) { |
| 183 | orphanedJunctions.push({ |
| 184 | table: 'learning_categories', |
| 185 | id: junction.id, |
| 186 | foreignId: junction.learning_id, |
| 187 | foreignTable: 'learning', |
| 188 | foreignKey: 'learning_id' |
| 189 | }); |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | console.log(`Found ${orphanedJunctions.filter(j => j.table === 'learning_categories').length} orphaned entries in learning_categories`); |
| 194 | } |
| 195 | |
| 196 | // Part 3: Clean Up Orphaned Entries |
| 197 | if (orphanedJunctions.length > 0) { |
| 198 | console.log('\nTotal orphaned junction entries found:', orphanedJunctions.length); |
| 199 | |
| 200 | // Group by table for reporting |
| 201 | const tableGroups: Record<string, OrphanedJunction[]> = {}; |
| 202 | for (const junction of orphanedJunctions) { |
| 203 | if (!tableGroups[junction.table]) { |
| 204 | tableGroups[junction.table] = []; |
| 205 | } |
| 206 | tableGroups[junction.table].push(junction); |
| 207 | } |
| 208 | |
| 209 | // Show orphaned entries by table |
| 210 | console.log('\nOrphaned entries by table:'); |
| 211 | for (const [table, junctions] of Object.entries(tableGroups)) { |
| 212 | console.log(`- ${table}: ${junctions.length} entries`); |
| 213 | |
| 214 | // Sample a few entries |
| 215 | const sample = junctions.slice(0, 5); |
| 216 | console.log(' Sample entries:'); |
| 217 | for (const junction of sample) { |
| 218 | console.log(` - ID ${junction.id}, ${junction.foreignKey}=${junction.foreignId} (missing in ${junction.foreignTable})`); |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | // Option to clean up |
| 223 | console.log('\nTo clean up orphaned entries, run this script with --execute flag'); |
| 224 | console.log('Example: npx ts-node fix-database-integrity.ts --execute'); |
| 225 | |
| 226 | if (process.argv.includes('--execute')) { |
| 227 | console.log('\n===== EXECUTING CLEANUP ====='); |
| 228 | |
| 229 | // Delete orphaned entries by table in batches |
| 230 | for (const [table, junctions] of Object.entries(tableGroups)) { |
| 231 | console.log(`\nCleaning up ${junctions.length} orphaned entries in ${table}...`); |
| 232 | |
| 233 | // Process in batches of 50 |
| 234 | for (let i = 0; i < junctions.length; i += 50) { |
| 235 | const batch = junctions.slice(i, i + 50); |
| 236 | const batchIds = batch.map(j => j.id); |
| 237 | |
| 238 | console.log(`Deleting batch ${Math.floor(i/50) + 1}/${Math.ceil(junctions.length/50)} (${batch.length} entries)`); |
| 239 | |
| 240 | const { error: deleteError } = await supabase |
| 241 | .from(table) |
| 242 | .delete() |
| 243 | .in('id', batchIds); |
| 244 | |
| 245 | if (deleteError) { |
| 246 | console.error(`Error deleting batch from ${table}:`, deleteError); |
| 247 | } else { |
| 248 | console.log(`Successfully deleted batch ${Math.floor(i/50) + 1}`); |
| 249 | } |
| 250 | } |
| 251 | } |
| 252 | } |
| 253 | } else { |
| 254 | console.log('\nNo orphaned junction entries found. Database integrity looks good!'); |
| 255 | } |
| 256 | |
| 257 | // Part 4: Verify Triggers and Constraints |
| 258 | console.log('\n===== VERIFYING DATABASE CONSTRAINTS ====='); |
| 259 | |
| 260 | // Check if all junction tables have proper cascade constraints |
| 261 | const junctionTables = ['tools_categories', 'news_categories', 'post_categories', 'learning_categories']; |
| 262 | |
| 263 | for (const table of junctionTables) { |
| 264 | console.log(`\nChecking constraints for ${table}...`); |
| 265 | |
| 266 | const { data: constraintData, error: constraintError } = await supabase.rpc('check_table_constraints', { table_name: table }); |
| 267 | |
| 268 | if (constraintError) { |
| 269 | console.error(`Error checking constraints for ${table}:`, constraintError); |
| 270 | continue; |
| 271 | } |
| 272 | |
| 273 | if (constraintData && constraintData.length > 0) { |
| 274 | let hasProperCascade = true; |
| 275 | |
| 276 | for (const constraint of constraintData) { |
| 277 | if (constraint.constraint_type === 'FOREIGN KEY') { |
| 278 | const hasCascade = constraint.constraint_def.includes('ON DELETE CASCADE'); |
| 279 | console.log(`- Foreign key: ${constraint.constraint_name}, Cascade delete: ${hasCascade ? 'YES' : 'NO'}`); |
| 280 | |
| 281 | if (!hasCascade) { |
| 282 | hasProperCascade = false; |
| 283 | } |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | if (!hasProperCascade) { |
| 288 | console.log(` |
| 289 | WARNING: Some foreign key constraints in ${table} don't have CASCADE DELETE. |
| 290 | To add proper constraints, run SQL like this: |
| 291 | |
| 292 | ALTER TABLE ${table} DROP CONSTRAINT <constraint_name>; |
| 293 | ALTER TABLE ${table} ADD CONSTRAINT <new_constraint_name> |
| 294 | FOREIGN KEY (...) REFERENCES ... ON DELETE CASCADE; |
| 295 | `); |
| 296 | } else { |
| 297 | console.log(`✅ ${table} has proper cascade delete constraints`); |
| 298 | } |
| 299 | } else { |
| 300 | console.log(`No constraints found for ${table}`); |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | console.log('\n===== RECOMMENDATIONS ====='); |
| 305 | console.log(` |
| 306 | 1. Regular Maintenance: Run this script periodically to check for and clean up any orphaned entries. |
| 307 | |
| 308 | 2. Use Application Deletion: Always delete items through the application APIs rather than direct |
| 309 | database manipulation, as the APIs ensure proper constraint handling. |
| 310 | |
| 311 | 3. Database Monitoring: Consider setting up a monitoring job that alerts when orphaned junction |
| 312 | entries are detected. |
| 313 | |
| 314 | 4. Migration Script: When making database schema changes, include migration scripts that clean up |
| 315 | any orphaned data. |
| 316 | |
| 317 | 5. Documentation: Document the cascade delete constraints in your schema and ensure all developers |
| 318 | are aware of how the relationships work. |
| 319 | |
| 320 | 6. Create a maintenance endpoint: Add an admin-only endpoint that can be used to periodically check |
| 321 | and clean up database integrity issues. |
| 322 | `); |
| 323 | |
| 324 | console.log('\nTo create the needed database functions for constraint checking, run this script with --create-functions flag'); |
| 325 | |
| 326 | if (process.argv.includes('--create-functions')) { |
| 327 | console.log('\n===== CREATING DATABASE FUNCTIONS ====='); |
| 328 | |
| 329 | const { error: createFunctionsError } = await supabase.rpc('create_constraint_check_functions'); |
| 330 | |
| 331 | if (createFunctionsError) { |
| 332 | console.error('Error creating functions:', createFunctionsError); |
| 333 | console.log(` |
| 334 | To manually create the constraint checking functions, run this SQL in the Supabase SQL editor: |
| 335 | |
| 336 | CREATE OR REPLACE FUNCTION check_table_constraints(table_name TEXT) |
| 337 | RETURNS TABLE(constraint_name TEXT, constraint_type TEXT, constraint_def TEXT) AS $$ |
| 338 | BEGIN |
| 339 | RETURN QUERY |
| 340 | SELECT |
| 341 | tc.constraint_name, |
| 342 | tc.constraint_type, |
| 343 | pg_get_constraintdef(c.oid) as constraint_def |
| 344 | FROM |
| 345 | information_schema.table_constraints tc |
| 346 | JOIN pg_constraint c ON c.conname = tc.constraint_name |
| 347 | JOIN pg_namespace n ON n.oid = c.connamespace |
| 348 | WHERE |
| 349 | tc.table_name = check_table_constraints.table_name |
| 350 | AND n.nspname = 'public'; |
| 351 | END; |
| 352 | $$ LANGUAGE plpgsql SECURITY DEFINER; |
| 353 | |
| 354 | CREATE OR REPLACE FUNCTION create_constraint_check_functions() |
| 355 | RETURNS VOID AS $$ |
| 356 | BEGIN |
| 357 | -- Create the check_table_constraints function if it doesn't exist |
| 358 | IF NOT EXISTS ( |
| 359 | SELECT 1 FROM pg_proc |
| 360 | WHERE proname = 'check_table_constraints' |
| 361 | AND pronamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public') |
| 362 | ) THEN |
| 363 | EXECUTE ' |
| 364 | CREATE OR REPLACE FUNCTION check_table_constraints(table_name TEXT) |
| 365 | RETURNS TABLE(constraint_name TEXT, constraint_type TEXT, constraint_def TEXT) AS $$ |
| 366 | BEGIN |
| 367 | RETURN QUERY |
| 368 | SELECT |
| 369 | tc.constraint_name, |
| 370 | tc.constraint_type, |
| 371 | pg_get_constraintdef(c.oid) as constraint_def |
| 372 | FROM |
| 373 | information_schema.table_constraints tc |
| 374 | JOIN pg_constraint c ON c.conname = tc.constraint_name |
| 375 | JOIN pg_namespace n ON n.oid = c.connamespace |
| 376 | WHERE |
| 377 | tc.table_name = check_table_constraints.table_name |
| 378 | AND n.nspname = ''public''; |
| 379 | END; |
| 380 | $$ LANGUAGE plpgsql SECURITY DEFINER; |
| 381 | '; |
| 382 | END IF; |
| 383 | |
| 384 | -- Create the check_foreign_keys_enabled function if it doesn't exist |
| 385 | IF NOT EXISTS ( |
| 386 | SELECT 1 FROM pg_proc |
| 387 | WHERE proname = 'check_foreign_keys_enabled' |
| 388 | AND pronamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public') |
| 389 | ) THEN |
| 390 | EXECUTE ' |
| 391 | CREATE OR REPLACE FUNCTION check_foreign_keys_enabled() |
| 392 | RETURNS BOOLEAN AS $$ |
| 393 | DECLARE |
| 394 | result BOOLEAN; |
| 395 | BEGIN |
| 396 | SELECT current_setting(''session.force_foreign_key_checks'')::BOOLEAN INTO result; |
| 397 | RETURN result; |
| 398 | EXCEPTION |
| 399 | WHEN OTHERS THEN |
| 400 | RETURN TRUE; -- Default to assuming enabled if we can''t check |
| 401 | END; |
| 402 | $$ LANGUAGE plpgsql SECURITY DEFINER; |
| 403 | '; |
| 404 | END IF; |
| 405 | END; |
| 406 | $$ LANGUAGE plpgsql SECURITY DEFINER; |
| 407 | `); |
| 408 | } else { |
| 409 | console.log('Successfully created constraint checking functions'); |
| 410 | } |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | fixDatabaseIntegrity().catch(console.error); |