[GORM FAQs] GORM FAQs

Gorm FAQs

Gorm is the fantastic ORM library for Golang aims to be developer friendly.

unsupported data type: &[]

Use pq.StringArray instead of []string to tore string array.

Error:

1
2
3
type User struct {
Tags []string // [error] unsupported data type: &[]
}

Good:

1
2
3
type User struct {
Tags pq.StringArray `gorm:"type:text[]"`
}

cannot convert x to Text

1
x may be 0, 1, 2...

This is caused by the combination of pgx internally using prepared statements and PostgreSQL not being able to determine the type of the placeholders. The simplest solution is to include type information with your placeholders. e.g. $1::int.

Alternatively, you could configure pgx to use the simple protocol instead of prepared statements.

1
2
3
4
5
// https://github.com/go-gorm/postgres
db, err := gorm.Open(postgres.New(postgres.Config{
DSN: "user=gorm password=gorm dbname=gorm port=9920 sslmode=disable TimeZone=Asia/Shanghai",
PreferSimpleProtocol: true, // disables implicit prepared statement usage
}), &gorm.Config{})

“cannot convert 1 to Text” · Issue #798 · jackc/pgx · GitHub - https://github.com/jackc/pgx/issues/798

invalid value, should be pointer to struct or slice

Error:

1
2
var object *Object
result := db.Where(params).Limit(1).Find(object) // invalid value, should be pointer to struct or slice

Good:

1
2
var object Object
result := db.Where(params).Limit(1).Find(&object)

panic: reflect: reflect.Value.Set using unaddressable value

1
2
3
4
5
6

var users []*User
# var users []User

- result := db.Find(users)
+ result := db.Find(&users)

References

[1] GitHub - go-gorm/gorm: The fantastic ORM library for Golang, aims to be developer friendly - https://github.com/go-gorm/gorm

[2] GORM - The fantastic ORM library for Golang, aims to be developer friendly. - https://gorm.io/

[3] GitHub - jackc/pgx: PostgreSQL driver and toolkit for Go - https://github.com/jackc/pgx

[4] pgx · pkg.go.dev - https://pkg.go.dev/github.com/jackc/pgx/v4

[5] Connecting to a Database | GORM - The fantastic ORM library for Golang, aims to be developer friendly. - https://gorm.io/docs/connecting_to_the_database.html