Branchwell

AI Resource Pro / website / scripts / update-instance-count.sql

1-- SQL to properly update instance_count to reflect actual usage
2-- This assumes the column has already been renamed from tool_count to instance_count
3
4-- Begin transaction
5BEGIN;
6
7-- First, check if the column exists with new name
8DO $$
9DECLARE
10 column_exists BOOLEAN;
11BEGIN
12 SELECT EXISTS (
13 SELECT 1 FROM information_schema.columns
14 WHERE table_schema = 'public'
15 AND table_name = 'categories'
16 AND column_name = 'instance_count'
17 ) INTO column_exists;
18
19 IF column_exists THEN
20 RAISE NOTICE 'Using column instance_count';
21 ELSE
22 RAISE NOTICE 'Column instance_count not found, using tool_count instead';
23 END IF;
24END $$;
25
26-- Update the instance_count in the categories table to reflect current usage
27UPDATE categories c
28SET
29 -- Use the appropriate column name based on what exists in your database
30 instance_count = (
31 -- Count tools with this category
32 SELECT COUNT(*) FROM tools
33 WHERE category_id = c.id
34 ) + (
35 -- Count news with this category
36 SELECT COUNT(*) FROM news
37 WHERE category_id = c.id
38 );
39
40-- Show current counts for verification
41SELECT
42 c.id,
43 c.name,
44 c.instance_count AS current_count,
45 (SELECT COUNT(*) FROM tools WHERE category_id = c.id) AS tools_count,
46 (SELECT COUNT(*) FROM news WHERE category_id = c.id) AS news_count,
47 ((SELECT COUNT(*) FROM tools WHERE category_id = c.id) +
48 (SELECT COUNT(*) FROM news WHERE category_id = c.id)) AS total_calculated
49FROM
50 categories c
51ORDER BY
52 c.instance_count DESC
53LIMIT 20;
54
55-- Check for any discrepancies
56SELECT
57 c.id,
58 c.name,
59 c.instance_count AS stored_count,
60 ((SELECT COUNT(*) FROM tools WHERE category_id = c.id) +
61 (SELECT COUNT(*) FROM news WHERE category_id = c.id)) AS calculated_count,
62 ABS(c.instance_count - ((SELECT COUNT(*) FROM tools WHERE category_id = c.id) +
63 (SELECT COUNT(*) FROM news WHERE category_id = c.id))) AS difference
64FROM
65 categories c
66WHERE
67 c.instance_count != ((SELECT COUNT(*) FROM tools WHERE category_id = c.id) +
68 (SELECT COUNT(*) FROM news WHERE category_id = c.id))
69ORDER BY
70 difference DESC;
71
72-- Commit the transaction
73COMMIT;