|
5 | 5 | "encoding/hex" |
6 | 6 | "fmt" |
7 | 7 | "io" |
| 8 | + "net/url" |
8 | 9 | "os" |
9 | 10 | "os/exec" |
10 | 11 | "path/filepath" |
@@ -61,9 +62,10 @@ type ( |
61 | 62 | } |
62 | 63 |
|
63 | 64 | RestoreOptions struct { |
64 | | - InputPath string |
65 | | - Format SnapshotFormat |
66 | | - Clean bool // drop existing objects before restore |
| 65 | + InputPath string |
| 66 | + Format SnapshotFormat |
| 67 | + Clean bool // drop existing objects before restore |
| 68 | + TargetDatabase string // override database name from connection string |
67 | 69 | } |
68 | 70 | ) |
69 | 71 |
|
@@ -428,21 +430,41 @@ func ShouldAutoRestore(cfg *SnapshotConfig) bool { |
428 | 430 | return *cfg.AutoRestore |
429 | 431 | } |
430 | 432 |
|
| 433 | +// replaceDatabase returns a new connection string with a different database |
| 434 | +func replaceDatabase(pguri, newDB string) (string, error) { |
| 435 | + u, err := url.Parse(pguri) |
| 436 | + if err != nil { |
| 437 | + return "", err |
| 438 | + } |
| 439 | + u.Path = "/" + newDB |
| 440 | + return u.String(), nil |
| 441 | +} |
| 442 | + |
431 | 443 | // RestoreSnapshot restores a database snapshot using pg_restore or psql |
432 | 444 | func RestoreSnapshot(pguri string, opts RestoreOptions) error { |
433 | 445 | if _, err := os.Stat(opts.InputPath); os.IsNotExist(err) { |
434 | 446 | return fmt.Errorf("snapshot file not found: %s", opts.InputPath) |
435 | 447 | } |
436 | 448 |
|
| 449 | + // Override target database if specified |
| 450 | + targetURI := pguri |
| 451 | + if opts.TargetDatabase != "" { |
| 452 | + var err error |
| 453 | + targetURI, err = replaceDatabase(pguri, opts.TargetDatabase) |
| 454 | + if err != nil { |
| 455 | + return fmt.Errorf("failed to set target database: %w", err) |
| 456 | + } |
| 457 | + } |
| 458 | + |
437 | 459 | format := opts.Format |
438 | 460 | if format == "" { |
439 | 461 | format = DetectSnapshotFormat(opts.InputPath) |
440 | 462 | } |
441 | 463 |
|
442 | 464 | if format == FormatPlain { |
443 | | - return restoreWithPsql(pguri, opts) |
| 465 | + return restoreWithPsql(targetURI, opts) |
444 | 466 | } |
445 | | - return restoreWithPgRestore(pguri, opts, format) |
| 467 | + return restoreWithPgRestore(targetURI, opts, format) |
446 | 468 | } |
447 | 469 |
|
448 | 470 | func restoreWithPgRestore(pguri string, opts RestoreOptions, format SnapshotFormat) error { |
|
0 commit comments