AI Resource Pro / website / scripts / update-category-columns.sql
| 1 | -- Add tool_count column if it doesn't exist |
| 2 | DO $$ |
| 3 | BEGIN |
| 4 | IF NOT EXISTS ( |
| 5 | SELECT FROM information_schema.columns |
| 6 | WHERE table_schema = 'public' |
| 7 | AND table_name = 'categories' |
| 8 | AND column_name = 'tool_count' |
| 9 | ) THEN |
| 10 | ALTER TABLE categories ADD COLUMN tool_count INTEGER NOT NULL DEFAULT 0; |
| 11 | END IF; |
| 12 | END $$; |
| 13 | |
| 14 | -- Now add the other count columns to categories table |
| 15 | ALTER TABLE categories |
| 16 | ADD COLUMN IF NOT EXISTS learning_count INTEGER NOT NULL DEFAULT 0, |
| 17 | ADD COLUMN IF NOT EXISTS news_count INTEGER NOT NULL DEFAULT 0, |
| 18 | ADD COLUMN IF NOT EXISTS posts_count INTEGER NOT NULL DEFAULT 0; |
| 19 | |
| 20 | -- Initial population of counts based on existing relationships |
| 21 | -- Only update if junction tables exist |
| 22 | DO $$ |
| 23 | BEGIN |
| 24 | -- Update tool_count if tools_categories exists |
| 25 | IF EXISTS ( |
| 26 | SELECT FROM information_schema.tables |
| 27 | WHERE table_schema = 'public' AND table_name = 'tools_categories' |
| 28 | ) THEN |
| 29 | EXECUTE ' |
| 30 | UPDATE categories c |
| 31 | SET tool_count = ( |
| 32 | SELECT COUNT(*) |
| 33 | FROM tools_categories tc |
| 34 | WHERE tc.category_id = c.id |
| 35 | ) |
| 36 | '; |
| 37 | END IF; |
| 38 | |
| 39 | -- Update learning_count if learning_categories exists |
| 40 | IF EXISTS ( |
| 41 | SELECT FROM information_schema.tables |
| 42 | WHERE table_schema = 'public' AND table_name = 'learning_categories' |
| 43 | ) THEN |
| 44 | EXECUTE ' |
| 45 | UPDATE categories c |
| 46 | SET learning_count = ( |
| 47 | SELECT COUNT(*) |
| 48 | FROM learning_categories lc |
| 49 | WHERE lc.category_id = c.id |
| 50 | ) |
| 51 | '; |
| 52 | END IF; |
| 53 | |
| 54 | -- Update news_count if news_categories exists |
| 55 | IF EXISTS ( |
| 56 | SELECT FROM information_schema.tables |
| 57 | WHERE table_schema = 'public' AND table_name = 'news_categories' |
| 58 | ) THEN |
| 59 | EXECUTE ' |
| 60 | UPDATE categories c |
| 61 | SET news_count = ( |
| 62 | SELECT COUNT(*) |
| 63 | FROM news_categories nc |
| 64 | WHERE nc.category_id = c.id |
| 65 | ) |
| 66 | '; |
| 67 | END IF; |
| 68 | |
| 69 | -- Update posts_count if post_categories exists |
| 70 | IF EXISTS ( |
| 71 | SELECT FROM information_schema.tables |
| 72 | WHERE table_schema = 'public' AND table_name = 'post_categories' |
| 73 | ) THEN |
| 74 | EXECUTE ' |
| 75 | UPDATE categories c |
| 76 | SET posts_count = ( |
| 77 | SELECT COUNT(*) |
| 78 | FROM post_categories pc |
| 79 | WHERE pc.category_id = c.id |
| 80 | ) |
| 81 | '; |
| 82 | END IF; |
| 83 | END $$; |