MCPcopy Create free account
hub / github.com/HKUDS/AgentSpace / migratePostgresToPostgres

Function migratePostgresToPostgres

packages/db/src/postgres.ts:372–455  ·  view source on GitHub ↗
(
  input: PostgresToPostgresMigrationInput,
)

Source from the content-addressed store, hash-verified

370}
371
372export async function migratePostgresToPostgres(
373 input: PostgresToPostgresMigrationInput,
374): Promise<PostgresToPostgresMigrationReport> {
375 const startedAt = new Date().toISOString();
376 const sourceDatabaseUrl = input.sourceDatabaseUrl.trim();
377 const targetDatabaseUrl = input.targetDatabaseUrl.trim();
378 if (!sourceDatabaseUrl) {
379 throw new Error("Missing source PostgreSQL database URL.");
380 }
381 if (!targetDatabaseUrl) {
382 throw new Error("Missing target PostgreSQL database URL.");
383 }
384 if (sourceDatabaseUrl === targetDatabaseUrl) {
385 throw new Error("Source and target PostgreSQL database URLs must be different.");
386 }
387
388 const sourceClient = createPostgresClient(sourceDatabaseUrl);
389 const targetClient = createPostgresClient(targetDatabaseUrl);
390 await sourceClient.connect();
391 await targetClient.connect();
392 try {
393 const snapshot = await collectPostgresMigrationSnapshot(sourceClient);
394 const report: PostgresToPostgresMigrationReport = {
395 sourceDatabaseUrl: redactPostgresDatabaseUrl(sourceDatabaseUrl),
396 targetDatabaseUrl: redactPostgresDatabaseUrl(targetDatabaseUrl),
397 dryRun: input.dryRun === true,
398 reset: input.reset === true,
399 startedAt,
400 finishedAt: startedAt,
401 tables: snapshot.map((table) => ({
402 tableName: table.tableName,
403 sourceCount: table.rows.length,
404 insertedCount: input.dryRun ? table.rows.length : 0,
405 skippedCount: input.dryRun ? 0 : table.rows.length,
406 })),
407 };
408
409 if (input.dryRun) {
410 report.finishedAt = new Date().toISOString();
411 return report;
412 }
413
414 await targetClient.query("BEGIN");
415 try {
416 for (const statement of getPostgresSchemaStatements()) {
417 await targetClient.query(statement);
418 }
419 if (input.reset) {
420 await truncatePostgresTables(targetClient);
421 await targetClient.query(
422 `INSERT INTO app_metadata (key, value)
423 VALUES ('schema_version', $1)
424 ON CONFLICT(key) DO UPDATE SET value = EXCLUDED.value`,
425 [POSTGRES_SCHEMA_VERSION],
426 );
427 }
428 for (const [index, table] of snapshot.entries()) {
429 const insertedCount = await migrateTableRows(targetClient, table);

Callers 1

mainFunction · 0.90

Calls 7

createPostgresClientFunction · 0.85
truncatePostgresTablesFunction · 0.85
migrateTableRowsFunction · 0.85
connectMethod · 0.80

Tested by

no test coverage detected