-
Notifications
You must be signed in to change notification settings - Fork 17
/
builder_test.go
1693 lines (1335 loc) · 43 KB
/
builder_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 buildsqlx
import (
"database/sql"
"errors"
"fmt"
"os"
"testing"
"time"
_ "github.com/lib/pq"
"github.com/stretchr/testify/require"
)
const (
TestTable = "test"
PostsTable = "test_posts"
UsersTable = "test_users"
TestUserName = "Dead Beaf"
)
type DataStruct struct {
Foo string
Bar string
Baz *int64
}
var (
dbConnInfo = fmt.Sprintf("host=%s port=%d user=%s "+
"password=%s dbname=%s sslmode=disable",
"localhost", 5432, "postgres", "postgres", "postgres")
dataMap = map[string]interface{}{"foo": "foo foo foo", "bar": "bar bar bar", "baz": int64(123)}
baz = int64(123)
data = DataStruct{
Foo: "foo foo foo",
Bar: "bar bar bar",
Baz: &baz,
}
db = NewDb(NewConnection("postgres", dbConnInfo))
)
func TestMain(m *testing.M) {
_, err := db.Sql().Exec("create table if not exists test_users (id serial primary key, name varchar(128) not null, points integer)")
if err != nil {
panic(err)
}
_, err = db.Sql().Exec("create table if not exists test_posts (id serial primary key, title varchar(128) not null, post text, user_id integer, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW())")
if err != nil {
panic(err)
}
_, err = db.Sql().Exec("create table if not exists test (id serial primary key, foo varchar(128) not null, bar varchar(128) not null, baz integer)")
if err != nil {
panic(err)
}
os.Exit(m.Run())
}
// TestNewConnectionFromDB tests the NewConnectionFromDB function.
//
// This function takes a testing.T object as a parameter and creates a new connection
// from a database. It then asserts that the created connection's "db" field is equal
// to the provided sql.DB object.
func TestNewConnectionFromDB(t *testing.T) {
conn := NewConnectionFromDb(&sql.DB{})
require.Equal(t, conn.db, &sql.DB{})
}
// TestSelectAndLimit is a test function that tests the SelectAndLimit functionality.
//
// It truncates the TestTable, inserts data into it, performs a select query with specific columns and a limit of 15,
// and scans the results into a slice of DataStruct.
// Finally, it asserts that the expected data is equal to the scanned data, and that the length of the testStructs slice is 2.
func TestSelectAndLimit(t *testing.T) {
_, err := db.Truncate(TestTable)
require.NoError(t, err)
err = db.Table(TestTable).Insert(data)
require.NoError(t, err)
err = db.Table(TestTable).Insert(data)
require.NoError(t, err)
toScan := DataStruct{}
qDb := db.Table(TestTable).Select("foo", "bar")
var testStructs []DataStruct
err = qDb.AddSelect("baz").Limit(15).EachToStruct(func(rows *sql.Rows) error {
err = db.Next(rows, &toScan)
if err != nil {
return err
}
testStructs = append(testStructs, toScan)
return nil
})
require.NoError(t, err)
require.Equal(t, data, toScan)
require.Len(t, testStructs, 2)
for _, strct := range testStructs {
require.Equal(t, data.Foo, strct.Foo)
require.Equal(t, data.Bar, strct.Bar)
require.Equal(t, data.Baz, strct.Baz)
}
_, err = db.Truncate(TestTable)
require.NoError(t, err)
}
func TestDB_EachToStruct_RetErr(t *testing.T) {
err := db.Table(TestTable).Select("foo", "bar").EachToStruct(func(rows *sql.Rows) error {
return errors.New("some err")
})
require.EqualError(t, err, "some err")
}
func TestDB_ChunkErrs(t *testing.T) {
_, err := db.Truncate(TestTable)
require.NoError(t, err)
err = db.Table(TestTable).Insert(data)
require.NoError(t, err)
err = db.Table("").Chunk(&DataStruct{}, 1, func(rows []any) bool {
return false
})
require.EqualError(t, err, "pq: zero-length delimited identifier at or near \"\"\"\"")
var nilPtr *int = nil
err = db.Table(TestTable).Chunk(nilPtr, 1, func(rows []any) bool {
return false
})
require.EqualError(t, err, "cannot decode into nil type *int")
err = db.Table(TestTable).Chunk(nilPtr, 2, func(rows []any) bool {
return false
})
require.EqualError(t, err, "cannot decode into nil type *int")
_, err = db.Truncate(TestTable)
require.NoError(t, err)
}
func TestInsert(t *testing.T) {
_, err := db.Truncate(TestTable)
require.NoError(t, err)
err = db.Table(TestTable).Insert(data)
require.NoError(t, err)
dataStruct := &DataStruct{}
err = db.Table(TestTable).Select("foo", "bar", "baz").ScanStruct(dataStruct)
require.NoError(t, err)
require.Equal(t, data, data)
_, err = db.Truncate(TestTable)
require.NoError(t, err)
}
var batchDataStruct = []DataStruct{
{Foo: "foo foo foo", Bar: "bar bar bar", Baz: &baz},
{Foo: "foo foo foo foo", Bar: "bar bar bar bar", Baz: &baz},
{Foo: "foo foo foo foo foo", Bar: "bar bar bar bar bar", Baz: &baz},
}
func TestInsertBatchSelectMultiple(t *testing.T) {
_, err := db.Truncate(TestTable)
require.NoError(t, err)
err = db.Table(TestTable).InsertBatch(batchDataStruct)
require.NoError(t, err)
dataStruct := DataStruct{}
var dataStructs []DataStruct
err = db.Table(TestTable).Select("foo", "bar", "baz").OrderBy("foo", "ASC").
EachToStruct(func(rows *sql.Rows) error {
err = db.Next(rows, &dataStruct)
if err != nil {
return err
}
dataStructs = append(dataStructs, dataStruct)
return nil
})
require.NoError(t, err)
for mapKey, dStruct := range dataStructs {
require.Equal(t, batchDataStruct[mapKey], dStruct)
}
_, err = db.Truncate(TestTable)
require.NoError(t, err)
}
func TestWhereOnly(t *testing.T) {
var cmp = "foo foo foo"
_, err := db.Truncate(TestTable)
require.NoError(t, err)
err = db.Table(TestTable).InsertBatch(batchDataStruct)
require.NoError(t, err)
dataStruct := &DataStruct{}
err = db.Table(TestTable).Select("foo", "bar", "baz").Where("foo", "=", cmp).ScanStruct(dataStruct)
require.NoError(t, err)
require.Equal(t, dataStruct.Foo, cmp)
_, err = db.Truncate(TestTable)
require.NoError(t, err)
}
func TestWhereAndOr(t *testing.T) {
var cmp = "foo foo foo"
_, err := db.Truncate(TestTable)
require.NoError(t, err)
err = db.Table(TestTable).InsertBatch(batchDataStruct)
require.NoError(t, err)
dataStruct := &DataStruct{}
err = db.Table(TestTable).Select("foo", "bar", "baz").Where("foo", "=", cmp).
AndWhere("bar", "!=", "foo").
OrWhere("baz", "=", 123).ScanStruct(dataStruct)
require.NoError(t, err)
require.Equal(t, dataStruct.Foo, cmp)
_, err = db.Truncate(TestTable)
require.NoError(t, err)
}
var batchUsers = []DataStructUser{
{ID: int64(1), Name: "Alex Shmidt", Points: int64(123)},
{ID: int64(2), Name: "Darth Vader", Points: int64(1234)},
{ID: int64(3), Name: "Dead Beaf", Points: int64(12345)},
{ID: int64(4), Name: "Dead Beaf", Points: int64(12345)},
}
type DataStructPost struct {
ID int64
Title string
Post *string
UserID *int64 `db:"user_id"`
UpdatedAt time.Time `db:"updated_at"`
}
var userID, userIDTwo, userIDThree = int64(1), int64(2), int64(3)
var post = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
var timeNow = time.Now()
var batchPosts = []DataStructPost{
{ID: 1, Title: "Lorem ipsum dolor sit amet,", Post: &post, UserID: &userID, UpdatedAt: timeNow},
{ID: 2, Title: "Sed ut perspiciatis unde omnis iste natus", Post: &post, UserID: &userIDTwo, UpdatedAt: timeNow},
{ID: 3, Title: "Ut enim ad minima veniam", Post: &post, UserID: &userIDThree, UpdatedAt: timeNow},
{ID: 4, Title: "Lorem ipsum dolor sit amet,", Post: nil, UserID: nil, UpdatedAt: timeNow},
}
type DataStructUser struct {
ID int64
Name string
Points int64
}
type DataStructUserPosts struct {
ID int64
Name *string
Post *string
Points *int64
UserID *int64 `db:"user_id"`
}
var batchUsersStruct = []DataStructUser{
0: {ID: int64(1), Name: "Alex Shmidt", Points: int64(123)},
1: {ID: int64(2), Name: "Darth Vader", Points: int64(1234)},
2: {ID: int64(3), Name: "Dead Beaf", Points: int64(12345)},
3: {ID: int64(4), Name: "Dead Beaf", Points: int64(12345)},
}
func TestJoins(t *testing.T) {
_, err := db.Truncate(UsersTable)
require.NoError(t, err)
_, err = db.Truncate(PostsTable)
require.NoError(t, err)
var posts []DataStructPost
for _, v := range batchUsersStruct {
id, err := db.Table(UsersTable).InsertGetId(v)
require.NoError(t, err)
iID := int64(id)
posts = append(posts, DataStructPost{
ID: v.ID, Title: "ttl", Post: &post, UserID: &iID,
})
}
err = db.Table(PostsTable).InsertBatch(posts)
require.NoError(t, err)
var dataStructs []DataStructUserPosts
dataStruct := &DataStructUserPosts{}
err = db.Table(UsersTable).Select("name", "post", "user_id").LeftJoin(
PostsTable, UsersTable+".id", "=", PostsTable+".user_id").EachToStruct(func(rows *sql.Rows) error {
err = db.Next(rows, dataStruct)
if err != nil {
return err
}
dataStructs = append(dataStructs, *dataStruct)
return nil
})
require.NoError(t, err)
for k, val := range dataStructs {
require.Equal(t, *val.Name, batchUsers[k].Name)
require.Equal(t, *val.Post, *posts[k].Post)
require.Equal(t, *val.UserID, *posts[k].UserID)
}
_, err = db.Truncate(UsersTable)
require.NoError(t, err)
_, err = db.Truncate(PostsTable)
require.NoError(t, err)
}
var rowsToUpdate = []struct {
insert DataStruct
update DataStruct
}{
{DataStruct{Foo: "foo foo foo", Bar: "bar bar bar", Baz: &baz}, DataStruct{Foo: "foo changed", Baz: nil}},
}
func TestUpdate(t *testing.T) {
_, err := db.Truncate(TestTable)
require.NoError(t, err)
for _, obj := range rowsToUpdate {
err = db.Table(TestTable).Insert(obj.insert)
require.NoError(t, err)
rows, err := db.Table(TestTable).Where("foo", "=", "foo foo foo").Update(obj.update)
require.NoError(t, err)
require.GreaterOrEqual(t, rows, int64(1))
dataStruct := &DataStruct{}
err = db.Table(TestTable).Select("foo").Where("foo", "=", obj.update.Foo).
ScanStruct(dataStruct)
require.NoError(t, err)
require.Equal(t, obj.update.Foo, dataStruct.Foo)
}
_, err = db.Truncate(TestTable)
require.NoError(t, err)
}
var rowsToDelete = []struct {
insert DataStruct
where map[string]interface{}
}{
{DataStruct{Foo: "foo foo foo", Bar: "bar bar bar", Baz: &baz}, map[string]interface{}{"bar": 123}},
}
func TestDelete(t *testing.T) {
_, err := db.Truncate(TestTable)
require.NoError(t, err)
for _, obj := range rowsToDelete {
err := db.Table(TestTable).Insert(obj.insert)
require.NoError(t, err)
rows, err := db.Table(TestTable).Where("baz", "=", obj.where["bar"]).Delete()
require.NoError(t, err)
require.GreaterOrEqual(t, rows, int64(1))
}
}
var incrDecr = []struct {
insert DataStruct
incr uint64
incrRes uint64
decr uint64
decrRes uint64
}{
{DataStruct{Foo: "foo foo foo", Bar: "bar bar bar", Baz: &baz}, 3, 126, 1, 125},
}
func TestDB_Increment_Decrement(t *testing.T) {
_, err := db.Truncate(TestTable)
require.NoError(t, err)
for _, obj := range incrDecr {
err = db.Table(TestTable).Insert(obj.insert)
require.NoError(t, err)
_, err = db.Table(TestTable).Increment("baz", obj.incr)
require.NoError(t, err)
dataStruct := &DataStruct{}
err = db.Table(TestTable).Select("baz").Where("baz", "=", obj.incrRes).
ScanStruct(dataStruct)
require.NoError(t, err)
require.Equal(t, *dataStruct.Baz, int64(obj.incrRes))
_, err = db.Table(TestTable).Decrement("baz", obj.decr)
require.NoError(t, err)
err = db.Table(TestTable).Select("baz").Where("baz", "=", obj.decrRes).ScanStruct(dataStruct)
require.NoError(t, err)
require.Equal(t, *dataStruct.Baz, int64(obj.decrRes))
}
_, err = db.Truncate(TestTable)
require.NoError(t, err)
}
type DataStructID struct {
ID int64
Foo string
Bar string
Baz int64
}
var rowsToReplace = []struct {
insert DataStructID
conflict string
replace DataStructID
}{
{DataStructID{ID: 1, Foo: "foo foo foo", Bar: "bar bar bar", Baz: 123}, "id", DataStructID{ID: 1, Foo: "baz baz baz", Bar: "bar bar bar", Baz: 123}},
}
func TestDB_Replace(t *testing.T) {
_, err := db.Truncate(TestTable)
require.NoError(t, err)
for _, obj := range rowsToReplace {
_, err := db.Table(TestTable).Replace(obj.insert, obj.conflict)
require.NoError(t, err)
rows, err := db.Table(TestTable).Replace(obj.replace, obj.conflict)
require.NoError(t, err)
require.GreaterOrEqual(t, rows, int64(1))
dataStruct := &DataStruct{}
err = db.Table(TestTable).Select("foo").Where("baz", "=", obj.replace.Baz).
ScanStruct(dataStruct)
require.NoError(t, err)
require.Equal(t, dataStruct.Foo, obj.replace.Foo)
}
_, err = db.Truncate(TestTable)
require.NoError(t, err)
}
type User struct {
ID int64
Name string
Points int64
}
var userForUnion = User{ID: int64(1), Name: "Alex Shmidt", Points: int64(123)}
func TestDB_Union(t *testing.T) {
_, err := db.Truncate(TestTable)
require.NoError(t, err)
_, err = db.Truncate(UsersTable)
require.NoError(t, err)
err = db.Table(TestTable).Insert(data)
require.NoError(t, err)
err = db.Table(UsersTable).Insert(userForUnion)
require.NoError(t, err)
union := db.Table(TestTable).Select("bar", "baz").Union()
dataStruct := DataStruct{}
var dataStructs []DataStruct
err = union.Table(UsersTable).Select("name", "points").EachToStruct(func(rows *sql.Rows) error {
err = union.Next(rows, &dataStruct)
if err != nil {
return err
}
dataStructs = append(dataStructs, dataStruct)
return nil
})
require.NoError(t, err)
for _, v := range dataStructs {
require.Equal(t, *v.Baz, userForUnion.Points)
}
_, err = db.Truncate(TestTable)
require.NoError(t, err)
_, err = db.Truncate(UsersTable)
require.NoError(t, err)
}
func TestDB_InTransaction(t *testing.T) {
var tests = map[string]struct {
dataMap DataStruct
res interface{}
err error
}{
"transaction commit ok": {
dataMap: data,
res: 1,
err: nil,
},
"transaction commit ok int64": {
dataMap: data,
res: int64(1),
err: nil,
},
"transaction commit ok uint64": {
dataMap: data,
res: uint64(1),
err: nil,
},
"transaction commit ok map[string]interface{}": {
dataMap: data,
res: map[string]interface{}{"foo": "foo foo foo", "bar": "bar bar bar", "baz": int64(123)},
err: nil,
},
"transaction commit ok []map[string]interface{}": {
dataMap: data,
res: []map[string]interface{}{
{
"foo": "foo foo foo", "bar": "bar bar bar", "baz": int64(123),
},
},
err: nil,
},
"transaction early exit err": {
dataMap: data,
res: 0,
err: errors.New("some error"),
},
"transaction rollback": {
dataMap: data,
res: 0,
err: nil,
},
}
for n, tt := range tests {
t.Run(n, func(t *testing.T) {
_, err := db.Truncate(TestTable)
require.NoError(t, err)
defer func() {
_, err = db.Truncate(TestTable)
require.NoError(t, err)
}()
err = db.InTransaction(func() (any, error) {
err = db.Table(TestTable).Insert(tt.dataMap)
return tt.res, tt.err
})
if tt.err != nil {
require.Error(t, tt.err, err)
} else {
require.NoError(t, err)
}
})
}
}
func TestDB_HasTable(t *testing.T) {
tblExists, err := db.HasTable("public", PostsTable)
require.NoError(t, err)
require.True(t, tblExists)
}
func TestDB_HasColumns(t *testing.T) {
colsExists, err := db.HasColumns("public", PostsTable, "title", "user_id")
require.NoError(t, err)
require.True(t, colsExists)
}
func TestDB_First(t *testing.T) {
_, err := db.Truncate(TestTable)
require.NoError(t, err)
err = db.Table(TestTable).Insert(data)
require.NoError(t, err)
// write concurrent row to order and get the only 1st
bazz := int64(1234)
err = db.Table(TestTable).Insert(DataStruct{
Foo: "foo foo foo 2",
Bar: "bar bar bar 2",
Baz: &bazz,
})
require.NoError(t, err)
dataStruct := &DataStruct{}
err = db.Table(TestTable).Select("baz").OrderBy("baz", "desc").OrderBy("foo", "desc").First(dataStruct)
require.NoError(t, err)
require.Equal(t, *dataStruct.Baz, int64(1234))
err = db.Table(TestTable).Select("baz").OrderBy("baz", "desc").OrderBy("fo", "desc").First(dataStruct)
require.Error(t, err)
_, err = db.Truncate(TestTable)
require.NoError(t, err)
}
func TestDB_Find(t *testing.T) {
_, err := db.Truncate(TestTable)
require.NoError(t, err)
id, err := db.Table(TestTable).InsertGetId(data)
require.NoError(t, err)
dataStruct := &DataStructID{}
err = db.Table(TestTable).Find(dataStruct, id)
require.NoError(t, err)
require.Equal(t, dataStruct.Foo, data.Foo)
require.Equal(t, dataStruct.Bar, data.Bar)
require.Equal(t, dataStruct.Baz, *data.Baz)
_, err = db.Truncate(TestTable)
require.NoError(t, err)
}
func TestDB_WhereExists(t *testing.T) {
_, err := db.Truncate(UsersTable)
require.NoError(t, err)
err = db.Table(UsersTable).InsertBatch(batchUsers)
require.NoError(t, err)
dataStruct := &DataStructUser{}
er := db.Table(UsersTable).Select("name").WhereExists(
db.Table(UsersTable).Select("name").Where("points", ">=", int64(12345)),
).First(dataStruct)
require.NoError(t, er)
require.Equal(t, TestUserName, dataStruct.Name)
_, err = db.Truncate(UsersTable)
require.NoError(t, err)
}
func TestDB_WhereNotExists(t *testing.T) {
_, err := db.Truncate(UsersTable)
require.NoError(t, err)
err = db.Table(UsersTable).InsertBatch(batchUsers)
require.NoError(t, err)
dataStruct := &DataStructUser{}
er := db.Table(UsersTable).Select("name").WhereNotExists(
db.Table(UsersTable).Select("name").Where("points", ">=", int64(12345)),
).First(dataStruct)
require.NoError(t, er)
require.Equal(t, TestUserName, dataStruct.Name)
_, err = db.Truncate(UsersTable)
require.NoError(t, err)
}
func TestDB_Value(t *testing.T) {
_, err := db.Truncate(UsersTable)
require.NoError(t, err)
err = db.Table(UsersTable).InsertBatch(batchUsers)
require.NoError(t, err)
dataStruct := &DataStructUser{}
err = db.Table(UsersTable).OrderBy("points", "desc").Value(dataStruct, "name")
require.NoError(t, err)
require.Equal(t, TestUserName, dataStruct.Name)
err = db.Table(UsersTable).OrderBy("poin", "desc").Value(dataStruct, "name")
require.Error(t, err)
_, err = db.Truncate(UsersTable)
require.NoError(t, err)
}
func TestDB_Pluck(t *testing.T) {
_, err := db.Truncate(UsersTable)
require.NoError(t, err)
err = db.Table(UsersTable).InsertBatch(batchUsers)
require.NoError(t, err)
dataStruct := &DataStructUser{}
res, err := db.Table(UsersTable).Pluck(dataStruct)
require.NoError(t, err)
for k, v := range res {
resVal := v.(DataStructUser)
require.Equal(t, batchUsers[k].Name, resVal.Name)
}
_, err = db.Table("nonexistent").Pluck(dataStruct)
require.Error(t, err)
_, err = db.Truncate(UsersTable)
require.NoError(t, err)
}
func TestDB_PluckMap(t *testing.T) {
_, err := db.Truncate(UsersTable)
require.NoError(t, err)
err = db.Table(UsersTable).InsertBatch(batchUsers)
require.NoError(t, err)
dataStruct := &DataStructUser{}
res, err := db.Table(UsersTable).PluckMap(dataStruct, "name", "points")
require.NoError(t, err)
for k, m := range res {
for key, value := range m {
keyVal := key.(string)
valueVal := value.(DataStructUser)
require.Equal(t, batchUsers[k].Name, keyVal)
require.Equal(t, batchUsers[k].Points, valueVal.Points)
}
}
_, err = db.Table("nonexistent").PluckMap(dataStruct, "name", "points")
require.Error(t, err)
_, err = db.Table("nonexistent").PluckMap(dataStruct, "namee", "points")
require.EqualError(t, err, "field 'Namee' not found in struct")
_, err = db.Truncate(UsersTable)
require.NoError(t, err)
}
func TestDB_Exists(t *testing.T) {
_, err := db.Truncate(UsersTable)
require.NoError(t, err)
err = db.Table(UsersTable).InsertBatch(batchUsers)
require.NoError(t, err)
prepared := db.Table(UsersTable).Select("name").Where("points", ">=", int64(12345))
exists, err := prepared.Exists()
require.NoError(t, err)
doesntEx, err := prepared.DoesntExists()
require.NoError(t, err)
require.True(t, exists, "The record must exist at this state of db data")
require.False(t, doesntEx, "The record must exist at this state of db data")
_, err = db.Truncate(UsersTable)
require.NoError(t, err)
}
func TestDB_Count(t *testing.T) {
_, err := db.Truncate(UsersTable)
require.NoError(t, err)
err = db.Table(UsersTable).InsertBatch(batchUsers)
require.NoError(t, err)
cnt, err := db.Table(UsersTable).Count()
require.NoError(t, err)
require.Equalf(t, int64(len(batchUsers)), cnt, "want: %d, got: %d", len(batchUsers), cnt)
_, err = db.Truncate(UsersTable)
require.NoError(t, err)
}
func TestDB_Avg(t *testing.T) {
_, err := db.Truncate(UsersTable)
require.NoError(t, err)
err = db.Table(UsersTable).InsertBatch(batchUsers)
require.NoError(t, err)
avg, err := db.Table(UsersTable).Avg("points")
require.NoError(t, err)
var cntBatch float64
for _, v := range batchUsers {
cntBatch += float64(v.Points) / float64(len(batchUsers))
}
require.Equalf(t, cntBatch, avg, "want: %d, got: %d", cntBatch, avg)
_, err = db.Truncate(UsersTable)
require.NoError(t, err)
}
func TestDB_MinMax(t *testing.T) {
_, err := db.Truncate(UsersTable)
require.NoError(t, err)
err = db.Table(UsersTable).InsertBatch(batchUsers)
require.NoError(t, err)
mn, err := db.Table(UsersTable).Min("points")
require.NoError(t, err)
mx, err := db.Table(UsersTable).Max("points")
require.NoError(t, err)
var max float64
var min = float64(123456)
for _, v := range batchUsers {
val := float64(v.Points)
if val > max {
max = val
}
if val < min {
min = val
}
}
require.Equalf(t, mn, min, "want: %d, got: %d", mn, min)
require.Equalf(t, mx, max, "want: %d, got: %d", mx, max)
_, err = db.Truncate(UsersTable)
require.NoError(t, err)
}
func TestDB_Sum(t *testing.T) {
_, err := db.Truncate(UsersTable)
require.NoError(t, err)
err = db.Table(UsersTable).InsertBatch(batchUsers)
require.NoError(t, err)
sum, err := db.Table(UsersTable).Sum("points")
require.NoError(t, err)
var cntBatch float64
for _, v := range batchUsers {
cntBatch += float64(v.Points)
}
require.Equalf(t, cntBatch, sum, "want: %d, got: %d", cntBatch, sum)
_, err = db.Truncate(UsersTable)
require.NoError(t, err)
}
func TestDB_GroupByHaving(t *testing.T) {
_, err := db.Truncate(UsersTable)
require.NoError(t, err)
err = db.Table(UsersTable).InsertBatch(batchUsers)
require.NoError(t, err)
dataStruct := &DataStructUser{}
var dataStructs []DataStructUser
err = db.Table(UsersTable).Select("points").GroupBy("points").
Having("points", ">=", 123).EachToStruct(func(rows *sql.Rows) error {
err = db.Next(rows, dataStruct)
if err != nil {
return err
}
dataStructs = append(dataStructs, *dataStruct)
return nil
})
require.NoError(t, err)
require.Equal(t, len(dataStructs), len(batchUsers)-1)
_, err = db.Truncate(UsersTable)
require.NoError(t, err)
}
func TestDB_HavingRaw(t *testing.T) {
_, err := db.Truncate(UsersTable)
require.NoError(t, err)
err = db.Table(UsersTable).InsertBatch(batchUsers)
require.NoError(t, err)
dataStruct := &DataStructUser{}
var dataStructs []DataStructUser
err = db.Table(UsersTable).Select("points").GroupBy("points").
HavingRaw("points > 123").AndHavingRaw("points < 12345").OrHavingRaw("points = 0").
EachToStruct(func(rows *sql.Rows) error {
err = db.Next(rows, dataStruct)
if err != nil {
return err
}
dataStructs = append(dataStructs, *dataStruct)
return nil
})
require.NoError(t, err)
require.Equal(t, len(batchUsers)-3, len(dataStructs))
_, err = db.Truncate(UsersTable)
require.NoError(t, err)
}
func TestDB_AllJoins(t *testing.T) {
_, err := db.Truncate(PostsTable)
require.NoError(t, err)
_, err = db.Truncate(UsersTable)
require.NoError(t, err)
err = db.Table(UsersTable).InsertBatch(batchUsers)
require.NoError(t, err)
err = db.Table(PostsTable).InsertBatch(batchPosts)
require.NoError(t, err)
dataStruct := &DataStructUserPosts{}
var dataStructs []DataStructUserPosts
err = db.Table(UsersTable).Select("name", "post", "user_id").InnerJoin(PostsTable, UsersTable+".id",
"=", PostsTable+".user_id").EachToStruct(func(rows *sql.Rows) error {
err = db.Next(rows, dataStruct)
if err != nil {
return err
}
dataStructs = append(dataStructs, *dataStruct)
return nil
})
require.NoError(t, err)
require.Equal(t, len(dataStructs), len(batchPosts)-1)
dataStruct = &DataStructUserPosts{}
dataStructs = []DataStructUserPosts{}
err = db.Table(PostsTable).Select("name", "post", "user_id").RightJoin(UsersTable, PostsTable+".user_id",
"=", UsersTable+".id").EachToStruct(func(rows *sql.Rows) error {
err = db.Next(rows, dataStruct)
if err != nil {
return err
}
dataStructs = append(dataStructs, *dataStruct)
return nil
})
require.NoError(t, err)
require.Equal(t, len(dataStructs), len(batchUsers))
dataStruct = &DataStructUserPosts{}
dataStructs = []DataStructUserPosts{}
err = db.Table(UsersTable).Select("name", "post", "user_id").FullJoin(PostsTable, UsersTable+".id",
"=", PostsTable+".user_id").EachToStruct(func(rows *sql.Rows) error {
err = db.Next(rows, dataStruct)
if err != nil {
return err
}
dataStructs = append(dataStructs, *dataStruct)
return nil
})
require.NoError(t, err)
require.Equal(t, len(dataStructs), len(batchUsers)+1)
dataStruct = &DataStructUserPosts{}
dataStructs = []DataStructUserPosts{}
err = db.Table(UsersTable).Select("name", "post", "user_id").FullOuterJoin(PostsTable,
UsersTable+".id", "=", PostsTable+".user_id").EachToStruct(func(rows *sql.Rows) error {
err = db.Next(rows, dataStruct)
if err != nil {
return err
}
dataStructs = append(dataStructs, *dataStruct)
return nil
})
require.NoError(t, err)
require.Equal(t, len(dataStructs), len(batchUsers)+1)
// note InRandomOrder check
dataStruct = &DataStructUserPosts{}
dataStructs = []DataStructUserPosts{}
err = db.Table(UsersTable).Select("name", "post", "user_id").FullJoin(
PostsTable, UsersTable+".id", "=", PostsTable+".user_id").InRandomOrder().EachToStruct(func(rows *sql.Rows) error {
err = db.Next(rows, dataStruct)
if err != nil {
return err
}
dataStructs = append(dataStructs, *dataStruct)
return nil