diff options
author | xengineering <me@xengineering.eu> | 2024-05-09 21:31:19 +0200 |
---|---|---|
committer | xengineering <me@xengineering.eu> | 2024-05-09 21:31:19 +0200 |
commit | ca19c73b305932a4ef41d31787eabb25f9417a05 (patch) | |
tree | c35a6855053c8f4f6cfec05c154f6e9bfb3a1d9a /model/database.go | |
parent | 2db08f564ddb38e80c79c9338047f4e8f3a977e8 (diff) | |
download | ceres-ca19c73b305932a4ef41d31787eabb25f9417a05.tar ceres-ca19c73b305932a4ef41d31787eabb25f9417a05.tar.zst ceres-ca19c73b305932a4ef41d31787eabb25f9417a05.zip |
model: Detect if database is empty
An empty database requires to add the metadata table with the version
entry to make migrations possible. Thus this detection will be required.
Diffstat (limited to 'model/database.go')
-rw-r--r-- | model/database.go | 25 |
1 files changed, 25 insertions, 0 deletions
diff --git a/model/database.go b/model/database.go index 3953c92..16a6cea 100644 --- a/model/database.go +++ b/model/database.go @@ -57,8 +57,33 @@ func Transaction(f func(*sql.Tx) error) error { return tx.Commit() } +func isDatabaseEmpty(tx *sql.Tx) bool { + cmd := `SELECT COUNT(*) FROM sqlite_master WHERE type='table'` + rows, err := tx.Query(cmd) + if err != nil { + log.Fatal(err) + } + defer rows.Close() + + if !rows.Next() { + log.Fatalf("No rows on request of database table number") + } + + var number int + err = rows.Scan(&number) + if err != nil { + log.Fatalf("Failed to scan number of database tables to integer") + } + + return number == 0 +} + func MigrateDatabase() { err := Transaction(func(tx *sql.Tx) error { + if isDatabaseEmpty(tx) { + log.Println("Starting with empty database") + } + query, err := GetSql(`migrate`) if err != nil { log.Fatal(err) |