const { Pool } = require('pg'); async function run() { const pool = new Pool({ connectionString: 'postgresql://postgres:postgres@localhost:5432/xflow' }); const oldId = 'almalexyz'; const newId = 'GqbpMyUW0NaxjIy5nvCiXCiQu9t2'; console.log(`Fixing user ID from ${oldId} to ${newId}...`); try { // 1. Check if user exists const userRes = await pool.query('SELECT * FROM "User" WHERE id = $1', [oldId]); if (userRes.rowCount === 0) { console.log('User almalexyz not found. Checking if Gqbp... already exists.'); const checkRes = await pool.query('SELECT * FROM "User" WHERE id = $1', [newId]); if (checkRes.rowCount > 0) { console.log('User Gqbp... already exists. Just updating canvases.'); await pool.query('UPDATE "Canvas" SET "ownerId" = $1', [newId]); await pool.query('UPDATE "Group" SET "ownerId" = $1', [newId]); console.log('Done.'); return; } console.log('User not found at all.'); return; } // 2. We need to handle constraints. The safest way in one transaction. await pool.query('BEGIN'); // Disable constraints (Postgres specific) await pool.query('SET CONSTRAINTS ALL DEFERRED'); // Update User ID await pool.query('UPDATE "User" SET id = $1 WHERE id = $2', [newId, oldId]); // Update relations manually since schema didn't have ON UPDATE CASCADE await pool.query('UPDATE "Profile" SET "userId" = $1 WHERE "userId" = $2', [newId, oldId]); await pool.query('UPDATE "Canvas" SET "ownerId" = $1 WHERE "ownerId" = $2', [newId, oldId]); await pool.query('UPDATE "GroupMember" SET "userId" = $1 WHERE "userId" = $2', [newId, oldId]); await pool.query('UPDATE "Activity" SET "userId" = $1 WHERE "userId" = $2', [newId, oldId]); await pool.query('UPDATE "Follow" SET "followerId" = $1 WHERE "followerId" = $2', [newId, oldId]); await pool.query('UPDATE "Follow" SET "followingId" = $1 WHERE "followingId" = $2', [newId, oldId]); await pool.query('COMMIT'); console.log('Successfully migrated user ID and all relations.'); } catch (err) { await pool.query('ROLLBACK'); console.error('Migration failed:', err); } finally { await pool.end(); } } run();