Skip to content

Postgres Automigrate Issue for Conn: sqlDB #7675

@lesichkovm

Description

@lesichkovm

Description

gorm.Open(postgres.New(postgres.Config{
			Conn:       sqlDB,
}), &gorm.Config{Logger: gormLogger})

Throws an error during Automigrate at GetRows

return m.DB.Session(&gorm.Session{}).Table(name).Limit(1).Scopes(func(d *gorm.DB) *gorm.DB {
		dialector, _ := m.Dialector.(Dialector)
		// use simple protocol
		if !m.DB.PrepareStmt && (dialector.Config != nil && (dialector.Config.DriverName == "" || dialector.Config.DriverName == "pgx")) {
			d.Statement.Vars = append([]interface{}{pgx.QueryExecModeSimpleProtocol}, d.Statement.Vars...)
		}
		return d
	}).Rows()

Temporary fix:

gorm.Open(postgres.New(postgres.Config{
			Conn:       sqlDB,
			DriverName: "postgres",
}), &gorm.Config{Logger: gormLogger})

According to AI:

In gorm.io/driver/postgres, Config.DriverName is used by the dialector/migrator to decide whether it can apply pgx-specific behavior (like injecting pgx.QueryExecModeSimpleProtocol into Statement.Vars). When you pass an existing *sql.DB that’s actually lib/pq, leaving DriverName empty makes GORM assume “pgx-ish” defaults and you hit that bug.

So for Postgres, if you reuse an existing *sql.DB, it’s a good idea to always set:

DriverName: "postgres" for lib/pq
DriverName: "pgx" only if the underlying driver is actually pgx
For MySQL / SQLite
MySQL (gorm.io/driver/mysql): there isn’t an equivalent pgx-vs-pq switch. If your *sql.DB is opened by github.com/go-sql-driver/mysql, you don’t need (and generally can’t use) a similar DriverName field in the same way.
SQLite (gorm.io/driver/sqlite): same story—no pgx-style protocol mode decisions.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions