Refactor db open to helper func

This commit is contained in:
Tim Van Baak 2025-01-23 08:36:25 -08:00
parent cb161b4f91
commit 4355a79ec0
5 changed files with 28 additions and 26 deletions

View File

@ -43,13 +43,7 @@ func feed() {
log.Fatal(err)
}
db, err := core.OpenDb(getDbPath())
if err != nil {
log.Fatalf("error: failed to open %s", dbPath)
}
core.InitDatabase(db)
core.MigrateDatabase(db)
db := openAndMigrateDb()
var items []core.Item
if feedSource != "" {

View File

@ -57,15 +57,9 @@ func itemAdd() {
addId = hex.EncodeToString(bytes)
}
db, err := core.OpenDb(getDbPath())
if err != nil {
log.Fatalf("Failed to open %s", dbPath)
}
db := openAndMigrateDb()
core.InitDatabase(db)
core.MigrateDatabase(db)
err = core.AddItem(db, addSource, addId, addTitle, addAuthor, addBody, addLink, addTime)
err := core.AddItem(db, addSource, addId, addTitle, addAuthor, addBody, addLink, addTime)
if err != nil {
log.Fatalf("Failed to add item: %s", err)
}

View File

@ -34,13 +34,7 @@ func init() {
}
func itemDeactivate() {
db, err := core.OpenDb(getDbPath())
if err != nil {
log.Fatalf("Failed to open %s", dbPath)
}
core.InitDatabase(db)
core.MigrateDatabase(db)
db := openAndMigrateDb()
active, err := core.DeactivateItem(db, deacSource, deacItem)
if err != nil {

View File

@ -29,10 +29,7 @@ func init() {
}
func migrate() {
db, err := core.OpenDb(getDbPath())
if err != nil {
log.Fatal(err)
}
db := openDb()
core.InitDatabase(db)
if migrateListOnly {

View File

@ -2,8 +2,10 @@ package cmd
import (
"fmt"
"log"
"os"
"github.com/Jaculabilis/intake/core"
"github.com/spf13/cobra"
)
@ -42,3 +44,24 @@ func getDbPath() string {
os.Exit(1)
return ""
}
// Attempt to open the specified database and exit with an error if it fails.
func openDb() *core.DB {
db, err := core.OpenDb(getDbPath())
if err != nil {
log.Fatalf("error: Failed to open %s", dbPath)
}
return db
}
// Attempt to open and migrate the specified database and exit with an error if it fails.
func openAndMigrateDb() *core.DB {
db := openDb()
if err := core.InitDatabase(db); err != nil {
log.Fatalf("error: Failed to init database: %v", err)
}
if err := core.MigrateDatabase(db); err != nil {
log.Fatalf("error: Failed to migrate database: %v", err)
}
return db
}