-- SQL functions for database maintenance -- Check if foreign key constraints are enabled 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; -- Get constraints for a table 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; -- Find orphaned junction entries CREATE OR REPLACE FUNCTION find_orphaned_entries(junction_table TEXT, foreign_table TEXT, foreign_key TEXT) RETURNS TABLE(id BIGINT, foreign_id TEXT) AS $$ DECLARE query TEXT; BEGIN -- Dynamically build the query to find orphaned entries query := format(' SELECT j.id, j.%I::TEXT as foreign_id FROM %I j LEFT JOIN %I f ON j.%I = f.id WHERE f.id IS NULL ', foreign_key, junction_table, foreign_table, foreign_key); RETURN QUERY EXECUTE query; END; $$ LANGUAGE plpgsql SECURITY DEFINER; -- Clean orphaned junction entries CREATE OR REPLACE FUNCTION clean_orphaned_entries(junction_table TEXT, foreign_table TEXT, foreign_key TEXT) RETURNS INTEGER AS $$ DECLARE orphaned_ids BIGINT[]; deleted_count INTEGER; query TEXT; BEGIN -- Find the orphaned IDs SELECT array_agg(id) INTO orphaned_ids FROM find_orphaned_entries(junction_table, foreign_table, foreign_key); IF orphaned_ids IS NULL OR array_length(orphaned_ids, 1) IS NULL THEN RETURN 0; END IF; -- Delete the orphaned entries query := format(' DELETE FROM %I WHERE id = ANY($1) RETURNING id ', junction_table); EXECUTE query INTO deleted_count USING orphaned_ids; RETURN coalesce(deleted_count, 0); END; $$ LANGUAGE plpgsql SECURITY DEFINER; -- Create a trigger to ensure referential integrity for tools_categories CREATE OR REPLACE FUNCTION ensure_tools_categories_integrity() RETURNS TRIGGER AS $$ BEGIN -- Check if the referenced tool exists IF NOT EXISTS (SELECT 1 FROM tools WHERE id = NEW.tool_id) THEN RAISE EXCEPTION 'Referenced tool ID % does not exist', NEW.tool_id; END IF; -- Check if the referenced category exists IF NOT EXISTS (SELECT 1 FROM categories WHERE id = NEW.category_id) THEN RAISE EXCEPTION 'Referenced category ID % does not exist', NEW.category_id; END IF; RETURN NEW; END; $$ LANGUAGE plpgsql; -- Apply the trigger if it doesn't exist DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM pg_trigger WHERE tgname = 'ensure_tools_categories_integrity_trigger' ) THEN CREATE TRIGGER ensure_tools_categories_integrity_trigger BEFORE INSERT OR UPDATE ON tools_categories FOR EACH ROW EXECUTE FUNCTION ensure_tools_categories_integrity(); END IF; EXCEPTION WHEN OTHERS THEN RAISE NOTICE 'Could not create trigger: %', SQLERRM; END; $$; -- Run maintenance on all junction tables CREATE OR REPLACE FUNCTION run_junction_tables_maintenance() RETURNS TABLE(table_name TEXT, orphaned_count INTEGER, cleaned_count INTEGER) AS $$ DECLARE tables TEXT[] := ARRAY['tools_categories', 'news_categories', 'post_categories', 'learning_categories']; foreign_tables TEXT[] := ARRAY['tools', 'news', 'posts', 'learning']; foreign_keys TEXT[] := ARRAY['tool_id', 'news_id', 'post_id', 'learning_id']; i INTEGER; orphaned INTEGER; cleaned INTEGER; BEGIN FOR i IN 1..array_length(tables, 1) LOOP table_name := tables[i]; -- Find orphaned entries SELECT count(*) INTO orphaned FROM find_orphaned_entries(tables[i], foreign_tables[i], foreign_keys[i]); orphaned_count := orphaned; -- Clean them if found IF orphaned > 0 THEN cleaned := clean_orphaned_entries(tables[i], foreign_tables[i], foreign_keys[i]); cleaned_count := cleaned; ELSE cleaned_count := 0; END IF; RETURN NEXT; END LOOP; END; $$ LANGUAGE plpgsql SECURITY DEFINER; -- Check foreign key constraint configurations CREATE OR REPLACE FUNCTION check_foreign_key_cascades() RETURNS TABLE(table_name TEXT, constraint_name TEXT, has_cascade BOOLEAN) AS $$ BEGIN RETURN QUERY SELECT tc.table_name, tc.constraint_name, pg_get_constraintdef(c.oid) LIKE '%ON DELETE CASCADE%' as has_cascade 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.constraint_type = 'FOREIGN KEY' AND n.nspname = 'public' AND tc.table_name IN ('tools_categories', 'news_categories', 'post_categories', 'learning_categories'); END; $$ LANGUAGE plpgsql SECURITY DEFINER; -- Add CASCADE DELETE to a constraint if missing CREATE OR REPLACE FUNCTION add_cascade_delete_to_constraint( p_table_name TEXT, p_constraint_name TEXT ) RETURNS VOID AS $$ DECLARE constraint_def TEXT; referenced_table TEXT; referenced_column TEXT; local_column TEXT; new_constraint_name TEXT; drop_query TEXT; add_query TEXT; BEGIN -- Get the constraint definition SELECT pg_get_constraintdef(c.oid), c.confrelid::regclass::text, a.attname, al.attname INTO constraint_def, referenced_table, referenced_column, local_column FROM pg_constraint c JOIN pg_attribute a ON a.attnum = ANY(c.confkey) AND a.attrelid = c.confrelid JOIN pg_attribute al ON al.attnum = ANY(c.conkey) AND al.attrelid = c.conrelid WHERE c.conname = p_constraint_name AND c.contype = 'f'; -- Verify we found the constraint IF constraint_def IS NULL THEN RAISE EXCEPTION 'Constraint % not found or is not a foreign key', p_constraint_name; END IF; -- Generate a new constraint name new_constraint_name := p_constraint_name || '_cascade'; -- Create the drop query drop_query := format('ALTER TABLE %I DROP CONSTRAINT %I', p_table_name, p_constraint_name); -- Create the add query with CASCADE add_query := format( 'ALTER TABLE %I ADD CONSTRAINT %I FOREIGN KEY (%I) REFERENCES %s (%I) ON DELETE CASCADE', p_table_name, new_constraint_name, local_column, referenced_table, referenced_column ); -- Execute the queries EXECUTE drop_query; EXECUTE add_query; RAISE NOTICE 'Added cascade delete to constraint % (renamed to %)', p_constraint_name, new_constraint_name; END; $$ LANGUAGE plpgsql;