forked from go-gorp/gorp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gorp_test.go
2091 lines (1801 loc) · 50.9 KB
/
gorp_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 gorp
import (
"bytes"
"database/sql"
"encoding/json"
"errors"
"fmt"
"log"
"math/rand"
"os"
"reflect"
"strings"
"testing"
"time"
_ "github.com/go-sql-driver/mysql"
_ "github.com/lib/pq"
_ "github.com/mattn/go-sqlite3"
_ "github.com/ziutek/mymysql/godrv"
)
// verify interface compliance
var _ Dialect = SqliteDialect{}
var _ Dialect = PostgresDialect{}
var _ Dialect = MySQLDialect{}
var _ Dialect = SqlServerDialect{}
var _ Dialect = OracleDialect{}
type testable interface {
GetId() int64
Rand()
}
type Invoice struct {
Id int64
Created int64
Updated int64
Memo string
PersonId int64
IsPaid bool
}
func (me *Invoice) GetId() int64 { return me.Id }
func (me *Invoice) Rand() {
me.Memo = fmt.Sprintf("random %d", rand.Int63())
me.Created = rand.Int63()
me.Updated = rand.Int63()
}
type InvoiceTag struct {
Id int64 `db:"myid"`
Created int64 `db:"myCreated"`
Updated int64 `db:"date_updated"`
Memo string
PersonId int64 `db:"person_id"`
IsPaid bool `db:"is_Paid"`
}
func (me *InvoiceTag) GetId() int64 { return me.Id }
func (me *InvoiceTag) Rand() {
me.Memo = fmt.Sprintf("random %d", rand.Int63())
me.Created = rand.Int63()
me.Updated = rand.Int63()
}
// See: https://github.com/coopernurse/gorp/issues/175
type AliasTransientField struct {
Id int64 `db:"id"`
Bar int64 `db:"-"`
BarStr string `db:"bar"`
}
func (me *AliasTransientField) GetId() int64 { return me.Id }
func (me *AliasTransientField) Rand() {
me.BarStr = fmt.Sprintf("random %d", rand.Int63())
}
type OverriddenInvoice struct {
Invoice
Id string
}
type Person struct {
Id int64
Created int64
Updated int64
FName string
LName string
Version int64
}
type FNameOnly struct {
FName string
}
type InvoicePersonView struct {
InvoiceId int64
PersonId int64
Memo string
FName string
LegacyVersion int64
}
type TableWithNull struct {
Id int64
Str sql.NullString
Int64 sql.NullInt64
Float64 sql.NullFloat64
Bool sql.NullBool
Bytes []byte
}
type WithIgnoredColumn struct {
internal int64 `db:"-"`
Id int64
Created int64
}
type IdCreated struct {
Id int64
Created int64
}
type IdCreatedExternal struct {
IdCreated
External int64
}
type WithStringPk struct {
Id string
Name string
}
type CustomStringType string
type TypeConversionExample struct {
Id int64
PersonJSON Person
Name CustomStringType
}
type PersonUInt32 struct {
Id uint32
Name string
}
type PersonUInt64 struct {
Id uint64
Name string
}
type PersonUInt16 struct {
Id uint16
Name string
}
type WithEmbeddedStruct struct {
Id int64
Names
}
type WithEmbeddedStructBeforeAutoincrField struct {
Names
Id int64
}
type WithEmbeddedAutoincr struct {
WithEmbeddedStruct
MiddleName string
}
type Names struct {
FirstName string
LastName string
}
type UniqueColumns struct {
FirstName string
LastName string
City string
ZipCode int64
}
type SingleColumnTable struct {
SomeId string
}
type CustomDate struct {
time.Time
}
type WithCustomDate struct {
Id int64
Added CustomDate
}
type testTypeConverter struct{}
func (me testTypeConverter) ToDb(val interface{}) (interface{}, error) {
switch t := val.(type) {
case Person:
b, err := json.Marshal(t)
if err != nil {
return "", err
}
return string(b), nil
case CustomStringType:
return string(t), nil
case CustomDate:
return t.Time, nil
}
return val, nil
}
func (me testTypeConverter) FromDb(target interface{}) (CustomScanner, bool) {
switch target.(type) {
case *Person:
binder := func(holder, target interface{}) error {
s, ok := holder.(*string)
if !ok {
return errors.New("FromDb: Unable to convert Person to *string")
}
b := []byte(*s)
return json.Unmarshal(b, target)
}
return CustomScanner{new(string), target, binder}, true
case *CustomStringType:
binder := func(holder, target interface{}) error {
s, ok := holder.(*string)
if !ok {
return errors.New("FromDb: Unable to convert CustomStringType to *string")
}
st, ok := target.(*CustomStringType)
if !ok {
return errors.New(fmt.Sprint("FromDb: Unable to convert target to *CustomStringType: ", reflect.TypeOf(target)))
}
*st = CustomStringType(*s)
return nil
}
return CustomScanner{new(string), target, binder}, true
case *CustomDate:
binder := func(holder, target interface{}) error {
t, ok := holder.(*time.Time)
if !ok {
return errors.New("FromDb: Unable to convert CustomDate to *time.Time")
}
dateTarget, ok := target.(*CustomDate)
if !ok {
return errors.New(fmt.Sprint("FromDb: Unable to convert target to *CustomDate: ", reflect.TypeOf(target)))
}
dateTarget.Time = *t
return nil
}
return CustomScanner{new(time.Time), target, binder}, true
}
return CustomScanner{}, false
}
func (p *Person) PreInsert(s SqlExecutor) error {
p.Created = time.Now().UnixNano()
p.Updated = p.Created
if p.FName == "badname" {
return fmt.Errorf("Invalid name: %s", p.FName)
}
return nil
}
func (p *Person) PostInsert(s SqlExecutor) error {
p.LName = "postinsert"
return nil
}
func (p *Person) PreUpdate(s SqlExecutor) error {
p.FName = "preupdate"
return nil
}
func (p *Person) PostUpdate(s SqlExecutor) error {
p.LName = "postupdate"
return nil
}
func (p *Person) PreDelete(s SqlExecutor) error {
p.FName = "predelete"
return nil
}
func (p *Person) PostDelete(s SqlExecutor) error {
p.LName = "postdelete"
return nil
}
func (p *Person) PostGet(s SqlExecutor) error {
p.LName = "postget"
return nil
}
type PersistentUser struct {
Key int32
Id string
PassedTraining bool
}
func TestCreateTablesIfNotExists(t *testing.T) {
dbmap := initDbMap()
defer dropAndClose(dbmap)
err := dbmap.CreateTablesIfNotExists()
if err != nil {
t.Error(err)
}
}
func TestTruncateTables(t *testing.T) {
dbmap := initDbMap()
defer dropAndClose(dbmap)
err := dbmap.CreateTablesIfNotExists()
if err != nil {
t.Error(err)
}
// Insert some data
p1 := &Person{0, 0, 0, "Bob", "Smith", 0}
dbmap.Insert(p1)
inv := &Invoice{0, 0, 1, "my invoice", 0, true}
dbmap.Insert(inv)
err = dbmap.TruncateTables()
if err != nil {
t.Error(err)
}
// Make sure all rows are deleted
rows, _ := dbmap.Select(Person{}, "SELECT * FROM person_test")
if len(rows) != 0 {
t.Errorf("Expected 0 person rows, got %d", len(rows))
}
rows, _ = dbmap.Select(Invoice{}, "SELECT * FROM invoice_test")
if len(rows) != 0 {
t.Errorf("Expected 0 invoice rows, got %d", len(rows))
}
}
func TestCustomDateType(t *testing.T) {
dbmap := newDbMap()
dbmap.TypeConverter = testTypeConverter{}
dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
dbmap.AddTable(WithCustomDate{}).SetKeys(true, "Id")
err := dbmap.CreateTables()
if err != nil {
panic(err)
}
defer dropAndClose(dbmap)
test1 := &WithCustomDate{Added: CustomDate{Time: time.Now().Truncate(time.Second)}}
err = dbmap.Insert(test1)
if err != nil {
t.Errorf("Could not insert struct with custom date field: %s", err)
t.FailNow()
}
// Unfortunately, the mysql driver doesn't handle time.Time
// values properly during Get(). I can't find a way to work
// around that problem - every other type that I've tried is just
// silently converted. time.Time is the only type that causes
// the issue that this test checks for. As such, if the driver is
// mysql, we'll just skip the rest of this test.
if _, driver := dialectAndDriver(); driver == "mysql" {
t.Skip("TestCustomDateType can't run Get() with the mysql driver; skipping the rest of this test...")
}
result, err := dbmap.Get(new(WithCustomDate), test1.Id)
if err != nil {
t.Errorf("Could not get struct with custom date field: %s", err)
t.FailNow()
}
test2 := result.(*WithCustomDate)
if test2.Added.UTC() != test1.Added.UTC() {
t.Errorf("Custom dates do not match: %v != %v", test2.Added.UTC(), test1.Added.UTC())
}
}
func TestUIntPrimaryKey(t *testing.T) {
dbmap := newDbMap()
dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
dbmap.AddTable(PersonUInt64{}).SetKeys(true, "Id")
dbmap.AddTable(PersonUInt32{}).SetKeys(true, "Id")
dbmap.AddTable(PersonUInt16{}).SetKeys(true, "Id")
err := dbmap.CreateTablesIfNotExists()
if err != nil {
panic(err)
}
defer dropAndClose(dbmap)
p1 := &PersonUInt64{0, "name1"}
p2 := &PersonUInt32{0, "name2"}
p3 := &PersonUInt16{0, "name3"}
err = dbmap.Insert(p1, p2, p3)
if err != nil {
t.Error(err)
}
if p1.Id != 1 {
t.Errorf("%d != 1", p1.Id)
}
if p2.Id != 1 {
t.Errorf("%d != 1", p2.Id)
}
if p3.Id != 1 {
t.Errorf("%d != 1", p3.Id)
}
}
func TestSetUniqueTogether(t *testing.T) {
dbmap := newDbMap()
dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
dbmap.AddTable(UniqueColumns{}).SetUniqueTogether("FirstName", "LastName").SetUniqueTogether("City", "ZipCode")
err := dbmap.CreateTablesIfNotExists()
if err != nil {
panic(err)
}
defer dropAndClose(dbmap)
n1 := &UniqueColumns{"Steve", "Jobs", "Cupertino", 95014}
err = dbmap.Insert(n1)
if err != nil {
t.Error(err)
}
// Should fail because of the first constraint
n2 := &UniqueColumns{"Steve", "Jobs", "Sunnyvale", 94085}
err = dbmap.Insert(n2)
if err == nil {
t.Error(err)
}
// "unique" for Postgres/SQLite, "Duplicate entry" for MySQL
errLower := strings.ToLower(err.Error())
if !strings.Contains(errLower, "unique") && !strings.Contains(errLower, "duplicate entry") {
t.Error(err)
}
// Should also fail because of the second unique-together
n3 := &UniqueColumns{"Steve", "Wozniak", "Cupertino", 95014}
err = dbmap.Insert(n3)
if err == nil {
t.Error(err)
}
// "unique" for Postgres/SQLite, "Duplicate entry" for MySQL
errLower = strings.ToLower(err.Error())
if !strings.Contains(errLower, "unique") && !strings.Contains(errLower, "duplicate entry") {
t.Error(err)
}
// This one should finally succeed
n4 := &UniqueColumns{"Steve", "Wozniak", "Sunnyvale", 94085}
err = dbmap.Insert(n4)
if err != nil {
t.Error(err)
}
}
func TestPersistentUser(t *testing.T) {
dbmap := newDbMap()
dbmap.Exec("drop table if exists PersistentUser")
dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
table := dbmap.AddTable(PersistentUser{}).SetKeys(false, "Key")
table.ColMap("Key").Rename("mykey")
err := dbmap.CreateTablesIfNotExists()
if err != nil {
panic(err)
}
defer dropAndClose(dbmap)
pu := &PersistentUser{43, "33r", false}
err = dbmap.Insert(pu)
if err != nil {
panic(err)
}
// prove we can pass a pointer into Get
pu2, err := dbmap.Get(pu, pu.Key)
if err != nil {
panic(err)
}
if !reflect.DeepEqual(pu, pu2) {
t.Errorf("%v!=%v", pu, pu2)
}
arr, err := dbmap.Select(pu, "select * from PersistentUser")
if err != nil {
panic(err)
}
if !reflect.DeepEqual(pu, arr[0]) {
t.Errorf("%v!=%v", pu, arr[0])
}
// prove we can get the results back in a slice
var puArr []*PersistentUser
_, err = dbmap.Select(&puArr, "select * from PersistentUser")
if err != nil {
panic(err)
}
if len(puArr) != 1 {
t.Errorf("Expected one persistentuser, found none")
}
if !reflect.DeepEqual(pu, puArr[0]) {
t.Errorf("%v!=%v", pu, puArr[0])
}
// prove we can get the results back in a non-pointer slice
var puValues []PersistentUser
_, err = dbmap.Select(&puValues, "select * from PersistentUser")
if err != nil {
panic(err)
}
if len(puValues) != 1 {
t.Errorf("Expected one persistentuser, found none")
}
if !reflect.DeepEqual(*pu, puValues[0]) {
t.Errorf("%v!=%v", *pu, puValues[0])
}
// prove we can get the results back in a string slice
var idArr []*string
_, err = dbmap.Select(&idArr, "select Id from PersistentUser")
if err != nil {
panic(err)
}
if len(idArr) != 1 {
t.Errorf("Expected one persistentuser, found none")
}
if !reflect.DeepEqual(pu.Id, *idArr[0]) {
t.Errorf("%v!=%v", pu.Id, *idArr[0])
}
// prove we can get the results back in an int slice
var keyArr []*int32
_, err = dbmap.Select(&keyArr, "select mykey from PersistentUser")
if err != nil {
panic(err)
}
if len(keyArr) != 1 {
t.Errorf("Expected one persistentuser, found none")
}
if !reflect.DeepEqual(pu.Key, *keyArr[0]) {
t.Errorf("%v!=%v", pu.Key, *keyArr[0])
}
// prove we can get the results back in a bool slice
var passedArr []*bool
_, err = dbmap.Select(&passedArr, "select PassedTraining from PersistentUser")
if err != nil {
panic(err)
}
if len(passedArr) != 1 {
t.Errorf("Expected one persistentuser, found none")
}
if !reflect.DeepEqual(pu.PassedTraining, *passedArr[0]) {
t.Errorf("%v!=%v", pu.PassedTraining, *passedArr[0])
}
// prove we can get the results back in a non-pointer slice
var stringArr []string
_, err = dbmap.Select(&stringArr, "select Id from PersistentUser")
if err != nil {
panic(err)
}
if len(stringArr) != 1 {
t.Errorf("Expected one persistentuser, found none")
}
if !reflect.DeepEqual(pu.Id, stringArr[0]) {
t.Errorf("%v!=%v", pu.Id, stringArr[0])
}
}
func TestNamedQueryMap(t *testing.T) {
dbmap := newDbMap()
dbmap.Exec("drop table if exists PersistentUser")
dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
table := dbmap.AddTable(PersistentUser{}).SetKeys(false, "Key")
table.ColMap("Key").Rename("mykey")
err := dbmap.CreateTablesIfNotExists()
if err != nil {
panic(err)
}
defer dropAndClose(dbmap)
pu := &PersistentUser{43, "33r", false}
pu2 := &PersistentUser{500, "abc", false}
err = dbmap.Insert(pu, pu2)
if err != nil {
panic(err)
}
// Test simple case
var puArr []*PersistentUser
_, err = dbmap.Select(&puArr, "select * from PersistentUser where mykey = :Key", map[string]interface{}{
"Key": 43,
})
if err != nil {
t.Errorf("Failed to select: %s", err)
t.FailNow()
}
if len(puArr) != 1 {
t.Errorf("Expected one persistentuser, found none")
}
if !reflect.DeepEqual(pu, puArr[0]) {
t.Errorf("%v!=%v", pu, puArr[0])
}
// Test more specific map value type is ok
puArr = nil
_, err = dbmap.Select(&puArr, "select * from PersistentUser where mykey = :Key", map[string]int{
"Key": 43,
})
if err != nil {
t.Errorf("Failed to select: %s", err)
t.FailNow()
}
if len(puArr) != 1 {
t.Errorf("Expected one persistentuser, found none")
}
// Test multiple parameters set.
puArr = nil
_, err = dbmap.Select(&puArr, `
select * from PersistentUser
where mykey = :Key
and PassedTraining = :PassedTraining
and Id = :Id`, map[string]interface{}{
"Key": 43,
"PassedTraining": false,
"Id": "33r",
})
if err != nil {
t.Errorf("Failed to select: %s", err)
t.FailNow()
}
if len(puArr) != 1 {
t.Errorf("Expected one persistentuser, found none")
}
// Test colon within a non-key string
// Test having extra, unused properties in the map.
puArr = nil
_, err = dbmap.Select(&puArr, `
select * from PersistentUser
where mykey = :Key
and Id != 'abc:def'`, map[string]interface{}{
"Key": 43,
"PassedTraining": false,
})
if err != nil {
t.Errorf("Failed to select: %s", err)
t.FailNow()
}
if len(puArr) != 1 {
t.Errorf("Expected one persistentuser, found none")
}
}
func TestNamedQueryStruct(t *testing.T) {
dbmap := newDbMap()
dbmap.Exec("drop table if exists PersistentUser")
dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
table := dbmap.AddTable(PersistentUser{}).SetKeys(false, "Key")
table.ColMap("Key").Rename("mykey")
err := dbmap.CreateTablesIfNotExists()
if err != nil {
panic(err)
}
defer dropAndClose(dbmap)
pu := &PersistentUser{43, "33r", false}
pu2 := &PersistentUser{500, "abc", false}
err = dbmap.Insert(pu, pu2)
if err != nil {
panic(err)
}
// Test select self
var puArr []*PersistentUser
_, err = dbmap.Select(&puArr, `
select * from PersistentUser
where mykey = :Key
and PassedTraining = :PassedTraining
and Id = :Id`, pu)
if err != nil {
t.Errorf("Failed to select: %s", err)
t.FailNow()
}
if len(puArr) != 1 {
t.Errorf("Expected one persistentuser, found none")
}
if !reflect.DeepEqual(pu, puArr[0]) {
t.Errorf("%v!=%v", pu, puArr[0])
}
}
// Ensure that the slices containing SQL results are non-nil when the result set is empty.
func TestReturnsNonNilSlice(t *testing.T) {
dbmap := initDbMap()
defer dropAndClose(dbmap)
noResultsSQL := "select * from invoice_test where id=99999"
var r1 []*Invoice
_rawselect(dbmap, &r1, noResultsSQL)
if r1 == nil {
t.Errorf("r1==nil")
}
r2 := _rawselect(dbmap, Invoice{}, noResultsSQL)
if r2 == nil {
t.Errorf("r2==nil")
}
}
func TestOverrideVersionCol(t *testing.T) {
dbmap := newDbMap()
t1 := dbmap.AddTable(InvoicePersonView{}).SetKeys(false, "InvoiceId", "PersonId")
err := dbmap.CreateTables()
if err != nil {
panic(err)
}
defer dropAndClose(dbmap)
c1 := t1.SetVersionCol("LegacyVersion")
if c1.ColumnName != "LegacyVersion" {
t.Errorf("Wrong col returned: %v", c1)
}
ipv := &InvoicePersonView{1, 2, "memo", "fname", 0}
_update(dbmap, ipv)
if ipv.LegacyVersion != 1 {
t.Errorf("LegacyVersion not updated: %d", ipv.LegacyVersion)
}
}
func TestOptimisticLocking(t *testing.T) {
dbmap := initDbMap()
defer dropAndClose(dbmap)
p1 := &Person{0, 0, 0, "Bob", "Smith", 0}
dbmap.Insert(p1) // Version is now 1
if p1.Version != 1 {
t.Errorf("Insert didn't incr Version: %d != %d", 1, p1.Version)
return
}
if p1.Id == 0 {
t.Errorf("Insert didn't return a generated PK")
return
}
obj, err := dbmap.Get(Person{}, p1.Id)
if err != nil {
panic(err)
}
p2 := obj.(*Person)
p2.LName = "Edwards"
dbmap.Update(p2) // Version is now 2
if p2.Version != 2 {
t.Errorf("Update didn't incr Version: %d != %d", 2, p2.Version)
}
p1.LName = "Howard"
count, err := dbmap.Update(p1)
if _, ok := err.(OptimisticLockError); !ok {
t.Errorf("update - Expected OptimisticLockError, got: %v", err)
}
if count != -1 {
t.Errorf("update - Expected -1 count, got: %d", count)
}
count, err = dbmap.Delete(p1)
if _, ok := err.(OptimisticLockError); !ok {
t.Errorf("delete - Expected OptimisticLockError, got: %v", err)
}
if count != -1 {
t.Errorf("delete - Expected -1 count, got: %d", count)
}
}
// what happens if a legacy table has a null value?
func TestDoubleAddTable(t *testing.T) {
dbmap := newDbMap()
t1 := dbmap.AddTable(TableWithNull{}).SetKeys(false, "Id")
t2 := dbmap.AddTable(TableWithNull{})
if t1 != t2 {
t.Errorf("%v != %v", t1, t2)
}
}
// what happens if a legacy table has a null value?
func TestNullValues(t *testing.T) {
dbmap := initDbMapNulls()
defer dropAndClose(dbmap)
// insert a row directly
_rawexec(dbmap, "insert into TableWithNull values (10, null, "+
"null, null, null, null)")
// try to load it
expected := &TableWithNull{Id: 10}
obj := _get(dbmap, TableWithNull{}, 10)
t1 := obj.(*TableWithNull)
if !reflect.DeepEqual(expected, t1) {
t.Errorf("%v != %v", expected, t1)
}
// update it
t1.Str = sql.NullString{"hi", true}
expected.Str = t1.Str
t1.Int64 = sql.NullInt64{999, true}
expected.Int64 = t1.Int64
t1.Float64 = sql.NullFloat64{53.33, true}
expected.Float64 = t1.Float64
t1.Bool = sql.NullBool{true, true}
expected.Bool = t1.Bool
t1.Bytes = []byte{1, 30, 31, 33}
expected.Bytes = t1.Bytes
_update(dbmap, t1)
obj = _get(dbmap, TableWithNull{}, 10)
t1 = obj.(*TableWithNull)
if t1.Str.String != "hi" {
t.Errorf("%s != hi", t1.Str.String)
}
if !reflect.DeepEqual(expected, t1) {
t.Errorf("%v != %v", expected, t1)
}
}
func TestColumnProps(t *testing.T) {
dbmap := newDbMap()
dbmap.TraceOn("", log.New(os.Stdout, "gorptest: ", log.Lmicroseconds))
t1 := dbmap.AddTable(Invoice{}).SetKeys(true, "Id")
t1.ColMap("Created").Rename("date_created")
t1.ColMap("Updated").SetTransient(true)
t1.ColMap("Memo").SetMaxSize(10)
t1.ColMap("PersonId").SetUnique(true)
err := dbmap.CreateTables()
if err != nil {
panic(err)
}
defer dropAndClose(dbmap)
// test transient
inv := &Invoice{0, 0, 1, "my invoice", 0, true}
_insert(dbmap, inv)
obj := _get(dbmap, Invoice{}, inv.Id)
inv = obj.(*Invoice)
if inv.Updated != 0 {
t.Errorf("Saved transient column 'Updated'")
}
// test max size
inv.Memo = "this memo is too long"
err = dbmap.Insert(inv)
if err == nil {
t.Errorf("max size exceeded, but Insert did not fail.")
}
// test unique - same person id
inv = &Invoice{0, 0, 1, "my invoice2", 0, false}
err = dbmap.Insert(inv)
if err == nil {
t.Errorf("same PersonId inserted, but Insert did not fail.")
}
}
func TestRawSelect(t *testing.T) {
dbmap := initDbMap()
defer dropAndClose(dbmap)
p1 := &Person{0, 0, 0, "bob", "smith", 0}
_insert(dbmap, p1)
inv1 := &Invoice{0, 0, 0, "xmas order", p1.Id, true}
_insert(dbmap, inv1)
expected := &InvoicePersonView{inv1.Id, p1.Id, inv1.Memo, p1.FName, 0}
query := "select i.Id InvoiceId, p.Id PersonId, i.Memo, p.FName " +
"from invoice_test i, person_test p " +
"where i.PersonId = p.Id"
list := _rawselect(dbmap, InvoicePersonView{}, query)
if len(list) != 1 {
t.Errorf("len(list) != 1: %d", len(list))
} else if !reflect.DeepEqual(expected, list[0]) {
t.Errorf("%v != %v", expected, list[0])
}
}
func TestHooks(t *testing.T) {
dbmap := initDbMap()
defer dropAndClose(dbmap)
p1 := &Person{0, 0, 0, "bob", "smith", 0}
_insert(dbmap, p1)
if p1.Created == 0 || p1.Updated == 0 {
t.Errorf("p1.PreInsert() didn't run: %v", p1)
} else if p1.LName != "postinsert" {
t.Errorf("p1.PostInsert() didn't run: %v", p1)
}
obj := _get(dbmap, Person{}, p1.Id)
p1 = obj.(*Person)
if p1.LName != "postget" {
t.Errorf("p1.PostGet() didn't run: %v", p1)
}
_update(dbmap, p1)
if p1.FName != "preupdate" {
t.Errorf("p1.PreUpdate() didn't run: %v", p1)
} else if p1.LName != "postupdate" {
t.Errorf("p1.PostUpdate() didn't run: %v", p1)
}
var persons []*Person
bindVar := dbmap.Dialect.BindVar(0)
_rawselect(dbmap, &persons, "select * from person_test where id = "+bindVar, p1.Id)
if persons[0].LName != "postget" {
t.Errorf("p1.PostGet() didn't run after select: %v", p1)
}
_del(dbmap, p1)
if p1.FName != "predelete" {
t.Errorf("p1.PreDelete() didn't run: %v", p1)
} else if p1.LName != "postdelete" {
t.Errorf("p1.PostDelete() didn't run: %v", p1)
}
// Test error case
p2 := &Person{0, 0, 0, "badname", "", 0}
err := dbmap.Insert(p2)
if err == nil {
t.Errorf("p2.PreInsert() didn't return an error")
}
}
func TestTransaction(t *testing.T) {
dbmap := initDbMap()
defer dropAndClose(dbmap)
inv1 := &Invoice{0, 100, 200, "t1", 0, true}
inv2 := &Invoice{0, 100, 200, "t2", 0, false}
trans, err := dbmap.Begin()
if err != nil {
panic(err)
}
trans.Insert(inv1, inv2)
called := false
trans.AfterCommit(func() error {
called = true
return nil
})
err = trans.Commit()
if err != nil {
panic(err)
}
obj, err := dbmap.Get(Invoice{}, inv1.Id)
if err != nil {
panic(err)
}
if !reflect.DeepEqual(inv1, obj) {
t.Errorf("%v != %v", inv1, obj)
}
obj, err = dbmap.Get(Invoice{}, inv2.Id)
if err != nil {
panic(err)
}
if !reflect.DeepEqual(inv2, obj) {
t.Errorf("%v != %v", inv2, obj)
}
}
func TestSavepoint(t *testing.T) {
dbmap := initDbMap()
defer dropAndClose(dbmap)
inv1 := &Invoice{0, 100, 200, "unpaid", 0, false}
trans, err := dbmap.Begin()
if err != nil {
panic(err)
}
trans.Insert(inv1)
var checkMemo = func(want string) {
memo, err := trans.SelectStr("select memo from invoice_test")
if err != nil {
panic(err)
}
if memo != want {
t.Errorf("%q != %q", want, memo)
}
}
checkMemo("unpaid")