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

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

View File

@ -4,6 +4,7 @@ import (
"fmt"
"io/fs"
"log"
"os"
"path"
"strconv"
"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)
// 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
for currentVersion != latestVersion {
targetVersion := currentVersion + 1