aboutsummaryrefslogtreecommitdiff
path: root/server/store/string_slice.go
blob: a443cddbd7c9cd7ff10fbfcbe9f792cbfc834609 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package store

import (
	"database/sql/driver"
	"encoding/json"
)

// StringSlice is a []string which will be stored in a database as a JSON array.
type StringSlice []string

var _ driver.Valuer = (*StringSlice)(nil)

// Value implements the driver.Valuer interface, marshalling the raw value to
// a JSON array.
func (s StringSlice) Value() (driver.Value, error) {
	v, err := json.Marshal(s)
	if err != nil {
		return nil, err
	}
	return string(v), err
}

// Scan implements the sql.Scanner interface, unmarshalling the value coming
// off the wire and storing the result in the StringSlice.
func (s *StringSlice) Scan(value interface{}) error {
	if value == nil {
		s = &StringSlice{}
		return nil
	}
	var err error
	v, err := driver.String.ConvertValue(value)
	if err == nil {
		if v, ok := v.([]byte); ok {
			err = json.Unmarshal(v, s)
		}
	}
	return err
}