forked from go-gorm/gorm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgorm_test.go
1597 lines (1311 loc) · 45.2 KB
/
gorm_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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package gorm
import (
"database/sql"
"database/sql/driver"
"errors"
"fmt"
_ "github.com/go-sql-driver/mysql"
_ "github.com/lib/pq"
_ "github.com/mattn/go-sqlite3"
"os"
"reflect"
"strconv"
"testing"
"time"
)
type User struct {
Id int64 // Id: Primary key
Birthday time.Time // Time
Age int64
Name string `sql:"size:255"`
CreatedAt time.Time // CreatedAt: Time of record is created, will be insert automatically
UpdatedAt time.Time // UpdatedAt: Time of record is updated, will be updated automatically
DeletedAt time.Time // DeletedAt: Time of record is deleted, refer Soft Delete for more
Emails []Email // Embedded structs
BillingAddress Address // Embedded struct
BillingAddressId sql.NullInt64 // Embedded struct's foreign key
ShippingAddress Address // Embedded struct
ShippingAddressId int64 // Embedded struct's foreign key
When time.Time
CreditCard CreditCard
Latitude float64
PasswordHash []byte
IgnoreMe int64 `sql:"-"`
}
type CreditCard struct {
Id int8
Number string
UserId sql.NullInt64
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt time.Time
}
type Email struct {
Id int16
UserId int
Email string `sql:"type:varchar(100); unique"`
CreatedAt time.Time
UpdatedAt time.Time
}
type Address struct {
Id int
Address1 string
Address2 string
Post string
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt time.Time
}
type Product struct {
Id int64
Code string
Price int64
CreatedAt time.Time
UpdatedAt time.Time
BeforeCreateCallTimes int64
AfterCreateCallTimes int64
BeforeUpdateCallTimes int64
AfterUpdateCallTimes int64
BeforeSaveCallTimes int64
AfterSaveCallTimes int64
BeforeDeleteCallTimes int64
AfterDeleteCallTimes int64
}
var (
db DB
t1, t2, t3, t4, t5 time.Time
)
func init() {
var err error
switch os.Getenv("GORM_DIALECT") {
case "mysql":
// CREATE USER 'gorm'@'localhost' IDENTIFIED BY 'gorm';
// CREATE DATABASE 'gorm';
// GRANT ALL ON gorm.* TO 'gorm'@'localhost';
fmt.Println("testing mysql...")
db, err = Open("mysql", "gorm:gorm@/gorm?charset=utf8&parseTime=True")
case "sqlite":
fmt.Println("testing sqlite3...")
db, err = Open("sqlite3", "/tmp/gorm.db")
default:
fmt.Println("testing postgres...")
db, err = Open("postgres", "user=gorm dbname=gorm sslmode=disable")
}
// db.SetLogger(log.New(os.Stdout, "\r\n", 0))
db.LogMode(false)
if err != nil {
panic(fmt.Sprintf("No error should happen when connect database, but got %+v", err))
}
db.DB().SetMaxIdleConns(10)
if err := db.DropTable(&User{}).Error; err != nil {
fmt.Printf("Got error when try to delete table users, %+v\n", err)
}
db.Exec("drop table products;")
db.Exec("drop table emails;")
db.Exec("drop table addresses")
db.Exec("drop table credit_cards")
if err = db.CreateTable(&User{}).Error; err != nil {
panic(fmt.Sprintf("No error should happen when create table, but got %+v", err))
}
if err = db.CreateTable(&Product{}).Error; err != nil {
panic(fmt.Sprintf("No error should happen when create table, but got %+v", err))
}
if err = db.CreateTable(Email{}).Error; err != nil {
panic(fmt.Sprintf("No error should happen when create table, but got %+v", err))
}
if err = db.AutoMigrate(Address{}).Error; err != nil {
panic(fmt.Sprintf("No error should happen when create table, but got %+v", err))
}
if err = db.AutoMigrate(&CreditCard{}).Error; err != nil {
panic(fmt.Sprintf("No error should happen when create table, but got %+v", err))
}
var shortForm = "2006-01-02 15:04:05"
t1, _ = time.Parse(shortForm, "2000-10-27 12:02:40")
t2, _ = time.Parse(shortForm, "2002-01-01 00:00:00")
t3, _ = time.Parse(shortForm, "2005-01-01 00:00:00")
t4, _ = time.Parse(shortForm, "2010-01-01 00:00:00")
t5, _ = time.Parse(shortForm, "2020-01-01 00:00:00")
db.Save(&User{Name: "1", Age: 18, Birthday: t1, When: time.Now()})
db.Save(&User{Name: "2", Age: 20, Birthday: t2})
db.Save(&User{Name: "3", Age: 22, Birthday: t3})
db.Save(&User{Name: "3", Age: 24, Birthday: t4})
db.Save(&User{Name: "5", Age: 26, Birthday: t4})
}
func TestFirstAndLast(t *testing.T) {
var user1, user2, user3, user4 User
db.First(&user1)
db.Order("id").Find(&user2)
db.Last(&user3)
db.Order("id desc").Find(&user4)
if user1.Id != user2.Id || user3.Id != user4.Id {
t.Errorf("First and Last should works correctly")
}
var users []User
db.First(&users)
if len(users) != 1 {
t.Errorf("Find first record as map")
}
}
func TestPrecision(t *testing.T) {
f := 35.03554004971999
user := User{Name: "Precision", Latitude: f}
db.Save(&user)
if user.Latitude != f {
t.Errorf("Float64 should not be changed after save")
}
var u User
db.First(&u, "name = ?", "Precision")
if u.Latitude != f {
t.Errorf("Float64 should not be changed after query")
}
}
func TestCreateAndUpdate(t *testing.T) {
name, name2, new_name := "update", "update2", "new_update"
user := User{Name: name, Age: 1, PasswordHash: []byte{'f', 'a', 'k', '4'}}
if !db.NewRecord(user) {
t.Error("User should be new record")
}
if !db.NewRecord(&user) {
t.Error("User should be new record")
}
db.Save(&user)
if user.Id == 0 {
t.Errorf("Should have ID after create")
}
if db.NewRecord(user) {
t.Error("User should not new record after save")
}
if db.NewRecord(&user) {
t.Error("User should not new record after save")
}
var u User
db.First(&u, user.Id)
if !reflect.DeepEqual(u.PasswordHash, []byte{'f', 'a', 'k', '4'}) {
t.Errorf("User's Password should be saved")
}
db.Save(&User{Name: name2, Age: 1})
user.Name = new_name
db.Save(&user)
if db.Where("name = ?", name).First(&User{}).Error != RecordNotFound {
t.Errorf("Should raise RecordNotFound error when looking with an outdated name")
}
if db.Where("name = ?", new_name).First(&User{}).Error != nil {
t.Errorf("Shouldn't raise error when looking with the new name")
}
if db.Where("name = ?", name2).First(&User{}).Error != nil {
t.Errorf("Shouldn't update other users when update one")
}
}
func TestDelete(t *testing.T) {
name, name2 := "delete", "delete2"
user := User{Name: name, Age: 1}
db.Save(&user)
db.Save(&User{Name: name2, Age: 1})
if db.Delete(&user).Error != nil {
t.Errorf("Shouldn't raise any error when delete a user")
}
if db.Where("name = ?", name).First(&User{}).Error == nil {
t.Errorf("User can't be found after delete")
}
if db.Where("name = ?", name2).First(&User{}).Error != nil {
t.Errorf("Other users shouldn't be deleted")
}
}
func TestWhere(t *testing.T) {
name := "where"
db.Save(&User{Name: name, Age: 1})
user := &User{}
db.Where("name = ?", name).First(user)
if user.Name != name {
t.Errorf("Search user with name")
}
if db.Where(user.Id).First(&User{}).Error != nil {
t.Errorf("Search user with primary key")
}
if db.Where("name LIKE ?", "%nonono%").First(&User{}).Error == nil {
t.Errorf("Search non-existing user with regexp name")
}
if db.Where("name LIKE ?", "%whe%").First(&User{}).Error != nil {
t.Errorf("Search user with regexp name")
}
if db.Where("name = ?", "non-existing user").First(&User{}).Error == nil {
t.Errorf("Search non-existing user should get error")
}
var users []User
if db.Where("name = ?", "none-noexisting").Find(&users).Error != nil {
t.Errorf("Shouldn't return error when looking for none existing records with find")
}
if len(users) != 0 {
t.Errorf("Users should be empty")
}
}
func TestComplexWhere(t *testing.T) {
var users []User
db.Where("age > ?", 20).Find(&users)
if len(users) != 3 {
t.Errorf("Should found 3 users that age > 20, but got %v", len(users))
}
var user_ids []int64
db.Table("users").Where("age > ?", 20).Pluck("id", &user_ids)
if len(user_ids) != 3 {
t.Errorf("Should found 3 users that age > 20, but got %v", len(users))
}
users = []User{}
db.Where(user_ids).Find(&users)
if len(users) != 3 {
t.Errorf("Should found 3 users that age > 20 when search with primary keys, but got %v", len(users))
}
users = []User{}
db.Where("age >= ?", 20).Find(&users)
if len(users) != 4 {
t.Errorf("Should found 4 users that age >= 20, but got %v", len(users))
}
users = []User{}
db.Where("age = ?", 20).Find(&users)
if len(users) != 1 {
t.Errorf("Should found 1 users age == 20, but got %v", len(users))
}
users = []User{}
db.Where("age <> ?", 20).Find(&users)
if len(users) < 3 {
t.Errorf("Should found more than 3 users age != 20, but got %v", len(users))
}
users = []User{}
db.Where("name = ? and age >= ?", "3", 20).Find(&users)
if len(users) != 2 {
t.Errorf("Should found 2 users that age >= 20 with name 3, but got %v", len(users))
}
users = []User{}
db.Where("name = ?", "3").Where("age >= ?", 20).Find(&users)
if len(users) != 2 {
t.Errorf("Should found 2 users that age >= 20 with name 3, but got %v", len(users))
}
users = []User{}
db.Where("birthday > ?", t2).Find(&users)
if len(users) != 3 {
t.Errorf("Should found 3 users's birthday >= t2, but got %v", len(users))
}
users = []User{}
db.Where("birthday > ?", "2002-10-10").Find(&users)
if len(users) != 3 {
t.Errorf("Should found 3 users's birthday >= 2002-10-10, but got %v", len(users))
}
users = []User{}
db.Where("birthday >= ?", t1).Where("birthday < ?", t2).Find(&users)
if len(users) != 1 {
t.Errorf("Should found 1 users's birthday <= t2, but got %v", len(users))
}
users = []User{}
db.Where("birthday >= ? and birthday <= ?", t1, t2).Find(&users)
if len(users) != 2 {
t.Errorf("Should found 2 users's birthday <= t2, but got %v", len(users))
}
users = []User{}
db.Where("name in (?)", []string{"1", "3"}).Find(&users)
if len(users) != 3 {
t.Errorf("Should found 3 users's name in (1, 3), but got %v", len(users))
}
user_ids = []int64{}
for _, user := range users {
user_ids = append(user_ids, user.Id)
}
users = []User{}
db.Where("id in (?)", user_ids).Find(&users)
if len(users) != 3 {
t.Errorf("Should found 3 users's name in (1, 3), but got %v", len(users))
}
users = []User{}
db.Where("id in (?)", user_ids[0]).Find(&users)
if len(users) != 1 {
t.Errorf("Should found 1 users's name in (1), but got %v", len(users))
}
users = []User{}
db.Where("name in (?)", []string{"1", "2"}).Find(&users)
if len(users) != 2 {
t.Errorf("Should found 2 users's name in (1, 2), but got %v", len(users))
}
}
func TestSearchWithStruct(t *testing.T) {
var user User
db.First(&user, &User{Name: "2"})
if user.Id == 0 || user.Name != "2" {
t.Errorf("Search first record with inline struct pointer")
}
db.First(&user, User{Name: "2"})
if user.Id == 0 || user.Name != "2" {
t.Errorf("Search first record with inline struct")
}
db.Where(&User{Name: "2"}).First(&user)
if user.Id == 0 || user.Name != "2" {
t.Errorf("Search first record with where struct")
}
var users []User
db.Find(&users, &User{Name: "3"})
if len(users) != 2 {
t.Errorf("Search all records with inline struct")
}
db.Where(User{Name: "3"}).Find(&users)
if user.Id == 0 || user.Name != "2" {
t.Errorf("Search all records with where struct")
}
}
func TestSearchWithMap(t *testing.T) {
var user User
db.First(&user, map[string]interface{}{"name": "2"})
if user.Id == 0 || user.Name != "2" {
t.Errorf("Search first record with inline map")
}
db.Where(map[string]interface{}{"name": "2"}).First(&user)
if user.Id == 0 || user.Name != "2" {
t.Errorf("Search first record with where map")
}
var users []User
db.Find(&users, map[string]interface{}{"name": "3"})
if len(users) != 2 {
t.Errorf("Search all records with inline map")
}
db.Where(map[string]interface{}{"name": "3"}).Find(&users)
if user.Id == 0 || user.Name != "2" {
t.Errorf("Search all records with where map")
}
}
func TestInitlineCondition(t *testing.T) {
var u1, u2, u3, u4, u5, u6, u7 User
db.Where("name = ?", "3").Order("age desc").First(&u1).First(&u2)
db.Where("name = ?", "3").First(&u3, "age = 22").First(&u4, "age = ?", 24).First(&u5, "age = ?", 26)
if !((u5.Id == 0) && (u3.Age == 22 && u3.Name == "3") && (u4.Age == 24 && u4.Name == "3")) {
t.Errorf("Find first record with inline condition and where")
}
db.First(&u6, u1.Id)
if !(u6.Id == u1.Id && u6.Id != 0) {
t.Errorf("Find first record with primary key")
}
db.First(&u7, strconv.Itoa(int(u1.Id)))
if !(u6.Id == u1.Id && u6.Id != 0) {
t.Errorf("Find first record with string primary key")
}
var us1, us2, us3, us4 []User
db.Find(&us1, "age = 22").Find(&us2, "name = ?", "3").Find(&us3, "age > ?", 20)
if !(len(us1) == 1 && len(us2) == 2 && len(us3) == 3) {
t.Errorf("Find all records with inline condition and where")
}
db.Find(&us4, "name = ? and age > ?", "3", "22")
if len(us4) != 1 {
t.Errorf("Find all records with complex inline condition")
}
}
func TestSelect(t *testing.T) {
var user User
db.Where("name = ?", "3").Select("name").Find(&user)
if user.Id != 0 {
t.Errorf("Should not have ID because only searching age, %+v", user.Id)
}
if user.Name != "3" {
t.Errorf("Should got Name = 3 when searching with it, %+v", user.Id)
}
query := db.Where("name = ?", "3").Select("nam;e")
if query.Error == nil {
t.Errorf("Should got error with invalid select string")
}
}
func TestOrderAndPluck(t *testing.T) {
var ages, ages1, ages2, ages3, ages4, ages5 []int64
db.Model(&[]User{}).Order("age desc").Pluck("age", &ages)
if ages[0] != 26 {
t.Errorf("The first age should be 26 when order with age desc")
}
db.Model([]User{}).Order("age desc").Pluck("age", &ages1).Order("age").Pluck("age", &ages2)
if !reflect.DeepEqual(ages1, ages2) {
t.Errorf("The first order is the primary order")
}
db.Model(&User{}).Order("age desc").Pluck("age", &ages3).Order("age", true).Pluck("age", &ages4)
if reflect.DeepEqual(ages3, ages4) {
t.Errorf("Reorder should works")
}
var names []string
db.Model(User{}).Order("name").Order("age desc").Pluck("age", &ages5).Pluck("name", &names)
if !(names[0] == "1" && names[2] == "3" && names[3] == "3" && ages5[2] == 24 && ages5[3] == 22) {
t.Errorf("Order with multiple orders")
}
db.Model(User{}).Select("name, age").Find(&[]User{})
}
func TestLimit(t *testing.T) {
var users1, users2, users3 []User
db.Order("age desc").Limit(3).Find(&users1).Limit(5).Find(&users2).Limit(-1).Find(&users3)
if len(users1) != 3 || len(users2) != 5 || len(users3) <= 5 {
t.Errorf("Limit should works")
}
}
func TestOffset(t *testing.T) {
var users1, users2, users3, users4 []User
db.Limit(100).Order("age desc").Find(&users1).Offset(3).Find(&users2).Offset(5).Find(&users3).Offset(-1).Find(&users4)
if (len(users1) != len(users4)) || (len(users1)-len(users2) != 3) || (len(users1)-len(users3) != 5) {
t.Errorf("Offset should works")
}
}
func TestOr(t *testing.T) {
var users []User
db.Where("name = ?", "1").Or("name = ?", "3").Find(&users)
if len(users) != 3 {
t.Errorf("Find users with or")
}
}
func TestCount(t *testing.T) {
var count, count1, count2 int64
var users []User
if err := db.Where("name = ?", "1").Or("name = ?", "3").Find(&users).Count(&count).Error; err != nil {
t.Errorf("Count should works", err)
}
if count != int64(len(users)) {
t.Errorf("Count() method should get correct value")
}
db.Model(&User{}).Where("name = ?", "1").Count(&count1).Or("name = ?", "3").Count(&count2)
if count1 != 1 || count2 != 3 {
t.Errorf("Multiple count should works")
}
}
func TestCreatedAtAndUpdatedAt(t *testing.T) {
name := "check_created_at_and_updated_at"
u := User{Name: name, Age: 1}
db.Save(&u)
created_at := u.CreatedAt
updated_at := u.UpdatedAt
if created_at.IsZero() {
t.Errorf("Should have created_at after create")
}
if updated_at.IsZero() {
t.Errorf("Should have updated_at after create")
}
u.Name = "check_created_at_and_updated_at_2"
db.Save(&u)
created_at2 := u.CreatedAt
updated_at2 := u.UpdatedAt
if created_at != created_at2 {
t.Errorf("Created At should not changed after update")
}
if updated_at == updated_at2 {
t.Errorf("Updated At should be changed after update")
}
}
func (s *Product) BeforeCreate() (err error) {
if s.Code == "Invalid" {
err = errors.New("invalid product")
}
s.BeforeCreateCallTimes = s.BeforeCreateCallTimes + 1
return
}
func (s *Product) BeforeUpdate() (err error) {
if s.Code == "dont_update" {
err = errors.New("Can't update")
}
s.BeforeUpdateCallTimes = s.BeforeUpdateCallTimes + 1
return
}
func (s *Product) BeforeSave() (err error) {
if s.Code == "dont_save" {
err = errors.New("Can't save")
}
s.BeforeSaveCallTimes = s.BeforeSaveCallTimes + 1
return
}
func (s *Product) AfterCreate(db *DB) {
db.Model(s).UpdateColumn(Product{AfterCreateCallTimes: s.AfterCreateCallTimes + 1})
}
func (s *Product) AfterUpdate() {
s.AfterUpdateCallTimes = s.AfterUpdateCallTimes + 1
}
func (s *Product) AfterSave() (err error) {
if s.Code == "after_save_error" {
err = errors.New("Can't save")
}
s.AfterSaveCallTimes = s.AfterSaveCallTimes + 1
return
}
func (s *Product) BeforeDelete() (err error) {
if s.Code == "dont_delete" {
err = errors.New("Can't delete")
}
s.BeforeDeleteCallTimes = s.BeforeDeleteCallTimes + 1
return
}
func (s *Product) AfterDelete() (err error) {
if s.Code == "after_delete_error" {
err = errors.New("Can't delete")
}
s.AfterDeleteCallTimes = s.AfterDeleteCallTimes + 1
return
}
func (p *Product) GetCallTimes() []int64 {
return []int64{p.BeforeCreateCallTimes, p.BeforeSaveCallTimes, p.BeforeUpdateCallTimes, p.AfterCreateCallTimes, p.AfterSaveCallTimes, p.AfterUpdateCallTimes, p.BeforeDeleteCallTimes, p.AfterDeleteCallTimes}
}
func TestRunCallbacks(t *testing.T) {
p := Product{Code: "unique_code", Price: 100}
db.Save(&p)
if !reflect.DeepEqual(p.GetCallTimes(), []int64{1, 1, 0, 1, 1, 0, 0, 0}) {
t.Errorf("Callbacks should be invoked successfully, %v", p.GetCallTimes())
}
db.Where("Code = ?", "unique_code").First(&p)
if !reflect.DeepEqual(p.GetCallTimes(), []int64{1, 1, 0, 1, 0, 0, 0, 0}) {
t.Errorf("After callbacks values are not saved, %v", p.GetCallTimes())
}
p.Price = 200
db.Save(&p)
if !reflect.DeepEqual(p.GetCallTimes(), []int64{1, 2, 1, 1, 1, 1, 0, 0}) {
t.Errorf("After update callbacks should be invoked successfully, %v", p.GetCallTimes())
}
db.Where("Code = ?", "unique_code").First(&p)
if !reflect.DeepEqual(p.GetCallTimes(), []int64{1, 2, 1, 1, 0, 0, 0, 0}) {
t.Errorf("After update callbacks values are not saved, %v", p.GetCallTimes())
}
db.Delete(&p)
if !reflect.DeepEqual(p.GetCallTimes(), []int64{1, 2, 1, 1, 0, 0, 1, 1}) {
t.Errorf("After delete callbacks should be invoked successfully, %v", p.GetCallTimes())
}
if db.Where("Code = ?", "unique_code").First(&p).Error == nil {
t.Errorf("Can't find a deleted record")
}
}
func TestCallbacksWithErrors(t *testing.T) {
p := Product{Code: "Invalid", Price: 100}
if db.Save(&p).Error == nil {
t.Errorf("An error from before create callbacks happened when create with invalid value")
}
if db.Where("code = ?", "Invalid").First(&Product{}).Error == nil {
t.Errorf("Should not save record that have errors")
}
if db.Save(&Product{Code: "dont_save", Price: 100}).Error == nil {
t.Errorf("An error from after create callbacks happened when create with invalid value")
}
p2 := Product{Code: "update_callback", Price: 100}
db.Save(&p2)
p2.Code = "dont_update"
if db.Save(&p2).Error == nil {
t.Errorf("An error from before update callbacks happened when update with invalid value")
}
if db.Where("code = ?", "update_callback").First(&Product{}).Error != nil {
t.Errorf("Record Should not be updated due to errors happened in before update callback")
}
if db.Where("code = ?", "dont_update").First(&Product{}).Error == nil {
t.Errorf("Record Should not be updated due to errors happened in before update callback")
}
p2.Code = "dont_save"
if db.Save(&p2).Error == nil {
t.Errorf("An error from before save callbacks happened when update with invalid value")
}
p3 := Product{Code: "dont_delete", Price: 100}
db.Save(&p3)
if db.Delete(&p3).Error == nil {
t.Errorf("An error from before delete callbacks happened when delete")
}
if db.Where("Code = ?", "dont_delete").First(&p3).Error != nil {
t.Errorf("An error from before delete callbacks happened")
}
p4 := Product{Code: "after_save_error", Price: 100}
db.Save(&p4)
if err := db.First(&Product{}, "code = ?", "after_save_error").Error; err == nil {
t.Errorf("Record should be reverted if get an error in after save callback", err)
}
p5 := Product{Code: "after_delete_error", Price: 100}
db.Save(&p5)
if err := db.First(&Product{}, "code = ?", "after_delete_error").Error; err != nil {
t.Errorf("Record should be found", err)
}
db.Delete(&p5)
if err := db.First(&Product{}, "code = ?", "after_delete_error").Error; err != nil {
t.Errorf("Record shouldn't be deleted because of an error happened in after delete callback", err)
}
}
func TestFillSmallerStructCorrectly(t *testing.T) {
type SimpleUser struct {
Name string
Id int64
UpdatedAt time.Time
CreatedAt time.Time
}
var simple_user SimpleUser
db.Table("users").Find(&simple_user)
if simple_user.Id == 0 || simple_user.Name == "" {
t.Errorf("Should fill data correctly even some column missing")
}
}
func TestExceptionsWithInvalidSql(t *testing.T) {
var columns []string
if db.Where("sdsd.zaaa = ?", "sd;;;aa").Pluck("aaa", &columns).Error == nil {
t.Errorf("Should got error with invalid SQL")
}
if db.Model(&User{}).Where("sdsd.zaaa = ?", "sd;;;aa").Pluck("aaa", &columns).Error == nil {
t.Errorf("Should got error with invalid SQL")
}
type Article struct {
Name string
}
db.Where("sdsd.zaaa = ?", "sd;;;aa").Find(&Article{})
db.Where("name = ?", "3").Find(&[]User{})
var count1, count2 int64
db.Model(&User{}).Count(&count1)
if count1 <= 0 {
t.Errorf("Should find some users")
}
q := db.Where("name = ?", "jinzhu; delete * from users").First(&User{})
if q.Error == nil {
t.Errorf("Can't find user")
}
db.Model(&User{}).Count(&count2)
if count1 != count2 {
t.Errorf("Users should not be deleted by invalid SQL")
}
db.Where("non-existing = ?", "3").Find(&[]User{})
}
func TestSetTableDirectly(t *testing.T) {
var ages []int64
if db.Table("users").Pluck("age", &ages).Error != nil {
t.Errorf("No errors should happen if set table for pluck")
}
if len(ages) == 0 {
t.Errorf("Should get some records")
}
var users []User
if db.Table("users").Find(&users).Error != nil {
t.Errorf("No errors should happen if set table for find")
}
if db.Table("unexisting_users_table").Find(&users).Error == nil {
t.Errorf("Should got error if set table to an invalid table")
}
db.Exec("drop table deleted_users;")
if db.Table("deleted_users").CreateTable(&User{}).Error != nil {
t.Errorf("Should create table with specified table")
}
db.Table("deleted_users").Save(&User{Name: "DeletedUser"})
var deleted_users []User
db.Table("deleted_users").Find(&deleted_users)
if len(deleted_users) != 1 {
t.Errorf("Query from specified table")
}
var deleted_user User
db.Table("deleted_users").First(&deleted_user)
if deleted_user.Name != "DeletedUser" {
t.Errorf("Query from specified table")
}
var user1, user2, user3 User
db.First(&user1).Table("deleted_users").First(&user2).Table("").First(&user3)
if (user1.Name == user2.Name) || (user1.Name != user3.Name) {
t.Errorf("unset specified table with blank string")
}
}
func TestUpdate(t *testing.T) {
product1 := Product{Code: "123"}
product2 := Product{Code: "234"}
db.Save(&product1).Save(&product2).Update("code", "456")
if product2.Code != "456" {
t.Errorf("Record should be updated with update attributes")
}
db.First(&product1, product1.Id)
db.First(&product2, product2.Id)
updated_at1 := product1.UpdatedAt
updated_at2 := product2.UpdatedAt
var product3 Product
db.First(&product3, product2.Id).Update("code", "456")
if updated_at2.Format(time.RFC3339Nano) != product3.UpdatedAt.Format(time.RFC3339Nano) {
t.Errorf("updated_at should not be updated if nothing changed")
}
if db.First(&Product{}, "code = '123'").Error != nil {
t.Errorf("Product 123 should not be updated")
}
if db.First(&Product{}, "code = '234'").Error == nil {
t.Errorf("Product 234 should be changed to 456")
}
if db.First(&Product{}, "code = '456'").Error != nil {
t.Errorf("Product 234 should be changed to 456")
}
db.Table("products").Where("code in (?)", []string{"123"}).Update("code", "789")
var product4 Product
db.First(&product4, product1.Id)
if updated_at1.Format(time.RFC3339Nano) != product4.UpdatedAt.Format(time.RFC3339Nano) {
t.Errorf("updated_at should be updated if something changed")
}
if db.First(&Product{}, "code = '123'").Error == nil {
t.Errorf("Product 123 should be changed to 789")
}
if db.First(&Product{}, "code = '456'").Error != nil {
t.Errorf("Product 456 should not be changed to 789")
}
if db.First(&Product{}, "code = '789'").Error != nil {
t.Errorf("Product 456 should be changed to 789")
}
if db.Model(product2).Update("CreatedAt", time.Now().Add(time.Hour)).Error != nil {
t.Error("No error should raise when update with CamelCase")
}
if db.Model(&product2).UpdateColumn("CreatedAt", time.Now().Add(time.Hour)).Error != nil {
t.Error("No error should raise when update_column with CamelCase")
}
}
func TestUpdates(t *testing.T) {
product1 := Product{Code: "abc", Price: 10}
product2 := Product{Code: "cde", Price: 20}
db.Save(&product1).Save(&product2).Updates(map[string]interface{}{"code": "edf", "price": 100})
if product2.Code != "edf" || product2.Price != 100 {
t.Errorf("Record should be updated also with update attributes")
}
db.First(&product1, product1.Id)
db.First(&product2, product2.Id)
updated_at1 := product1.UpdatedAt
updated_at2 := product2.UpdatedAt
var product3 Product
db.First(&product3, product2.Id).Updates(Product{Code: "edf", Price: 100})
if product3.Code != "edf" || product3.Price != 100 {
t.Errorf("Record should be updated with update attributes")
}
if updated_at2.Format(time.RFC3339Nano) != product3.UpdatedAt.Format(time.RFC3339Nano) {
t.Errorf("updated_at should not be updated if nothing changed")
}
if db.First(&Product{}, "code = 'abc' and price = 10").Error != nil {
t.Errorf("Product abc should not be updated")
}
if db.First(&Product{}, "code = 'cde'").Error == nil {
t.Errorf("Product cde should be renamed to edf")
}
if db.First(&Product{}, "code = 'edf' and price = 100").Error != nil {
t.Errorf("Product cde should be renamed to edf")
}
db.Table("products").Where("code in (?)", []string{"abc"}).Updates(map[string]string{"code": "fgh", "price": "200"})
if db.First(&Product{}, "code = 'abc'").Error == nil {
t.Errorf("Product abc's code should be changed to fgh")
}
var product4 Product
db.First(&product4, product1.Id)
if updated_at1.Format(time.RFC3339Nano) != product4.UpdatedAt.Format(time.RFC3339Nano) {
t.Errorf("updated_at should be updated if something changed")
}
if db.First(&Product{}, "code = 'edf' and price = ?", 100).Error != nil {
t.Errorf("Product cde's code should not be changed to fgh")
}
if db.First(&Product{}, "code = 'fgh' and price = 200").Error != nil {
t.Errorf("We should have Product fgh")
}
}
func TestUpdateColumn(t *testing.T) {
product1 := Product{Code: "update_column 1", Price: 10}
product2 := Product{Code: "update_column 2", Price: 20}
db.Save(&product1).Save(&product2).UpdateColumn(map[string]interface{}{"code": "update_column 3", "price": 100})
if product2.Code != "update_column 3" || product2.Price != 100 {
t.Errorf("product 2 should be updated with update column")
}
var product3 Product
db.First(&product3, product1.Id)
if product3.Code != "update_column 1" || product3.Price != 10 {
t.Errorf("product 1 should not be updated")
}
var product4, product5 Product
db.First(&product4, product2.Id)
updated_at1 := product4.UpdatedAt
db.Model(Product{}).Where(product2.Id).UpdateColumn("code", "update_column_new")
db.First(&product5, product2.Id)
if updated_at1.Format(time.RFC3339Nano) != product5.UpdatedAt.Format(time.RFC3339Nano) {
t.Errorf("updated_at should not be updated with update column")
}
}
func TestSoftDelete(t *testing.T) {
type Order struct {
Id int64
Amount int64
DeletedAt time.Time
}
db.Exec("drop table orders;")
db.CreateTable(&Order{})
order := Order{Amount: 1234}
db.Save(&order)
if db.First(&Order{}, "amount = ?", 1234).Error != nil {
t.Errorf("No errors should happen when save an order")
}