gorm icon indicating copy to clipboard operation
gorm copied to clipboard

GORM connects to "postgres" db instead of explicitly specified

Open const-tmp opened this issue 2 years ago • 4 comments

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

const-tmp avatar May 02 '22 11:05 const-tmp

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{})

townsymush avatar May 03 '22 14:05 townsymush

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

ttrubel avatar May 04 '22 18:05 ttrubel

Ah okay that makes more sense

townsymush avatar May 06 '22 12:05 townsymush

Using

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

and running into the same issue

corest avatar May 30 '22 16:05 corest