Debian Codegraph @

tests/scanner_valuer_test.go

raw
1 package tests_test
2
3 import (
4 "context"
5 "database/sql"
6 "database/sql/driver"
7 "encoding/json"
8 "errors"
9 "fmt"
10 "reflect"
11 "regexp"
12 "strconv"
13 "testing"
14 "time"
15
16 "gorm.io/gorm"
17 "gorm.io/gorm/clause"
18 . "gorm.io/gorm/utils/tests"
19 )
20
21 func TestScannerValuer(t *testing.T) {
22 DB.Migrator().DropTable(&ScannerValuerStruct{})
23 if err := DB.Migrator().AutoMigrate(&ScannerValuerStruct{}); err != nil {
24 t.Fatalf("no error should happen when migrate scanner, valuer struct, got error %v", err)
25 }
26
27 data := ScannerValuerStruct{
28 Name: sql.NullString{String: "name", Valid: true},
29 Gender: &sql.NullString{String: "M", Valid: true},
30 Age: sql.NullInt64{Int64: 18, Valid: true},
31 Male: sql.NullBool{Bool: true, Valid: true},
32 Height: sql.NullFloat64{Float64: 1.8888, Valid: true},
33 Birthday: sql.NullTime{Time: time.Now(), Valid: true},
34 Allergen: NullString{sql.NullString{String: "Allergen", Valid: true}},
35 Password: EncryptedData("pass1"),
36 Bytes: []byte("byte"),
37 Num: 18,
38 Strings: StringsSlice{"a", "b", "c"},
39 Structs: StructsSlice{
40 {"name1", "value1"},
41 {"name2", "value2"},
42 },
43 Role: Role{Name: "admin"},
44 ExampleStruct: ExampleStruct{"name", "value1"},
45 ExampleStructPtr: &ExampleStruct{"name", "value2"},
46 }
47
48 if err := DB.Create(&data).Error; err != nil {
49 t.Fatalf("No error should happened when create scanner valuer struct, but got %v", err)
50 }
51
52 var result ScannerValuerStruct
53
54 if err := DB.Find(&result, "id = ?", data.ID).Error; err != nil {
55 t.Fatalf("no error should happen when query scanner, valuer struct, but got %v", err)
56 }
57
58 if result.ExampleStructPtr.Val != "value2" {
59 t.Errorf(`ExampleStructPtr.Val should equal to "value2", but got %v`, result.ExampleStructPtr.Val)
60 }
61
62 if result.ExampleStruct.Val != "value1" {
63 t.Errorf(`ExampleStruct.Val should equal to "value1", but got %#v`, result.ExampleStruct)
64 }
65 AssertObjEqual(t, data, result, "Name", "Gender", "Age", "Male", "Height", "Birthday", "Password", "Bytes", "Num", "Strings", "Structs")
66 }
67
68 func TestScannerValuerWithFirstOrCreate(t *testing.T) {
69 DB.Migrator().DropTable(&ScannerValuerStruct{})
70 if err := DB.Migrator().AutoMigrate(&ScannerValuerStruct{}); err != nil {
71 t.Errorf("no error should happen when migrate scanner, valuer struct")
72 }
73
74 data := ScannerValuerStruct{
75 Name: sql.NullString{String: "name", Valid: true},
76 Gender: &sql.NullString{String: "M", Valid: true},
77 Age: sql.NullInt64{Int64: 18, Valid: true},
78 ExampleStruct: ExampleStruct{"name", "value1"},
79 ExampleStructPtr: &ExampleStruct{"name", "value2"},
80 }
81
82 var result ScannerValuerStruct
83 tx := DB.Where(data).FirstOrCreate(&result)
84
85 if tx.RowsAffected != 1 {
86 t.Errorf("RowsAffected should be 1 after create some record")
87 }
88
89 if tx.Error != nil {
90 t.Errorf("Should not raise any error, but got %v", tx.Error)
91 }
92
93 AssertObjEqual(t, result, data, "Name", "Gender", "Age")
94
95 if err := DB.Where(data).Assign(ScannerValuerStruct{Age: sql.NullInt64{Int64: 18, Valid: true}}).FirstOrCreate(&result).Error; err != nil {
96 t.Errorf("Should not raise any error, but got %v", err)
97 }
98
99 if result.Age.Int64 != 18 {
100 t.Errorf("should update age to 18")
101 }
102
103 var result2 ScannerValuerStruct
104 if err := DB.First(&result2, result.ID).Error; err != nil {
105 t.Errorf("got error %v when query with %v", err, result.ID)
106 }
107
108 AssertObjEqual(t, result2, result, "ID", "CreatedAt", "UpdatedAt", "Name", "Gender", "Age")
109 }
110
111 func TestInvalidValuer(t *testing.T) {
112 DB.Migrator().DropTable(&ScannerValuerStruct{})
113 if err := DB.Migrator().AutoMigrate(&ScannerValuerStruct{}); err != nil {
114 t.Errorf("no error should happen when migrate scanner, valuer struct")
115 }
116
117 data := ScannerValuerStruct{
118 Password: EncryptedData("xpass1"),
119 ExampleStruct: ExampleStruct{"name", "value1"},
120 ExampleStructPtr: &ExampleStruct{"name", "value2"},
121 }
122
123 if err := DB.Create(&data).Error; err == nil {
124 t.Errorf("Should failed to create data with invalid data")
125 }
126
127 data.Password = EncryptedData("pass1")
128 if err := DB.Create(&data).Error; err != nil {
129 t.Errorf("Should got no error when creating data, but got %v", err)
130 }
131
132 if err := DB.Model(&data).Update("password", EncryptedData("xnewpass")).Error; err == nil {
133 t.Errorf("Should failed to update data with invalid data")
134 }
135
136 if err := DB.Model(&data).Update("password", EncryptedData("newpass")).Error; err != nil {
137 t.Errorf("Should got no error update data with valid data, but got %v", err)
138 }
139
140 AssertEqual(t, data.Password, EncryptedData("newpass"))
141 }
142
143 type ScannerValuerStruct struct {
144 gorm.Model
145 Name sql.NullString
146 Gender *sql.NullString
147 Age sql.NullInt64
148 Male sql.NullBool
149 Height sql.NullFloat64
150 Birthday sql.NullTime
151 Allergen NullString
152 Password EncryptedData
153 Bytes []byte
154 Num Num
155 Strings StringsSlice
156 Structs StructsSlice
157 Role Role
158 UserID *sql.NullInt64
159 User User
160 EmptyTime EmptyTime
161 ExampleStruct ExampleStruct
162 ExampleStructPtr *ExampleStruct
163 }
164
165 type EncryptedData []byte
166
167 func (data *EncryptedData) Scan(value interface{}) error {
168 if b, ok := value.([]byte); ok {
169 if len(b) < 3 || b[0] != '*' || b[1] != '*' || b[2] != '*' {
170 return errors.New("Too short")
171 }
172
173 *data = append((*data)[0:], b[3:]...)
174 return nil
175 } else if s, ok := value.(string); ok {
176 *data = []byte(s[3:])
177 return nil
178 }
179
180 return errors.New("Bytes expected")
181 }
182
183 func (data EncryptedData) Value() (driver.Value, error) {
184 if len(data) > 0 && data[0] == 'x' {
185 // needed to test failures
186 return nil, errors.New("Should not start with 'x'")
187 }
188
189 // prepend asterisks
190 return append([]byte("***"), data...), nil
191 }
192
193 type Num int64
194
195 func (i *Num) Scan(src interface{}) error {
196 switch s := src.(type) {
197 case []byte:
198 n, _ := strconv.Atoi(string(s))
199 *i = Num(n)
200 case int64:
201 *i = Num(s)
202 default:
203 return errors.New("Cannot scan NamedInt from " + reflect.ValueOf(src).String())
204 }
205 return nil
206 }
207
208 type StringsSlice []string
209
210 func (l StringsSlice) Value() (driver.Value, error) {
211 bytes, err := json.Marshal(l)
212 return string(bytes), err
213 }
214
215 func (l *StringsSlice) Scan(input interface{}) error {
216 switch value := input.(type) {
217 case string:
218 return json.Unmarshal([]byte(value), l)
219 case []byte:
220 return json.Unmarshal(value, l)
221 default:
222 return errors.New("not supported")
223 }
224 }
225
226 type ExampleStruct struct {
227 Name string
228 Val string
229 }
230
231 func (ExampleStruct) GormDataType() string {
232 return "bytes"
233 }
234
235 func (s ExampleStruct) Value() (driver.Value, error) {
236 if len(s.Name) == 0 {
237 return nil, nil
238 }
239 // for test, has no practical meaning
240 s.Name = ""
241 return json.Marshal(s)
242 }
243
244 func (s *ExampleStruct) Scan(src interface{}) error {
245 switch value := src.(type) {
246 case string:
247 return json.Unmarshal([]byte(value), s)
248 case []byte:
249 return json.Unmarshal(value, s)
250 default:
251 return errors.New("not supported")
252 }
253 }
254
255 type StructsSlice []ExampleStruct
256
257 func (l StructsSlice) Value() (driver.Value, error) {
258 bytes, err := json.Marshal(l)
259 return string(bytes), err
260 }
261
262 func (l *StructsSlice) Scan(input interface{}) error {
263 switch value := input.(type) {
264 case string:
265 return json.Unmarshal([]byte(value), l)
266 case []byte:
267 return json.Unmarshal(value, l)
268 default:
269 return errors.New("not supported")
270 }
271 }
272
273 type Role struct {
274 Name string `gorm:"size:256"`
275 }
276
277 func (role *Role) Scan(value interface{}) error {
278 if b, ok := value.([]uint8); ok {
279 role.Name = string(b)
280 } else {
281 role.Name = value.(string)
282 }
283 return nil
284 }
285
286 func (role Role) Value() (driver.Value, error) {
287 return role.Name, nil
288 }
289
290 func (role Role) IsAdmin() bool {
291 return role.Name == "admin"
292 }
293
294 type EmptyTime struct {
295 time.Time
296 }
297
298 func (t *EmptyTime) Scan(v interface{}) error {
299 nullTime := sql.NullTime{}
300 err := nullTime.Scan(v)
301 t.Time = nullTime.Time
302 return err
303 }
304
305 func (t EmptyTime) Value() (driver.Value, error) {
306 return time.Now() /* pass tests, mysql 8 doesn't support 0000-00-00 by default */, nil
307 }
308
309 type NullString struct {
310 sql.NullString
311 }
312
313 type Point struct {
314 X, Y int
315 }
316
317 func (point Point) GormDataType() string {
318 return "geo"
319 }
320
321 func (point Point) GormValue(ctx context.Context, db *gorm.DB) clause.Expr {
322 return clause.Expr{
323 SQL: "ST_PointFromText(?)",
324 Vars: []interface{}{fmt.Sprintf("POINT(%d %d)", point.X, point.Y)},
325 }
326 }
327
328 func TestGORMValuer(t *testing.T) {
329 type UserWithPoint struct {
330 Name string
331 Point Point
332 }
333
334 dryRunDB := DB.Session(&gorm.Session{DryRun: true})
335
336 stmt := dryRunDB.Create(&UserWithPoint{
337 Name: "jinzhu",
338 Point: Point{X: 100, Y: 100},
339 }).Statement
340
341 if stmt.SQL.String() == "" || len(stmt.Vars) != 2 {
342 t.Errorf("Failed to generate sql, got %v", stmt.SQL.String())
343 }
344
345 if !regexp.MustCompile(`INSERT INTO .user_with_points. \(.name.,.point.\) VALUES \(.+,ST_PointFromText\(.+\)\)`).MatchString(stmt.SQL.String()) {
346 t.Errorf("insert with sql.Expr, but got %v", stmt.SQL.String())
347 }
348
349 if !reflect.DeepEqual([]interface{}{"jinzhu", "POINT(100 100)"}, stmt.Vars) {
350 t.Errorf("generated vars is not equal, got %v", stmt.Vars)
351 }
352
353 stmt = dryRunDB.Model(UserWithPoint{}).Create(map[string]interface{}{
354 "Name": "jinzhu",
355 "Point": clause.Expr{SQL: "ST_PointFromText(?)", Vars: []interface{}{"POINT(100 100)"}},
356 }).Statement
357
358 if !regexp.MustCompile(`INSERT INTO .user_with_points. \(.name.,.point.\) VALUES \(.+,ST_PointFromText\(.+\)\)`).MatchString(stmt.SQL.String()) {
359 t.Errorf("insert with sql.Expr, but got %v", stmt.SQL.String())
360 }
361
362 if !reflect.DeepEqual([]interface{}{"jinzhu", "POINT(100 100)"}, stmt.Vars) {
363 t.Errorf("generated vars is not equal, got %v", stmt.Vars)
364 }
365
366 stmt = dryRunDB.Table("user_with_points").Create(&map[string]interface{}{
367 "Name": "jinzhu",
368 "Point": clause.Expr{SQL: "ST_PointFromText(?)", Vars: []interface{}{"POINT(100 100)"}},
369 }).Statement
370
371 if !regexp.MustCompile(`INSERT INTO .user_with_points. \(.Name.,.Point.\) VALUES \(.+,ST_PointFromText\(.+\)\)`).MatchString(stmt.SQL.String()) {
372 t.Errorf("insert with sql.Expr, but got %v", stmt.SQL.String())
373 }
374
375 if !reflect.DeepEqual([]interface{}{"jinzhu", "POINT(100 100)"}, stmt.Vars) {
376 t.Errorf("generated vars is not equal, got %v", stmt.Vars)
377 }
378
379 stmt = dryRunDB.Session(&gorm.Session{
380 AllowGlobalUpdate: true,
381 }).Model(&UserWithPoint{}).Updates(UserWithPoint{
382 Name: "jinzhu",
383 Point: Point{X: 100, Y: 100},
384 }).Statement
385
386 if !regexp.MustCompile(`UPDATE .user_with_points. SET .name.=.+,.point.=ST_PointFromText\(.+\)`).MatchString(stmt.SQL.String()) {
387 t.Errorf("update with sql.Expr, but got %v", stmt.SQL.String())
388 }
389
390 if !reflect.DeepEqual([]interface{}{"jinzhu", "POINT(100 100)"}, stmt.Vars) {
391 t.Errorf("generated vars is not equal, got %v", stmt.Vars)
392 }
393 }