From 72601b87ef040a3c6882368ac85c12c1ae705cd2 Mon Sep 17 00:00:00 2001 From: xengineering Date: Mon, 21 Oct 2024 21:30:12 +0200 Subject: model: Refactor public API of DB This commit makes not externally needed methods private and adds error return values since something like log.Fatal() should be called outside this package since it is control-flow-related. --- model/database.go | 34 +++++++++++++--------------------- 1 file changed, 13 insertions(+), 21 deletions(-) (limited to 'model') 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() } -- cgit v1.2.3-70-g09d2