From ca19c73b305932a4ef41d31787eabb25f9417a05 Mon Sep 17 00:00:00 2001 From: xengineering Date: Thu, 9 May 2024 21:31:19 +0200 Subject: 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. --- model/database.go | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) 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) -- cgit v1.2.3-70-g09d2