Backup databases before migrating
All checks were successful
Build / build (push) Successful in 1m35s
All checks were successful
Build / build (push) Successful in 1m35s
This commit is contained in:
parent
3e7455ef31
commit
850e4a27d8
@ -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.
|
||||
|
15
migrator.go
15
migrator.go
@ -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
|
||||
|
Loading…
x
Reference in New Issue
Block a user