import { createClient } from '@supabase/supabase-js'; import * as dotenv from 'dotenv'; import path from 'path'; import * as fs from 'fs'; // Load environment variables const envLocalPath = path.resolve(process.cwd(), '.env.local'); if (fs.existsSync(envLocalPath)) { console.log(`Loading environment from: ${envLocalPath}`); dotenv.config({ path: envLocalPath }); } else { console.log(`No .env.local file found at: ${envLocalPath}`); dotenv.config(); } async function createPostCategoriesTable() { console.log('Creating post_categories junction table...'); const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY; if (!supabaseUrl || !supabaseServiceKey) { console.error('Missing Supabase environment variables'); process.exit(1); } const supabase = createClient(supabaseUrl, supabaseServiceKey); try { // First, check if table already exists by trying to select from it const { data: existingData, error: checkError } = await supabase .from('post_categories') .select('id') .limit(1); if (!checkError) { console.log('post_categories table already exists!'); // Migrate existing primary_category_id values to the junction table console.log('Checking for posts with primary_category_id to migrate...'); const { data: posts, error: postsError } = await supabase .from('posts') .select('id, primary_category_id') .not('primary_category_id', 'is', null); if (postsError) { console.error('Error fetching posts:', postsError); return; } console.log(`Found ${posts?.length || 0} posts with primary_category_id`); if (posts && posts.length > 0) { for (const post of posts) { // Check if this post already has a junction entry const { data: existing } = await supabase .from('post_categories') .select('id') .eq('post_id', post.id) .eq('category_id', post.primary_category_id) .maybeSingle(); if (!existing) { const { error: insertError } = await supabase .from('post_categories') .insert({ post_id: post.id, category_id: post.primary_category_id, is_primary: true }); if (insertError) { console.error(`Error inserting junction for post ${post.id}:`, insertError); } else { console.log(`Created junction entry for post ${post.id} -> category ${post.primary_category_id}`); } } else { console.log(`Junction entry already exists for post ${post.id}`); } } } console.log('Migration complete!'); return; } // Table doesn't exist - we need to create it via Supabase Dashboard // The service client can't run DDL (CREATE TABLE) statements directly console.log('\n========================================'); console.log('The post_categories table does not exist.'); console.log('Please create it manually in Supabase SQL Editor:'); console.log('========================================\n'); console.log(` -- Create post_categories junction table for multi-category blog support CREATE TABLE IF NOT EXISTS public.post_categories ( id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, post_id UUID NOT NULL REFERENCES public.posts(id) ON DELETE CASCADE, category_id BIGINT NOT NULL REFERENCES public.categories(id) ON DELETE CASCADE, is_primary BOOLEAN DEFAULT false, created_at TIMESTAMPTZ DEFAULT now(), UNIQUE(post_id, category_id) ); -- Enable RLS ALTER TABLE public.post_categories ENABLE ROW LEVEL SECURITY; -- Public read access CREATE POLICY "Post categories are publicly viewable" ON public.post_categories FOR SELECT USING (true); -- Allow all operations for authenticated service role CREATE POLICY "Service role can manage post categories" ON public.post_categories FOR ALL USING (true); `); console.log('\nAfter creating the table, run this script again to migrate existing data.\n'); } catch (error) { console.error('Error:', error); } } createPostCategoriesTable();