-
-
Notifications
You must be signed in to change notification settings - Fork 110
/
json_type_test.go
218 lines (192 loc) · 6.56 KB
/
json_type_test.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
package datatypes_test
import (
"database/sql/driver"
"testing"
"gorm.io/datatypes"
"gorm.io/gorm"
. "gorm.io/gorm/utils/tests"
)
var _ driver.Valuer = &datatypes.JSONType[[]int]{}
func newJSONType[T any](b []byte) datatypes.JSONType[T] {
var t datatypes.JSONType[T]
_ = t.UnmarshalJSON(b)
return t
}
func TestJSONType(t *testing.T) {
if SupportedDriver("sqlite", "mysql", "postgres") {
type Attribute struct {
Sex int
Age int
Orgs map[string]string
Tags []string
Admin bool
Role string
}
type UserWithJSON struct {
gorm.Model
Name string
Attributes datatypes.JSONType[Attribute]
}
DB.Migrator().DropTable(&UserWithJSON{})
if err := DB.Migrator().AutoMigrate(&UserWithJSON{}); err != nil {
t.Errorf("failed to migrate, got error: %v", err)
}
// Go's json marshaler removes whitespace & orders keys alphabetically
// use to compare against marshaled []byte of datatypes.JSON
user1Attrs := `{"age":18,"name":"json-1","orgs":{"orga":"orga"},"tags":["tag1","tag2"],"admin":true}`
users := []UserWithJSON{{
Name: "json-1",
Attributes: newJSONType[Attribute]([]byte(user1Attrs)),
}, {
Name: "json-2",
Attributes: newJSONType[Attribute]([]byte(`{"name": "json-2", "age": 28, "tags": ["tag1", "tag3"], "role": "admin", "orgs": {"orgb": "orgb"}}`)),
}, {
Name: "json-3",
Attributes: newJSONType[Attribute]([]byte(`{"tags": ["tag1","tag2","tag3"]`)),
}, {
Name: "json-4",
Attributes: datatypes.NewJSONType(Attribute{Tags: []string{"tag1", "tag2", "tag3"}}),
}, {
Name: "json-5",
Attributes: datatypes.NewJSONType(Attribute{Tags: []string{"tag1", "tag2", "tag3"}}),
}}
if err := DB.Create(&users).Error; err != nil {
t.Errorf("Failed to create users %v", err)
}
var result UserWithJSON
if err := DB.First(&result, users[1].ID).Error; err != nil {
t.Fatalf("failed to find user with json key, got error %v", err)
}
AssertEqual(t, result.Name, users[1].Name)
AssertEqual(t, result.Attributes.Data().Age, users[1].Attributes.Data().Age)
AssertEqual(t, result.Attributes.Data().Admin, users[1].Attributes.Data().Admin)
AssertEqual(t, len(result.Attributes.Data().Orgs), len(users[1].Attributes.Data().Orgs))
// List
var users2 []UserWithJSON
if err := DB.Model(&UserWithJSON{}).Limit(10).Order("id asc").Find(&users2).Error; err != nil {
t.Fatalf("failed to select attribute field, got error %v", err)
}
AssertEqual(t, users2[0].Attributes.Data().Age, 18)
// Select Field
var singleUser UserWithJSON
if err := DB.Model(&UserWithJSON{}).Select("attributes").Limit(1).Order("id asc").Find(&singleUser).Error; err != nil {
t.Fatalf("failed to select attribute field, got error %v", err)
}
AssertEqual(t, singleUser.Attributes.Data().Age, 18)
// Pluck
var attr datatypes.JSONType[Attribute]
if err := DB.Model(&UserWithJSON{}).Limit(1).Order("id asc").Pluck("attributes", &attr).Error; err != nil {
t.Fatalf("failed to pluck for field, got error %v", err)
}
var attribute = attr.Data()
AssertEqual(t, attribute.Age, 18)
// Smart Select Fields
var row struct {
Attributes datatypes.JSONType[Attribute]
}
if err := DB.Model(&UserWithJSON{}).Limit(1).Order("id asc").Find(&row).Error; err != nil {
t.Fatalf("failed to select attribute field, got error %v", err)
}
AssertEqual(t, row.Attributes.Data().Age, 18)
// FirstOrCreate
jsonMap := UserWithJSON{
Attributes: newJSONType[Attribute]([]byte(`{"age":19,"name":"json-1","orgs":{"orga":"orga"},"tags":["tag1","tag2"]}`)),
}
if err := DB.Where(&UserWithJSON{Name: "json-1"}).Assign(jsonMap).FirstOrCreate(&UserWithJSON{}).Error; err != nil {
t.Errorf("failed to run FirstOrCreate")
}
// Update
jsonMap = UserWithJSON{
Attributes: datatypes.NewJSONType(
Attribute{
Age: 18,
Sex: 1,
Orgs: map[string]string{"orga": "orga"},
Tags: []string{"tag1", "tag2", "tag3"},
},
),
}
var result3 UserWithJSON
result3.ID = 1
if err := DB.Model(&result3).Updates(jsonMap).Error; err != nil {
t.Errorf("failed to run FirstOrCreate")
}
}
}
func TestJSONSlice(t *testing.T) {
if SupportedDriver("sqlite", "mysql", "postgres") {
type Tag struct {
Name string
Score float64
}
type UserWithJSON2 struct {
gorm.Model
Name string
Tags datatypes.JSONSlice[Tag]
}
type UserWithJSON = UserWithJSON2
DB.Migrator().DropTable(&UserWithJSON{})
if err := DB.Migrator().AutoMigrate(&UserWithJSON{}); err != nil {
t.Errorf("failed to migrate, got error: %v", err)
}
// Go's json marshaler removes whitespace & orders keys alphabetically
// use to compare against marshaled []byte of datatypes.JSON
var tags = []Tag{{Name: "tag1", Score: 0.1}, {Name: "tag2", Score: 0.2}}
users := []UserWithJSON{{
Name: "json-1",
Tags: datatypes.JSONSlice[Tag]{{Name: "tag1", Score: 1.1}, {Name: "tag2", Score: 1.2}},
}, {
Name: "json-2",
Tags: datatypes.NewJSONSlice([]Tag{{Name: "tag3", Score: 0.3}, {Name: "tag4", Score: 0.4}}),
}, {
Name: "json-3",
Tags: datatypes.JSONSlice[Tag](tags),
}, {
Name: "json-4",
Tags: datatypes.NewJSONSlice(tags),
}}
if err := DB.Create(&users).Error; err != nil {
t.Errorf("Failed to create users %v", err)
}
var result UserWithJSON
if err := DB.First(&result, users[0].ID).Error; err != nil {
t.Fatalf("failed to find user with json key, got error %v", err)
}
AssertEqual(t, result.Name, users[0].Name)
AssertEqual(t, result.Tags[0], users[0].Tags[0])
// Pluck
/*
var pluckTags datatypes.JSONSlice[Tag]
if err := DB.Model(&UserWithJSON{}).Limit(1).Order("id asc").Pluck("tags", &pluckTags).Error; err != nil {
t.Fatalf("failed to pluck for field, got error %v", err)
}
AssertEqual(t, len(pluckTags), 2)
AssertEqual(t, pluckTags[0].Name, "tag1")
*/
// Smart Select Fields
var row struct {
Tags datatypes.JSONSlice[Tag]
}
if err := DB.Model(&UserWithJSON{}).Limit(1).Order("id asc").Find(&row).Error; err != nil {
t.Fatalf("failed to select attribute field, got error %v", err)
}
AssertEqual(t, len(row.Tags), 2)
AssertEqual(t, row.Tags[0].Name, "tag1")
// FirstOrCreate
jsonMap := UserWithJSON{
Tags: datatypes.NewJSONSlice(tags),
}
if err := DB.Where(&UserWithJSON{Name: "json-1"}).Assign(jsonMap).FirstOrCreate(&UserWithJSON{}).Error; err != nil {
t.Errorf("failed to run FirstOrCreate")
}
// Update
jsonMap = UserWithJSON{
Tags: datatypes.NewJSONSlice(tags),
}
var result3 UserWithJSON
result3.ID = 1
if err := DB.Model(&result3).Updates(jsonMap).Error; err != nil {
t.Errorf("failed to run Updates")
}
}
}