From 0e8a199d6144fcfab05eb0c8a793073bc53783be Mon Sep 17 00:00:00 2001 From: xengineering Date: Thu, 9 May 2024 22:04:06 +0200 Subject: model: Require same version for executable and DB Currently only an empty database and an existing database with the same version are supported. Support for migrations based on semantic versioning will be added in future versions of Ceres. --- model/database.go | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) (limited to 'model') diff --git a/model/database.go b/model/database.go index 8e002d6..b6e64bb 100644 --- a/model/database.go +++ b/model/database.go @@ -93,6 +93,26 @@ VALUES return err } +func getDatabaseVersion(tx *sql.Tx) string { + rows, err := tx.Query(`SELECT value FROM metadata WHERE key='version';`) + if err != nil { + log.Fatal(err) + } + defer rows.Close() + + if !rows.Next() { + log.Fatalf("No rows on request of database version") + } + + var version string + err = rows.Scan(&version) + if err != nil { + log.Fatalf("Failed to scan database version to string") + } + + return version +} + func MigrateDatabase(version string) { err := Transaction(func(tx *sql.Tx) error { if isDatabaseEmpty(tx) { @@ -113,6 +133,15 @@ func MigrateDatabase(version string) { } } + dbVersion := getDatabaseVersion(tx) + if dbVersion != version { + log.Fatalf( + "Database version '%s' does not match executable version '%s'", + dbVersion, + version, + ) + } + return nil }) if err != nil { -- cgit v1.2.3-70-g09d2