Skip to content

Commit 34fc7de

Browse files
authored
Create parent directory on replica restore (#793)
1 parent d4dfb33 commit 34fc7de

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

replica.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,14 @@ import (
77
"io"
88
"log/slog"
99
"os"
10+
"path/filepath"
1011
"sync"
1112
"time"
1213

1314
"filippo.io/age"
1415
"github.com/superfly/ltx"
16+
17+
"github.com/benbjohnson/litestream/internal"
1518
)
1619

1720
// Default replica settings.
@@ -446,6 +449,15 @@ func (r *Replica) Restore(ctx context.Context, opt RestoreOptions) (err error) {
446449
return fmt.Errorf("no matching backup files available")
447450
}
448451

452+
// Create parent directory if it doesn't exist.
453+
var dirInfo os.FileInfo
454+
if db := r.DB(); db != nil {
455+
dirInfo = db.dirInfo
456+
}
457+
if err := internal.MkdirAll(filepath.Dir(opt.OutputPath), dirInfo); err != nil {
458+
return fmt.Errorf("create parent directory: %w", err)
459+
}
460+
449461
// Output to temp file & atomically rename.
450462
tmpOutputPath := opt.OutputPath + ".tmp"
451463
r.Logger().Debug("compacting into database", "path", tmpOutputPath, "n", len(rdrs))

replica_test.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -217,14 +217,16 @@ func TestReplica_RestoreAndReplicateAfterDataLoss(t *testing.T) {
217217
t.Fatal(err)
218218
}
219219

220-
// Restore again
220+
// Restore to a path with non-existent parent directory to verify it gets created
221+
restoredPath := dbDir + "/restored/db.sqlite"
222+
restoreOpt.OutputPath = restoredPath
221223
if err := db2.Replica.Restore(ctx, restoreOpt); err != nil {
222224
t.Fatal(err)
223225
}
224-
t.Log("Step 4 complete: Second restore from backup")
226+
t.Log("Step 4 complete: Second restore from backup to path with non-existent parent")
225227

226228
// Step 5: Verify the new data (value=2) exists in restored database
227-
sqldb3 := testingutil.MustOpenSQLDB(t, dbPath)
229+
sqldb3 := testingutil.MustOpenSQLDB(t, restoredPath)
228230
defer sqldb3.Close()
229231

230232
var count int

0 commit comments

Comments
 (0)