Custom enum type sql
Closed this issue · 0 comments
GGXXLL commented
Your Question
In the following code, if you delete StatusEnum.String
, the generate sql will be status="1"
instead of status=1
.
What happened?
package db_test
import (
"testing"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type StatusEnum int64
const (
StatusEnumEnable StatusEnum = iota
StatusEnumDisable
)
var StatusEnumMap = map[StatusEnum]string{
StatusEnumEnable: "Enable",
StatusEnumDisable: "Disable",
}
func (e StatusEnum) String() string {
if v, ok := StatusEnumMap[e]; ok {
return v
}
return "unknown"
}
type module struct {
Status StatusEnum
}
func TestEnum(t *testing.T) {
db, _ := gorm.Open(sqlite.Open(":memory:"))
db.AutoMigrate(&module{})
db.Model(&module{}).Create(&module{Status: StatusEnumDisable})
var out *module
// SELECT * FROM `modules` WHERE status=1 ORDER BY `modules`.`status` LIMIT 1
db.Debug().Model(&module{}).Where("status=?", StatusEnumDisable).First(&out)
t.Log(out)
t.Logf("status value: %d, status string: %s", out.Status, out.Status)
}