From 9d0135f7c72df5b45612cdeb584461d4597bfa03 Mon Sep 17 00:00:00 2001 From: AvineshTripathi Date: Fri, 17 May 2024 01:52:44 +0530 Subject: [PATCH] fix: db nil error during initiation --- internal/internal.go | 2 +- internal/resources_test.go | 2 +- utils/database.go | 13 +++++++------ 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/internal/internal.go b/internal/internal.go index 30cc4805e..64288a8cc 100644 --- a/internal/internal.go +++ b/internal/internal.go @@ -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 } diff --git a/internal/resources_test.go b/internal/resources_test.go index c9bdf4cd6..dbd3af9c0 100644 --- a/internal/resources_test.go +++ b/internal/resources_test.go @@ -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) } diff --git a/utils/database.go b/utils/database.go index ecea30704..79d95b129 100644 --- a/utils/database.go +++ b/utils/database.go @@ -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 {