You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ims/util/db/dts/color.go

84 lines
1.4 KiB

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))
}