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(); } interface OrphanedJunction { table: string; id: number; foreignId: number | string; foreignTable: string; foreignKey: string; } async function fixDatabaseIntegrity() { 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); // Part 1: Validate Foreign Key Constraints console.log('Checking if foreign key constraints are enabled...'); const { data: fkData, error: fkError } = await supabase.rpc('check_foreign_keys_enabled'); if (fkError) { console.error('Error checking foreign key constraints:', fkError); // Create the function if it doesn't exist console.log('Creating check_foreign_keys_enabled function...'); const { error: createFunctionError } = await supabase.rpc('create_check_foreign_keys_function'); if (createFunctionError) { console.error('Error creating function:', createFunctionError); console.log(` To enable checking foreign key constraints, run this SQL in the Supabase SQL editor: CREATE OR REPLACE FUNCTION check_foreign_keys_enabled() RETURNS BOOLEAN AS $$ DECLARE result BOOLEAN; BEGIN SELECT current_setting('session.force_foreign_key_checks')::BOOLEAN INTO result; RETURN result; EXCEPTION WHEN OTHERS THEN RETURN TRUE; -- Default to assuming enabled if we can't check END; $$ LANGUAGE plpgsql SECURITY DEFINER; `); } } else { console.log(`Foreign key constraints are ${fkData ? 'enabled' : 'disabled'}`); if (!fkData) { console.log(` To enable foreign key constraints, run this SQL in the Supabase SQL editor: ALTER SYSTEM SET session.force_foreign_key_checks = on; SELECT pg_reload_conf(); `); } } // Part 2: Find Orphaned Junction Entries console.log('\nFinding orphaned junction entries...'); // Check tools_categories const orphanedJunctions: OrphanedJunction[] = []; const { data: toolsJunctions, error: toolsJunctionsError } = await supabase .from('tools_categories') .select('*'); if (toolsJunctionsError) { console.error('Error fetching tools_categories:', toolsJunctionsError); } else if (toolsJunctions) { // Get all valid tool IDs const { data: tools } = await supabase.from('tools').select('id'); const validToolIds = new Set((tools || []).map(t => t.id)); // Find orphaned entries for (const junction of toolsJunctions) { if (!validToolIds.has(junction.tool_id)) { orphanedJunctions.push({ table: 'tools_categories', id: junction.id, foreignId: junction.tool_id, foreignTable: 'tools', foreignKey: 'tool_id' }); } } console.log(`Found ${orphanedJunctions.length} orphaned entries in tools_categories`); } // Check news_categories const { data: newsJunctions, error: newsJunctionsError } = await supabase .from('news_categories') .select('*'); if (newsJunctionsError) { console.error('Error fetching news_categories:', newsJunctionsError); } else if (newsJunctions) { // Get all valid news IDs const { data: news } = await supabase.from('news').select('id'); const validNewsIds = new Set((news || []).map(n => n.id)); // Find orphaned entries for (const junction of newsJunctions) { if (!validNewsIds.has(junction.news_id)) { orphanedJunctions.push({ table: 'news_categories', id: junction.id, foreignId: junction.news_id, foreignTable: 'news', foreignKey: 'news_id' }); } } console.log(`Found ${orphanedJunctions.filter(j => j.table === 'news_categories').length} orphaned entries in news_categories`); } // Check post_categories const { data: postJunctions, error: postJunctionsError } = await supabase .from('post_categories') .select('*'); if (postJunctionsError) { console.error('Error fetching post_categories:', postJunctionsError); } else if (postJunctions) { // Get all valid post IDs const { data: posts } = await supabase.from('posts').select('id'); const validPostIds = new Set((posts || []).map(p => p.id)); // Find orphaned entries for (const junction of postJunctions) { if (!validPostIds.has(junction.post_id)) { orphanedJunctions.push({ table: 'post_categories', id: junction.id, foreignId: junction.post_id, foreignTable: 'posts', foreignKey: 'post_id' }); } } console.log(`Found ${orphanedJunctions.filter(j => j.table === 'post_categories').length} orphaned entries in post_categories`); } // Check learning_categories const { data: learningJunctions, error: learningJunctionsError } = await supabase .from('learning_categories') .select('*'); if (learningJunctionsError) { console.error('Error fetching learning_categories:', learningJunctionsError); } else if (learningJunctions) { // Get all valid learning IDs const { data: learning } = await supabase.from('learning').select('id'); const validLearningIds = new Set((learning || []).map(l => l.id)); // Find orphaned entries for (const junction of learningJunctions) { if (!validLearningIds.has(junction.learning_id)) { orphanedJunctions.push({ table: 'learning_categories', id: junction.id, foreignId: junction.learning_id, foreignTable: 'learning', foreignKey: 'learning_id' }); } } console.log(`Found ${orphanedJunctions.filter(j => j.table === 'learning_categories').length} orphaned entries in learning_categories`); } // Part 3: Clean Up Orphaned Entries if (orphanedJunctions.length > 0) { console.log('\nTotal orphaned junction entries found:', orphanedJunctions.length); // Group by table for reporting const tableGroups: Record = {}; for (const junction of orphanedJunctions) { if (!tableGroups[junction.table]) { tableGroups[junction.table] = []; } tableGroups[junction.table].push(junction); } // Show orphaned entries by table console.log('\nOrphaned entries by table:'); for (const [table, junctions] of Object.entries(tableGroups)) { console.log(`- ${table}: ${junctions.length} entries`); // Sample a few entries const sample = junctions.slice(0, 5); console.log(' Sample entries:'); for (const junction of sample) { console.log(` - ID ${junction.id}, ${junction.foreignKey}=${junction.foreignId} (missing in ${junction.foreignTable})`); } } // Option to clean up console.log('\nTo clean up orphaned entries, run this script with --execute flag'); console.log('Example: npx ts-node fix-database-integrity.ts --execute'); if (process.argv.includes('--execute')) { console.log('\n===== EXECUTING CLEANUP ====='); // Delete orphaned entries by table in batches for (const [table, junctions] of Object.entries(tableGroups)) { console.log(`\nCleaning up ${junctions.length} orphaned entries in ${table}...`); // Process in batches of 50 for (let i = 0; i < junctions.length; i += 50) { const batch = junctions.slice(i, i + 50); const batchIds = batch.map(j => j.id); console.log(`Deleting batch ${Math.floor(i/50) + 1}/${Math.ceil(junctions.length/50)} (${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/50) + 1}`); } } } } } else { console.log('\nNo orphaned junction entries found. Database integrity looks good!'); } // Part 4: Verify Triggers and Constraints console.log('\n===== VERIFYING DATABASE CONSTRAINTS ====='); // Check if all junction tables have proper cascade constraints const junctionTables = ['tools_categories', 'news_categories', 'post_categories', 'learning_categories']; for (const table of junctionTables) { console.log(`\nChecking constraints for ${table}...`); const { data: constraintData, error: constraintError } = await supabase.rpc('check_table_constraints', { table_name: table }); if (constraintError) { console.error(`Error checking constraints for ${table}:`, constraintError); continue; } if (constraintData && constraintData.length > 0) { let hasProperCascade = true; for (const constraint of constraintData) { if (constraint.constraint_type === 'FOREIGN KEY') { const hasCascade = constraint.constraint_def.includes('ON DELETE CASCADE'); console.log(`- Foreign key: ${constraint.constraint_name}, Cascade delete: ${hasCascade ? 'YES' : 'NO'}`); if (!hasCascade) { hasProperCascade = false; } } } if (!hasProperCascade) { console.log(` WARNING: Some foreign key constraints in ${table} don't have CASCADE DELETE. To add proper constraints, run SQL like this: ALTER TABLE ${table} DROP CONSTRAINT ; ALTER TABLE ${table} ADD CONSTRAINT FOREIGN KEY (...) REFERENCES ... ON DELETE CASCADE; `); } else { console.log(`✅ ${table} has proper cascade delete constraints`); } } else { console.log(`No constraints found for ${table}`); } } console.log('\n===== RECOMMENDATIONS ====='); console.log(` 1. Regular Maintenance: Run this script periodically to check for and clean up any orphaned entries. 2. Use Application Deletion: Always delete items through the application APIs rather than direct database manipulation, as the APIs ensure proper constraint handling. 3. Database Monitoring: Consider setting up a monitoring job that alerts when orphaned junction entries are detected. 4. Migration Script: When making database schema changes, include migration scripts that clean up any orphaned data. 5. Documentation: Document the cascade delete constraints in your schema and ensure all developers are aware of how the relationships work. 6. Create a maintenance endpoint: Add an admin-only endpoint that can be used to periodically check and clean up database integrity issues. `); console.log('\nTo create the needed database functions for constraint checking, run this script with --create-functions flag'); if (process.argv.includes('--create-functions')) { console.log('\n===== CREATING DATABASE FUNCTIONS ====='); const { error: createFunctionsError } = await supabase.rpc('create_constraint_check_functions'); if (createFunctionsError) { console.error('Error creating functions:', createFunctionsError); console.log(` To manually create the constraint checking functions, run this SQL in the Supabase SQL editor: CREATE OR REPLACE FUNCTION check_table_constraints(table_name TEXT) RETURNS TABLE(constraint_name TEXT, constraint_type TEXT, constraint_def TEXT) AS $$ BEGIN RETURN QUERY SELECT tc.constraint_name, tc.constraint_type, pg_get_constraintdef(c.oid) as constraint_def FROM information_schema.table_constraints tc JOIN pg_constraint c ON c.conname = tc.constraint_name JOIN pg_namespace n ON n.oid = c.connamespace WHERE tc.table_name = check_table_constraints.table_name AND n.nspname = 'public'; END; $$ LANGUAGE plpgsql SECURITY DEFINER; CREATE OR REPLACE FUNCTION create_constraint_check_functions() RETURNS VOID AS $$ BEGIN -- Create the check_table_constraints function if it doesn't exist IF NOT EXISTS ( SELECT 1 FROM pg_proc WHERE proname = 'check_table_constraints' AND pronamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public') ) THEN EXECUTE ' CREATE OR REPLACE FUNCTION check_table_constraints(table_name TEXT) RETURNS TABLE(constraint_name TEXT, constraint_type TEXT, constraint_def TEXT) AS $$ BEGIN RETURN QUERY SELECT tc.constraint_name, tc.constraint_type, pg_get_constraintdef(c.oid) as constraint_def FROM information_schema.table_constraints tc JOIN pg_constraint c ON c.conname = tc.constraint_name JOIN pg_namespace n ON n.oid = c.connamespace WHERE tc.table_name = check_table_constraints.table_name AND n.nspname = ''public''; END; $$ LANGUAGE plpgsql SECURITY DEFINER; '; END IF; -- Create the check_foreign_keys_enabled function if it doesn't exist IF NOT EXISTS ( SELECT 1 FROM pg_proc WHERE proname = 'check_foreign_keys_enabled' AND pronamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public') ) THEN EXECUTE ' CREATE OR REPLACE FUNCTION check_foreign_keys_enabled() RETURNS BOOLEAN AS $$ DECLARE result BOOLEAN; BEGIN SELECT current_setting(''session.force_foreign_key_checks'')::BOOLEAN INTO result; RETURN result; EXCEPTION WHEN OTHERS THEN RETURN TRUE; -- Default to assuming enabled if we can''t check END; $$ LANGUAGE plpgsql SECURITY DEFINER; '; END IF; END; $$ LANGUAGE plpgsql SECURITY DEFINER; `); } else { console.log('Successfully created constraint checking functions'); } } } fixDatabaseIntegrity().catch(console.error);