Skip to content

Commit

Permalink
Merge pull request #1423 from AvineshTripathi/fix-db-init
Browse files Browse the repository at this point in the history
fix: db nil error during initiation
  • Loading branch information
Azanul authored May 21, 2024
2 parents 0da0ecd + a54a516 commit e1cb5f1
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 8 deletions.
2 changes: 1 addition & 1 deletion internal/internal.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func Exec(address string, port int, configPath string, telemetry bool, a utils.A
return err
}

err = utils.SetupDBConnection(cfg, db)
db, err = utils.SetupDBConnection(cfg)
if err != nil {
return err
}
Expand Down
2 changes: 1 addition & 1 deletion internal/resources_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func BenchmarkFetchResources(b *testing.B) {
if err != nil {
b.Fatalf("Error during config setup: %v", err)
}
err = utils.SetupDBConnection(cfg, db)
db, err = utils.SetupDBConnection(cfg)
if err != nil {
b.Fatalf("Error during DB setup: %v", err)
}
Expand Down
13 changes: 7 additions & 6 deletions utils/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,33 +16,34 @@ import (
"github.com/uptrace/bun/migrate"
)

func SetupDBConnection(c *models.Config, db *bun.DB) error {
func SetupDBConnection(c *models.Config) (*bun.DB, error) {
var sqldb *sql.DB
var err error
var db *bun.DB

if len(c.SQLite.File) == 0 && len(c.Postgres.URI) == 0 {
log.Println("Database wasn't configured yet")
return nil
return nil, nil
}

if len(c.SQLite.File) > 0 {
sqldb, err = sql.Open(sqliteshim.ShimName, fmt.Sprintf("file:%s?cache=shared", c.SQLite.File))
if err != nil {
return err
return nil, err
}
sqldb.SetMaxIdleConns(1000)
sqldb.SetConnMaxLifetime(0)

*db = *bun.NewDB(sqldb, sqlitedialect.New())
db = bun.NewDB(sqldb, sqlitedialect.New())

log.Println("Data will be stored in SQLite")
} else {
sqldb = sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(c.Postgres.URI)))
*db = *bun.NewDB(sqldb, pgdialect.New())
db = bun.NewDB(sqldb, pgdialect.New())
log.Println("Data will be stored in PostgreSQL")
}

return nil
return db, nil
}

func SetupSchema(db *bun.DB, c *models.Config, accounts []models.Account) error {
Expand Down

0 comments on commit e1cb5f1

Please sign in to comment.