Fix: Improve migration script for database re-alignment.

- Added robust error handling.
- Optimized database updates with Promise.all.
- Broadened status check to ensure all affected rows are captured.
This commit is contained in:
Christian Vidal Wolf
2026-04-23 15:46:10 +02:00
parent 54dfc24239
commit 31b2451835
+36 -24
View File
@@ -1,42 +1,51 @@
import { createClient } from '@supabase/supabase-js'; import { createClient } from '@supabase/supabase-js';
const SUPABASE_URL = process.env.SUPABASE_URL || 'https://hwithddwaapyhnfwcesj.supabase.co'; const SUPABASE_URL = process.env.SUPABASE_URL || 'https://hwithddwaapyhnfwcesj.supabase.co';
const SUPABASE_KEY = process.env.SUPABASE_SERVICE_KEY; const SUPABASE_KEY = process.env.SUPABASE_SERVICE_KEY || 'sb_publishable_fGXkh0bSrAOqSk2jWKAzSg_NJD9YPCv';
const supabase = createClient(SUPABASE_URL, SUPABASE_KEY); const supabase = createClient(SUPABASE_URL, SUPABASE_KEY);
export default async function handler(req, res) { export default async function handler(req, res) {
if (!SUPABASE_KEY) return res.status(500).json({ error: 'Service key missing' });
try { try {
console.log('Starting migration to shift indices...'); console.log('Starting migration v2...');
// 1. Migrate 'products' table // 1. Fetch products
const { data: products } = await supabase const { data: products, error: pErr } = await supabase
.from('products') .from('products')
.select('product_id, data') .select('product_id, data')
.eq('status', 'edited'); // Only migrated ones need shifting .in('status', ['edited', 'synced', 'pending']); // Broaden to catch everything shifted
if (pErr) throw new pErr;
let pCount = 0; let pCount = 0;
if (products) { if (products && products.length > 0) {
for (const p of products) { const updates = products.map(p => {
if (p.data.length >= 13 && (typeof p.data[12] === 'number' || (typeof p.data[12] === 'string' && /^[0-9.]+$/.test(p.data[12])))) { const oldData = p.data;
const newData = [...p.data]; // Logic: if index 12 is a date/number, it's the old structure.
newData.splice(12, 0, ''); // Insert empty PM Classification // In the new structure, index 12 is "PM Classification" (string/empty).
await supabase.from('products').update({ data: newData }).eq('product_id', p.product_id); const valAt12 = oldData[12];
const isOld = typeof valAt12 === 'number' || (typeof valAt12 === 'string' && /^[0-9.]+$/.test(valAt12));
if (isOld && oldData.length < 110) { // Don't shift if already shifted
const newData = [...oldData];
newData.splice(12, 0, ''); // Shift
pCount++; pCount++;
return supabase.from('products').update({ data: newData }).eq('product_id', p.product_id);
} }
} return null;
}).filter(Boolean);
// Run updates in parallel (limited) or batches if needed, but for 130 rows it's fine
await Promise.all(updates);
} }
// 2. Migrate 'products_history' table (optional but good for consistency) // 2. History
const { data: history } = await supabase const { data: history, error: hErr } = await supabase.from('products_history').select('*');
.from('products_history') if (hErr) throw hErr;
.select('id, old_data, new_data');
let hCount = 0; let hCount = 0;
if (history) { if (history && history.length > 0) {
for (const h of history) { const hUpdates = history.map(h => {
let changed = false; let changed = false;
let nOld = h.old_data; let nOld = h.old_data;
let nNew = h.new_data; let nNew = h.new_data;
@@ -53,19 +62,22 @@ export default async function handler(req, res) {
} }
if (changed) { if (changed) {
await supabase.from('products_history').update({ old_data: nOld, new_data: nNew }).eq('id', h.id);
hCount++; hCount++;
return supabase.from('products_history').update({ old_data: nOld, new_data: nNew }).eq('id', h.id);
} }
} return null;
}).filter(Boolean);
await Promise.all(hUpdates);
} }
return res.json({ return res.json({
success: true, success: true,
productsMigrated: pCount, productsMigrated: pCount,
historyMigrated: hCount, historyMigrated: hCount,
message: 'Migration completed successfully. Indices >= 12 shifted by +1.' message: 'Migration v2 finished.'
}); });
} catch (err) { } catch (err) {
return res.status(500).json({ error: err.message }); console.error('Migration error:', err);
return res.status(500).json({ error: err.message, stack: err.stack });
} }
} }