From 7b327c7d91a2d00b522ba896aa94f9d5768b2737 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Urban?= Date: Wed, 11 Oct 2023 17:59:52 +0200 Subject: [PATCH] fix(backend): set default db name --- backend/internal/database/database.go | 53 ++++++--------------------- 1 file changed, 12 insertions(+), 41 deletions(-) diff --git a/backend/internal/database/database.go b/backend/internal/database/database.go index 0d1da89..c684288 100644 --- a/backend/internal/database/database.go +++ b/backend/internal/database/database.go @@ -23,37 +23,13 @@ func InitializeDatabase() (*gorm.DB, error) { var dsn string var db *gorm.DB - switch dbType { - case "mysql": - dbHost, err := util.GetEnvOrError("DB_HOST") - if err != nil { - return nil, err - } - - dbPort, err := util.GetEnvOrError("DB_PORT") - if err != nil { - return nil, err - } - - dbUser, err := util.GetEnvOrError("DB_USER") - if err != nil { - return nil, err - } - - dbPassword, err := util.GetEnvOrError("DB_PASSWORD") - if err != nil { - return nil, err - } - - dbName, err := util.GetEnvOrDefault("DB_NAME", "kubevoyage") - if err != nil { - return nil, err - } - - dsn = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", dbUser, dbPassword, dbHost, dbPort, dbName) - db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{}) + dbName, err := util.GetEnvOrDefault("DB_NAME", "kubevoyage") + if err != nil { + return nil, err + } - case "postgres": + switch dbType { + case "mysql", "postgres": dbHost, err := util.GetEnvOrError("DB_HOST") if err != nil { return nil, err @@ -74,20 +50,15 @@ func InitializeDatabase() (*gorm.DB, error) { return nil, err } - dbName, err := util.GetEnvOrDefault("DB_NAME", "kubevoyage") - if err != nil { - return nil, err + if dbType == "mysql" { + dsn = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", dbUser, dbPassword, dbHost, dbPort, dbName) + db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{}) + } else { + dsn = fmt.Sprintf("host=%s port=%s user=%s dbname=%s password=%s sslmode=disable", dbHost, dbPort, dbUser, dbName, dbPassword) + db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{}) } - dsn = fmt.Sprintf("host=%s port=%s user=%s dbname=%s password=%s sslmode=disable", dbHost, dbPort, dbUser, dbName, dbPassword) - db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{}) - case "sqlite": - dbName, err := util.GetEnvOrDefault("DB_NAME", "kubevoyage") - if err != nil { - return nil, err - } - dsn = dbName // For SQLite, dbName would be the path to the .db file db, err = gorm.Open(sqlite.Open(dsn), &gorm.Config{})