9 "github.com/jinzhu/gorm"
12 func TestScannableSlices(t *testing.T) {
13 if err := DB.AutoMigrate(&RecordWithSlice{}).Error; err != nil {
14 t.Errorf("Should create table with slice values correctly: %s", err)
17 r1 := RecordWithSlice{
18 Strings: ExampleStringSlice{"a", "b", "c"},
19 Structs: ExampleStructSlice{
25 if err := DB.Save(&r1).Error; err != nil {
26 t.Errorf("Should save record with slice values")
29 var r2 RecordWithSlice
31 if err := DB.Find(&r2).Error; err != nil {
32 t.Errorf("Should fetch record with slice values")
35 if len(r2.Strings) != 3 || r2.Strings[0] != "a" || r2.Strings[1] != "b" || r2.Strings[2] != "c" {
36 t.Errorf("Should have serialised and deserialised a string array")
39 if len(r2.Structs) != 2 || r2.Structs[0].Name != "name1" || r2.Structs[0].Value != "value1" || r2.Structs[1].Name != "name2" || r2.Structs[1].Value != "value2" {
40 t.Errorf("Should have serialised and deserialised a struct array")
44 type RecordWithSlice struct {
46 Strings ExampleStringSlice `sql:"type:text"`
47 Structs ExampleStructSlice `sql:"type:text"`
50 type ExampleStringSlice []string
52 func (l ExampleStringSlice) Value() (driver.Value, error) {
53 bytes, err := json.Marshal(l)
54 return string(bytes), err
57 func (l *ExampleStringSlice) Scan(input interface{}) error {
58 switch value := input.(type) {
60 return json.Unmarshal([]byte(value), l)
62 return json.Unmarshal(value, l)
64 return errors.New("not supported")
68 type ExampleStruct struct {
73 type ExampleStructSlice []ExampleStruct
75 func (l ExampleStructSlice) Value() (driver.Value, error) {
76 bytes, err := json.Marshal(l)
77 return string(bytes), err
80 func (l *ExampleStructSlice) Scan(input interface{}) error {
81 switch value := input.(type) {
83 return json.Unmarshal([]byte(value), l)
85 return json.Unmarshal(value, l)
87 return errors.New("not supported")
91 type ScannerDataType struct {
92 Street string `sql:"TYPE:varchar(24)"`
95 func (ScannerDataType) Value() (driver.Value, error) {
99 func (*ScannerDataType) Scan(input interface{}) error {
103 type ScannerDataTypeTestStruct struct {
105 ScannerDataType *ScannerDataType `sql:"TYPE:json"`
108 type ScannerDataType2 struct {
109 Street string `sql:"TYPE:varchar(24)"`
112 func (ScannerDataType2) Value() (driver.Value, error) {
116 func (*ScannerDataType2) Scan(input interface{}) error {
120 type ScannerDataTypeTestStruct2 struct {
122 ScannerDataType *ScannerDataType2
125 func TestScannerDataType(t *testing.T) {
126 scope := gorm.Scope{Value: &ScannerDataTypeTestStruct{}}
127 if field, ok := scope.FieldByName("ScannerDataType"); ok {
128 if DB.Dialect().DataTypeOf(field.StructField) != "json" {
129 t.Errorf("data type for scanner is wrong")
133 scope = gorm.Scope{Value: &ScannerDataTypeTestStruct2{}}
134 if field, ok := scope.FieldByName("ScannerDataType"); ok {
135 if DB.Dialect().DataTypeOf(field.StructField) != "varchar(24)" {
136 t.Errorf("data type for scanner is wrong")