Skip to content

Commit

Permalink
add the string slice type
Browse files Browse the repository at this point in the history
  • Loading branch information
xgfone committed Sep 24, 2024
1 parent 38e61ab commit dcf2b9e
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions model.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ import (
"time"
)

// SliceSep is used to combine a string slice to a string.
const SliceSep = ","

const (
// DateZero is the ZERO of the sql date.
DateZero = "0000-00-00"
Expand All @@ -43,6 +46,19 @@ type Base struct {
DeletedAt time.Time `sql:"deleted_at,omitempty" json:"-"`
}

// String is a string slice value type, which is encoded to a string or decoded from a []byte or string.
type Strings []string

// Value implements the interface driver.Valuer to encode the map to a sql value(string).
func (vs Strings) Value() (driver.Value, error) {
return strings.Join(vs, ","), nil
}

// Scan implements the interface sql.Scanner to scan a sql value to the map.
func (vs *Strings) Scan(src any) error {
return decodestrings((*[]string)(vs), src, SliceSep)
}

// Map is a map value type, which is encoded to a string or decoded from a []byte or string.
type Map[T any] map[string]T

Expand Down Expand Up @@ -99,6 +115,19 @@ func decodemap[M ~map[string]T, T any](m *M, src any) (err error) {
return
}

func decodestrings(vs *[]string, src any, sep string) (err error) {
switch data := src.(type) {
case nil:
case []byte:
*vs = strings.Split(string(data), sep)
case string:
*vs = strings.Split(data, sep)
default:
err = fmt.Errorf("converting %T to []string is unsupported", src)
}
return
}

var (
_jsonbraces = []byte("{}")
_jsonnull = []byte("null")
Expand Down

0 comments on commit dcf2b9e

Please sign in to comment.