|
| 1 | +import { Client } from 'pg'; |
| 2 | + |
| 3 | +const args = new Map( |
| 4 | + process.argv.slice(2).map((entry) => { |
| 5 | + const [key, ...rest] = entry.split('='); |
| 6 | + return [key, rest.join('=')]; |
| 7 | + }), |
| 8 | +); |
| 9 | + |
| 10 | +const normalizeBaseUrl = (value) => value.trim().replace(/\/$/, ''); |
| 11 | + |
| 12 | +const sourceBaseUrl = normalizeBaseUrl(args.get('--from') || process.env.MEDIA_HOST_FROM || ''); |
| 13 | +const targetBaseUrl = normalizeBaseUrl(args.get('--to') || process.env.MEDIA_HOST_TO || ''); |
| 14 | +const dryRun = ['1', 'true', 'yes'].includes((args.get('--dry-run') || '').trim().toLowerCase()); |
| 15 | +const databaseUrl = process.env.DATABASE_URL || ''; |
| 16 | + |
| 17 | +if (!databaseUrl) { |
| 18 | + console.error('DATABASE_URL is required'); |
| 19 | + process.exit(1); |
| 20 | +} |
| 21 | + |
| 22 | +if (!sourceBaseUrl || !targetBaseUrl) { |
| 23 | + console.error('Usage: node packages/db/scripts/replace-media-host.mjs --from=https://old-host --to=https://new-host [--dry-run=true]'); |
| 24 | + process.exit(1); |
| 25 | +} |
| 26 | + |
| 27 | +const client = new Client({ connectionString: databaseUrl }); |
| 28 | + |
| 29 | +const listMatchingRows = async () => |
| 30 | + client.query( |
| 31 | + `select id, object_key, public_url |
| 32 | + from assets |
| 33 | + where public_url like $1 |
| 34 | + order by updated_at desc, created_at desc`, |
| 35 | + [`${sourceBaseUrl}/%`], |
| 36 | + ); |
| 37 | + |
| 38 | +const main = async () => { |
| 39 | + await client.connect(); |
| 40 | + |
| 41 | + const before = await listMatchingRows(); |
| 42 | + |
| 43 | + console.log( |
| 44 | + JSON.stringify( |
| 45 | + { |
| 46 | + dryRun, |
| 47 | + sourceBaseUrl, |
| 48 | + targetBaseUrl, |
| 49 | + matches: before.rowCount, |
| 50 | + sample: before.rows.slice(0, 10), |
| 51 | + }, |
| 52 | + null, |
| 53 | + 2, |
| 54 | + ), |
| 55 | + ); |
| 56 | + |
| 57 | + if (dryRun || before.rowCount === 0) { |
| 58 | + return; |
| 59 | + } |
| 60 | + |
| 61 | + const updated = await client.query( |
| 62 | + `update assets |
| 63 | + set public_url = replace(public_url, $1, $2), |
| 64 | + updated_at = now() |
| 65 | + where public_url like $3 |
| 66 | + returning id, object_key, public_url`, |
| 67 | + [sourceBaseUrl, targetBaseUrl, `${sourceBaseUrl}/%`], |
| 68 | + ); |
| 69 | + |
| 70 | + console.log( |
| 71 | + JSON.stringify( |
| 72 | + { |
| 73 | + updated: updated.rowCount, |
| 74 | + sample: updated.rows.slice(0, 10), |
| 75 | + }, |
| 76 | + null, |
| 77 | + 2, |
| 78 | + ), |
| 79 | + ); |
| 80 | +}; |
| 81 | + |
| 82 | +main() |
| 83 | + .catch((error) => { |
| 84 | + console.error(error); |
| 85 | + process.exitCode = 1; |
| 86 | + }) |
| 87 | + .finally(async () => { |
| 88 | + await client.end().catch(() => undefined); |
| 89 | + }); |
0 commit comments