forked from go-gorm/gorm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata_type.go
56 lines (49 loc) · 1.17 KB
/
data_type.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
package gorm
import (
"database/sql"
"database/sql/driver"
"encoding/json"
"fmt"
"reflect"
)
// Array returns the optimal driver.Valuer and sql.Scanner for an array or
// slice of any dimension.
func Array(a interface{}) interface {
driver.Valuer
sql.Scanner
} {
return &Generic{a}
}
func Any(a interface{}) interface {
driver.Valuer
sql.Scanner
} {
return &Generic{a}
}
// Generic implements the driver.Valuer and sql.Scanner interfaces for
// an array or slice of any dimension.
type Generic struct{ A interface{} }
// Scan implements the sql.Scanner interface.
func (a *Generic) Scan(src interface{}) error {
if a == nil {
return fmt.Errorf("GenericStruct.Scan: %s", "a is nil")
}
if src == nil {
return nil
}
dpv := reflect.ValueOf(a.A)
switch {
case dpv.Kind() != reflect.Ptr:
return fmt.Errorf("pq: destination %T is not a pointer to array or slice", a.A)
case dpv.IsNil():
return fmt.Errorf("pq: destination %T is nil", a.A)
}
return json.Unmarshal(reflect.ValueOf(src).Bytes(), a.A)
}
// Value implements the driver.Valuer interface.
func (a Generic) Value() (driver.Value, error) {
if a.A == nil {
return nil, nil
}
return json.Marshal(a.A)
}