Branchwell

AI Resource Pro / website / scripts / create-faqs-table.ts

1import { createClient } from '@supabase/supabase-js';
2import * as path from 'path';
3import { readFileSync, existsSync } from 'fs';
4import * as dotenv from 'dotenv';
5import { fileURLToPath } from 'url';
6
7// Get the current file's directory path in ESM
8const __filename = fileURLToPath(import.meta.url);
9const __dirname = path.dirname(__filename);
10
11// Load environment variables from .env.local
12const envLocalPath = path.resolve(process.cwd(), '.env.local');
13if (existsSync(envLocalPath)) {
14 console.log(`Loading environment from: ${envLocalPath}`);
15 dotenv.config({ path: envLocalPath });
16} else {
17 console.log(`No .env.local file found at: ${envLocalPath}`);
18 dotenv.config(); // Try loading from default .env
19}
20
21async function createFaqsTable() {
22 console.log('Starting to create faqs table...');
23
24 // Initialize Supabase client
25 const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
26 const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
27
28 if (!supabaseUrl || !supabaseServiceKey) {
29 console.error('Missing Supabase environment variables. Please set NEXT_PUBLIC_SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY.');
30 process.exit(1);
31 }
32
33 console.log(`Using Supabase URL: ${supabaseUrl}`);
34
35 const supabase = createClient(supabaseUrl, supabaseServiceKey, {
36 auth: {
37 autoRefreshToken: false,
38 persistSession: false
39 }
40 });
41
42 try {
43 console.log('Running SQL migration for faqs table...');
44
45 // Read the SQL file
46 const sqlFilePath = path.join(process.cwd(), 'create-faqs-table.sql');
47 if (!existsSync(sqlFilePath)) {
48 console.error(`SQL file not found at: ${sqlFilePath}`);
49 process.exit(1);
50 }
51
52 const sqlContent = readFileSync(sqlFilePath, 'utf8');
53
54 // Split the SQL content into individual statements
55 const statements = sqlContent
56 .replace(/\/\*[\s\S]*?\*\//g, '') // Remove multi-line comments
57 .replace(/--.*?(\r?\n|$)/g, '$1') // Remove single-line comments
58 .split(';') // Split by semicolon
59 .map(stmt => stmt.trim())
60 .filter(stmt => stmt.length > 0);
61
62 console.log(`Found ${statements.length} SQL statements to execute`);
63
64 // Execute each statement sequentially
65 for (let i = 0; i < statements.length; i++) {
66 const statement = statements[i];
67 console.log(`Executing statement ${i + 1}/${statements.length}:`);
68 console.log(statement.substring(0, 100) + (statement.length > 100 ? '...' : ''));
69
70 try {
71 // Execute the SQL statement directly using a raw query
72 // We'll use the internal query method which is safer for executing raw SQL
73 const { error } = await supabase.rpc('exec_sql', { command: statement });
74
75 if (error) {
76 console.error(`Error executing statement ${i + 1}:`, error);
77
78 // Continue with other statements rather than failing completely
79 console.log('Continuing with next statement...');
80 } else {
81 console.log(`Statement ${i + 1} executed successfully`);
82 }
83 } catch (stmtError) {
84 console.error(`Exception executing statement ${i + 1}:`, stmtError);
85 console.log('Continuing with next statement...');
86 }
87 }
88
89 // Verify the table was created
90 console.log('Verifying faqs table was created...');
91 const { error: tableError } = await supabase
92 .from('faqs')
93 .select('id')
94 .limit(1);
95
96 if (tableError) {
97 console.error('Error verifying faqs table:', tableError);
98 console.log('The table may not have been created successfully.');
99
100 // Provide alternative instructions
101 console.log('\nAlternative instructions:');
102 console.log('1. Go to the Supabase dashboard for your project');
103 console.log('2. Navigate to the SQL Editor');
104 console.log('3. Copy and paste the contents of create-faqs-table.sql');
105 console.log('4. Run the SQL script manually');
106 } else {
107 console.log('Successfully verified faqs table exists!');
108 console.log('Table structure has been created.');
109 }
110
111 console.log('\nNext steps:');
112 console.log('Run the following command to seed FAQs data:');
113 console.log(' npm run supabase:seed-faqs');
114 } catch (error) {
115 console.error('Unexpected error during table creation:', error);
116 process.exit(1);
117 }
118}
119
120// Run the function
121createFaqsTable()
122 .then(() => {
123 console.log('Table creation script completed.');
124 process.exit(0);
125 })
126 .catch((error) => {
127 console.error('Error in table creation script:', error);
128 process.exit(1);
129 });