Branchwell

AI Resource Pro / website / scripts / run-additive-schema-v2.mjs

1import fs from 'fs';
2import crypto from 'crypto';
3import path from 'path';
4import dotenv from 'dotenv';
5import { createClient } from '@supabase/supabase-js';
6
7dotenv.config({ path: path.join(process.cwd(), '.env') });
8
9const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
10const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
11
12if (!supabaseUrl || !serviceKey) {
13 throw new Error('Missing NEXT_PUBLIC_SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY in .env');
14}
15
16const supabase = createClient(supabaseUrl, serviceKey, {
17 auth: { autoRefreshToken: false, persistSession: false }
18});
19
20const results = {
21 startedAt: new Date().toISOString(),
22 sqlSource: '/tmp/additive-schema-plan.sql',
23 sqlCleaned: '/tmp/additive-schema-plan-v2.sql',
24 migration: { totalStatements: 0, executed: 0, failed: [] },
25 verification: {}
26};
27
28function splitSqlStatements(sql) {
29 const out = [];
30 let cur = '';
31 let inSingle = false;
32 let inDouble = false;
33 let inLineComment = false;
34 let inBlockComment = false;
35
36 for (let i = 0; i < sql.length; i++) {
37 const c = sql[i];
38 const n = sql[i + 1] || '';
39
40 if (inLineComment) {
41 cur += c;
42 if (c === '\n') inLineComment = false;
43 continue;
44 }
45 if (inBlockComment) {
46 cur += c;
47 if (c === '*' && n === '/') {
48 cur += n;
49 i++;
50 inBlockComment = false;
51 }
52 continue;
53 }
54
55 if (!inSingle && !inDouble) {
56 if (c === '-' && n === '-') {
57 inLineComment = true;
58 cur += c;
59 continue;
60 }
61 if (c === '/' && n === '*') {
62 inBlockComment = true;
63 cur += c;
64 continue;
65 }
66 }
67
68 if (!inDouble && c === "'") {
69 if (inSingle && n === "'") {
70 cur += c + n;
71 i++;
72 continue;
73 }
74 inSingle = !inSingle;
75 cur += c;
76 continue;
77 }
78
79 if (!inSingle && c === '"') {
80 inDouble = !inDouble;
81 cur += c;
82 continue;
83 }
84
85 if (!inSingle && !inDouble && c === ';') {
86 const stmt = cur.trim();
87 if (stmt) out.push(stmt + ';');
88 cur = '';
89 continue;
90 }
91
92 cur += c;
93 }
94
95 const tail = cur.trim();
96 if (tail) out.push(tail);
97
98 return out
99 .map((s) => s.trim())
100 .filter(Boolean)
101 .filter((s) => !/^(BEGIN|COMMIT)\s*;?$/i.test(s));
102}
103
104function sha(value) {
105 return crypto.createHash('sha256').update(JSON.stringify(value)).digest('hex');
106}
107
108async function fetchToolsSnapshot() {
109 const pageSize = 1000;
110 const rows = [];
111 for (let from = 0; ; from += pageSize) {
112 const { data, error } = await supabase
113 .from('tools')
114 .select('*')
115 .order('id', { ascending: true })
116 .range(from, from + pageSize - 1);
117
118 if (error) throw new Error(`tools snapshot failed: ${error.message}`);
119 if (!data || data.length === 0) break;
120 rows.push(...data);
121 if (data.length < pageSize) break;
122 }
123 return rows;
124}
125
126async function checkTable(table) {
127 const { count, error } = await supabase.from(table).select('*', { count: 'exact', head: true });
128 if (error) return { table, exists: false, count: null, error: error.message };
129 return { table, exists: true, count: count ?? 0, error: null };
130}
131
132async function main() {
133 const sql = fs.readFileSync('/tmp/additive-schema-plan-v2.sql', 'utf8');
134 const createTableMatches = [...sql.matchAll(/CREATE\s+TABLE\s+IF\s+NOT\s+EXISTS\s+public\.([a-z0-9_]+)/gi)].map((m) => m[1]);
135 const statements = splitSqlStatements(sql);
136 results.migration.totalStatements = statements.length;
137
138 const toolsBefore = await fetchToolsSnapshot();
139 const baseKeys = toolsBefore.length ? Object.keys(toolsBefore[0]).filter((k) => !k.startsWith('tutorial_')).sort() : [];
140 const toolsBeforeProjected = toolsBefore.map((r) => Object.fromEntries(baseKeys.map((k) => [k, r[k]])));
141 const toolsBeforeHash = sha(toolsBeforeProjected);
142
143 for (let i = 0; i < statements.length; i++) {
144 const st = statements[i];
145 const { data, error } = await supabase.rpc('exec_sql', { sql: st });
146
147 if (error) {
148 results.migration.failed.push({ statement: i + 1, error: error.message, preview: st.slice(0, 180) });
149 continue;
150 }
151
152 if (data && data.success === false) {
153 results.migration.failed.push({ statement: i + 1, error: data.error || data.message || 'Unknown SQL error', preview: st.slice(0, 180) });
154 continue;
155 }
156
157 results.migration.executed++;
158 }
159
160 const requiredColumns = [
161 'tutorial_enabled',
162 'tutorial_overview',
163 'tutorial_quick_verdict',
164 'tutorial_hero_video_url',
165 'tutorial_last_reviewed_at',
166 'tutorial_schema_version'
167 ];
168
169 const { error: colErr } = await supabase.from('tools').select(requiredColumns.join(',')).limit(1);
170 const columnsOk = !colErr;
171
172 const tableChecks = [];
173 for (const t of createTableMatches) {
174 tableChecks.push(await checkTable(t));
175 }
176
177 const toolsAfter = await fetchToolsSnapshot();
178 const toolsAfterProjected = toolsAfter.map((r) => Object.fromEntries(baseKeys.map((k) => [k, r[k]])));
179 const toolsAfterHash = sha(toolsAfterProjected);
180
181 results.verification = {
182 toolsColumns: {
183 expected: 6,
184 columns: requiredColumns,
185 success: columnsOk,
186 error: colErr ? colErr.message : null
187 },
188 tablesFromSql: {
189 definedInSql: createTableMatches.length,
190 names: createTableMatches,
191 checks: tableChecks,
192 allExist: tableChecks.every((x) => x.exists),
193 allEmpty: tableChecks.every((x) => x.exists && x.count === 0)
194 },
195 expectedEightTablesCheck: {
196 expected: 8,
197 actualDefinedInSql: createTableMatches.length,
198 success: createTableMatches.length === 8
199 },
200 existingToolsUnchanged: {
201 beforeCount: toolsBefore.length,
202 afterCount: toolsAfter.length,
203 beforeHash: toolsBeforeHash,
204 afterHash: toolsAfterHash,
205 success: toolsBefore.length === toolsAfter.length && toolsBeforeHash === toolsAfterHash
206 }
207 };
208
209 results.success = results.migration.failed.length === 0
210 && results.verification.toolsColumns.success
211 && results.verification.tablesFromSql.allExist
212 && results.verification.tablesFromSql.allEmpty
213 && results.verification.existingToolsUnchanged.success;
214
215 results.finishedAt = new Date().toISOString();
216
217 fs.writeFileSync('/tmp/migration-results-v2.txt', JSON.stringify(results, null, 2));
218 console.log(JSON.stringify({ success: results.success, failedStatements: results.migration.failed.length }, null, 2));
219}
220
221main().catch((err) => {
222 fs.writeFileSync('/tmp/migration-results-v2.txt', JSON.stringify({ success: false, error: err.message, stack: err.stack }, null, 2));
223 console.error(err.message);
224 process.exit(1);
225});