Branchwell

AI Resource Pro / website / scripts / run-learning-slug-migration.js

1import { createClient } from '@supabase/supabase-js';
2import fs from 'fs';
3import path from 'path';
4import { fileURLToPath } from 'url';
5import dotenv from 'dotenv';
6
7// Get the directory name
8const __filename = fileURLToPath(import.meta.url);
9const __dirname = path.dirname(__filename);
10
11// Load environment variables
12dotenv.config({ path: '.env.local' });
13
14// Validate required environment variables
15if (!process.env.NEXT_PUBLIC_SUPABASE_URL || !process.env.SUPABASE_SERVICE_ROLE_KEY) {
16 console.error('Error: Missing Supabase environment variables.');
17 console.error('Make sure NEXT_PUBLIC_SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY are set in .env.local');
18 process.exit(1);
19}
20
21// Create Supabase client
22const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
23const supabaseKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
24const supabase = createClient(supabaseUrl, supabaseKey, {
25 auth: {
26 autoRefreshToken: false,
27 persistSession: false
28 }
29});
30
31// Function to execute SQL directly (fallback)
32async function executeSQL(sql) {
33 try {
34 // First try the exec_sql RPC function
35 const { error } = await supabase.rpc('exec_sql', { sql });
36
37 if (error) {
38 // If the RPC function fails, try direct SQL execution
39 console.log('Falling back to direct SQL execution...');
40 const { error: directError } = await supabase.from('_exec_sql').select('*').eq('sql', sql).maybeSingle();
41
42 if (directError) {
43 throw new Error(`Failed to execute SQL: ${directError.message}`);
44 }
45 }
46
47 return { success: true };
48 } catch (error) {
49 return { success: false, error };
50 }
51}
52
53// Read and execute the migration SQL
54async function runMigration() {
55 try {
56 // Import the file path
57 const sqlFilePath = path.join(__dirname, 'add-slug-to-learning-simple.sql');
58
59 // Inside the runMigration function, replace the file path
60 console.log('Reading migration SQL file...');
61 const migrationSql = fs.readFileSync(sqlFilePath, 'utf8');
62
63 // Split the SQL into individual statements
64 const statements = migrationSql
65 .replace(/\/\*.*?\*\//g, '') // Remove block comments
66 .replace(/--.*?$/gm, '') // Remove line comments
67 .split(';')
68 .map(s => s.trim())
69 .filter(s => s.length > 0); // Filter out empty statements
70
71 console.log(`Found ${statements.length} SQL statements to execute.`);
72
73 // Execute each statement
74 for (let i = 0; i < statements.length; i++) {
75 const statement = statements[i];
76 console.log(`Executing statement ${i + 1}/${statements.length}...`);
77
78 // Try executing the SQL statement
79 const { success, error } = await executeSQL(statement);
80
81 if (!success) {
82 console.error(`Error executing statement ${i + 1}:`, error.message);
83 console.error('SQL Statement:', statement);
84 // Continue with other statements
85 console.log('Continuing with remaining statements...');
86 }
87 }
88
89 console.log('Migration completed!');
90
91 // Verify the migration by checking if slug column exists
92 const { data, error: verifyError } = await supabase
93 .from('learning')
94 .select('slug')
95 .limit(1);
96
97 if (verifyError) {
98 console.warn('Warning: Could not verify migration:', verifyError.message);
99 } else if (data && data.length > 0) {
100 console.log('Verification successful: slug column exists and contains data.');
101 } else {
102 console.log('Slug column exists but may not contain data yet.');
103 }
104 } catch (error) {
105 console.error('Error executing migration:', error.message);
106 process.exit(1);
107 }
108}
109
110runMigration();