forked from go-pg/pg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db_test.go
2093 lines (1826 loc) · 49.1 KB
/
db_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 pg_test
import (
"bytes"
"context"
"crypto/tls"
"database/sql"
"fmt"
"net"
"testing"
"time"
"github.com/go-pg/pg"
"github.com/go-pg/pg/orm"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
func TestGinkgo(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "pg")
}
func pgOptions() *pg.Options {
return &pg.Options{
User: "postgres",
Database: "postgres",
TLSConfig: &tls.Config{
InsecureSkipVerify: true,
},
MaxRetries: 1,
MinRetryBackoff: -1,
DialTimeout: 30 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
PoolSize: 10,
MaxConnAge: 10 * time.Second,
PoolTimeout: 30 * time.Second,
IdleTimeout: 10 * time.Second,
IdleCheckFrequency: 100 * time.Millisecond,
}
}
func TestDBString(t *testing.T) {
db := pg.Connect(pgOptions())
defer db.Close()
wanted := `DB<Addr="localhost:5432">`
if db.String() != wanted {
t.Fatalf("got %q, wanted %q", db.String(), wanted)
}
db = db.WithParam("param1", "value1").WithParam("param2", 2)
wanted = `DB<Addr="localhost:5432" param1=value1 param2=2>`
if db.String() != wanted {
t.Fatalf("got %q, wanted %q", db.String(), wanted)
}
}
func TestOnConnect(t *testing.T) {
opt := pgOptions()
opt.OnConnect = func(db *pg.Conn) error {
_, err := db.Exec("SET application_name = 'myapp'")
return err
}
db := pg.Connect(opt)
defer db.Close()
var name string
_, err := db.QueryOne(pg.Scan(&name), "SHOW application_name")
if err != nil {
t.Fatal(err)
}
if name != "myapp" {
t.Fatalf(`got %q, wanted "myapp"`, name)
}
}
func TestEmptyQuery(t *testing.T) {
db := pg.Connect(pgOptions())
defer db.Close()
assert := func(err error) {
if err == nil {
t.Fatal("error expected")
}
if err.Error() != "pg: query is empty" {
t.Fatal(err)
}
}
_, err := db.Exec("")
assert(err)
_, err = db.Query(pg.Discard, "")
assert(err)
stmt, err := db.Prepare("")
if err != nil {
t.Fatal(err)
}
_, err = stmt.Exec()
assert(err)
}
var _ = Describe("DB", func() {
var db *pg.DB
var tx *pg.Tx
BeforeEach(func() {
db = pg.Connect(pgOptions())
var err error
tx, err = db.Begin()
Expect(err).NotTo(HaveOccurred())
})
AfterEach(func() {
Expect(db.Close()).NotTo(HaveOccurred())
})
Describe("Query", func() {
It("does not return an error when there are no results", func() {
_, err := db.Query(pg.Discard, "SELECT 1 WHERE 1 = 2")
Expect(err).NotTo(HaveOccurred())
})
It("does not return an error when there are no results", func() {
_, err := tx.Query(pg.Discard, "SELECT 1 WHERE 1 = 2")
Expect(err).NotTo(HaveOccurred())
})
})
Describe("QueryOne", func() {
It("returns pg.ErrNoRows when there are no results", func() {
_, err := db.QueryOne(pg.Discard, "SELECT 1 WHERE 1 = 2")
Expect(err).To(Equal(pg.ErrNoRows))
})
It("returns pg.ErrNoRows when there are no results", func() {
_, err := tx.QueryOne(pg.Discard, "SELECT 1 WHERE 1 = 2")
Expect(err).To(Equal(pg.ErrNoRows))
})
})
Describe("Exec", func() {
It("does not return an error when there are no results", func() {
_, err := db.Exec("SELECT 1 WHERE 1 = 2")
Expect(err).NotTo(HaveOccurred())
})
It("does not return an error when there are no results", func() {
_, err := tx.Exec("SELECT 1 WHERE 1 = 2")
Expect(err).NotTo(HaveOccurred())
})
})
Describe("ExecOne", func() {
It("returns pg.ErrNoRows when there are no results", func() {
_, err := db.ExecOne("SELECT 1 WHERE 1 = 2")
Expect(err).To(Equal(pg.ErrNoRows))
})
It("returns pg.ErrNoRows when there are no results", func() {
_, err := tx.ExecOne("SELECT 1 WHERE 1 = 2")
Expect(err).To(Equal(pg.ErrNoRows))
})
})
Describe("Prepare", func() {
It("returns an error when query can't be prepared", func() {
for i := 0; i < 3; i++ {
_, err := db.Prepare("totally invalid sql")
Expect(err).To(MatchError(`ERROR #42601 syntax error at or near "totally"`))
_, err = db.Exec("SELECT 1")
Expect(err).NotTo(HaveOccurred())
}
})
})
Describe("Context", func() {
It("cancels query when context is cancelled", func() {
c := context.Background()
c, cancel := context.WithTimeout(c, time.Second)
defer cancel()
_, err := db.ExecContext(c, "SELECT pg_sleep(10)")
Expect(err).To(MatchError(`ERROR #57014 canceling statement due to user request`))
})
})
})
var _ = Describe("db.Conn", func() {
var db *pg.DB
BeforeEach(func() {
db = pg.Connect(pgOptions())
})
AfterEach(func() {
Expect(db.Close()).NotTo(HaveOccurred())
})
It("does not ackquire connection immediately", func() {
conn := db.Conn()
stats := db.PoolStats()
Expect(stats.TotalConns).To(Equal(uint32(0)))
err := conn.Close()
Expect(err).NotTo(HaveOccurred())
})
It("ackquires connection when used and frees when closed", func() {
conn := db.Conn()
_, err := conn.Exec("SELECT 1")
Expect(err).NotTo(HaveOccurred())
stats := db.PoolStats()
Expect(stats.TotalConns).To(Equal(uint32(1)))
Expect(stats.IdleConns).To(Equal(uint32(0)))
err = conn.Close()
Expect(err).NotTo(HaveOccurred())
stats = db.PoolStats()
Expect(stats.TotalConns).To(Equal(uint32(1)))
Expect(stats.IdleConns).To(Equal(uint32(1)))
})
It("supports Tx", func() {
conn := db.Conn()
tx, err := conn.Begin()
Expect(err).NotTo(HaveOccurred())
_, err = tx.Exec("SELECT 1")
Expect(err).NotTo(HaveOccurred())
_, err = conn.Exec("SELECT 1")
Expect(err).NotTo(HaveOccurred())
err = tx.Commit()
Expect(err).NotTo(HaveOccurred())
_, err = conn.Exec("SELECT 1")
Expect(err).NotTo(HaveOccurred())
err = conn.Close()
Expect(err).NotTo(HaveOccurred())
stats := db.PoolStats()
Expect(stats.TotalConns).To(Equal(uint32(1)))
Expect(stats.IdleConns).To(Equal(uint32(1)))
})
})
var _ = Describe("Time", func() {
var tests = []struct {
str string
wanted time.Time
}{
{"0001-01-01 00:00:00+00", time.Time{}},
{"0000-01-01 00:00:00+00", time.Date(0, time.January, 1, 0, 0, 0, 0, time.UTC)},
{"2001-02-03", time.Date(2001, time.February, 3, 0, 0, 0, 0, time.UTC)},
{"2001-02-03 04:05:06", time.Date(2001, time.February, 3, 4, 5, 6, 0, time.UTC)},
{"2001-02-03 04:05:06.000001", time.Date(2001, time.February, 3, 4, 5, 6, 1000, time.UTC)},
{"2001-02-03 04:05:06.00001", time.Date(2001, time.February, 3, 4, 5, 6, 10000, time.UTC)},
{"2001-02-03 04:05:06.0001", time.Date(2001, time.February, 3, 4, 5, 6, 100000, time.UTC)},
{"2001-02-03 04:05:06.001", time.Date(2001, time.February, 3, 4, 5, 6, 1000000, time.UTC)},
{"2001-02-03 04:05:06.01", time.Date(2001, time.February, 3, 4, 5, 6, 10000000, time.UTC)},
{"2001-02-03 04:05:06.1", time.Date(2001, time.February, 3, 4, 5, 6, 100000000, time.UTC)},
{"2001-02-03 04:05:06.12", time.Date(2001, time.February, 3, 4, 5, 6, 120000000, time.UTC)},
{"2001-02-03 04:05:06.123", time.Date(2001, time.February, 3, 4, 5, 6, 123000000, time.UTC)},
{"2001-02-03 04:05:06.1234", time.Date(2001, time.February, 3, 4, 5, 6, 123400000, time.UTC)},
{"2001-02-03 04:05:06.12345", time.Date(2001, time.February, 3, 4, 5, 6, 123450000, time.UTC)},
{"2001-02-03 04:05:06.123456", time.Date(2001, time.February, 3, 4, 5, 6, 123456000, time.UTC)},
{"2001-02-03 04:05:06.123-07", time.Date(2001, time.February, 3, 4, 5, 6, 123000000, time.FixedZone("", -7*60*60))},
{"2001-02-03 04:05:06-07", time.Date(2001, time.February, 3, 4, 5, 6, 0, time.FixedZone("", -7*60*60))},
{"2001-02-03 04:05:06-07:42", time.Date(2001, time.February, 3, 4, 5, 6, 0, time.FixedZone("", -(7*60*60+42*60)))},
{"2001-02-03 04:05:06-07:30:09", time.Date(2001, time.February, 3, 4, 5, 6, 0, time.FixedZone("", -(7*60*60+30*60+9)))},
{"2001-02-03 04:05:06+07", time.Date(2001, time.February, 3, 4, 5, 6, 0, time.FixedZone("", 7*60*60))},
}
var db *pg.DB
BeforeEach(func() {
db = pg.Connect(pgOptions())
})
AfterEach(func() {
Expect(db.Close()).NotTo(HaveOccurred())
})
It("is formatted correctly", func() {
for i, test := range tests {
var tm time.Time
_, err := db.QueryOne(pg.Scan(&tm), "SELECT ?", test.wanted)
Expect(err).NotTo(HaveOccurred())
Expect(tm.Unix()).To(
Equal(test.wanted.Unix()),
"#%d str=%q wanted=%q", i, test.str, test.wanted,
)
}
})
It("is parsed correctly", func() {
for i, test := range tests {
var tm time.Time
_, err := db.QueryOne(pg.Scan(&tm), "SELECT ?", test.str)
Expect(err).NotTo(HaveOccurred())
Expect(tm.Unix()).To(
Equal(test.wanted.Unix()),
"#%d str=%q wanted=%q", i, test.str, test.wanted,
)
}
})
})
var _ = Describe("array model", func() {
type value struct {
Values []int16 `sql:",array"`
}
var db *pg.DB
BeforeEach(func() {
db = pg.Connect(pgOptions())
})
AfterEach(func() {
Expect(db.Close()).NotTo(HaveOccurred())
})
It("selects values", func() {
model := new(value)
_, err := db.QueryOne(model, "SELECT ? AS values", pg.Array([]int16{1, 2}))
Expect(err).NotTo(HaveOccurred())
Expect(model.Values).To(Equal([]int16{1, 2}))
})
It("selects empty values", func() {
model := &value{
Values: []int16{1, 2},
}
_, err := db.QueryOne(model, "SELECT ? AS values", pg.Array([]int16{}))
Expect(err).NotTo(HaveOccurred())
Expect(model.Values).To(BeEmpty())
})
It("selects null values", func() {
model := &value{
Values: []int16{1, 2},
}
_, err := db.QueryOne(model, "SELECT NULL AS values", pg.Array([]int16{}))
Expect(err).NotTo(HaveOccurred())
Expect(model.Values).To(BeEmpty())
})
})
var _ = Describe("slice model", func() {
type value struct {
Id int
}
var db *pg.DB
BeforeEach(func() {
db = pg.Connect(pgOptions())
})
AfterEach(func() {
Expect(db.Close()).NotTo(HaveOccurred())
})
It("does not error when there are no rows", func() {
ints := make([]int, 1)
_, err := db.Query(&ints, "SELECT generate_series(1, 0)")
Expect(err).NotTo(HaveOccurred())
Expect(ints).To(BeEmpty())
})
It("does not error when there are no rows", func() {
slice := make([]value, 1)
_, err := db.Query(&slice, "SELECT generate_series(1, 0)")
Expect(err).NotTo(HaveOccurred())
Expect(slice).To(BeEmpty())
})
It("does not error when there are no rows", func() {
slice := make([]*value, 1)
_, err := db.Query(&slice, "SELECT generate_series(1, 0)")
Expect(err).NotTo(HaveOccurred())
Expect(slice).To(BeEmpty())
})
It("supports slice of structs", func() {
var slice []value
_, err := db.Query(&slice, `SELECT generate_series(1, 3) AS id`)
Expect(err).NotTo(HaveOccurred())
Expect(slice).To(Equal([]value{{1}, {2}, {3}}))
})
It("supports slice of pointers", func() {
var slice []*value
_, err := db.Query(&slice, `SELECT generate_series(1, 3) AS id`)
Expect(err).NotTo(HaveOccurred())
Expect(slice).To(Equal([]*value{{1}, {2}, {3}}))
})
It("supports Ints", func() {
var ints pg.Ints
_, err := db.Query(&ints, `SELECT generate_series(1, 3)`)
Expect(err).NotTo(HaveOccurred())
Expect(ints).To(Equal(pg.Ints{1, 2, 3}))
})
It("supports slice of ints", func() {
var ints []int
_, err := db.Query(&ints, `SELECT generate_series(1, 3)`)
Expect(err).NotTo(HaveOccurred())
Expect(ints).To(Equal([]int{1, 2, 3}))
})
It("supports slice of time.Time", func() {
var times []time.Time
_, err := db.Query(×, `
WITH data (time) AS (VALUES (clock_timestamp()), (clock_timestamp()))
SELECT time FROM data
`)
Expect(err).NotTo(HaveOccurred())
Expect(times).To(HaveLen(2))
})
It("resets slice", func() {
ints := []int{1, 2, 3}
_, err := db.Query(&ints, `SELECT 1`)
Expect(err).NotTo(HaveOccurred())
Expect(ints).To(Equal([]int{1}))
})
It("resets slice when there are no results", func() {
ints := []int{1, 2, 3}
_, err := db.Query(&ints, `SELECT 1 WHERE FALSE`)
Expect(err).NotTo(HaveOccurred())
Expect(ints).To(BeEmpty())
})
})
var _ = Describe("read/write timeout", func() {
var db *pg.DB
BeforeEach(func() {
opt := pgOptions()
opt.ReadTimeout = time.Millisecond
db = pg.Connect(opt)
})
AfterEach(func() {
Expect(db.Close()).NotTo(HaveOccurred())
})
It("slow query timeouts", func() {
_, err := db.Exec(`SELECT pg_sleep(1)`)
Expect(err.(net.Error).Timeout()).To(BeTrue())
})
Context("WithTimeout", func() {
It("slow query passes", func() {
_, err := db.WithTimeout(time.Minute).Exec(`SELECT pg_sleep(1)`)
Expect(err).NotTo(HaveOccurred())
})
})
})
var _ = Describe("CopyFrom/CopyTo", func() {
const n = 1000000
var db *pg.DB
BeforeEach(func() {
db = pg.Connect(pgOptions())
qs := []string{
"CREATE TEMP TABLE copy_src(n int)",
"CREATE TEMP TABLE copy_dst(n int)",
fmt.Sprintf("INSERT INTO copy_src SELECT generate_series(1, %d)", n),
}
for _, q := range qs {
_, err := db.Exec(q)
Expect(err).NotTo(HaveOccurred())
}
})
AfterEach(func() {
err := db.Close()
Expect(err).NotTo(HaveOccurred())
})
It("copies data from a table and to a table", func() {
var buf bytes.Buffer
res, err := db.CopyTo(&buf, "COPY copy_src TO STDOUT")
Expect(err).NotTo(HaveOccurred())
Expect(res.RowsAffected()).To(Equal(n))
res, err = db.CopyFrom(&buf, "COPY copy_dst FROM STDIN")
Expect(err).NotTo(HaveOccurred())
Expect(res.RowsAffected()).To(Equal(n))
st := db.PoolStats()
Expect(st.Hits).To(Equal(uint32(4)))
Expect(st.Misses).To(Equal(uint32(1)))
Expect(st.Timeouts).To(Equal(uint32(0)))
Expect(st.TotalConns).To(Equal(uint32(1)))
Expect(st.IdleConns).To(Equal(uint32(1)))
var count int
_, err = db.QueryOne(pg.Scan(&count), "SELECT count(*) FROM copy_dst")
Expect(err).NotTo(HaveOccurred())
Expect(count).To(Equal(n))
})
It("copies corrupted data to a table", func() {
buf := bytes.NewBufferString("corrupted,data\nrow,two\r\nrow three")
res, err := db.CopyFrom(buf, "COPY copy_dst FROM STDIN WITH FORMAT csv")
Expect(err).To(MatchError(`ERROR #42601 syntax error at or near "FORMAT"`))
Expect(res).To(BeNil())
st := db.Pool().Stats()
Expect(st.Hits).To(Equal(uint32(3)))
Expect(st.Misses).To(Equal(uint32(1)))
Expect(st.Timeouts).To(Equal(uint32(0)))
Expect(st.TotalConns).To(Equal(uint32(1)))
Expect(st.IdleConns).To(Equal(uint32(1)))
var count int
_, err = db.QueryOne(pg.Scan(&count), "SELECT count(*) FROM copy_dst")
Expect(err).NotTo(HaveOccurred())
Expect(count).To(Equal(0))
})
})
var _ = Describe("CountEstimate", func() {
var db *pg.DB
BeforeEach(func() {
db = pg.Connect(pgOptions())
})
AfterEach(func() {
Expect(db.Close()).NotTo(HaveOccurred())
})
It("works", func() {
count, err := db.Model().
TableExpr("generate_series(1, 10)").
CountEstimate(1000)
Expect(err).NotTo(HaveOccurred())
Expect(count).To(Equal(10))
})
It("works when there are no results", func() {
count, err := db.Model().
TableExpr("generate_series(1, 0)").
CountEstimate(1000)
Expect(err).NotTo(HaveOccurred())
Expect(count).To(Equal(0))
})
It("works with GROUP", func() {
count, err := db.Model().
TableExpr("generate_series(1, 10)").
Group("generate_series").
CountEstimate(1000)
Expect(err).NotTo(HaveOccurred())
Expect(count).To(Equal(10))
})
It("works with GROUP when there are no results", func() {
count, err := db.Model().
TableExpr("generate_series(1, 0)").
Group("generate_series").
CountEstimate(1000)
Expect(err).NotTo(HaveOccurred())
Expect(count).To(Equal(0))
})
})
var _ = Describe("DB nulls", func() {
var db *pg.DB
BeforeEach(func() {
db = pg.Connect(pgOptions())
_, err := db.Exec("CREATE TEMP TABLE tests (id int, value int)")
Expect(err).To(BeNil())
})
AfterEach(func() {
Expect(db.Close()).NotTo(HaveOccurred())
})
Describe("sql.NullInt64", func() {
type Test struct {
Id int
Value sql.NullInt64
}
It("inserts null value", func() {
ins := Test{
Id: 1,
}
err := db.Insert(&ins)
Expect(err).NotTo(HaveOccurred())
sel := Test{
Id: 1,
}
err = db.Select(&sel)
Expect(err).NotTo(HaveOccurred())
Expect(sel.Value.Valid).To(BeFalse())
})
It("inserts non-null value", func() {
ins := Test{
Id: 1,
Value: sql.NullInt64{
Int64: 2,
Valid: true,
},
}
err := db.Insert(&ins)
Expect(err).NotTo(HaveOccurred())
sel := Test{
Id: 1,
}
err = db.Select(&sel)
Expect(err).NotTo(HaveOccurred())
Expect(sel.Value.Valid).To(BeTrue())
Expect(sel.Value.Int64).To(Equal(int64(2)))
})
})
Context("nil ptr", func() {
type Test struct {
Id int
Value *int
}
It("inserts null value", func() {
ins := Test{
Id: 1,
}
err := db.Insert(&ins)
Expect(err).NotTo(HaveOccurred())
sel := Test{
Id: 1,
}
err = db.Select(&sel)
Expect(err).NotTo(HaveOccurred())
Expect(sel.Value).To(BeNil())
})
It("inserts non-null value", func() {
value := 2
ins := Test{
Id: 1,
Value: &value,
}
err := db.Insert(&ins)
Expect(err).NotTo(HaveOccurred())
sel := Test{
Id: 1,
}
err = db.Select(&sel)
Expect(err).NotTo(HaveOccurred())
Expect(sel.Value).NotTo(BeNil())
Expect(*sel.Value).To(Equal(2))
})
})
})
var _ = Describe("DB.Select", func() {
var db *pg.DB
BeforeEach(func() {
db = pg.Connect(pgOptions())
qs := []string{
`CREATE TEMP TABLE tests (col bytea)`,
fmt.Sprintf(`INSERT INTO tests VALUES ('\x%x')`, []byte("bytes")),
}
for _, q := range qs {
_, err := db.Exec(q)
Expect(err).NotTo(HaveOccurred())
}
})
AfterEach(func() {
Expect(db.Close()).NotTo(HaveOccurred())
})
It("selects bytea", func() {
var col []byte
err := db.Model().Table("tests").Column("col").Select(pg.Scan(&col))
Expect(err).NotTo(HaveOccurred())
})
})
var _ = Describe("DB.Insert", func() {
var db *pg.DB
BeforeEach(func() {
db = pg.Connect(pgOptions())
})
AfterEach(func() {
Expect(db.Close()).NotTo(HaveOccurred())
})
It("returns an error on nil", func() {
err := db.Insert(nil)
Expect(err).To(MatchError("pg: Model(nil)"))
})
It("returns an error if value is not settable", func() {
err := db.Insert(1)
Expect(err).To(MatchError("pg: Model(non-pointer int)"))
})
It("returns an error if value is not supported", func() {
var v int
err := db.Insert(&v)
Expect(err).To(MatchError("pg: Model(unsupported int)"))
})
})
var _ = Describe("DB.Update", func() {
var db *pg.DB
BeforeEach(func() {
db = pg.Connect(pgOptions())
})
AfterEach(func() {
Expect(db.Close()).NotTo(HaveOccurred())
})
It("returns an error on nil", func() {
err := db.Update(nil)
Expect(err).To(MatchError("pg: Model(nil)"))
})
It("returns an error if there are no pks", func() {
type Test struct{}
var test Test
err := db.Update(&test)
Expect(err).To(MatchError(`pg: model=Test does not have primary keys`))
})
})
var _ = Describe("DB.Delete", func() {
var db *pg.DB
BeforeEach(func() {
db = pg.Connect(pgOptions())
})
AfterEach(func() {
Expect(db.Close()).NotTo(HaveOccurred())
})
It("returns an error on nil", func() {
err := db.Delete(nil)
Expect(err).To(MatchError("pg: Model(nil)"))
})
It("returns an error if there are no pks", func() {
type Test struct{}
var test Test
err := db.Delete(&test)
Expect(err).To(MatchError(`pg: model=Test does not have primary keys`))
})
It("returns an error if there are no where", func() {
var test []struct {
Id int
}
_, err := db.Model(&test).Delete()
Expect(err).To(MatchError(`pg: Update and Delete queries require Where clause (try WherePK)`))
})
})
var _ = Describe("errors", func() {
var db *pg.DB
BeforeEach(func() {
db = pg.Connect(pgOptions())
})
AfterEach(func() {
Expect(db.Close()).NotTo(HaveOccurred())
})
It("unknown column error", func() {
type Test struct {
Col1 int
}
var test Test
_, err := db.QueryOne(&test, "SELECT 1 AS col1, 2 AS col2")
Expect(err).To(MatchError("pg: can't find column=col2 in model=Test (try discard_unknown_columns)"))
Expect(test.Col1).To(Equal(1))
})
It("Scan error", func() {
var n1 int
_, err := db.QueryOne(pg.Scan(&n1), "SELECT 1, 2")
Expect(err).To(MatchError(`pg: no Scan var for column index=1 name="?column?"`))
Expect(n1).To(Equal(1))
})
})
type Genre struct {
// tableName is an optional field that specifies custom table name and alias.
// By default go-pg generates table name and alias from struct name.
tableName struct{} `sql:"genres,alias:genre"` // default values are the same
Id int // Id is automatically detected as primary key
Name string
Rating int `sql:"-"` // - is used to ignore field
Books []Book `pg:"many2many:book_genres"` // many to many relation
ParentId int
Subgenres []Genre `pg:"fk:parent_id"`
}
func (g Genre) String() string {
return fmt.Sprintf("Genre<Id=%d Name=%q>", g.Id, g.Name)
}
type Image struct {
Id int
Path string
}
type Author struct {
ID int // both "Id" and "ID" are detected as primary key
Name string `sql:",unique"`
Books []*Book // has many relation
AvatarId int
Avatar Image
}
func (a Author) String() string {
return fmt.Sprintf("Author<ID=%d Name=%q>", a.ID, a.Name)
}
type BookGenre struct {
tableName struct{} `sql:"alias:bg"` // custom table alias
BookId int `sql:",pk"` // pk tag is used to mark field as primary key
Book *Book
GenreId int `sql:",pk"`
Genre *Genre
Genre_Rating int // belongs to and is copied to Genre model
}
type Book struct {
Id int
Title string
AuthorID int
Author Author // has one relation
EditorID int
Editor *Author // has one relation
CreatedAt time.Time `sql:"default:now()"`
UpdatedAt time.Time
Genres []Genre `pg:"many2many:book_genres"` // many to many relation
Translations []Translation // has many relation
Comments []Comment `pg:"polymorphic:trackable_"` // has many polymorphic relation
}
func (b Book) String() string {
return fmt.Sprintf("Book<Id=%d Title=%q>", b.Id, b.Title)
}
func (b *Book) BeforeInsert(c context.Context, db orm.DB) error {
if b.CreatedAt.IsZero() {
b.CreatedAt = time.Now()
}
return nil
}
// BookWithCommentCount is like Book model, but has additional CommentCount
// field that is used to select data into it. The use of `pg:",inherit"` tag
// is essential here so it inherits internal model properties such as table name.
type BookWithCommentCount struct {
Book `pg:",inherit"`
CommentCount int
}
type Translation struct {
tableName struct{} `sql:",alias:tr"` // custom table alias
Id int
BookId int `sql:"unique:book_id_lang"`
Book *Book // has one relation
Lang string `sql:"unique:book_id_lang"`
Comments []Comment `pg:",polymorphic:trackable_"` // has many polymorphic relation
}
type Comment struct {
TrackableId int // Book.Id or Translation.Id
TrackableType string // "Book" or "Translation"
Text string
}
func createTestSchema(db *pg.DB) error {
models := []interface{}{
(*Image)(nil),
(*Author)(nil),
(*Book)(nil),
(*Genre)(nil),
(*BookGenre)(nil),
(*Translation)(nil),
(*Comment)(nil),
}
for _, model := range models {
err := db.DropTable(model, &orm.DropTableOptions{
IfExists: true,
Cascade: true,
})
if err != nil {
return err
}
err = db.CreateTable(model, nil)
if err != nil {
return err
}
}
return nil
}
var _ = Describe("ORM", func() {
var db *pg.DB
BeforeEach(func() {
db = pg.Connect(pgOptions())
err := createTestSchema(db)
Expect(err).NotTo(HaveOccurred())
genres := []Genre{{
Id: 1,
Name: "genre 1",
}, {
Id: 2,
Name: "genre 2",
}, {
Id: 3,
Name: "subgenre 1",
ParentId: 1,
}, {
Id: 4,
Name: "subgenre 2",
ParentId: 1,
}}
err = db.Insert(&genres)
Expect(err).NotTo(HaveOccurred())
Expect(genres).To(HaveLen(4))
images := []Image{{
Id: 1,
Path: "/path/to/1.jpg",
}, {
Id: 2,
Path: "/path/to/2.jpg",
}, {
Id: 3,
Path: "/path/to/3.jpg",
}}
err = db.Insert(&images)
Expect(err).NotTo(HaveOccurred())