Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: db nil error during initiation #1423

Merged
merged 2 commits into from
May 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading