-- Add tool_count column if it doesn't exist DO $$ BEGIN IF NOT EXISTS ( SELECT FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'categories' AND column_name = 'tool_count' ) THEN ALTER TABLE categories ADD COLUMN tool_count INTEGER NOT NULL DEFAULT 0; END IF; END $$; -- Now add the other count columns to categories table ALTER TABLE categories ADD COLUMN IF NOT EXISTS learning_count INTEGER NOT NULL DEFAULT 0, ADD COLUMN IF NOT EXISTS news_count INTEGER NOT NULL DEFAULT 0, ADD COLUMN IF NOT EXISTS posts_count INTEGER NOT NULL DEFAULT 0; -- Initial population of counts based on existing relationships -- Only update if junction tables exist DO $$ BEGIN -- Update tool_count if tools_categories exists IF EXISTS ( SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'tools_categories' ) THEN EXECUTE ' UPDATE categories c SET tool_count = ( SELECT COUNT(*) FROM tools_categories tc WHERE tc.category_id = c.id ) '; END IF; -- Update learning_count if learning_categories exists IF EXISTS ( SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'learning_categories' ) THEN EXECUTE ' UPDATE categories c SET learning_count = ( SELECT COUNT(*) FROM learning_categories lc WHERE lc.category_id = c.id ) '; END IF; -- Update news_count if news_categories exists IF EXISTS ( SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'news_categories' ) THEN EXECUTE ' UPDATE categories c SET news_count = ( SELECT COUNT(*) FROM news_categories nc WHERE nc.category_id = c.id ) '; END IF; -- Update posts_count if post_categories exists IF EXISTS ( SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'post_categories' ) THEN EXECUTE ' UPDATE categories c SET posts_count = ( SELECT COUNT(*) FROM post_categories pc WHERE pc.category_id = c.id ) '; END IF; END $$;