diff options
| author | xengineering <me@xengineering.eu> | 2026-05-31 21:34:44 +0200 |
|---|---|---|
| committer | xengineering <me@xengineering.eu> | 2026-05-31 21:37:16 +0200 |
| commit | 29ae857b5ca13fa12f1d07d4a30597ff9ce28767 (patch) | |
| tree | 8ae97fc41d2e0724d29f88fe8ddbb65b482c13d2 | |
| parent | efb324070827bd1fe713b93f80c601551d246579 (diff) | |
| download | finserv-29ae857b5ca13fa12f1d07d4a30597ff9ce28767.tar finserv-29ae857b5ca13fa12f1d07d4a30597ff9ce28767.tar.zst finserv-29ae857b5ca13fa12f1d07d4a30597ff9ce28767.zip | |
Add UserVersion()
This function gets the user_version SQLite3 field describing which
migration was the last executed one.
A test checking this before applying any migrations and after each
migration is included.
| -rw-r--r-- | database.go | 13 | ||||
| -rw-r--r-- | database_test.go | 33 |
2 files changed, 37 insertions, 9 deletions
diff --git a/database.go b/database.go index c71ff78..44a172d 100644 --- a/database.go +++ b/database.go @@ -66,3 +66,16 @@ func Migrate(db *sql.DB, index int) error { return err }) } + +func UserVersion(db *sql.DB) (int, error) { + var version int + + err := Transaction(db, func(tx *sql.Tx) error { + return tx.QueryRow(`PRAGMA user_version`).Scan(&version) + }) + if err != nil { + return 0, err + } + + return version, nil +} diff --git a/database_test.go b/database_test.go index b412af0..901db42 100644 --- a/database_test.go +++ b/database_test.go @@ -29,21 +29,21 @@ func TestMigrationContent(t *testing.T) { if !strings.HasPrefix(migration, expectation) { t.Fatalf("Expected '%s' at start of '%s'.", expectation, path) } - - n := strings.Count(migration, `user_version`) - if n != 1 { - t.Fatalf( - "'user_version' was mentioned more than once in %s. "+ - "This is likely not intended.", - path, - ) - } } } func TestMigrations(t *testing.T) { db, _ := emptyDB(t) + userVersion, err := UserVersion(db) + if err != nil { + t.Fatalf("Failed to get initial user_version: %v", err) + } + + if userVersion != 0 { + t.Fatalf("Expected user_version 0 but got %d.", userVersion) + } + for i := range migrations { path := migrationPath(i) t.Logf("Test execution of %s", path) @@ -52,5 +52,20 @@ func TestMigrations(t *testing.T) { if err != nil { t.Fatalf("Failed to execute migration %s: %v", path, err) } + + userVersion, err = UserVersion(db) + if err != nil { + t.Fatalf("Failed to get user_version after migration: %v", err) + } + + expected := i + 1 + if userVersion != expected { + t.Fatalf( + "Expected user_version %d after running %s but got %d.", + expected, + path, + userVersion, + ) + } } } |
