Debian Codegraph @

tests/query_test.go

raw
1 package tests_test
2
3 import (
4 "database/sql"
5 "database/sql/driver"
6 "fmt"
7 "reflect"
8 "regexp"
9 "sort"
10 "strconv"
11 "strings"
12 "testing"
13 "time"
14
15 "gorm.io/gorm"
16 "gorm.io/gorm/clause"
17 . "gorm.io/gorm/utils/tests"
18 )
19
20 func TestFind(t *testing.T) {
21 users := []User{
22 *GetUser("find", Config{}),
23 *GetUser("find", Config{}),
24 *GetUser("find", Config{}),
25 }
26
27 if err := DB.Create(&users).Error; err != nil {
28 t.Fatalf("errors happened when create users: %v", err)
29 }
30
31 t.Run("First", func(t *testing.T) {
32 var first User
33 if err := DB.Where("name = ?", "find").First(&first).Error; err != nil {
34 t.Errorf("errors happened when query first: %v", err)
35 } else {
36 CheckUser(t, first, users[0])
37 }
38 })
39
40 t.Run("Last", func(t *testing.T) {
41 var last User
42 if err := DB.Where("name = ?", "find").Last(&last).Error; err != nil {
43 t.Errorf("errors happened when query last: %v", err)
44 } else {
45 CheckUser(t, last, users[2])
46 }
47 })
48
49 var all []User
50 if err := DB.Where("name = ?", "find").Find(&all).Error; err != nil || len(all) != 3 {
51 t.Errorf("errors happened when query find: %v, length: %v", err, len(all))
52 } else {
53 for idx, user := range users {
54 t.Run("FindAll#"+strconv.Itoa(idx+1), func(t *testing.T) {
55 CheckUser(t, all[idx], user)
56 })
57 }
58 }
59
60 t.Run("FirstMap", func(t *testing.T) {
61 first := map[string]interface{}{}
62 if err := DB.Model(&User{}).Where("name = ?", "find").First(first).Error; err != nil {
63 t.Errorf("errors happened when query first: %v", err)
64 } else {
65 for _, name := range []string{"Name", "Age", "Birthday"} {
66 t.Run(name, func(t *testing.T) {
67 dbName := DB.NamingStrategy.ColumnName("", name)
68
69 switch name {
70 case "Name":
71 if _, ok := first[dbName].(string); !ok {
72 t.Errorf("invalid data type for %v, got %#v", dbName, first[dbName])
73 }
74 case "Age":
75 if _, ok := first[dbName].(uint); !ok {
76 t.Errorf("invalid data type for %v, got %#v", dbName, first[dbName])
77 }
78 case "Birthday":
79 if _, ok := first[dbName].(*time.Time); !ok {
80 t.Errorf("invalid data type for %v, got %#v", dbName, first[dbName])
81 }
82 }
83
84 reflectValue := reflect.Indirect(reflect.ValueOf(users[0]))
85 AssertEqual(t, first[dbName], reflectValue.FieldByName(name).Interface())
86 })
87 }
88 }
89 })
90
91 t.Run("FirstMapWithTable", func(t *testing.T) {
92 first := map[string]interface{}{}
93 if err := DB.Table("users").Where("name = ?", "find").Find(first).Error; err != nil {
94 t.Errorf("errors happened when query first: %v", err)
95 } else {
96 for _, name := range []string{"Name", "Age", "Birthday"} {
97 t.Run(name, func(t *testing.T) {
98 dbName := DB.NamingStrategy.ColumnName("", name)
99 resultType := reflect.ValueOf(first[dbName]).Type().Name()
100
101 switch name {
102 case "Name":
103 if !strings.Contains(resultType, "string") {
104 t.Errorf("invalid data type for %v, got %v %#v", dbName, resultType, first[dbName])
105 }
106 case "Age":
107 if !strings.Contains(resultType, "int") {
108 t.Errorf("invalid data type for %v, got %v %#v", dbName, resultType, first[dbName])
109 }
110 case "Birthday":
111 if !strings.Contains(resultType, "Time") && !(DB.Dialector.Name() == "sqlite" && strings.Contains(resultType, "string")) {
112 t.Errorf("invalid data type for %v, got %v %#v", dbName, resultType, first[dbName])
113 }
114 }
115
116 reflectValue := reflect.Indirect(reflect.ValueOf(users[0]))
117 AssertEqual(t, first[dbName], reflectValue.FieldByName(name).Interface())
118 })
119 }
120 }
121 })
122
123 t.Run("FirstPtrMap", func(t *testing.T) {
124 first := map[string]interface{}{}
125 if err := DB.Model(&User{}).Where("name = ?", "find").First(&first).Error; err != nil {
126 t.Errorf("errors happened when query first: %v", err)
127 } else {
128 for _, name := range []string{"Name", "Age", "Birthday"} {
129 t.Run(name, func(t *testing.T) {
130 dbName := DB.NamingStrategy.ColumnName("", name)
131 reflectValue := reflect.Indirect(reflect.ValueOf(users[0]))
132 AssertEqual(t, first[dbName], reflectValue.FieldByName(name).Interface())
133 })
134 }
135 }
136 })
137
138 t.Run("FirstSliceOfMap", func(t *testing.T) {
139 allMap := []map[string]interface{}{}
140 if err := DB.Model(&User{}).Where("name = ?", "find").Find(&allMap).Error; err != nil {
141 t.Errorf("errors happened when query find: %v", err)
142 } else {
143 for idx, user := range users {
144 t.Run("FindAllMap#"+strconv.Itoa(idx+1), func(t *testing.T) {
145 for _, name := range []string{"Name", "Age", "Birthday"} {
146 t.Run(name, func(t *testing.T) {
147 dbName := DB.NamingStrategy.ColumnName("", name)
148
149 switch name {
150 case "Name":
151 if _, ok := allMap[idx][dbName].(string); !ok {
152 t.Errorf("invalid data type for %v, got %#v", dbName, allMap[idx][dbName])
153 }
154 case "Age":
155 if _, ok := allMap[idx][dbName].(uint); !ok {
156 t.Errorf("invalid data type for %v, got %#v", dbName, allMap[idx][dbName])
157 }
158 case "Birthday":
159 if _, ok := allMap[idx][dbName].(*time.Time); !ok {
160 t.Errorf("invalid data type for %v, got %#v", dbName, allMap[idx][dbName])
161 }
162 }
163
164 reflectValue := reflect.Indirect(reflect.ValueOf(user))
165 AssertEqual(t, allMap[idx][dbName], reflectValue.FieldByName(name).Interface())
166 })
167 }
168 })
169 }
170 }
171 })
172
173 t.Run("FindSliceOfMapWithTable", func(t *testing.T) {
174 allMap := []map[string]interface{}{}
175 if err := DB.Table("users").Where("name = ?", "find").Find(&allMap).Error; err != nil {
176 t.Errorf("errors happened when query find: %v", err)
177 } else {
178 for idx, user := range users {
179 t.Run("FindAllMap#"+strconv.Itoa(idx+1), func(t *testing.T) {
180 for _, name := range []string{"Name", "Age", "Birthday"} {
181 t.Run(name, func(t *testing.T) {
182 dbName := DB.NamingStrategy.ColumnName("", name)
183 resultType := reflect.ValueOf(allMap[idx][dbName]).Type().Name()
184
185 switch name {
186 case "Name":
187 if !strings.Contains(resultType, "string") {
188 t.Errorf("invalid data type for %v, got %v %#v", dbName, resultType, allMap[idx][dbName])
189 }
190 case "Age":
191 if !strings.Contains(resultType, "int") {
192 t.Errorf("invalid data type for %v, got %v %#v", dbName, resultType, allMap[idx][dbName])
193 }
194 case "Birthday":
195 if !strings.Contains(resultType, "Time") && !(DB.Dialector.Name() == "sqlite" && strings.Contains(resultType, "string")) {
196 t.Errorf("invalid data type for %v, got %v %#v", dbName, resultType, allMap[idx][dbName])
197 }
198 }
199
200 reflectValue := reflect.Indirect(reflect.ValueOf(user))
201 AssertEqual(t, allMap[idx][dbName], reflectValue.FieldByName(name).Interface())
202 })
203 }
204 })
205 }
206 }
207 })
208
209 var models []User
210 if err := DB.Where("name in (?)", []string{"find"}).Find(&models).Error; err != nil || len(models) != 3 {
211 t.Errorf("errors happened when query find with in clause: %v, length: %v", err, len(models))
212 } else {
213 for idx, user := range users {
214 t.Run("FindWithInClause#"+strconv.Itoa(idx+1), func(t *testing.T) {
215 CheckUser(t, models[idx], user)
216 })
217 }
218 }
219
220 // test array
221 var models2 [3]User
222 if err := DB.Where("name in (?)", []string{"find"}).Find(&models2).Error; err != nil {
223 t.Errorf("errors happened when query find with in clause: %v, length: %v", err, len(models2))
224 } else {
225 for idx, user := range users {
226 t.Run("FindWithInClause#"+strconv.Itoa(idx+1), func(t *testing.T) {
227 CheckUser(t, models2[idx], user)
228 })
229 }
230 }
231
232 // test smaller array
233 var models3 [2]User
234 if err := DB.Where("name in (?)", []string{"find"}).Find(&models3).Error; err != nil {
235 t.Errorf("errors happened when query find with in clause: %v, length: %v", err, len(models3))
236 } else {
237 for idx, user := range users[:2] {
238 t.Run("FindWithInClause#"+strconv.Itoa(idx+1), func(t *testing.T) {
239 CheckUser(t, models3[idx], user)
240 })
241 }
242 }
243
244 var none []User
245 if err := DB.Where("name in (?)", []string{}).Find(&none).Error; err != nil || len(none) != 0 {
246 t.Errorf("errors happened when query find with in clause and zero length parameter: %v, length: %v", err, len(none))
247 }
248 }
249
250 func TestQueryWithAssociation(t *testing.T) {
251 user := *GetUser("query_with_association", Config{Account: true, Pets: 2, Toys: 1, Company: true, Manager: true, Team: 2, Languages: 1, Friends: 3})
252
253 if err := DB.Create(&user).Error; err != nil {
254 t.Fatalf("errors happened when create user: %v", err)
255 }
256
257 user.CreatedAt = time.Time{}
258 user.UpdatedAt = time.Time{}
259 if err := DB.Where(&user).First(&User{}).Error; err != nil {
260 t.Errorf("search with struct with association should returns no error, but got %v", err)
261 }
262
263 if err := DB.Where(user).First(&User{}).Error; err != nil {
264 t.Errorf("search with struct with association should returns no error, but got %v", err)
265 }
266 }
267
268 func TestFindInBatches(t *testing.T) {
269 users := []User{
270 *GetUser("find_in_batches", Config{}),
271 *GetUser("find_in_batches", Config{}),
272 *GetUser("find_in_batches", Config{}),
273 *GetUser("find_in_batches", Config{}),
274 *GetUser("find_in_batches", Config{}),
275 *GetUser("find_in_batches", Config{}),
276 }
277
278 DB.Create(&users)
279
280 var (
281 results []User
282 totalBatch int
283 )
284
285 if result := DB.Table("users as u").Where("name = ?", users[0].Name).FindInBatches(&results, 2, func(tx *gorm.DB, batch int) error {
286 totalBatch += batch
287
288 if tx.RowsAffected != 2 {
289 t.Errorf("Incorrect affected rows, expects: 2, got %v", tx.RowsAffected)
290 }
291
292 if len(results) != 2 {
293 t.Errorf("Incorrect users length, expects: 2, got %v", len(results))
294 }
295
296 for idx := range results {
297 results[idx].Name = results[idx].Name + "_new"
298 }
299
300 if err := tx.Save(results).Error; err != nil {
301 t.Fatalf("failed to save users, got error %v", err)
302 }
303
304 return nil
305 }); result.Error != nil || result.RowsAffected != 6 {
306 t.Errorf("Failed to batch find, got error %v, rows affected: %v", result.Error, result.RowsAffected)
307 }
308
309 if totalBatch != 6 {
310 t.Errorf("incorrect total batch, expects: %v, got %v", 6, totalBatch)
311 }
312
313 var count int64
314 DB.Model(&User{}).Where("name = ?", "find_in_batches_new").Count(&count)
315 if count != 6 {
316 t.Errorf("incorrect count after update, expects: %v, got %v", 6, count)
317 }
318 }
319
320 func TestFindInBatchesWithOffsetLimit(t *testing.T) {
321 users := []User{
322 *GetUser("find_in_batches_with_offset_limit", Config{}),
323 *GetUser("find_in_batches_with_offset_limit", Config{}),
324 *GetUser("find_in_batches_with_offset_limit", Config{}),
325 *GetUser("find_in_batches_with_offset_limit", Config{}),
326 *GetUser("find_in_batches_with_offset_limit", Config{}),
327 *GetUser("find_in_batches_with_offset_limit", Config{}),
328 *GetUser("find_in_batches_with_offset_limit", Config{}),
329 *GetUser("find_in_batches_with_offset_limit", Config{}),
330 *GetUser("find_in_batches_with_offset_limit", Config{}),
331 *GetUser("find_in_batches_with_offset_limit", Config{}),
332 }
333
334 DB.Create(&users)
335
336 var (
337 sub, results []User
338 lastBatch int
339 )
340
341 // offset limit
342 if result := DB.Offset(3).Limit(5).Where("name = ?", users[0].Name).FindInBatches(&sub, 2, func(tx *gorm.DB, batch int) error {
343 results = append(results, sub...)
344 lastBatch = batch
345 return nil
346 }); result.Error != nil || result.RowsAffected != 5 {
347 t.Errorf("Failed to batch find, got error %v, rows affected: %v", result.Error, result.RowsAffected)
348 }
349 if lastBatch != 3 {
350 t.Fatalf("incorrect last batch, expected: %v, got: %v", 3, lastBatch)
351 }
352
353 targetUsers := users[3:8]
354 for i := 0; i < len(targetUsers); i++ {
355 AssertEqual(t, results[i], targetUsers[i])
356 }
357
358 var sub1 []User
359 // limit < batchSize
360 if result := DB.Limit(5).Where("name = ?", users[0].Name).FindInBatches(&sub1, 10, func(tx *gorm.DB, batch int) error {
361 return nil
362 }); result.Error != nil || result.RowsAffected != 5 {
363 t.Errorf("Failed to batch find, got error %v, rows affected: %v", result.Error, result.RowsAffected)
364 }
365
366 var sub2 []User
367 // only offset
368 if result := DB.Offset(3).Where("name = ?", users[0].Name).FindInBatches(&sub2, 2, func(tx *gorm.DB, batch int) error {
369 return nil
370 }); result.Error != nil || result.RowsAffected != 7 {
371 t.Errorf("Failed to batch find, got error %v, rows affected: %v", result.Error, result.RowsAffected)
372 }
373
374 var sub3 []User
375 if result := DB.Limit(4).Where("name = ?", users[0].Name).FindInBatches(&sub3, 2, func(tx *gorm.DB, batch int) error {
376 return nil
377 }); result.Error != nil || result.RowsAffected != 4 {
378 t.Errorf("Failed to batch find, got error %v, rows affected: %v", result.Error, result.RowsAffected)
379 }
380 }
381
382 func TestFindInBatchesWithError(t *testing.T) {
383 if name := DB.Dialector.Name(); name == "sqlserver" {
384 t.Skip("skip sqlserver due to it will raise data race for invalid sql")
385 }
386
387 users := []User{
388 *GetUser("find_in_batches_with_error", Config{}),
389 *GetUser("find_in_batches_with_error", Config{}),
390 *GetUser("find_in_batches_with_error", Config{}),
391 *GetUser("find_in_batches_with_error", Config{}),
392 *GetUser("find_in_batches_with_error", Config{}),
393 *GetUser("find_in_batches_with_error", Config{}),
394 }
395
396 DB.Create(&users)
397
398 var (
399 results []User
400 totalBatch int
401 )
402
403 if result := DB.Table("wrong_table").Where("name = ?", users[0].Name).FindInBatches(&results, 2, func(tx *gorm.DB, batch int) error {
404 totalBatch += batch
405 return nil
406 }); result.Error == nil || result.RowsAffected > 0 {
407 t.Fatal("expected errors to have occurred, but nothing happened")
408 }
409 if totalBatch != 0 {
410 t.Fatalf("incorrect total batch, expected: %v, got: %v", 0, totalBatch)
411 }
412
413 if result := DB.Omit("id").Where("name = ?", users[0].Name).FindInBatches(&results, 2, func(tx *gorm.DB, batch int) error {
414 totalBatch += batch
415 return nil
416 }); result.Error != gorm.ErrPrimaryKeyRequired {
417 t.Fatal("expected errors to have occurred, but nothing happened")
418 }
419 }
420
421 func TestFillSmallerStruct(t *testing.T) {
422 user := User{Name: "SmallerUser", Age: 100}
423 DB.Save(&user)
424 type SimpleUser struct {
425 ID int64
426 Name string
427 UpdatedAt time.Time
428 CreatedAt time.Time
429 }
430
431 var simpleUser SimpleUser
432 if err := DB.Table("users").Where("name = ?", user.Name).First(&simpleUser).Error; err != nil {
433 t.Fatalf("Failed to query smaller user, got error %v", err)
434 }
435
436 AssertObjEqual(t, user, simpleUser, "Name", "ID", "UpdatedAt", "CreatedAt")
437
438 var simpleUser2 SimpleUser
439 if err := DB.Model(&User{}).Select("id").First(&simpleUser2, user.ID).Error; err != nil {
440 t.Fatalf("Failed to query smaller user, got error %v", err)
441 }
442
443 AssertObjEqual(t, user, simpleUser2, "ID")
444
445 var simpleUsers []SimpleUser
446 if err := DB.Model(&User{}).Select("id").Find(&simpleUsers, user.ID).Error; err != nil || len(simpleUsers) != 1 {
447 t.Fatalf("Failed to query smaller user, got error %v", err)
448 }
449
450 AssertObjEqual(t, user, simpleUsers[0], "ID")
451
452 result := DB.Session(&gorm.Session{DryRun: true}).Model(&User{}).Find(&simpleUsers, user.ID)
453
454 if !regexp.MustCompile("SELECT .*id.*name.*updated_at.*created_at.* FROM .*users").MatchString(result.Statement.SQL.String()) {
455 t.Fatalf("SQL should include selected names, but got %v", result.Statement.SQL.String())
456 }
457
458 result = DB.Session(&gorm.Session{DryRun: true}).Model(&User{}).Find(&User{}, user.ID)
459
460 if regexp.MustCompile("SELECT .*name.* FROM .*users").MatchString(result.Statement.SQL.String()) {
461 t.Fatalf("SQL should not include selected names, but got %v", result.Statement.SQL.String())
462 }
463
464 result = DB.Session(&gorm.Session{DryRun: true}).Model(&User{}).Find(&[]User{}, user.ID)
465
466 if regexp.MustCompile("SELECT .*name.* FROM .*users").MatchString(result.Statement.SQL.String()) {
467 t.Fatalf("SQL should not include selected names, but got %v", result.Statement.SQL.String())
468 }
469
470 result = DB.Session(&gorm.Session{DryRun: true}).Model(&User{}).Find(&[]*User{}, user.ID)
471
472 if regexp.MustCompile("SELECT .*name.* FROM .*users").MatchString(result.Statement.SQL.String()) {
473 t.Fatalf("SQL should not include selected names, but got %v", result.Statement.SQL.String())
474 }
475 }
476
477 func TestFillSmallerStructWithAllFields(t *testing.T) {
478 user := User{Name: "SmallerUser", Age: 100}
479 DB.Save(&user)
480 type SimpleUser struct {
481 ID int64
482 Name string
483 UpdatedAt time.Time
484 CreatedAt time.Time
485 }
486 var simpleUsers []SimpleUser
487 dryDB := DB.Session(&gorm.Session{DryRun: true, QueryFields: true})
488
489 result := dryDB.Model(&User{}).Find(&simpleUsers, user.ID)
490 if !regexp.MustCompile("SELECT .users.*id.*users.*name.*users.*updated_at.*users.*created_at.* FROM .*users").MatchString(result.Statement.SQL.String()) {
491 t.Fatalf("SQL should include selected names, but got %v", result.Statement.SQL.String())
492 }
493
494 result = dryDB.Model(&User{}).Find(&User{}, user.ID)
495 if regexp.MustCompile("SELECT \\* FROM .*users").MatchString(result.Statement.SQL.String()) {
496 t.Fatalf("SQL should not include a * wildcard, but got %v", result.Statement.SQL.String())
497 }
498
499 result = dryDB.Model(&User{}).Find(&[]User{}, user.ID)
500 if regexp.MustCompile("SELECT \\* FROM .*users").MatchString(result.Statement.SQL.String()) {
501 t.Fatalf("SQL should not include a * wildcard, but got %v", result.Statement.SQL.String())
502 }
503
504 result = dryDB.Model(&User{}).Find(&[]*User{}, user.ID)
505 if regexp.MustCompile("SELECT \\* FROM .*users").MatchString(result.Statement.SQL.String()) {
506 t.Fatalf("SQL should not include a * wildcard, but got %v", result.Statement.SQL.String())
507 }
508 }
509
510 func TestNot(t *testing.T) {
511 dryDB := DB.Session(&gorm.Session{DryRun: true})
512
513 result := dryDB.Not(map[string]interface{}{"name": "jinzhu"}).Find(&User{})
514 if !regexp.MustCompile("SELECT \\* FROM .*users.* WHERE .*name.* <> .+").MatchString(result.Statement.SQL.String()) {
515 t.Fatalf("Build NOT condition, but got %v", result.Statement.SQL.String())
516 }
517
518 result = dryDB.Where("name = ?", "jinzhu1").Not("name = ?", "jinzhu2").Find(&User{})
519 if !regexp.MustCompile("SELECT \\* FROM .*users.* WHERE .*name.* = .+ AND NOT.*name.* = .+").MatchString(result.Statement.SQL.String()) {
520 t.Fatalf("Build NOT condition, but got %v", result.Statement.SQL.String())
521 }
522
523 result = dryDB.Where(map[string]interface{}{"name": []string{"jinzhu", "jinzhu 2"}}).Find(&User{})
524 if !regexp.MustCompile("SELECT \\* FROM .*users.* WHERE .*name.* IN \\(.+,.+\\)").MatchString(result.Statement.SQL.String()) {
525 t.Fatalf("Build NOT condition, but got %v", result.Statement.SQL.String())
526 }
527
528 result = dryDB.Not("name = ?", "jinzhu").Find(&User{})
529 if !regexp.MustCompile("SELECT \\* FROM .*users.* WHERE NOT.*name.* = .+").MatchString(result.Statement.SQL.String()) {
530 t.Fatalf("Build NOT condition, but got %v", result.Statement.SQL.String())
531 }
532
533 result = dryDB.Not(map[string]interface{}{"name": []string{}}).Find(&User{})
534 if !regexp.MustCompile("SELECT \\* FROM .*users.* WHERE .*name.* IS NOT NULL").MatchString(result.Statement.SQL.String()) {
535 t.Fatalf("Build NOT condition, but got %v", result.Statement.SQL.String())
536 }
537
538 result = dryDB.Not(map[string]interface{}{"name": []string{"jinzhu", "jinzhu 2"}}).Find(&User{})
539 if !regexp.MustCompile("SELECT \\* FROM .*users.* WHERE .*name.* NOT IN \\(.+,.+\\)").MatchString(result.Statement.SQL.String()) {
540 t.Fatalf("Build NOT condition, but got %v", result.Statement.SQL.String())
541 }
542
543 result = dryDB.Not([]int64{1, 2}).First(&User{})
544 if !regexp.MustCompile("SELECT \\* FROM .*users.* WHERE .*id.* NOT IN \\(.+,.+\\)").MatchString(result.Statement.SQL.String()) {
545 t.Fatalf("Build NOT condition, but got %v", result.Statement.SQL.String())
546 }
547
548 result = dryDB.Not([]int64{}).First(&User{})
549 if !regexp.MustCompile("SELECT \\* FROM .*users.* WHERE .users.\\..deleted_at. IS NULL ORDER BY").MatchString(result.Statement.SQL.String()) {
550 t.Fatalf("Build NOT condition, but got %v", result.Statement.SQL.String())
551 }
552
553 result = dryDB.Not(User{Name: "jinzhu", Age: 18}).First(&User{})
554 if !regexp.MustCompile("SELECT \\* FROM .*users.* WHERE .*users.*..*name.* <> .+ AND .*users.*..*age.* <> .+").MatchString(result.Statement.SQL.String()) {
555 t.Fatalf("Build NOT condition, but got %v", result.Statement.SQL.String())
556 }
557
558 result = dryDB.Not(DB.Where("manager IS NULL").Where("age >= ?", 20)).Find(&User{})
559 if !regexp.MustCompile("SELECT \\* FROM .*users.* WHERE NOT \\(manager IS NULL AND age >= .+\\) AND .users.\\..deleted_at. IS NULL").MatchString(result.Statement.SQL.String()) {
560 t.Fatalf("Build NOT condition, but got %v", result.Statement.SQL.String())
561 }
562
563 result = dryDB.Not(DB.Where("manager IS NULL").Or("age >= ?", 20)).Find(&User{})
564 if !regexp.MustCompile(`SELECT \* FROM .*users.* WHERE NOT \(manager IS NULL OR age >= .+\) AND .users.\..deleted_at. IS NULL`).MatchString(result.Statement.SQL.String()) {
565 t.Fatalf("Build NOT condition, but got %v", result.Statement.SQL.String())
566 }
567 }
568
569 func TestNotWithAllFields(t *testing.T) {
570 dryDB := DB.Session(&gorm.Session{DryRun: true, QueryFields: true})
571 userQuery := "SELECT .*users.*id.*users.*created_at.*users.*updated_at.*users.*deleted_at.*users.*name" +
572 ".*users.*age.*users.*birthday.*users.*company_id.*users.*manager_id.*users.*active.* FROM .*users.* "
573
574 result := dryDB.Not(map[string]interface{}{"users.name": "jinzhu"}).Find(&User{})
575
576 if !regexp.MustCompile(userQuery + "WHERE .*users.*name.* <> .+").MatchString(result.Statement.SQL.String()) {
577 t.Fatalf("Build NOT condition, but got %v", result.Statement.SQL.String())
578 }
579
580 result = dryDB.Where("users.name = ?", "jinzhu1").Not("users.name = ?", "jinzhu2").Find(&User{})
581 if !regexp.MustCompile(userQuery + "WHERE .*users.*name.* = .+ AND NOT .*users.*name.* = .+").MatchString(result.Statement.SQL.String()) {
582 t.Fatalf("Build NOT condition, but got %v", result.Statement.SQL.String())
583 }
584
585 result = dryDB.Where(map[string]interface{}{"users.name": []string{"jinzhu", "jinzhu 2"}}).Find(&User{})
586 if !regexp.MustCompile(userQuery + "WHERE .*users.*name.* IN \\(.+,.+\\)").MatchString(result.Statement.SQL.String()) {
587 t.Fatalf("Build NOT condition, but got %v", result.Statement.SQL.String())
588 }
589
590 result = dryDB.Not("users.name = ?", "jinzhu").Find(&User{})
591 if !regexp.MustCompile(userQuery + "WHERE NOT .*users.*name.* = .+").MatchString(result.Statement.SQL.String()) {
592 t.Fatalf("Build NOT condition, but got %v", result.Statement.SQL.String())
593 }
594
595 result = dryDB.Not(map[string]interface{}{"users.name": []string{"jinzhu", "jinzhu 2"}}).Find(&User{})
596 if !regexp.MustCompile(userQuery + "WHERE .*users.*name.* NOT IN \\(.+,.+\\)").MatchString(result.Statement.SQL.String()) {
597 t.Fatalf("Build NOT condition, but got %v", result.Statement.SQL.String())
598 }
599
600 result = dryDB.Not([]int64{1, 2}).First(&User{})
601 if !regexp.MustCompile(userQuery + "WHERE .*users.*id.* NOT IN \\(.+,.+\\)").MatchString(result.Statement.SQL.String()) {
602 t.Fatalf("Build NOT condition, but got %v", result.Statement.SQL.String())
603 }
604
605 result = dryDB.Not([]int64{}).First(&User{})
606 if !regexp.MustCompile(userQuery + "WHERE .users.\\..deleted_at. IS NULL ORDER BY").MatchString(result.Statement.SQL.String()) {
607 t.Fatalf("Build NOT condition, but got %v", result.Statement.SQL.String())
608 }
609
610 result = dryDB.Not(User{Name: "jinzhu", Age: 18}).First(&User{})
611 if !regexp.MustCompile(userQuery + "WHERE .*users.*..*name.* <> .+ AND .*users.*..*age.* <> .+").MatchString(result.Statement.SQL.String()) {
612 t.Fatalf("Build NOT condition, but got %v", result.Statement.SQL.String())
613 }
614 }
615
616 func TestOr(t *testing.T) {
617 dryDB := DB.Session(&gorm.Session{DryRun: true})
618
619 var count int64
620 result := dryDB.Model(&User{}).Or("role = ?", "admin").Count(&count)
621 if !regexp.MustCompile("SELECT count\\(\\*\\) FROM .*users.* WHERE role = .+ AND .*users.*\\..*deleted_at.* IS NULL").MatchString(result.Statement.SQL.String()) {
622 t.Fatalf("Build OR condition, but got %v", result.Statement.SQL.String())
623 }
624
625 result = dryDB.Where("role = ?", "admin").Where(DB.Or("role = ?", "super_admin")).Find(&User{})
626 if !regexp.MustCompile("SELECT \\* FROM .*users.* WHERE .*role.* = .+ AND .*role.* = .+").MatchString(result.Statement.SQL.String()) {
627 t.Fatalf("Build OR condition, but got %v", result.Statement.SQL.String())
628 }
629
630 result = dryDB.Where("role = ?", "admin").Where(DB.Or("role = ?", "super_admin").Or("role = ?", "admin")).Find(&User{})
631 if !regexp.MustCompile("SELECT \\* FROM .*users.* WHERE .*role.* = .+ AND (.*role.* = .+ OR .*role.* = .+)").MatchString(result.Statement.SQL.String()) {
632 t.Fatalf("Build OR condition, but got %v", result.Statement.SQL.String())
633 }
634
635 sub := dryDB.Clauses(clause.Where{
636 Exprs: []clause.Expression{
637 clause.OrConditions{
638 Exprs: []clause.Expression{
639 clause.Expr{SQL: "role = ?", Vars: []interface{}{"super_admin"}},
640 clause.Expr{SQL: "role = ?", Vars: []interface{}{"admin"}},
641 },
642 },
643 },
644 })
645 result = dryDB.Where(sub).Find(&User{})
646 if !regexp.MustCompile("SELECT \\* FROM .*users.* WHERE .*role.* = .+ OR .*role.* = .+").MatchString(result.Statement.SQL.String()) {
647 t.Fatalf("Build OR condition, but got %v", result.Statement.SQL.String())
648 }
649
650 result = dryDB.Where("role = ?", "admin").Or("role = ?", "super_admin").Find(&User{})
651 if !regexp.MustCompile("SELECT \\* FROM .*users.* WHERE .*role.* = .+ OR .*role.* = .+").MatchString(result.Statement.SQL.String()) {
652 t.Fatalf("Build OR condition, but got %v", result.Statement.SQL.String())
653 }
654
655 result = dryDB.Where("name = ?", "jinzhu").Or(User{Name: "jinzhu 2", Age: 18}).Find(&User{})
656 if !regexp.MustCompile("SELECT \\* FROM .*users.* WHERE .*name.* = .+ OR \\(.*name.* AND .*age.*\\)").MatchString(result.Statement.SQL.String()) {
657 t.Fatalf("Build OR condition, but got %v", result.Statement.SQL.String())
658 }
659
660 result = dryDB.Where("name = ?", "jinzhu").Or(map[string]interface{}{"name": "jinzhu 2", "age": 18}).Find(&User{})
661 if !regexp.MustCompile("SELECT \\* FROM .*users.* WHERE .*name.* = .+ OR \\(.*age.* AND .*name.*\\)").MatchString(result.Statement.SQL.String()) {
662 t.Fatalf("Build OR condition, but got %v", result.Statement.SQL.String())
663 }
664 }
665
666 func TestOrWithAllFields(t *testing.T) {
667 dryDB := DB.Session(&gorm.Session{DryRun: true, QueryFields: true})
668 userQuery := "SELECT .*users.*id.*users.*created_at.*users.*updated_at.*users.*deleted_at.*users.*name" +
669 ".*users.*age.*users.*birthday.*users.*company_id.*users.*manager_id.*users.*active.* FROM .*users.* "
670
671 result := dryDB.Where("role = ?", "admin").Or("role = ?", "super_admin").Find(&User{})
672 if !regexp.MustCompile(userQuery + "WHERE .*role.* = .+ OR .*role.* = .+").MatchString(result.Statement.SQL.String()) {
673 t.Fatalf("Build OR condition, but got %v", result.Statement.SQL.String())
674 }
675
676 result = dryDB.Where("users.name = ?", "jinzhu").Or(User{Name: "jinzhu 2", Age: 18}).Find(&User{})
677 if !regexp.MustCompile(userQuery + "WHERE .*users.*name.* = .+ OR \\(.*users.*name.* AND .*users.*age.*\\)").MatchString(result.Statement.SQL.String()) {
678 t.Fatalf("Build OR condition, but got %v", result.Statement.SQL.String())
679 }
680
681 result = dryDB.Where("users.name = ?", "jinzhu").Or(map[string]interface{}{"name": "jinzhu 2", "age": 18}).Find(&User{})
682 if !regexp.MustCompile(userQuery + "WHERE .*users.*name.* = .+ OR \\(.*age.* AND .*name.*\\)").MatchString(result.Statement.SQL.String()) {
683 t.Fatalf("Build OR condition, but got %v", result.Statement.SQL.String())
684 }
685 }
686
687 type Int64 int64
688
689 func (v Int64) Value() (driver.Value, error) {
690 return v - 1, nil
691 }
692
693 func (f *Int64) Scan(v interface{}) error {
694 y := v.(int64)
695 *f = Int64(y + 1)
696 return nil
697 }
698
699 func TestPluck(t *testing.T) {
700 users := []*User{
701 GetUser("pluck-user1", Config{}),
702 GetUser("pluck-user2", Config{}),
703 GetUser("pluck-user3", Config{}),
704 }
705
706 DB.Create(&users)
707
708 var names []string
709 if err := DB.Model(User{}).Where("name like ?", "pluck-user%").Order("name").Pluck("name", &names).Error; err != nil {
710 t.Errorf("got error when pluck name: %v", err)
711 }
712
713 var names2 []string
714 if err := DB.Model(User{}).Where("name like ?", "pluck-user%").Order("name desc").Pluck("name", &names2).Error; err != nil {
715 t.Errorf("got error when pluck name: %v", err)
716 }
717
718 sort.Slice(names2, func(i, j int) bool { return names2[i] < names2[j] })
719 AssertEqual(t, names, names2)
720
721 var ids []int
722 if err := DB.Model(User{}).Where("name like ?", "pluck-user%").Pluck("id", &ids).Error; err != nil {
723 t.Errorf("got error when pluck id: %v", err)
724 }
725
726 var ids2 []Int64
727 if err := DB.Model(User{}).Where("name like ?", "pluck-user%").Pluck("id", &ids2).Error; err != nil {
728 t.Errorf("got error when pluck id: %v", err)
729 }
730
731 for idx, name := range names {
732 if name != users[idx].Name {
733 t.Errorf("Unexpected result on pluck name, got %+v", names)
734 }
735 }
736
737 for idx, id := range ids {
738 if int(id) != int(users[idx].ID) {
739 t.Errorf("Unexpected result on pluck id, got %+v", ids)
740 }
741 }
742
743 for idx, id := range ids2 {
744 if int(id) != int(users[idx].ID+1) {
745 t.Errorf("Unexpected result on pluck id, got %+v", ids)
746 }
747 }
748
749 var times []time.Time
750 if err := DB.Model(User{}).Where("name like ?", "pluck-user%").Pluck("created_at", &times).Error; err != nil {
751 t.Errorf("got error when pluck time: %v", err)
752 }
753
754 for idx, tv := range times {
755 AssertEqual(t, tv, users[idx].CreatedAt)
756 }
757
758 var ptrtimes []*time.Time
759 if err := DB.Model(User{}).Where("name like ?", "pluck-user%").Pluck("created_at", &ptrtimes).Error; err != nil {
760 t.Errorf("got error when pluck time: %v", err)
761 }
762
763 for idx, tv := range ptrtimes {
764 AssertEqual(t, tv, users[idx].CreatedAt)
765 }
766
767 var nulltimes []sql.NullTime
768 if err := DB.Model(User{}).Where("name like ?", "pluck-user%").Pluck("created_at", &nulltimes).Error; err != nil {
769 t.Errorf("got error when pluck time: %v", err)
770 }
771
772 for idx, tv := range nulltimes {
773 AssertEqual(t, tv.Time, users[idx].CreatedAt)
774 }
775 }
776
777 func TestSelect(t *testing.T) {
778 user := User{Name: "SelectUser1"}
779 DB.Save(&user)
780
781 var result User
782 DB.Where("name = ?", user.Name).Select("name").Find(&result)
783 if result.ID != 0 {
784 t.Errorf("Should not have ID because only selected name, %+v", result.ID)
785 }
786
787 if user.Name != result.Name {
788 t.Errorf("Should have user Name when selected it")
789 }
790
791 var result2 User
792 DB.Where("name = ?", user.Name).Select("name as name").Find(&result2)
793 if result2.ID != 0 {
794 t.Errorf("Should not have ID because only selected name, %+v", result2.ID)
795 }
796
797 if user.Name != result2.Name {
798 t.Errorf("Should have user Name when selected it")
799 }
800
801 dryDB := DB.Session(&gorm.Session{DryRun: true})
802 r := dryDB.Select("name", "age").Find(&User{})
803 if !regexp.MustCompile("SELECT .*name.*,.*age.* FROM .*users.*").MatchString(r.Statement.SQL.String()) {
804 t.Fatalf("Build Select with strings, but got %v", r.Statement.SQL.String())
805 }
806
807 r = dryDB.Select([]string{"name", "age"}).Find(&User{})
808 if !regexp.MustCompile("SELECT .*name.*,.*age.* FROM .*users.*").MatchString(r.Statement.SQL.String()) {
809 t.Fatalf("Build Select with slice, but got %v", r.Statement.SQL.String())
810 }
811
812 // SELECT COALESCE(age,'42') FROM users;
813 r = dryDB.Table("users").Select("COALESCE(age,?)", 42).Find(&User{})
814 if !regexp.MustCompile(`SELECT COALESCE\(age,.*\) FROM .*users.*`).MatchString(r.Statement.SQL.String()) {
815 t.Fatalf("Build Select with func, but got %v", r.Statement.SQL.String())
816 }
817
818 // named arguments
819 r = dryDB.Table("users").Select("COALESCE(age, @default)", sql.Named("default", 42)).Find(&User{})
820 if !regexp.MustCompile(`SELECT COALESCE\(age,.*\) FROM .*users.*`).MatchString(r.Statement.SQL.String()) {
821 t.Fatalf("Build Select with func, but got %v", r.Statement.SQL.String())
822 }
823
824 if _, err := DB.Table("users").Select("COALESCE(age,?)", "42").Rows(); err != nil {
825 t.Fatalf("Failed, got error: %v", err)
826 }
827
828 r = dryDB.Select("u.*").Table("users as u").First(&User{}, user.ID)
829 if !regexp.MustCompile(`SELECT u\.\* FROM .*users.*`).MatchString(r.Statement.SQL.String()) {
830 t.Fatalf("Build Select with u.*, but got %v", r.Statement.SQL.String())
831 }
832
833 r = dryDB.Select("count(*)").Select("u.*").Table("users as u").First(&User{}, user.ID)
834 if !regexp.MustCompile(`SELECT u\.\* FROM .*users.*`).MatchString(r.Statement.SQL.String()) {
835 t.Fatalf("Build Select with u.*, but got %v", r.Statement.SQL.String())
836 }
837 }
838
839 func TestOmit(t *testing.T) {
840 user := User{Name: "OmitUser1", Age: 20}
841 DB.Save(&user)
842
843 var result User
844 DB.Where("name = ?", user.Name).Omit("name").Find(&result)
845 if result.ID == 0 {
846 t.Errorf("Should not have ID because only selected name, %+v", result.ID)
847 }
848
849 if result.Name != "" || result.Age != 20 {
850 t.Errorf("User Name should be omitted, got %v, Age should be ok, got %v", result.Name, result.Age)
851 }
852 }
853
854 func TestOmitWithAllFields(t *testing.T) {
855 user := User{Name: "OmitUser1", Age: 20}
856 DB.Save(&user)
857
858 var userResult User
859 DB.Session(&gorm.Session{QueryFields: true}).Where("users.name = ?", user.Name).Omit("name").Find(&userResult)
860 if userResult.ID == 0 {
861 t.Errorf("Should not have ID because only selected name, %+v", userResult.ID)
862 }
863
864 if userResult.Name != "" || userResult.Age != 20 {
865 t.Errorf("User Name should be omitted, got %v, Age should be ok, got %v", userResult.Name, userResult.Age)
866 }
867
868 dryDB := DB.Session(&gorm.Session{DryRun: true, QueryFields: true})
869 userQuery := "SELECT .*users.*id.*users.*created_at.*users.*updated_at.*users.*deleted_at.*users.*birthday" +
870 ".*users.*company_id.*users.*manager_id.*users.*active.* FROM .*users.* "
871
872 result := dryDB.Omit("name, age").Find(&User{})
873 if !regexp.MustCompile(userQuery).MatchString(result.Statement.SQL.String()) {
874 t.Fatalf("SQL must include table name and selected fields, got %v", result.Statement.SQL.String())
875 }
876 }
877
878 func TestMapColumns(t *testing.T) {
879 user := User{Name: "MapColumnsUser", Age: 12}
880 DB.Save(&user)
881
882 type result struct {
883 Name string
884 Nickname string
885 Age uint
886 }
887 var res result
888 DB.Table("users").Where("name = ?", user.Name).MapColumns(map[string]string{"name": "nickname"}).Scan(&res)
889 if res.Nickname != user.Name {
890 t.Errorf("Expected res.Nickname to be %s, but got %s", user.Name, res.Nickname)
891 }
892 if res.Name != "" {
893 t.Errorf("Expected res.Name to be empty, but got %s", res.Name)
894 }
895 if res.Age != user.Age {
896 t.Errorf("Expected res.Age to be %d, but got %d", user.Age, res.Age)
897 }
898 }
899
900 func TestPluckWithSelect(t *testing.T) {
901 users := []User{
902 {Name: "pluck_with_select_1", Age: 25},
903 {Name: "pluck_with_select_2", Age: 26},
904 }
905
906 DB.Create(&users)
907
908 var userAges []int
909 err := DB.Model(&User{}).Where("name like ?", "pluck_with_select%").Select("age + 1 as user_age").Pluck("user_age", &userAges).Error
910 if err != nil {
911 t.Fatalf("got error when pluck user_age: %v", err)
912 }
913
914 sort.Ints(userAges)
915
916 AssertEqual(t, userAges, []int{26, 27})
917 }
918
919 func TestSelectWithVariables(t *testing.T) {
920 DB.Save(&User{Name: "select_with_variables"})
921
922 rows, _ := DB.Table("users").Where("name = ?", "select_with_variables").Select("? as fake", gorm.Expr("name")).Rows()
923
924 if !rows.Next() {
925 t.Errorf("Should have returned at least one row")
926 } else {
927 columns, _ := rows.Columns()
928 AssertEqual(t, columns, []string{"fake"})
929 }
930
931 rows.Close()
932 }
933
934 func TestSelectWithArrayInput(t *testing.T) {
935 DB.Save(&User{Name: "select_with_array", Age: 42})
936
937 var user User
938 DB.Select([]string{"name", "age"}).Where("age = 42 AND name = ?", "select_with_array").First(&user)
939
940 if user.Name != "select_with_array" || user.Age != 42 {
941 t.Errorf("Should have selected both age and name")
942 }
943 }
944
945 func TestCustomizedTypePrimaryKey(t *testing.T) {
946 type ID uint
947 type CustomizedTypePrimaryKey struct {
948 ID ID
949 Name string
950 }
951
952 DB.Migrator().DropTable(&CustomizedTypePrimaryKey{})
953 if err := DB.AutoMigrate(&CustomizedTypePrimaryKey{}); err != nil {
954 t.Fatalf("failed to migrate, got error %v", err)
955 }
956
957 p1 := CustomizedTypePrimaryKey{Name: "p1"}
958 p2 := CustomizedTypePrimaryKey{Name: "p2"}
959 p3 := CustomizedTypePrimaryKey{Name: "p3"}
960 DB.Create(&p1)
961 DB.Create(&p2)
962 DB.Create(&p3)
963
964 var p CustomizedTypePrimaryKey
965
966 if err := DB.First(&p, p2.ID).Error; err != nil {
967 t.Errorf("No error should returns, but got %v", err)
968 }
969
970 AssertEqual(t, p, p2)
971
972 if err := DB.First(&p, "id = ?", p2.ID).Error; err != nil {
973 t.Errorf("No error should happen when querying with customized type for primary key, got err %v", err)
974 }
975
976 AssertEqual(t, p, p2)
977 }
978
979 func TestStringPrimaryKeyForNumericValueStartingWithZero(t *testing.T) {
980 type AddressByZipCode struct {
981 ZipCode string `gorm:"primary_key"`
982 Address string
983 }
984
985 DB.Migrator().DropTable(&AddressByZipCode{})
986 if err := DB.AutoMigrate(&AddressByZipCode{}); err != nil {
987 t.Fatalf("failed to migrate, got error %v", err)
988 }
989
990 address := AddressByZipCode{ZipCode: "00501", Address: "Holtsville"}
991 DB.Create(&address)
992
993 var result AddressByZipCode
994 DB.First(&result, "00501")
995
996 AssertEqual(t, result, address)
997 }
998
999 func TestSearchWithEmptyChain(t *testing.T) {
1000 user := User{Name: "search_with_empty_chain", Age: 1}
1001 DB.Create(&user)
1002
1003 var result User
1004 if DB.Where("").Where("").First(&result).Error != nil {
1005 t.Errorf("Should not raise any error if searching with empty strings")
1006 }
1007
1008 result = User{}
1009 if DB.Where(&User{}).Where("name = ?", user.Name).First(&result).Error != nil {
1010 t.Errorf("Should not raise any error if searching with empty struct")
1011 }
1012
1013 result = User{}
1014 if DB.Where(map[string]interface{}{}).Where("name = ?", user.Name).First(&result).Error != nil {
1015 t.Errorf("Should not raise any error if searching with empty map")
1016 }
1017 }
1018
1019 func TestOrder(t *testing.T) {
1020 dryDB := DB.Session(&gorm.Session{DryRun: true})
1021
1022 result := dryDB.Order("").Find(&User{})
1023 if !regexp.MustCompile("SELECT \\* FROM .*users.* IS NULL$").MatchString(result.Statement.SQL.String()) {
1024 t.Fatalf("Build Order condition, but got %v", result.Statement.SQL.String())
1025 }
1026
1027 result = dryDB.Order(nil).Find(&User{})
1028 if !regexp.MustCompile("SELECT \\* FROM .*users.* IS NULL$").MatchString(result.Statement.SQL.String()) {
1029 t.Fatalf("Build Order condition, but got %v", result.Statement.SQL.String())
1030 }
1031
1032 result = dryDB.Order("age desc, name").Find(&User{})
1033 if !regexp.MustCompile("SELECT \\* FROM .*users.* ORDER BY age desc, name").MatchString(result.Statement.SQL.String()) {
1034 t.Fatalf("Build Order condition, but got %v", result.Statement.SQL.String())
1035 }
1036
1037 result = dryDB.Order("age desc").Order("name").Find(&User{})
1038 if !regexp.MustCompile("SELECT \\* FROM .*users.* ORDER BY age desc,name").MatchString(result.Statement.SQL.String()) {
1039 t.Fatalf("Build Order condition, but got %v", result.Statement.SQL.String())
1040 }
1041
1042 stmt := dryDB.Clauses(clause.OrderBy{
1043 Expression: clause.Expr{SQL: "FIELD(id,?)", Vars: []interface{}{[]int{1, 2, 3}}, WithoutParentheses: true},
1044 }).Find(&User{}).Statement
1045
1046 explainedSQL := dryDB.Dialector.Explain(stmt.SQL.String(), stmt.Vars...)
1047 if !regexp.MustCompile("SELECT \\* FROM .*users.* ORDER BY FIELD\\(id,1,2,3\\)").MatchString(explainedSQL) {
1048 t.Fatalf("Build Order condition, but got %v", explainedSQL)
1049 }
1050 }
1051
1052 func TestOrderWithAllFields(t *testing.T) {
1053 dryDB := DB.Session(&gorm.Session{DryRun: true, QueryFields: true})
1054 userQuery := "SELECT .*users.*id.*users.*created_at.*users.*updated_at.*users.*deleted_at.*users.*name.*users.*age" +
1055 ".*users.*birthday.*users.*company_id.*users.*manager_id.*users.*active.* FROM .*users.* "
1056
1057 result := dryDB.Order("users.age desc, users.name").Find(&User{})
1058 if !regexp.MustCompile(userQuery + "users.age desc, users.name").MatchString(result.Statement.SQL.String()) {
1059 t.Fatalf("Build Order condition, but got %v", result.Statement.SQL.String())
1060 }
1061
1062 result = dryDB.Order("users.age desc").Order("users.name").Find(&User{})
1063 if !regexp.MustCompile(userQuery + "ORDER BY users.age desc,users.name").MatchString(result.Statement.SQL.String()) {
1064 t.Fatalf("Build Order condition, but got %v", result.Statement.SQL.String())
1065 }
1066
1067 stmt := dryDB.Clauses(clause.OrderBy{
1068 Expression: clause.Expr{SQL: "FIELD(id,?)", Vars: []interface{}{[]int{1, 2, 3}}, WithoutParentheses: true},
1069 }).Find(&User{}).Statement
1070
1071 explainedSQL := dryDB.Dialector.Explain(stmt.SQL.String(), stmt.Vars...)
1072 if !regexp.MustCompile(userQuery + "ORDER BY FIELD\\(id,1,2,3\\)").MatchString(explainedSQL) {
1073 t.Fatalf("Build Order condition, but got %v", explainedSQL)
1074 }
1075 }
1076
1077 func TestLimit(t *testing.T) {
1078 users := []User{
1079 {Name: "LimitUser1", Age: 1},
1080 {Name: "LimitUser2", Age: 10},
1081 {Name: "LimitUser3", Age: 20},
1082 {Name: "LimitUser4", Age: 10},
1083 {Name: "LimitUser5", Age: 20},
1084 {Name: "LimitUser6", Age: 20},
1085 }
1086
1087 DB.Create(&users)
1088
1089 var users1, users2, users3 []User
1090 DB.Order("age desc").Limit(3).Find(&users1).Limit(5).Find(&users2).Limit(-1).Find(&users3)
1091
1092 if len(users1) != 3 || len(users2) != 5 || len(users3) <= 5 {
1093 t.Errorf("Limit should works, users1 %v users2 %v users3 %v", len(users1), len(users2), len(users3))
1094 }
1095 }
1096
1097 func TestOffset(t *testing.T) {
1098 for i := 0; i < 20; i++ {
1099 DB.Save(&User{Name: fmt.Sprintf("OffsetUser%v", i)})
1100 }
1101 var users1, users2, users3, users4 []User
1102
1103 DB.Limit(100).Where("name like ?", "OffsetUser%").Order("age desc").Find(&users1).Offset(3).Find(&users2).Offset(5).Find(&users3).Offset(-1).Find(&users4)
1104
1105 if (len(users1) != len(users4)) || (len(users1)-len(users2) != 3) || (len(users1)-len(users3) != 5) {
1106 t.Errorf("Offset should work")
1107 }
1108
1109 DB.Where("name like ?", "OffsetUser%").Order("age desc").Find(&users1).Offset(3).Find(&users2).Offset(5).Find(&users3).Offset(-1).Find(&users4)
1110
1111 if (len(users1) != len(users4)) || (len(users1)-len(users2) != 3) || (len(users1)-len(users3) != 5) {
1112 t.Errorf("Offset should work without limit.")
1113 }
1114 }
1115
1116 func TestSearchWithMap(t *testing.T) {
1117 users := []User{
1118 *GetUser("map_search_user1", Config{}),
1119 *GetUser("map_search_user2", Config{}),
1120 *GetUser("map_search_user3", Config{}),
1121 *GetUser("map_search_user4", Config{Company: true}),
1122 }
1123
1124 DB.Create(&users)
1125
1126 var user User
1127 DB.First(&user, map[string]interface{}{"name": users[0].Name})
1128 CheckUser(t, user, users[0])
1129
1130 user = User{}
1131 DB.First(&user, map[string]interface{}{"users.name": users[0].Name})
1132 CheckUser(t, user, users[0])
1133
1134 user = User{}
1135 DB.Where(map[string]interface{}{"name": users[1].Name}).First(&user)
1136 CheckUser(t, user, users[1])
1137
1138 var results []User
1139 DB.Where(map[string]interface{}{"name": users[2].Name}).Find(&results)
1140 if len(results) != 1 {
1141 t.Fatalf("Search all records with inline map")
1142 }
1143
1144 CheckUser(t, results[0], users[2])
1145
1146 var results2 []User
1147 DB.Find(&results2, map[string]interface{}{"name": users[3].Name, "company_id": nil})
1148 if len(results2) != 0 {
1149 t.Errorf("Search all records with inline map containing null value finding 0 records")
1150 }
1151
1152 DB.Find(&results2, map[string]interface{}{"name": users[0].Name, "company_id": nil})
1153 if len(results2) != 1 {
1154 t.Errorf("Search all records with inline map containing null value finding 1 record")
1155 }
1156
1157 DB.Find(&results2, map[string]interface{}{"name": users[3].Name, "company_id": users[3].CompanyID})
1158 if len(results2) != 1 {
1159 t.Errorf("Search all records with inline multiple value map")
1160 }
1161 }
1162
1163 func TestSearchWithStruct(t *testing.T) {
1164 dryRunDB := DB.Session(&gorm.Session{DryRun: true})
1165
1166 result := dryRunDB.Where(User{Name: "jinzhu"}).Find(&User{})
1167 if !regexp.MustCompile(`WHERE .users.\..name. = .{1,3} AND .users.\..deleted_at. IS NULL`).MatchString(result.Statement.SQL.String()) {
1168 t.Errorf("invalid query SQL, got %v", result.Statement.SQL.String())
1169 }
1170
1171 result = dryRunDB.Where(User{Name: "jinzhu", Age: 18}).Find(&User{})
1172 if !regexp.MustCompile(`WHERE \(.users.\..name. = .{1,3} AND .users.\..age. = .{1,3}\) AND .users.\..deleted_at. IS NULL`).MatchString(result.Statement.SQL.String()) {
1173 t.Errorf("invalid query SQL, got %v", result.Statement.SQL.String())
1174 }
1175
1176 result = dryRunDB.Where(User{Name: "jinzhu"}, "name", "Age").Find(&User{})
1177 if !regexp.MustCompile(`WHERE \(.users.\..name. = .{1,3} AND .users.\..age. = .{1,3}\) AND .users.\..deleted_at. IS NULL`).MatchString(result.Statement.SQL.String()) {
1178 t.Errorf("invalid query SQL, got %v", result.Statement.SQL.String())
1179 }
1180
1181 result = dryRunDB.Where(User{Name: "jinzhu"}, "age").Find(&User{})
1182 if !regexp.MustCompile(`WHERE .users.\..age. = .{1,3} AND .users.\..deleted_at. IS NULL`).MatchString(result.Statement.SQL.String()) {
1183 t.Errorf("invalid query SQL, got %v", result.Statement.SQL.String())
1184 }
1185 }
1186
1187 func TestSubQuery(t *testing.T) {
1188 users := []User{
1189 {Name: "subquery_1", Age: 10},
1190 {Name: "subquery_2", Age: 20},
1191 {Name: "subquery_3", Age: 30},
1192 {Name: "subquery_4", Age: 40},
1193 }
1194
1195 DB.Create(&users)
1196
1197 if err := DB.Select("*").Where("name IN (?)", DB.Select("name").Table("users").Where("name LIKE ?", "subquery_%")).Find(&users).Error; err != nil {
1198 t.Fatalf("got error: %v", err)
1199 }
1200
1201 if len(users) != 4 {
1202 t.Errorf("Four users should be found, instead found %d", len(users))
1203 }
1204
1205 DB.Select("*").Where("name LIKE ?", "subquery%").Where("age >= (?)", DB.
1206 Select("AVG(age)").Table("users").Where("name LIKE ?", "subquery%")).Find(&users)
1207
1208 if len(users) != 2 {
1209 t.Errorf("Two users should be found, instead found %d", len(users))
1210 }
1211 }
1212
1213 func TestSubQueryWithRaw(t *testing.T) {
1214 users := []User{
1215 {Name: "subquery_raw_1", Age: 10},
1216 {Name: "subquery_raw_2", Age: 20},
1217 {Name: "subquery_raw_3", Age: 30},
1218 {Name: "subquery_raw_4", Age: 40},
1219 }
1220 DB.Create(&users)
1221
1222 var count int64
1223 err := DB.Raw("select count(*) from (?) tmp where 1 = ? AND name IN (?)", DB.Raw("select name from users where age >= ? and name in (?)", 10, []string{"subquery_raw_1", "subquery_raw_2", "subquery_raw_3"}), 1, DB.Raw("select name from users where age >= ? and name in (?)", 20, []string{"subquery_raw_1", "subquery_raw_2", "subquery_raw_3"})).Scan(&count).Error
1224 if err != nil {
1225 t.Errorf("Expected to get no errors, but got %v", err)
1226 }
1227
1228 if count != 2 {
1229 t.Errorf("Row count must be 2, instead got %d", count)
1230 }
1231
1232 err = DB.Raw("select count(*) from (?) tmp",
1233 DB.Table("users").
1234 Select("name").
1235 Where("age >= ? and name in (?)", 20, []string{"subquery_raw_1", "subquery_raw_3"}).
1236 Group("name"),
1237 ).Count(&count).Error
1238 if err != nil {
1239 t.Errorf("Expected to get no errors, but got %v", err)
1240 }
1241
1242 if count != 1 {
1243 t.Errorf("Row count must be 1, instead got %d", count)
1244 }
1245
1246 err = DB.Raw("select count(*) from (?) tmp",
1247 DB.Table("users").
1248 Select("name").
1249 Where("name LIKE ?", "subquery_raw%").
1250 Not("age <= ?", 10).Not("name IN (?)", []string{"subquery_raw_1", "subquery_raw_3"}).
1251 Group("name"),
1252 ).Count(&count).Error
1253 if err != nil {
1254 t.Errorf("Expected to get no errors, but got %v", err)
1255 }
1256
1257 if count != 2 {
1258 t.Errorf("Row count must be 2, instead got %d", count)
1259 }
1260 }
1261
1262 func TestSubQueryWithHaving(t *testing.T) {
1263 users := []User{
1264 {Name: "subquery_having_1", Age: 10},
1265 {Name: "subquery_having_2", Age: 20},
1266 {Name: "subquery_having_3", Age: 30},
1267 {Name: "subquery_having_4", Age: 40},
1268 }
1269 DB.Create(&users)
1270
1271 var results []User
1272 DB.Select("AVG(age) as avgage").Where("name LIKE ?", "subquery_having%").Group("name").Having("AVG(age) > (?)", DB.
1273 Select("AVG(age)").Where("name LIKE ?", "subquery_having%").Table("users")).Find(&results)
1274
1275 if len(results) != 2 {
1276 t.Errorf("Two user group should be found, instead found %d", len(results))
1277 }
1278 }
1279
1280 func TestScanNullValue(t *testing.T) {
1281 user := GetUser("scan_null_value", Config{})
1282 DB.Create(&user)
1283
1284 if err := DB.Model(&user).Update("age", nil).Error; err != nil {
1285 t.Fatalf("failed to update column age for struct, got error %v", err)
1286 }
1287
1288 var result User
1289 if err := DB.First(&result, "id = ?", user.ID).Error; err != nil {
1290 t.Fatalf("failed to query struct data with null age, got error %v", err)
1291 }
1292
1293 AssertEqual(t, result, user)
1294
1295 users := []User{
1296 *GetUser("scan_null_value_for_slice_1", Config{}),
1297 *GetUser("scan_null_value_for_slice_2", Config{}),
1298 *GetUser("scan_null_value_for_slice_3", Config{}),
1299 }
1300 DB.Create(&users)
1301
1302 if err := DB.Model(&users[0]).Update("age", nil).Error; err != nil {
1303 t.Fatalf("failed to update column age for struct, got error %v", err)
1304 }
1305
1306 var results []User
1307 if err := DB.Find(&results, "name like ?", "scan_null_value_for_slice%").Error; err != nil {
1308 t.Fatalf("failed to query slice data with null age, got error %v", err)
1309 }
1310 }
1311
1312 func TestQueryWithTableAndConditions(t *testing.T) {
1313 result := DB.Session(&gorm.Session{DryRun: true}).Table("user").Find(&User{}, User{Name: "jinzhu"})
1314
1315 if !regexp.MustCompile(`SELECT \* FROM .user. WHERE .user.\..name. = .+ AND .user.\..deleted_at. IS NULL`).MatchString(result.Statement.SQL.String()) {
1316 t.Errorf("invalid query SQL, got %v", result.Statement.SQL.String())
1317 }
1318 }
1319
1320 func TestQueryWithTableAndConditionsAndAllFields(t *testing.T) {
1321 result := DB.Session(&gorm.Session{DryRun: true, QueryFields: true}).Table("user").Find(&User{}, User{Name: "jinzhu"})
1322 userQuery := "SELECT .*user.*id.*user.*created_at.*user.*updated_at.*user.*deleted_at.*user.*name.*user.*age" +
1323 ".*user.*birthday.*user.*company_id.*user.*manager_id.*user.*active.* FROM .user. "
1324
1325 if !regexp.MustCompile(userQuery + `WHERE .user.\..name. = .+ AND .user.\..deleted_at. IS NULL`).MatchString(result.Statement.SQL.String()) {
1326 t.Errorf("invalid query SQL, got %v", result.Statement.SQL.String())
1327 }
1328 }
1329
1330 type DoubleInt64 struct {
1331 data int64
1332 }
1333
1334 func (t *DoubleInt64) Scan(val interface{}) error {
1335 switch v := val.(type) {
1336 case int64:
1337 t.data = v * 2
1338 return nil
1339 default:
1340 return fmt.Errorf("DoubleInt64 cant not scan with:%v", v)
1341 }
1342 }
1343
1344 // https://github.com/go-gorm/gorm/issues/5091
1345 func TestQueryScannerWithSingleColumn(t *testing.T) {
1346 user := User{Name: "scanner_raw_1", Age: 10}
1347 DB.Create(&user)
1348
1349 var result1 DoubleInt64
1350 if err := DB.Model(&User{}).Where("name LIKE ?", "scanner_raw_%").Limit(1).Pluck(
1351 "age", &result1).Error; err != nil {
1352 t.Errorf("Failed, got error: %v", err)
1353 }
1354
1355 AssertEqual(t, result1.data, 20)
1356
1357 var result2 DoubleInt64
1358 if err := DB.Model(&User{}).Where("name LIKE ?", "scanner_raw_%").Limit(1).Select(
1359 "age").Scan(&result2).Error; err != nil {
1360 t.Errorf("Failed, got error: %v", err)
1361 }
1362
1363 AssertEqual(t, result2.data, 20)
1364 }
1365
1366 func TestQueryResetNullValue(t *testing.T) {
1367 type QueryResetItem struct {
1368 ID string `gorm:"type:varchar(5)"`
1369 Name string
1370 }
1371
1372 type QueryResetNullValue struct {
1373 ID int
1374 Name string `gorm:"default:NULL"`
1375 Flag bool `gorm:"default:NULL"`
1376 Number1 int64 `gorm:"default:NULL"`
1377 Number2 uint64 `gorm:"default:NULL"`
1378 Number3 float64 `gorm:"default:NULL"`
1379 Now *time.Time `gorm:"default:NULL"`
1380 Item1Id string
1381 Item1 *QueryResetItem `gorm:"references:ID"`
1382 Item2Id string
1383 Item2 *QueryResetItem `gorm:"references:ID"`
1384 }
1385
1386 DB.Migrator().DropTable(&QueryResetNullValue{}, &QueryResetItem{})
1387 DB.AutoMigrate(&QueryResetNullValue{}, &QueryResetItem{})
1388
1389 now := time.Now()
1390 q1 := QueryResetNullValue{
1391 Name: "name",
1392 Flag: true,
1393 Number1: 100,
1394 Number2: 200,
1395 Number3: 300.1,
1396 Now: &now,
1397 Item1: &QueryResetItem{
1398 ID: "u_1_1",
1399 Name: "item_1_1",
1400 },
1401 Item2: &QueryResetItem{
1402 ID: "u_1_2",
1403 Name: "item_1_2",
1404 },
1405 }
1406
1407 q2 := QueryResetNullValue{
1408 Item1: &QueryResetItem{
1409 ID: "u_2_1",
1410 Name: "item_2_1",
1411 },
1412 Item2: &QueryResetItem{
1413 ID: "u_2_2",
1414 Name: "item_2_2",
1415 },
1416 }
1417
1418 var err error
1419 err = DB.Create(&q1).Error
1420 if err != nil {
1421 t.Errorf("failed to create:%v", err)
1422 }
1423
1424 err = DB.Create(&q2).Error
1425 if err != nil {
1426 t.Errorf("failed to create:%v", err)
1427 }
1428
1429 var qs []QueryResetNullValue
1430 err = DB.Joins("Item1").Joins("Item2").Find(&qs).Error
1431 if err != nil {
1432 t.Errorf("failed to find:%v", err)
1433 }
1434
1435 if len(qs) != 2 {
1436 t.Fatalf("find count not equal:%d", len(qs))
1437 }
1438
1439 AssertEqual(t, q1, qs[0])
1440 AssertEqual(t, q2, qs[1])
1441 }
1442
1443 func TestQueryError(t *testing.T) {
1444 type P struct{}
1445 var p1 P
1446 err := DB.Take(&p1, 1).Error
1447 AssertEqual(t, err, gorm.ErrModelAccessibleFieldsRequired)
1448
1449 var p2 interface{}
1450
1451 err = DB.Table("ps").Clauses(clause.Eq{Column: clause.Column{
1452 Table: clause.CurrentTable, Name: clause.PrimaryKey,
1453 }, Value: 1}).Scan(&p2).Error
1454 AssertEqual(t, err, gorm.ErrModelValueRequired)
1455 }
1456
1457 func TestQueryScanToArray(t *testing.T) {
1458 err := DB.Create(&User{Name: "testname1", Age: 10}).Error
1459 if err != nil {
1460 t.Fatal(err)
1461 }
1462
1463 users := [2]*User{{Name: "1"}, {Name: "2"}}
1464 err = DB.Model(&User{}).Where("name = ?", "testname1").Find(&users).Error
1465 if err != nil {
1466 t.Fatal(err)
1467 }
1468 if users[0] == nil || users[0].Name != "testname1" {
1469 t.Error("users[0] not covered")
1470 }
1471 if users[1] != nil {
1472 t.Error("users[1] should be empty")
1473 }
1474 }