Skip to content
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
15 changes: 15 additions & 0 deletions internal/infrastructure/persistence/gorm/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,23 @@ type Config struct {
SSLMode string
}

// Validate checks that the configuration is valid for the specified driver.
// For postgres and mysql drivers, username must not be empty.
func (c Config) Validate() error {
switch c.Driver {
case "postgres", "mysql":
if c.Username == "" {
return fmt.Errorf("username is required for %s driver", c.Driver)
}
}
return nil
}

// NewDB creates a new GORM database connection based on the configuration.
func NewDB(cfg Config) *gorm.DB {
if err := cfg.Validate(); err != nil {
panic(err)
}
driver := cfg.Driver
switch driver {
case "postgres":
Expand Down
81 changes: 81 additions & 0 deletions internal/infrastructure/persistence/gorm/db_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package gorm

import (
"testing"
)

func TestConfigValidate(t *testing.T) {
tests := []struct {
name string
config Config
wantErr bool
}{
{
name: "postgres with username",
config: Config{
Driver: "postgres",
Host: "localhost",
Port: 5432,
Username: "testuser",
Password: "testpass",
DbName: "testdb",
SSLMode: "disable",
},
wantErr: false,
},
{
name: "postgres without username",
config: Config{
Driver: "postgres",
Host: "localhost",
Port: 5432,
Username: "",
Password: "testpass",
DbName: "testdb",
SSLMode: "disable",
},
wantErr: true,
},
{
name: "mysql with username",
config: Config{
Driver: "mysql",
Host: "localhost",
Port: 3306,
Username: "testuser",
Password: "testpass",
DbName: "testdb",
},
wantErr: false,
},
{
name: "mysql without username",
config: Config{
Driver: "mysql",
Host: "localhost",
Port: 3306,
Username: "",
Password: "testpass",
DbName: "testdb",
},
wantErr: true,
},
{
name: "sqlite without username (allowed)",
config: Config{
Driver: "sqlite",
DbName: "test.db",
},
wantErr: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := tt.config.Validate()
if (err != nil) != tt.wantErr {
t.Errorf("Config.Validate() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}