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) log.Fatal(err)
} }
db, err := core.OpenDb(getDbPath()) db := openAndMigrateDb()
if err != nil {
log.Fatalf("error: failed to open %s", dbPath)
}
core.InitDatabase(db)
core.MigrateDatabase(db)
var items []core.Item var items []core.Item
if feedSource != "" { if feedSource != "" {

View File

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

View File

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

View File

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

View File

@ -2,8 +2,10 @@ package cmd
import ( import (
"fmt" "fmt"
"log"
"os" "os"
"github.com/Jaculabilis/intake/core"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -42,3 +44,24 @@ func getDbPath() string {
os.Exit(1) os.Exit(1)
return "" 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
}