summaryrefslogtreecommitdiff
path: root/model/database.go
diff options
context:
space:
mode:
Diffstat (limited to 'model/database.go')
-rw-r--r--model/database.go34
1 files changed, 13 insertions, 21 deletions
diff --git a/model/database.go b/model/database.go
index 84ed497..f3fb607 100644
--- a/model/database.go
+++ b/model/database.go
@@ -11,18 +11,18 @@ import (
type DB sql.DB
-func OpenDB(path string) *DB {
+func OpenDB(path string) (*DB, error) {
db, err := sql.Open("sqlite3", path)
if err != nil {
- log.Fatal(err)
+ return nil, fmt.Errorf("Failed to open SQLite3 database: %w", err)
}
err = db.Ping()
if err != nil {
- log.Fatal(err)
+ return nil, fmt.Errorf("Failed to ping SQLite3 database: %w", err)
}
- return (*DB)(db)
+ return (*DB)(db), nil
}
func (db *DB) Transaction(f func(*sql.Tx) error) error {
@@ -46,7 +46,7 @@ func (db *DB) Transaction(f func(*sql.Tx) error) error {
return tx.Commit()
}
-func (db *DB) IsEmpty(tx *sql.Tx) (bool, error) {
+func (db *DB) isEmpty(tx *sql.Tx) (bool, error) {
cmd := `SELECT COUNT(*) FROM sqlite_master WHERE type='table'`
rows, err := tx.Query(cmd)
if err != nil {
@@ -67,8 +67,8 @@ func (db *DB) IsEmpty(tx *sql.Tx) (bool, error) {
return number == 0, nil
}
-func (db *DB) SchemaVersion(tx *sql.Tx) (int, error) {
- empty, err := db.IsEmpty(tx)
+func (db *DB) schemaVersion(tx *sql.Tx) (int, error) {
+ empty, err := db.isEmpty(tx)
if err != nil {
return 0, fmt.Errorf("Failed to check if DB is empty: %w", err)
}
@@ -142,7 +142,7 @@ func (db *DB) Migrate() error {
var version int
for index, migration := range migrations {
var err error
- version, err = db.SchemaVersion(tx)
+ version, err = db.schemaVersion(tx)
if err != nil {
return fmt.Errorf("Failed to get DB schema version: %w", err)
}
@@ -155,7 +155,7 @@ func (db *DB) Migrate() error {
}
}
}
- version, err := db.SchemaVersion(tx)
+ version, err := db.schemaVersion(tx)
if err != nil {
return fmt.Errorf("Failed to get DB schema version: %w", err)
}
@@ -168,8 +168,8 @@ func (db *DB) Migrate() error {
})
}
-func (db *DB) CreateExamples() {
- err := db.Transaction(func(tx *sql.Tx) error {
+func (db *DB) CreateExamples() error {
+ return db.Transaction(func(tx *sql.Tx) error {
recipes := RecipeTestData()
for _, recipe := range recipes {
@@ -181,16 +181,8 @@ func (db *DB) CreateExamples() {
return nil
})
- if err != nil {
- log.Fatalf("Failed to inject example recipes: %v", err)
- }
}
-func (db *DB) Close() {
- err := (*sql.DB)(db).Close()
- if err != nil {
- log.Printf("Failed to close database: %v\n", err)
- } else {
- log.Println("Closed database")
- }
+func (db *DB) Close() error {
+ return (*sql.DB)(db).Close()
}