Branchwell

Become a Pro / website · becomeapro.ai / scripts / setup-and-fix-recursive-policies.ts

Raw 5.2 KB on 5069836c1e4c4e369ebe86b13dc7d299c5bed8c0
1import { createClient } from '@supabase/supabase-js';
2import { readFileSync, existsSync } from 'fs';
3import * as path from 'path';
4import * as dotenv from 'dotenv';
5
6// Load environment variables from .env.local
7const envLocalPath = path.resolve(process.cwd(), '.env.local');
8if (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(); // Try loading from default .env
14}
15
16// Get Supabase credentials from environment variables
17const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL || '';
18const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY || '';
19
20if (!supabaseUrl || !supabaseServiceKey) {
21 console.error('Missing Supabase environment variables');
22 process.exit(1);
23}
24
25// Create a service role client
26const supabase = createClient(supabaseUrl, supabaseServiceKey, {
27 auth: {
28 persistSession: false,
29 },
30});
31
32async function runSQL(sqlContent: string, description: string) {
33 console.log(`Executing SQL: ${description}`);
34
35 try {
36 // Execute SQL directly using REST API
37 const { data, error } = await supabase.rpc('exec_sql', { sql: sqlContent });
38
39 if (error) {
40 console.log(`Error executing ${description}:`, error);
41 return false;
42 }
43
44 console.log(`Successfully executed ${description}:`, data);
45 return true;
46 } catch (error) {
47 console.error(`Error executing ${description}:`, error);
48 return false;
49 }
50}
51
52async function createExecSQLFunction() {
53 console.log('Creating exec_sql function...');
54
55 try {
56 // Read the SQL file
57 const sqlPath = path.join(process.cwd(), 'scripts', 'create-exec-sql-function.sql');
58 const sqlContent = readFileSync(sqlPath, 'utf8');
59
60 // Try to execute exec_sql to test if it exists
61 try {
62 const { data, error } = await supabase.rpc('exec_sql', { sql: 'SELECT 1 as test' });
63
64 if (!error) {
65 console.log('exec_sql function already exists:', data);
66 return true;
67 }
68 } catch (err) {
69 console.log('exec_sql function does not exist yet. Creating it...');
70 }
71
72 // Try executing the SQL directly via raw query
73 try {
74 const response = await fetch(`${supabaseUrl}/rest/v1/rpc/postgres`, {
75 method: 'POST',
76 headers: {
77 'Content-Type': 'application/json',
78 'Authorization': `Bearer ${supabaseServiceKey}`,
79 'apikey': `${supabaseServiceKey}`
80 },
81 body: JSON.stringify({
82 query: sqlContent
83 })
84 });
85
86 if (!response.ok) {
87 const errorData = await response.json();
88 console.log('Error creating exec_sql function via postgres RPC:', errorData);
89 } else {
90 console.log('Successfully created exec_sql function via postgres RPC');
91 return true;
92 }
93 } catch (err) {
94 console.log('Error executing postgres RPC:', err);
95 }
96
97 // As a fallback, try direct HTTP request to the SQL endpoint
98 try {
99 const response = await fetch(`${supabaseUrl}/rest/v1/sql`, {
100 method: 'POST',
101 headers: {
102 'Content-Type': 'application/json',
103 'Authorization': `Bearer ${supabaseServiceKey}`,
104 'apikey': `${supabaseServiceKey}`,
105 'Prefer': 'return=representation'
106 },
107 body: JSON.stringify({
108 query: sqlContent
109 })
110 });
111
112 if (!response.ok) {
113 const errorData = await response.json();
114 console.error('Error creating exec_sql function via SQL endpoint:', errorData);
115 return false;
116 }
117
118 console.log('Successfully created exec_sql function via SQL endpoint');
119 return true;
120 } catch (error) {
121 console.error('Error accessing SQL endpoint:', error);
122 return false;
123 }
124 } catch (error) {
125 console.error('Error creating exec_sql function:', error);
126 return false;
127 }
128}
129
130async function fixRecursivePolicies() {
131 console.log('Applying fix for recursive policies...');
132
133 try {
134 // Read the SQL file
135 const sqlPath = path.join(process.cwd(), 'scripts', 'fix-recursive-policies.sql');
136 const sqlContent = readFileSync(sqlPath, 'utf8');
137
138 // Execute the SQL using our runSQL helper
139 const success = await runSQL(sqlContent, 'fix for recursive policies');
140
141 if (!success) {
142 throw new Error('Failed to apply recursive policy fixes');
143 }
144
145 console.log('Successfully applied fix for recursive policies');
146 console.log('Please restart your application for the changes to take effect.');
147 return true;
148 } catch (error) {
149 console.error('Error applying fix:', error);
150 return false;
151 }
152}
153
154async function main() {
155 // First, try to create the exec_sql function
156 const execSqlCreated = await createExecSQLFunction();
157
158 if (!execSqlCreated) {
159 console.error('Failed to create exec_sql function. Cannot proceed with policy fixes.');
160 process.exit(1);
161 }
162
163 // Then, apply the recursive policy fixes
164 const policiesFixed = await fixRecursivePolicies();
165
166 if (!policiesFixed) {
167 console.error('Failed to apply recursive policy fixes.');
168 process.exit(1);
169 }
170
171 console.log('All operations completed successfully!');
172}
173
174main();