Your Question

func Connect(cfg *Config) (db *gorm.DB, err error) {
    dsn := fmt.Sprintf(
        "host=%s user=%s password=%s dbname=%s port=%d sslmode=disable TimeZone=%s",
        cfg.Host,
        cfg.DBUser,
        cfg.DBPassword,
        cfg.DBName,
        cfg.Port,
        cfg.Timezone,
    )
    return gorm.Open(postgres.Open(dsn), &gorm.Config{})
}

func TestDB(t *testing.T) {
    t.Log("setup DB")
    cfg, err := LoadConfig(Test)
    if err != nil {
        t.Fatal(err)
    }
    t.Logf("config: %#v", cfg)

    db, err := Connect(cfg)
    if err != nil {
        t.Fatal(err)
    }

    current := db.Migrator().CurrentDatabase()
    t.Log(current)
}

result is:

=== RUN   TestDB
    db_test.go:53: setup DB
    db_test.go:58: config: &database.Config{Host:"localhost", Port:5432, DBName:"test", DBUser:"postgres", DBPassword:"", Timezone:"Europe/Moscow"}
    db_test.go:65: postgres
                   ~~~~~~~~
--- PASS: TestDB (0.02s)
PASS

database "test" is already created in postgres

I'm using Postgres App 12 for macos

If I do the same from, for example, Python - everything works as expected

How can I fix this?

The document you expected this should be explained

Expected answer

Comment From: townsymush

I'm not sure I understand your question.

Are you saying that the connection type should not be postgres?? I don't know how it could be doing anything other than connecting to postgres if you are specifying this in your Connect method

return gorm.Open(postgres.Open(dsn), &gorm.Config{})

Comment From: ttrubel

I guess @h1ght1me meant that gorm connects to the default "postgres" database instead of "test" one specified in config, it ignores dbname param.

I also had the same problem, solved it using connection URL

Comment From: townsymush

Ah okay that makes more sense

Comment From: corest

Using

        gorm.io/driver/postgres v1.3.6
        gorm.io/gorm v1.23.5

and running into the same issue

Comment From: hfdzz

I found this issue still open and thought I would like to share my findings. For me, the issue was an empty password, which caused the DSN to be read incorrectly. I solved this by wrapping the password in single quote ' to ensure that empty string is read properly. Here’s the code that worked for me: dsn := fmt.Sprintf("host=%s user=%s password='%s' dbname=%s port=%s sslmode=disable", dbHost, dbUser, dbPassword, dbName, dbPort)