I tried the following:
type Role string
const (
Customer Role = "CUSTOMER"
Instructor Role = "INSTRUCTOR"
Admin Role = "ADMIN"
SuperAdmin Role = "SUPERADMIN"
)
type User struct {
Id int64
Email string
Role Role //Falls over if not string
}
I kept getting the error below:
goroutine 38 [runnable]:
github.com/jinzhu/gorm.(*safeMap).Set(0xc210043ef0, 0x8598e0, 0x2, 0xc210000a08, 0x2)
/home/lee/Code/gocode/src/github.com/jinzhu/gorm/utils.go:17
created by github.com/jinzhu/gorm.toSnake
/home/lee/Code/gocode/src/github.com/jinzhu/gorm/utils.go:50 +0x219
Is it not possible to support custom primitives, and if not, is it possible to give a more detailed error message, it was difficult to try and work out what was wrong from that error message.
You need to implement a Scanner interface for the new type, then database driver could know how to store the data to database. http://golang.org/pkg/database/sql/#Scanner
Thanks
On Sun, Jan 5, 2014 at 3:57 PM, Jinzhu [email protected] wrote:
Closed #47 https://github.com/jinzhu/gorm/issues/47.
—
Reply to this email directly or view it on GitHubhttps://github.com/jinzhu/gorm/issues/47
.
func (role Role) Value() (driver.Value, error) {
return string(role), nil
}
func (role *Role) Scan(value interface{}) error {
*role = Role(string(value))
}
import database/sql/driver
func (role Role) Value() (driver.Value, error) {
return string(role), nil
}
func (role *Role) Scan(value interface{}) error {
value,_ = value.(string)
*role = Role(string(value))
}
More Complete
It only works in golang, but in postgresql the role column is still defined as a text when I run db.CreateTable(&User{})
Then I tried to define the custom type for role column
type User struct {
Id int64
Email string
Role Role `gorm:"type:role"`
}
This time an error will be thrown: pq: type "role" does not exist
Did I implement the wrong way or gorm haven't covered mapping custom type between golang and postgresql?
@qmn1711 you should provide a correct data type for gorm
type User struct {
Id int64
Email string
Role Role `gorm:"type:VARCHAR"`
}
assume as your Role valuer return string
Most helpful comment
func (role Role) Value() (driver.Value, error) {
return string(role), nil
}
func (role *Role) Scan(value interface{}) error {
*role = Role(string(value))
}