gorm
gorm copied to clipboard
GORM connects to "postgres" db instead of explicitly specified
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
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{})
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
Ah okay that makes more sense
Using
gorm.io/driver/postgres v1.3.6
gorm.io/gorm v1.23.5
and running into the same issue