Backup databases before migrating
All checks were successful
Build / build (push) Successful in 1m35s

This commit is contained in:
Sebastiaan de Schaetzen 2025-03-24 06:27:05 +01:00
parent 3e7455ef31
commit 850e4a27d8
2 changed files with 19 additions and 3 deletions

View File

@ -9,6 +9,7 @@ import (
// Db holds a connection to a SQLite database. // Db holds a connection to a SQLite database.
type Db struct { type Db struct {
Db *sqlite.Conn Db *sqlite.Conn
source string
lock sync.Mutex lock sync.Mutex
} }
@ -21,7 +22,7 @@ func OpenDb(databaseSource string) (*Db, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &Db{Db: conn}, nil return &Db{Db: conn, source: databaseSource}, nil
} }
// Close closes the database. // Close closes the database.

View File

@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"io/fs" "io/fs"
"log" "log"
"os"
"path" "path"
"strconv" "strconv"
"strings" "strings"
@ -40,6 +41,20 @@ func (d *Db) MigrateDb(filesystem ReadDirFileFS, directory string) error {
} }
log.Printf("Current version is %d, max migration version is %d", currentVersion, latestVersion) log.Printf("Current version is %d, max migration version is %d", currentVersion, latestVersion)
// Create a backup if we're not on the latest version
if currentVersion != latestVersion && d.source != ":memory:" {
target := d.source + ".backup." + strconv.Itoa(currentVersion)
log.Printf("Creating backup of database to %s", target)
data, err := d.Db.Serialize("main")
if err != nil {
return fmt.Errorf("error serializing database: %v", err)
}
err = os.WriteFile(target, data, 0644)
if err != nil {
return fmt.Errorf("error writing backup: %v", err)
}
}
// If we are no up-to-date, bring the db up-to-date // If we are no up-to-date, bring the db up-to-date
for currentVersion != latestVersion { for currentVersion != latestVersion {
targetVersion := currentVersion + 1 targetVersion := currentVersion + 1