AI Resource Pro / website / scripts / complete-update-category-counts.sql
| 1 | -- SQL to update the tool_count field in the categories table |
| 2 | -- Based on confirmed column names and with error handling |
| 3 | |
| 4 | -- First, check if blog_posts table has primary_category_id column |
| 5 | DO $$ |
| 6 | DECLARE |
| 7 | blog_has_primary_category_id BOOLEAN; |
| 8 | BEGIN |
| 9 | -- Check if blog_posts.primary_category_id exists |
| 10 | SELECT EXISTS ( |
| 11 | SELECT 1 FROM information_schema.columns |
| 12 | WHERE table_schema = 'public' |
| 13 | AND table_name = 'blog_posts' |
| 14 | AND column_name = 'primary_category_id' |
| 15 | ) INTO blog_has_primary_category_id; |
| 16 | |
| 17 | RAISE NOTICE 'blog_posts.primary_category_id exists: %', blog_has_primary_category_id; |
| 18 | |
| 19 | -- Update the tool_count based on what columns exist |
| 20 | IF blog_has_primary_category_id THEN |
| 21 | -- If blog_posts has primary_category_id, include blog posts in the count |
| 22 | UPDATE categories c |
| 23 | SET tool_count = ( |
| 24 | -- Count tools with this category |
| 25 | SELECT COUNT(*) FROM tools |
| 26 | WHERE category_id = c.id |
| 27 | ) + ( |
| 28 | -- Count news with this category |
| 29 | SELECT COUNT(*) FROM news |
| 30 | WHERE category_id = c.id |
| 31 | ) + ( |
| 32 | -- Count blog posts with this category |
| 33 | SELECT COUNT(*) FROM blog_posts |
| 34 | WHERE primary_category_id = c.id |
| 35 | ); |
| 36 | |
| 37 | RAISE NOTICE 'Updated category counts including blog posts'; |
| 38 | ELSE |
| 39 | -- If blog_posts does not have primary_category_id, only count tools and news |
| 40 | UPDATE categories c |
| 41 | SET tool_count = ( |
| 42 | -- Count tools with this category |
| 43 | SELECT COUNT(*) FROM tools |
| 44 | WHERE category_id = c.id |
| 45 | ) + ( |
| 46 | -- Count news with this category |
| 47 | SELECT COUNT(*) FROM news |
| 48 | WHERE category_id = c.id |
| 49 | ); |
| 50 | |
| 51 | RAISE NOTICE 'Updated category counts without blog posts (column not found)'; |
| 52 | END IF; |
| 53 | END $$; |
| 54 | |
| 55 | -- Output the results for verification |
| 56 | SELECT |
| 57 | c.id, |
| 58 | c.name, |
| 59 | c.tool_count, |
| 60 | (SELECT COUNT(*) FROM tools WHERE category_id = c.id) AS tools_count, |
| 61 | (SELECT COUNT(*) FROM news WHERE category_id = c.id) AS news_count, |
| 62 | CASE WHEN EXISTS ( |
| 63 | SELECT 1 FROM information_schema.columns |
| 64 | WHERE table_schema = 'public' |
| 65 | AND table_name = 'blog_posts' |
| 66 | AND column_name = 'primary_category_id' |
| 67 | ) THEN |
| 68 | (SELECT COUNT(*) FROM blog_posts WHERE primary_category_id = c.id) |
| 69 | ELSE |
| 70 | 0 |
| 71 | END AS blog_posts_count |
| 72 | FROM |
| 73 | categories c |
| 74 | ORDER BY |
| 75 | c.tool_count DESC; |