From ca96df29085f9ca6567cd474d0920e48c6410b42 Mon Sep 17 00:00:00 2001 From: xengineering Date: Thu, 9 May 2024 21:48:56 +0200 Subject: model: Initial database version injection If the database was empty on startup a metadata table with a key and value row is created. In addition the Ceres executable version is inserted as value under the key 'version'. This allows to detect on not-empty databases which Ceres version was used before which is the starting point to implement migrations. --- main.go | 2 +- model/database.go | 21 ++++++++++++++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/main.go b/main.go index 6c123da..4abe9ae 100644 --- a/main.go +++ b/main.go @@ -35,7 +35,7 @@ func main() { model.ConnectDatabase(filepath.Join(storage.Path, "ceres.sqlite3")) defer model.DisconnectDatabase() - model.MigrateDatabase() + model.MigrateDatabase(version) model.InjectTestRecipes() server := NewServer(config.HttpAddress) diff --git a/model/database.go b/model/database.go index 16a6cea..cdded4a 100644 --- a/model/database.go +++ b/model/database.go @@ -78,10 +78,29 @@ func isDatabaseEmpty(tx *sql.Tx) bool { return number == 0 } -func MigrateDatabase() { +func setupMinimalDatabase(tx *sql.Tx, version string) error { + cmd := ` +CREATE TABLE metadata ( + key TEXT PRIMARY KEY, + value TEXT +); +INSERT INTO metadata + (key, value) +VALUES + ('version', ?); +` + _, err := tx.Exec(cmd, version) + return err +} + +func MigrateDatabase(version string) { err := Transaction(func(tx *sql.Tx) error { if isDatabaseEmpty(tx) { log.Println("Starting with empty database") + err := setupMinimalDatabase(tx, version) + if err != nil { + log.Fatalf("Failed to setup minimal database schema: %v", err) + } } query, err := GetSql(`migrate`) -- cgit v1.2.3-70-g09d2