Branchwell

AI Resource Pro / website / scripts / create-maintainer-functions.sql

1-- SQL functions for database maintenance
2
3-- Check if foreign key constraints are enabled
4CREATE OR REPLACE FUNCTION check_foreign_keys_enabled()
5RETURNS BOOLEAN AS $$
6DECLARE
7 result BOOLEAN;
8BEGIN
9 SELECT current_setting('session.force_foreign_key_checks')::BOOLEAN INTO result;
10 RETURN result;
11EXCEPTION
12 WHEN OTHERS THEN
13 RETURN TRUE; -- Default to assuming enabled if we can't check
14END;
15$$ LANGUAGE plpgsql SECURITY DEFINER;
16
17-- Get constraints for a table
18CREATE OR REPLACE FUNCTION check_table_constraints(table_name TEXT)
19RETURNS TABLE(constraint_name TEXT, constraint_type TEXT, constraint_def TEXT) AS $$
20BEGIN
21 RETURN QUERY
22 SELECT
23 tc.constraint_name,
24 tc.constraint_type,
25 pg_get_constraintdef(c.oid) as constraint_def
26 FROM
27 information_schema.table_constraints tc
28 JOIN pg_constraint c ON c.conname = tc.constraint_name
29 JOIN pg_namespace n ON n.oid = c.connamespace
30 WHERE
31 tc.table_name = check_table_constraints.table_name
32 AND n.nspname = 'public';
33END;
34$$ LANGUAGE plpgsql SECURITY DEFINER;
35
36-- Find orphaned junction entries
37CREATE OR REPLACE FUNCTION find_orphaned_entries(junction_table TEXT, foreign_table TEXT, foreign_key TEXT)
38RETURNS TABLE(id BIGINT, foreign_id TEXT) AS $$
39DECLARE
40 query TEXT;
41BEGIN
42 -- Dynamically build the query to find orphaned entries
43 query := format('
44 SELECT j.id, j.%I::TEXT as foreign_id
45 FROM %I j
46 LEFT JOIN %I f ON j.%I = f.id
47 WHERE f.id IS NULL
48 ', foreign_key, junction_table, foreign_table, foreign_key);
49
50 RETURN QUERY EXECUTE query;
51END;
52$$ LANGUAGE plpgsql SECURITY DEFINER;
53
54-- Clean orphaned junction entries
55CREATE OR REPLACE FUNCTION clean_orphaned_entries(junction_table TEXT, foreign_table TEXT, foreign_key TEXT)
56RETURNS INTEGER AS $$
57DECLARE
58 orphaned_ids BIGINT[];
59 deleted_count INTEGER;
60 query TEXT;
61BEGIN
62 -- Find the orphaned IDs
63 SELECT array_agg(id) INTO orphaned_ids
64 FROM find_orphaned_entries(junction_table, foreign_table, foreign_key);
65
66 IF orphaned_ids IS NULL OR array_length(orphaned_ids, 1) IS NULL THEN
67 RETURN 0;
68 END IF;
69
70 -- Delete the orphaned entries
71 query := format('
72 DELETE FROM %I
73 WHERE id = ANY($1)
74 RETURNING id
75 ', junction_table);
76
77 EXECUTE query INTO deleted_count USING orphaned_ids;
78
79 RETURN coalesce(deleted_count, 0);
80END;
81$$ LANGUAGE plpgsql SECURITY DEFINER;
82
83-- Create a trigger to ensure referential integrity for tools_categories
84CREATE OR REPLACE FUNCTION ensure_tools_categories_integrity()
85RETURNS TRIGGER AS $$
86BEGIN
87 -- Check if the referenced tool exists
88 IF NOT EXISTS (SELECT 1 FROM tools WHERE id = NEW.tool_id) THEN
89 RAISE EXCEPTION 'Referenced tool ID % does not exist', NEW.tool_id;
90 END IF;
91
92 -- Check if the referenced category exists
93 IF NOT EXISTS (SELECT 1 FROM categories WHERE id = NEW.category_id) THEN
94 RAISE EXCEPTION 'Referenced category ID % does not exist', NEW.category_id;
95 END IF;
96
97 RETURN NEW;
98END;
99$$ LANGUAGE plpgsql;
100
101-- Apply the trigger if it doesn't exist
102DO $$
103BEGIN
104 IF NOT EXISTS (
105 SELECT 1 FROM pg_trigger
106 WHERE tgname = 'ensure_tools_categories_integrity_trigger'
107 ) THEN
108 CREATE TRIGGER ensure_tools_categories_integrity_trigger
109 BEFORE INSERT OR UPDATE ON tools_categories
110 FOR EACH ROW EXECUTE FUNCTION ensure_tools_categories_integrity();
111 END IF;
112EXCEPTION
113 WHEN OTHERS THEN
114 RAISE NOTICE 'Could not create trigger: %', SQLERRM;
115END;
116$$;
117
118-- Run maintenance on all junction tables
119CREATE OR REPLACE FUNCTION run_junction_tables_maintenance()
120RETURNS TABLE(table_name TEXT, orphaned_count INTEGER, cleaned_count INTEGER) AS $$
121DECLARE
122 tables TEXT[] := ARRAY['tools_categories', 'news_categories', 'post_categories', 'learning_categories'];
123 foreign_tables TEXT[] := ARRAY['tools', 'news', 'posts', 'learning'];
124 foreign_keys TEXT[] := ARRAY['tool_id', 'news_id', 'post_id', 'learning_id'];
125 i INTEGER;
126 orphaned INTEGER;
127 cleaned INTEGER;
128BEGIN
129 FOR i IN 1..array_length(tables, 1) LOOP
130 table_name := tables[i];
131
132 -- Find orphaned entries
133 SELECT count(*) INTO orphaned
134 FROM find_orphaned_entries(tables[i], foreign_tables[i], foreign_keys[i]);
135
136 orphaned_count := orphaned;
137
138 -- Clean them if found
139 IF orphaned > 0 THEN
140 cleaned := clean_orphaned_entries(tables[i], foreign_tables[i], foreign_keys[i]);
141 cleaned_count := cleaned;
142 ELSE
143 cleaned_count := 0;
144 END IF;
145
146 RETURN NEXT;
147 END LOOP;
148END;
149$$ LANGUAGE plpgsql SECURITY DEFINER;
150
151-- Check foreign key constraint configurations
152CREATE OR REPLACE FUNCTION check_foreign_key_cascades()
153RETURNS TABLE(table_name TEXT, constraint_name TEXT, has_cascade BOOLEAN) AS $$
154BEGIN
155 RETURN QUERY
156 SELECT
157 tc.table_name,
158 tc.constraint_name,
159 pg_get_constraintdef(c.oid) LIKE '%ON DELETE CASCADE%' as has_cascade
160 FROM
161 information_schema.table_constraints tc
162 JOIN pg_constraint c ON c.conname = tc.constraint_name
163 JOIN pg_namespace n ON n.oid = c.connamespace
164 WHERE
165 tc.constraint_type = 'FOREIGN KEY'
166 AND n.nspname = 'public'
167 AND tc.table_name IN ('tools_categories', 'news_categories', 'post_categories', 'learning_categories');
168END;
169$$ LANGUAGE plpgsql SECURITY DEFINER;
170
171-- Add CASCADE DELETE to a constraint if missing
172CREATE OR REPLACE FUNCTION add_cascade_delete_to_constraint(
173 p_table_name TEXT,
174 p_constraint_name TEXT
175)
176RETURNS VOID AS $$
177DECLARE
178 constraint_def TEXT;
179 referenced_table TEXT;
180 referenced_column TEXT;
181 local_column TEXT;
182 new_constraint_name TEXT;
183 drop_query TEXT;
184 add_query TEXT;
185BEGIN
186 -- Get the constraint definition
187 SELECT
188 pg_get_constraintdef(c.oid),
189 c.confrelid::regclass::text,
190 a.attname,
191 al.attname
192 INTO
193 constraint_def,
194 referenced_table,
195 referenced_column,
196 local_column
197 FROM
198 pg_constraint c
199 JOIN pg_attribute a ON a.attnum = ANY(c.confkey) AND a.attrelid = c.confrelid
200 JOIN pg_attribute al ON al.attnum = ANY(c.conkey) AND al.attrelid = c.conrelid
201 WHERE
202 c.conname = p_constraint_name
203 AND c.contype = 'f';
204
205 -- Verify we found the constraint
206 IF constraint_def IS NULL THEN
207 RAISE EXCEPTION 'Constraint % not found or is not a foreign key', p_constraint_name;
208 END IF;
209
210 -- Generate a new constraint name
211 new_constraint_name := p_constraint_name || '_cascade';
212
213 -- Create the drop query
214 drop_query := format('ALTER TABLE %I DROP CONSTRAINT %I', p_table_name, p_constraint_name);
215
216 -- Create the add query with CASCADE
217 add_query := format(
218 'ALTER TABLE %I ADD CONSTRAINT %I FOREIGN KEY (%I) REFERENCES %s (%I) ON DELETE CASCADE',
219 p_table_name,
220 new_constraint_name,
221 local_column,
222 referenced_table,
223 referenced_column
224 );
225
226 -- Execute the queries
227 EXECUTE drop_query;
228 EXECUTE add_query;
229
230 RAISE NOTICE 'Added cascade delete to constraint % (renamed to %)', p_constraint_name, new_constraint_name;
231END;
232$$ LANGUAGE plpgsql;