/
string_array.go
81 lines (73 loc) · 1.6 KB
/
string_array.go
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package datatype
import (
"context"
"database/sql/driver"
"encoding/json"
"errors"
"fmt"
"github.com/lib/pq"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"gorm.io/gorm/schema"
)
type StringArray []string
// GormDataType gorm common data type
func (StringArray) GormDataType() string {
return "string_array"
}
// GormDBDataType gorm db data type
func (StringArray) GormDBDataType(db *gorm.DB, field *schema.Field) string {
switch db.Dialector.Name() {
case "postgres":
return "text[]"
default:
return "JSON"
}
}
// Value return json value, implement driver.Valuer interface
func (j StringArray) Value() (driver.Value, error) {
return json.Marshal(j)
}
func (j StringArray) GormValue(ctx context.Context, db *gorm.DB) clause.Expr {
switch db.Dialector.Name() {
case "postgres":
return gorm.Expr("?", pq.StringArray(j))
default:
data, err := json.Marshal(j)
if err != nil {
db.Error = err
}
return gorm.Expr("?", string(data))
}
}
// implements sql.Scanner interface
func (j *StringArray) Scan(value interface{}) error {
var bytes []byte
switch v := value.(type) {
case []byte:
bytes = v
case string:
bytes = []byte(v)
default:
return errors.New(fmt.Sprint("Failed to unmarshal string array value:", value))
}
if len(bytes) == 0 {
*j = nil
return nil
}
if bytes[0] == '[' {
err := json.Unmarshal(bytes, j)
return err
}
if bytes[0] == '{' {
// Unmarshal as Postgres text array
var a pq.StringArray
err := a.Scan(value)
if err != nil {
return err
}
*j = StringArray(a)
return nil
}
return errors.New(fmt.Sprint("Failed to unmarshal string array value:", value))
}