package dts import ( "context" "database/sql/driver" "encoding/json" "errors" "fmt" "gorm.io/gorm" "gorm.io/gorm/clause" "gorm.io/gorm/schema" "zestack.dev/is" ) // Color 颜色,仅支持16进制 type Color string // Set 设置颜色值 func (c *Color) Set(s string) bool { if s == "" || is.HEXColor(s) { *c = Color(s) return true } return false } func (c Color) Value() (driver.Value, error) { if len(c) == 0 { return nil, nil } return string(c), nil } func (c *Color) Scan(value any) error { if value == nil { *c = "" return nil } var ok bool switch v := value.(type) { case []byte: ok = c.Set(string(v)) case string: ok = c.Set(v) } if !ok { return errors.New(fmt.Sprint("failed to unmarshal value:", value)) } return nil } func (c Color) MarshalJSON() ([]byte, error) { return json.Marshal(string(c)) } func (c *Color) UnmarshalJSON(b []byte) error { var str string err := json.Unmarshal(b, &str) if err != nil { return err } if !c.Set(str) { return errors.New("failed to unmarshal value") } return nil } func (c Color) String() string { return string(c) } // GormDBDataType gorm db data type func (Color) GormDBDataType(db *gorm.DB, field *schema.Field) string { return "varchar(7)" } func (c Color) GormValue(ctx context.Context, db *gorm.DB) clause.Expr { if len(c) == 0 { return gorm.Expr("NULL") } data, _ := c.MarshalJSON() return gorm.Expr("?", string(data)) }