Branchwell

AI Resource Pro / website / scripts / create-post-categories-table.ts

1import { createClient } from '@supabase/supabase-js';
2import * as dotenv from 'dotenv';
3import path from 'path';
4import * as fs from 'fs';
5
6// Load environment variables
7const envLocalPath = path.resolve(process.cwd(), '.env.local');
8if (fs.existsSync(envLocalPath)) {
9 console.log(`Loading environment from: ${envLocalPath}`);
10 dotenv.config({ path: envLocalPath });
11} else {
12 console.log(`No .env.local file found at: ${envLocalPath}`);
13 dotenv.config();
14}
15
16async function createPostCategoriesTable() {
17 console.log('Creating post_categories junction table...');
18
19 const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
20 const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
21
22 if (!supabaseUrl || !supabaseServiceKey) {
23 console.error('Missing Supabase environment variables');
24 process.exit(1);
25 }
26
27 const supabase = createClient(supabaseUrl, supabaseServiceKey);
28
29 try {
30 // First, check if table already exists by trying to select from it
31 const { data: existingData, error: checkError } = await supabase
32 .from('post_categories')
33 .select('id')
34 .limit(1);
35
36 if (!checkError) {
37 console.log('post_categories table already exists!');
38
39 // Migrate existing primary_category_id values to the junction table
40 console.log('Checking for posts with primary_category_id to migrate...');
41
42 const { data: posts, error: postsError } = await supabase
43 .from('posts')
44 .select('id, primary_category_id')
45 .not('primary_category_id', 'is', null);
46
47 if (postsError) {
48 console.error('Error fetching posts:', postsError);
49 return;
50 }
51
52 console.log(`Found ${posts?.length || 0} posts with primary_category_id`);
53
54 if (posts && posts.length > 0) {
55 for (const post of posts) {
56 // Check if this post already has a junction entry
57 const { data: existing } = await supabase
58 .from('post_categories')
59 .select('id')
60 .eq('post_id', post.id)
61 .eq('category_id', post.primary_category_id)
62 .maybeSingle();
63
64 if (!existing) {
65 const { error: insertError } = await supabase
66 .from('post_categories')
67 .insert({
68 post_id: post.id,
69 category_id: post.primary_category_id,
70 is_primary: true
71 });
72
73 if (insertError) {
74 console.error(`Error inserting junction for post ${post.id}:`, insertError);
75 } else {
76 console.log(`Created junction entry for post ${post.id} -> category ${post.primary_category_id}`);
77 }
78 } else {
79 console.log(`Junction entry already exists for post ${post.id}`);
80 }
81 }
82 }
83
84 console.log('Migration complete!');
85 return;
86 }
87
88 // Table doesn't exist - we need to create it via Supabase Dashboard
89 // The service client can't run DDL (CREATE TABLE) statements directly
90 console.log('\n========================================');
91 console.log('The post_categories table does not exist.');
92 console.log('Please create it manually in Supabase SQL Editor:');
93 console.log('========================================\n');
94 console.log(`
95-- Create post_categories junction table for multi-category blog support
96CREATE TABLE IF NOT EXISTS public.post_categories (
97 id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
98 post_id UUID NOT NULL REFERENCES public.posts(id) ON DELETE CASCADE,
99 category_id BIGINT NOT NULL REFERENCES public.categories(id) ON DELETE CASCADE,
100 is_primary BOOLEAN DEFAULT false,
101 created_at TIMESTAMPTZ DEFAULT now(),
102 UNIQUE(post_id, category_id)
103);
104
105-- Enable RLS
106ALTER TABLE public.post_categories ENABLE ROW LEVEL SECURITY;
107
108-- Public read access
109CREATE POLICY "Post categories are publicly viewable" ON public.post_categories
110 FOR SELECT USING (true);
111
112-- Allow all operations for authenticated service role
113CREATE POLICY "Service role can manage post categories" ON public.post_categories
114 FOR ALL USING (true);
115`);
116 console.log('\nAfter creating the table, run this script again to migrate existing data.\n');
117
118 } catch (error) {
119 console.error('Error:', error);
120 }
121}
122
123createPostCategoriesTable();