-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathpgx.go
More file actions
1070 lines (972 loc) · 37.2 KB
/
pgx.go
File metadata and controls
1070 lines (972 loc) · 37.2 KB
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
// Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import "C"
import (
"context"
"fmt"
"reflect"
"strconv"
"strings"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
)
// This file defines tests that can be called from Java and that will connect to any PGAdapter
// instance that is defined in the connection string that is passed in to each of the test
// functions. The PGAdapter instance can be an in-process instance that is created and started by
// the Java test framework, and the Spanner database that PGAdapter is connected to can be a mock
// Spanner database or a real Spanner database.
// Test errors are returned as C strings.
// An empty main method is required to build a shared C lib.
func main() {
}
//export TestHelloWorld
func TestHelloWorld(connString string) *C.char {
ctx := context.Background()
conn, err := pgx.Connect(ctx, connString)
if err != nil {
return C.CString(err.Error())
}
defer func() { _ = conn.Close(ctx) }()
var greeting string
err = conn.QueryRow(ctx, "select 'Hello world!' as hello").Scan(&greeting)
if err != nil {
return C.CString(err.Error())
}
if g, w := greeting, "Hello world!"; g != w {
return C.CString(fmt.Sprintf("greeting mismatch\n Got: %v\nWant: %v", g, w))
}
return nil
}
//export TestSelect1
func TestSelect1(connString string) *C.char {
ctx := context.Background()
conn, err := pgx.Connect(ctx, connString)
if err != nil {
return C.CString(err.Error())
}
defer func() { _ = conn.Close(ctx) }()
var value int64
err = conn.QueryRow(ctx, "SELECT 1").Scan(&value)
if err != nil {
return C.CString(err.Error())
}
if g, w := value, int64(1); g != w {
return C.CString(fmt.Sprintf("value mismatch\n Got: %v\nWant: %v", g, w))
}
return nil
}
//export TestShowApplicationName
func TestShowApplicationName(connString string) *C.char {
ctx := context.Background()
conn, err := pgx.Connect(ctx, connString)
if err != nil {
return C.CString(err.Error())
}
defer func() { _ = conn.Close(ctx) }()
var value string
err = conn.QueryRow(ctx, "show application_name").Scan(&value)
if err != nil {
return C.CString(err.Error())
}
if g, w := value, "pgx"; g != w {
return C.CString(fmt.Sprintf("value mismatch\n Got: %v\nWant: %v", g, w))
}
return nil
}
//export TestQueryWithParameter
func TestQueryWithParameter(connString string) *C.char {
ctx := context.Background()
conn, err := pgx.Connect(ctx, connString)
if err != nil {
return C.CString(err.Error())
}
defer func() { _ = conn.Close(ctx) }()
var value string
err = conn.QueryRow(ctx, "SELECT * FROM FOO WHERE BAR=$1", "baz").Scan(&value)
if err != nil {
return C.CString(fmt.Sprintf("Failed to execute query: %v", err.Error()))
}
if g, w := value, "baz"; g != w {
return C.CString(fmt.Sprintf("value mismatch\n Got: %v\nWant: %v", g, w))
}
return nil
}
//export TestQueryAllDataTypes
func TestQueryAllDataTypes(connString string, oid, format int16) *C.char {
ctx := context.Background()
conn, err := pgx.Connect(ctx, connString)
if err != nil {
return C.CString(err.Error())
}
defer func() { _ = conn.Close(ctx) }()
var bigintValue int64
var boolValue bool
var byteaValue []byte
var float4Value float32
var float8Value float64
var intValue int
var numericValue pgtype.Numeric // pgx by default maps numeric to string
var timestamptzValue time.Time
var intervalValue pgtype.Interval
var dateValue time.Time
var varcharValue string
var jsonbValue string
var row pgx.Row
if oid != 0 {
formats := make(pgx.QueryResultFormatsByOID)
for _, o := range []uint32{
pgtype.Int8OID, pgtype.BoolOID, pgtype.ByteaOID, pgtype.Float4OID, pgtype.Float8OID,
pgtype.Int4OID, pgtype.NumericOID, pgtype.TimestamptzOID, pgtype.IntervalOID, pgtype.DateOID,
pgtype.VarcharOID, pgtype.JSONBOID, pgtype.Int8ArrayOID, pgtype.BoolArrayOID,
pgtype.ByteaArrayOID, pgtype.Float4ArrayOID, pgtype.Float8ArrayOID, pgtype.Int4ArrayOID,
pgtype.NumericArrayOID, pgtype.TimestamptzArrayOID, pgtype.IntervalArrayOID, pgtype.DateArrayOID,
pgtype.VarcharArrayOID, pgtype.JSONBArrayOID} {
formats[o] = conn.TypeMap().FormatCodeForOID(o)
}
formats[uint32(oid)] = format
row = conn.QueryRow(ctx, "SELECT col_bigint, col_bool, col_bytea, col_float4, col_float8, col_int, col_numeric, col_timestamptz, col_interval::interval, col_date, col_varchar, col_jsonb, col_array_bigint, col_array_bool, col_array_bytea, col_array_float4, col_array_float8, col_array_int, col_array_numeric, col_array_timestamptz, col_array_interval, col_array_date, col_array_varchar, col_array_jsonb FROM all_types WHERE col_bigint=1", formats)
} else {
row = conn.QueryRow(ctx, "SELECT col_bigint, col_bool, col_bytea, col_float4, col_float8, col_int, col_numeric, col_timestamptz, col_interval::interval, col_date, col_varchar, col_jsonb, col_array_bigint, col_array_bool, col_array_bytea, col_array_float4, col_array_float8, col_array_int, col_array_numeric, col_array_timestamptz, col_array_interval, col_array_date, col_array_varchar, col_array_jsonb FROM all_types WHERE col_bigint=1")
}
var arrayBigint, arrayBool, arrayBytea, arrayFloat4, arrayFloat8, arrayInt, arrayNumeric, arrayTimestamptz, arrayInterval, arrayDate, arrayVarchar, arrayJsonb interface{}
err = row.Scan(
&bigintValue,
&boolValue,
&byteaValue,
&float4Value,
&float8Value,
&intValue,
&numericValue,
×tamptzValue,
&intervalValue,
&dateValue,
&varcharValue,
&jsonbValue,
&arrayBigint,
&arrayBool,
&arrayBytea,
&arrayFloat4,
&arrayFloat8,
&arrayInt,
&arrayNumeric,
&arrayTimestamptz,
&arrayInterval,
&arrayDate,
&arrayVarchar,
&arrayJsonb,
)
if err != nil {
return C.CString(fmt.Sprintf("Failed to execute query: %v", err.Error()))
}
if g, w := bigintValue, int64(1); g != w {
return C.CString(fmt.Sprintf("value mismatch\n Got: %v\nWant: %v", g, w))
}
if g, w := boolValue, true; g != w {
return C.CString(fmt.Sprintf("value mismatch\n Got: %v\nWant: %v", g, w))
}
if g, w := byteaValue, []byte("test"); !reflect.DeepEqual(g, w) {
return C.CString(fmt.Sprintf("value mismatch\n Got: %v\nWant: %v", g, w))
}
if g, w := float4Value, float32(3.14); g != w {
return C.CString(fmt.Sprintf("value mismatch\n Got: %v\nWant: %v", g, w))
}
if g, w := float8Value, 3.14; g != w {
return C.CString(fmt.Sprintf("value mismatch\n Got: %v\nWant: %v", g, w))
}
if g, w := intValue, 100; g != w {
return C.CString(fmt.Sprintf("value mismatch\n Got: %v\nWant: %v", g, w))
}
var wantNumericValue pgtype.Numeric
_ = wantNumericValue.Scan("6.626")
if g, w := numericValue, wantNumericValue; !reflect.DeepEqual(g, w) {
return C.CString(fmt.Sprintf("value mismatch\n Got: %v\nWant: %v", g, w))
}
wantDateValue, _ := time.Parse("2006-01-02", "2022-03-29")
if g, w := dateValue, wantDateValue; !reflect.DeepEqual(g, w) {
return C.CString(fmt.Sprintf("value mismatch\n Got: %v\nWant: %v", g, w))
}
wantTimestamptzValue, _ := time.Parse(time.RFC3339Nano, "2022-02-16T13:18:02.123456+00:00")
if g, w := timestamptzValue.UTC().String(), wantTimestamptzValue.UTC().String(); g != w {
return C.CString(fmt.Sprintf("value mismatch\n Got: %v\nWant: %v", g, w))
}
wantIntervalValue := pgtype.Interval{Valid: true, Months: 14, Days: 3, Microseconds: int64(4)*60*60*1000*1000 + 5*60*1000*1000 + 6*1000*1000 + 789*1000}
if g, w := intervalValue, wantIntervalValue; !reflect.DeepEqual(g, w) {
return C.CString(fmt.Sprintf("interval value mismatch\n Got: %v\nWant: %v", g, w))
}
if g, w := varcharValue, "testÄ"; g != w {
return C.CString(fmt.Sprintf("value mismatch\n Got: %v\nWant: %v", g, w))
}
if g, w := jsonbValue, "{\"key\": \"value\"}"; g != w {
return C.CString(fmt.Sprintf("value mismatch\n Got: %v\nWant: %v", g, w))
}
return nil
}
//export TestInsertAllDataTypes
func TestInsertAllDataTypes(connString string) *C.char {
ctx := context.Background()
conn, err := pgx.Connect(ctx, connString)
if err != nil {
return C.CString(err.Error())
}
defer func() { _ = conn.Close(ctx) }()
insertSql := "INSERT INTO all_types (col_bigint, col_bool, col_bytea, col_float8, col_int, col_numeric, col_timestamptz, col_date, col_varchar, col_jsonb, " +
"col_array_bigint, col_array_bool, col_array_bytea, col_array_float8, col_array_int, col_array_numeric, col_array_timestamptz, col_array_date, col_array_varchar, col_array_jsonb) " +
"values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20)"
numeric := pgtype.Numeric{}
_ = numeric.Scan("6.626")
numeric1 := pgtype.Numeric{}
_ = numeric1.Scan("-6.626")
numeric2 := pgtype.Numeric{}
_ = numeric2.Scan("3.14")
timestamptz, _ := time.Parse(time.RFC3339Nano, "2022-03-24T07:39:10.123456789+01:00")
timestamptz2, _ := time.Parse(time.RFC3339Nano, "2000-01-01T00:00:00Z")
var tag pgconn.CommandTag
date := pgtype.Date{}
_ = date.Scan("2022-04-02")
date2 := pgtype.Date{}
_ = date2.Scan("1970-01-01")
tag, err = conn.Exec(ctx, insertSql, 100, true, []byte("test_bytes"), 3.14, 1, numeric, timestamptz, date, "test_string", "{\"key\": \"value\"}",
pgtype.Array[pgtype.Int8]{Dims: []pgtype.ArrayDimension{{3, 1}}, Valid: true, Elements: []pgtype.Int8{{Int64: 100, Valid: true}, {}, {Int64: 200, Valid: true}}},
pgtype.Array[pgtype.Bool]{Dims: []pgtype.ArrayDimension{{3, 1}}, Valid: true, Elements: []pgtype.Bool{{Bool: true, Valid: true}, {}, {Bool: false, Valid: true}}},
[][]byte{[]byte("bytes1"), nil, []byte("bytes2")},
pgtype.Array[pgtype.Float8]{Dims: []pgtype.ArrayDimension{{3, 1}}, Valid: true, Elements: []pgtype.Float8{{Float64: 3.14, Valid: true}, {}, {Float64: 6.626, Valid: true}}},
pgtype.Array[pgtype.Int8]{Dims: []pgtype.ArrayDimension{{3, 1}}, Valid: true, Elements: []pgtype.Int8{{Int64: -1, Valid: true}, {}, {Int64: -2, Valid: true}}},
pgtype.Array[pgtype.Numeric]{Dims: []pgtype.ArrayDimension{{3, 1}}, Valid: true, Elements: []pgtype.Numeric{numeric1, {}, numeric2}},
pgtype.Array[pgtype.Timestamptz]{Dims: []pgtype.ArrayDimension{{3, 1}}, Valid: true, Elements: []pgtype.Timestamptz{{Time: timestamptz, Valid: true}, {}, {Time: timestamptz2, Valid: true}}},
pgtype.Array[pgtype.Date]{Dims: []pgtype.ArrayDimension{{3, 1}}, Valid: true, Elements: []pgtype.Date{date, {}, date2}},
pgtype.Array[pgtype.Text]{Dims: []pgtype.ArrayDimension{{3, 1}}, Valid: true, Elements: []pgtype.Text{{String: "string1", Valid: true}, {}, {String: "string2", Valid: true}}},
pgtype.Array[[]byte]{Dims: []pgtype.ArrayDimension{{3, 1}}, Valid: true, Elements: [][]byte{[]byte("{\"key\": \"value1\"}"), nil, []byte("{\"key\": \"value2\"}")}},
)
if err != nil {
return C.CString(fmt.Sprintf("failed to execute insert statement: %v", err))
}
if !tag.Insert() {
return C.CString("statement was not recognized as an insert")
}
if g, w := tag.RowsAffected(), int64(1); g != w {
return C.CString(fmt.Sprintf("rows affected mismatch:\n Got: %v\nWant: %v", g, w))
}
return nil
}
//export TestInsertNullsAllDataTypes
func TestInsertNullsAllDataTypes(connString string) *C.char {
ctx := context.Background()
conn, err := pgx.Connect(ctx, connString)
if err != nil {
return C.CString(err.Error())
}
defer func() { _ = conn.Close(ctx) }()
var tag pgconn.CommandTag
sql := "INSERT INTO all_types (col_bigint, col_bool, col_bytea, col_float8, col_int, col_numeric, col_timestamptz, col_date, col_varchar, col_jsonb) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)"
tag, err = conn.Exec(ctx, sql, int64(100), nil, nil, nil, nil, nil, nil, nil, nil, nil)
if err != nil {
return C.CString(fmt.Sprintf("failed to execute insert statement: %v", err))
}
if !tag.Insert() {
return C.CString("statement was not recognized as an insert")
}
if g, w := tag.RowsAffected(), int64(1); g != w {
return C.CString(fmt.Sprintf("rows affected mismatch:\n Got: %v\nWant: %v", g, w))
}
return nil
}
//export TestInsertAllDataTypesReturning
func TestInsertAllDataTypesReturning(connString string) *C.char {
ctx := context.Background()
conn, err := pgx.Connect(ctx, connString)
if err != nil {
return C.CString(err.Error())
}
defer func() { _ = conn.Close(ctx) }()
sql := "INSERT INTO all_types (col_bigint, col_bool, col_bytea, col_float4, col_float8, col_int, col_numeric, col_timestamptz, col_interval, col_date, col_varchar, col_jsonb) " +
"values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) returning *"
numeric := pgtype.Numeric{}
_ = numeric.Scan("6.626")
timestamptz, _ := time.Parse(time.RFC3339Nano, "2022-03-24T07:39:10.123456789+01:00")
interval := pgtype.Interval{Valid: true, Months: 14, Days: 3, Microseconds: int64(4)*60*60*1000*1000 + 5*60*1000*1000 + 6*1000*1000 + 789*1000}
date := pgtype.Date{}
_ = date.Scan("2022-04-02")
var row pgx.Row
if strings.Contains(connString, "prefer_simple_protocol=true") {
// Simple mode will format the date as '2022-04-02 00:00:00Z', which is not supported by the
// backend yet.
row = conn.QueryRow(ctx, sql, 100, true, []byte("test_bytes"), float32(3.14), 3.14, 1, numeric, timestamptz, interval, "2022-04-02", "test_string", "{\"key\": \"value\"}")
} else {
row = conn.QueryRow(ctx, sql, 100, true, []byte("test_bytes"), float32(3.14), 3.14, 1, numeric, timestamptz, interval, date, "test_string", "{\"key\": \"value\"}")
}
var bigintValue int64
var boolValue bool
var byteaValue []byte
var float4Value float32
var float8Value float64
var intValue int
var numericValue pgtype.Numeric // pgx by default maps numeric to string
var timestamptzValue time.Time
var intervalValue pgtype.Interval
var dateValue time.Time
var varcharValue string
var jsonbValue string
var arrayBigint, arrayBool, arrayBytea, arrayFloat4, arrayFloat8, arrayInt, arrayNumeric, arrayTimestamptz, arrayInterval, arrayDate, arrayVarchar, arrayJsonb interface{}
err = row.Scan(
&bigintValue,
&boolValue,
&byteaValue,
&float4Value,
&float8Value,
&intValue,
&numericValue,
×tamptzValue,
&intervalValue,
&dateValue,
&varcharValue,
&jsonbValue,
&arrayBigint,
&arrayBool,
&arrayBytea,
&arrayFloat4,
&arrayFloat8,
&arrayInt,
&arrayNumeric,
&arrayTimestamptz,
&arrayInterval,
&arrayDate,
&arrayVarchar,
&arrayJsonb,
)
if err != nil {
return C.CString(fmt.Sprintf("Failed to execute insert: %v", err.Error()))
}
if g, w := bigintValue, int64(1); g != w {
return C.CString(fmt.Sprintf("value mismatch\n Got: %v\nWant: %v", g, w))
}
if g, w := boolValue, true; g != w {
return C.CString(fmt.Sprintf("value mismatch\n Got: %v\nWant: %v", g, w))
}
if g, w := byteaValue, []byte("test"); !reflect.DeepEqual(g, w) {
return C.CString(fmt.Sprintf("value mismatch\n Got: %v\nWant: %v", g, w))
}
if g, w := float4Value, float32(3.14); g != w {
return C.CString(fmt.Sprintf("value mismatch\n Got: %v\nWant: %v", g, w))
}
if g, w := float8Value, 3.14; g != w {
return C.CString(fmt.Sprintf("value mismatch\n Got: %v\nWant: %v", g, w))
}
if g, w := intValue, 100; g != w {
return C.CString(fmt.Sprintf("value mismatch\n Got: %v\nWant: %v", g, w))
}
var wantNumericValue pgtype.Numeric
_ = wantNumericValue.Scan("6.626")
if g, w := numericValue, wantNumericValue; !reflect.DeepEqual(g, w) {
return C.CString(fmt.Sprintf("value mismatch\n Got: %v\nWant: %v", g, w))
}
wantDateValue, _ := time.Parse("2006-01-02", "2022-03-29")
if g, w := dateValue, wantDateValue; !reflect.DeepEqual(g, w) {
return C.CString(fmt.Sprintf("value mismatch\n Got: %v\nWant: %v", g, w))
}
// Encoding the timestamp values as a parameter will truncate it to microsecond precision.
wantTimestamptzValue, _ := time.Parse(time.RFC3339Nano, "2022-02-16T13:18:02.123456+00:00")
if g, w := timestamptzValue.UTC().String(), wantTimestamptzValue.UTC().String(); g != w {
return C.CString(fmt.Sprintf("value mismatch\n Got: %v\nWant: %v", g, w))
}
wantIntervalValue := pgtype.Interval{Valid: true, Months: 14, Days: 3, Microseconds: int64(4)*60*60*1000*1000 + 5*60*1000*1000 + 6*1000*1000 + 789*1000}
if g, w := intervalValue, wantIntervalValue; !reflect.DeepEqual(g, w) {
return C.CString(fmt.Sprintf("interval value mismatch\n Got: %v\nWant: %v", g, w))
}
if g, w := varcharValue, "testÄ"; g != w {
return C.CString(fmt.Sprintf("value mismatch\n Got: %v\nWant: %v", g, w))
}
if g, w := jsonbValue, "{\"key\": \"value\"}"; g != w {
return C.CString(fmt.Sprintf("value mismatch\n Got: %v\nWant: %v", g, w))
}
return nil
}
//export TestUpdateAllDataTypes
func TestUpdateAllDataTypes(connString string) *C.char {
ctx := context.Background()
conn, err := pgx.Connect(ctx, connString)
if err != nil {
return C.CString(err.Error())
}
defer func() { _ = conn.Close(ctx) }()
sql := "UPDATE \"all_types\" SET \"col_bigint\"=$1,\"col_bool\"=$2,\"col_bytea\"=$3,\"col_float4\"=$4,\"col_float8\"=$5,\"col_int\"=$6,\"col_numeric\"=$7,\"col_timestamptz\"=$8,\"col_date\"=$9,\"col_varchar\"=$10,\"col_jsonb\"=$11 WHERE \"col_varchar\" = $12"
numeric := pgtype.Numeric{}
_ = numeric.Scan("6.626")
timestamptz, _ := time.Parse(time.RFC3339Nano, "2022-03-24T07:39:10.123456789+01:00")
var tag pgconn.CommandTag
date := pgtype.Date{}
_ = date.Scan("2022-04-02")
if strings.Contains(connString, "prefer_simple_protocol=true") {
// Simple mode will format the date as '2022-04-02 00:00:00Z', which is not supported by the
// backend yet.
tag, err = conn.Exec(ctx, sql, 100, true, []byte("test_bytes"), float32(3.14), 3.14, 1, numeric, timestamptz, "2022-04-02", "test_string", "{\"key\": \"value\"}", "test")
} else {
tag, err = conn.Exec(ctx, sql, 100, true, []byte("test_bytes"), float32(3.14), 3.14, 1, numeric, timestamptz, date, "test_string", "{\"key\": \"value\"}", "test")
}
if err != nil {
return C.CString(fmt.Sprintf("failed to execute update statement: %v", err))
}
if !tag.Update() {
return C.CString("statement was not recognized as an update")
}
if g, w := tag.RowsAffected(), int64(1); g != w {
return C.CString(fmt.Sprintf("rows affected mismatch:\n Got: %v\nWant: %v", g, w))
}
return nil
}
//export TestPrepareStatement
func TestPrepareStatement(connString string) *C.char {
ctx := context.Background()
conn, err := pgx.Connect(ctx, connString)
if err != nil {
return C.CString(err.Error())
}
defer func() { _ = conn.Close(ctx) }()
sql := "UPDATE all_types SET col_int=$1, col_bool=$2, col_bytea=$3, col_float4=$4, col_float8=$5, " +
"col_numeric=$6, col_timestamptz=$7, col_date=$8, col_varchar=$9, col_jsonb=$10 WHERE col_bigint=$11"
sd, err := conn.Prepare(ctx, "update_all_types", sql)
if err != nil {
return C.CString(err.Error())
}
if g, w := len(sd.ParamOIDs), 11; g != w {
return C.CString(fmt.Sprintf("param type count mismatch:\n Got: %v\nWant: %v", g, w))
}
wantParamTypes := []int{
pgtype.Int8OID,
pgtype.BoolOID,
pgtype.ByteaOID,
pgtype.Float4OID,
pgtype.Float8OID,
pgtype.NumericOID,
pgtype.TimestamptzOID,
pgtype.DateOID,
pgtype.VarcharOID,
pgtype.JSONBOID,
pgtype.Int8OID,
}
for i, tp := range wantParamTypes {
if g, w := sd.ParamOIDs[i], uint32(tp); g != w {
return C.CString(fmt.Sprintf("param type mismatch for param[%v]:\n Got: %v\nWant: %v", i, g, w))
}
}
if g, w := len(sd.Fields), 0; g != w {
return C.CString(fmt.Sprintf("field count mismatch:\n Got: %v\nWant: %v", g, w))
}
return nil
}
//export TestPrepareSelectStatement
func TestPrepareSelectStatement(connString string) *C.char {
ctx := context.Background()
conn, err := pgx.Connect(ctx, connString)
if err != nil {
return C.CString(err.Error())
}
defer func() { _ = conn.Close(ctx) }()
sql := "SELECT col_bigint, col_bool, col_bytea, col_float8, col_int, col_numeric, col_timestamptz, col_date, col_varchar, col_jsonb " +
"FROM all_types " +
"WHERE col_int=$1 AND col_bool=$2 AND col_bytea=$3 AND col_float8=$4 AND " +
"col_numeric=$5 AND col_timestamptz=$6 AND col_date=$7 AND col_varchar=$8 AND col_jsonb::text=$9 AND col_bigint=$10"
sd, err := conn.Prepare(ctx, "select_all_types", sql)
if err != nil {
return C.CString(err.Error())
}
wantParamTypes := []int{
pgtype.Int8OID,
pgtype.BoolOID,
pgtype.ByteaOID,
pgtype.Float8OID,
pgtype.NumericOID,
pgtype.TimestamptzOID,
pgtype.DateOID,
pgtype.VarcharOID,
pgtype.VarcharOID,
pgtype.Int8OID,
}
if g, w := len(sd.ParamOIDs), len(wantParamTypes); g != w {
return C.CString(fmt.Sprintf("param type count mismatch:\n Got: %v\nWant: %v", g, w))
}
for i, tp := range wantParamTypes {
if g, w := sd.ParamOIDs[i], uint32(tp); g != w {
return C.CString(fmt.Sprintf("param type mismatch for param[%v]:\n Got: %v\nWant: %v", i, g, w))
}
}
wantFieldTypes := []int{
pgtype.Int8OID,
pgtype.BoolOID,
pgtype.ByteaOID,
pgtype.Float8OID,
pgtype.Int8OID,
pgtype.NumericOID,
pgtype.TimestamptzOID,
pgtype.DateOID,
pgtype.JSONBOID,
pgtype.VarcharOID,
}
if g, w := len(sd.Fields), len(wantFieldTypes); g != w {
return C.CString(fmt.Sprintf("field count mismatch:\n Got: %v\nWant: %v", g, w))
}
for i, tp := range wantParamTypes {
if g, w := sd.ParamOIDs[i], uint32(tp); g != w {
return C.CString(fmt.Sprintf("param type mismatch for param[%v]:\n Got: %v\nWant: %v", i, g, w))
}
}
return nil
}
//export TestInsertBatch
func TestInsertBatch(connString string) *C.char {
ctx := context.Background()
conn, err := pgx.Connect(ctx, connString)
if err != nil {
return C.CString(err.Error())
}
defer func() { _ = conn.Close(ctx) }()
batch := &pgx.Batch{}
batchSize := 10
if err := insertBatch(batch, connString, batchSize); err != nil {
return C.CString(err.Error())
}
res := conn.SendBatch(ctx, batch)
for i := 0; i < batchSize; i++ {
tag, err := res.Exec()
if err != nil {
return C.CString(fmt.Sprintf("failed to execute insert statement %d: %v", i, err))
}
if !tag.Insert() {
return C.CString(fmt.Sprintf("statement %d was not recognized as an insert", i))
}
if g, w := tag.RowsAffected(), int64(1); g != w {
return C.CString(fmt.Sprintf("rows affected mismatch for statement %d:\n Got: %v\nWant: %v", i, g, w))
}
}
if err := res.Close(); err != nil {
return C.CString(err.Error())
}
return nil
}
//export TestMixedBatch
func TestMixedBatch(connString string) *C.char {
ctx := context.Background()
conn, err := pgx.Connect(ctx, connString)
if err != nil {
return C.CString(err.Error())
}
defer func() { _ = conn.Close(ctx) }()
batch := &pgx.Batch{}
batchSize := 5
if err := insertBatch(batch, connString, batchSize); err != nil {
return C.CString(err.Error())
}
batch.Queue("select count(*) from all_types where col_bool=$1", true)
batch.Queue("update all_types set col_bool=false where col_bool=$1", true)
res := conn.SendBatch(ctx, batch)
for i := 0; i < batchSize; i++ {
tag, err := res.Exec()
if err != nil {
return C.CString(fmt.Sprintf("failed to execute insert statement %d: %v", i, err))
}
if !tag.Insert() {
return C.CString(fmt.Sprintf("statement %d was not recognized as an insert", i))
}
if g, w := tag.RowsAffected(), int64(1); g != w {
return C.CString(fmt.Sprintf("rows affected mismatch for statement %d:\n Got: %v\nWant: %v", i, g, w))
}
}
var count int64
if err := res.QueryRow().Scan(&count); err != nil {
return C.CString(fmt.Sprintf("failed to get row count: %v", err.Error()))
}
tag, err := res.Exec()
if err != nil {
return C.CString(fmt.Sprintf("failed to execute update: %v", err.Error()))
}
if !tag.Update() {
return C.CString("update statement was not recognized as an update")
}
if g, w := tag.RowsAffected(), count; g != w {
return C.CString(fmt.Sprintf("rows affected mismatch for update statement:\n Got: %v\nWant: %v", g, w))
}
if err := res.Close(); err != nil {
return C.CString(err.Error())
}
return nil
}
//export TestBatchError
func TestBatchError(connString string) *C.char {
ctx := context.Background()
conn, err := pgx.Connect(ctx, connString)
if err != nil {
return C.CString(err.Error())
}
defer func() { _ = conn.Close(ctx) }()
batch := &pgx.Batch{}
batchSize := 5
if err := insertBatch(batch, connString, batchSize); err != nil {
return C.CString(err.Error())
}
// This statement will fail.
batch.Queue("select count(*) from non_existent_table where col_bool=$1", true)
// This statement will not be executed as the previous statement failed.
batch.Queue("update all_types set col_bool=false where col_bool=$1", true)
res := conn.SendBatch(ctx, batch)
// Try to get results from the batch execution. Even though the error occurred for the select
// statement, it is returned for the first statement in the batch.
_, err = res.Exec()
if err == nil {
return C.CString(fmt.Sprintf("expected error for batch, but got nil"))
}
if err := res.Close(); err != nil {
return C.CString(err.Error())
}
return nil
}
//export TestBatchExecutionError
func TestBatchExecutionError(connString string) *C.char {
ctx := context.Background()
conn, err := pgx.Connect(ctx, connString)
if err != nil {
return C.CString(err.Error())
}
defer func() { _ = conn.Close(ctx) }()
batch := &pgx.Batch{}
batchSize := 3
if err := insertBatch(batch, connString, batchSize); err != nil {
return C.CString(err.Error())
}
res := conn.SendBatch(ctx, batch)
// Try to get results from the batch execution.
tag, err := res.Exec()
if err != nil {
return C.CString(fmt.Sprintf("failed to execute first insert statement: %v", err))
}
if !tag.Insert() {
return C.CString("the first statement was not recognized as an insert")
}
if g, w := tag.RowsAffected(), int64(1); g != w {
return C.CString(fmt.Sprintf("rows affected mismatch for first statement:\n Got: %v\nWant: %v", g, w))
}
_, err = res.Exec()
if err == nil {
return C.CString(fmt.Sprintf("expected error for second statement, but got nil"))
}
if err := res.Close(); err != nil {
return C.CString(fmt.Sprintf("closing batch result returned error: %v", err.Error()))
}
return nil
}
//export TestDdlBatch
func TestDdlBatch(connString string) *C.char {
ctx := context.Background()
conn, err := pgx.Connect(ctx, connString)
if err != nil {
return C.CString(err.Error())
}
defer func() { _ = conn.Close(ctx) }()
batch := &pgx.Batch{}
batch.Queue("CREATE SEQUENCE IF NOT EXISTS seq_merchants bit_reversed_positive")
batch.Queue("CREATE TABLE IF NOT EXISTS merchants (" +
" merchant_id varchar(36) DEFAULT spanner.generate_uuid() NOT NULL," +
" seq_id bigint DEFAULT nextval('seq_merchants')," +
" name varchar(255) NOT NULL," +
" created timestamptz DEFAULT CURRENT_TIMESTAMP," +
" created_by varchar(36)," +
" modified timestamptz DEFAULT CURRENT_TIMESTAMP," +
" modified_by varchar(36)," +
" PRIMARY KEY(merchant_id)" +
")")
batch.Queue("CREATE UNIQUE INDEX idx_uq_email ON users(email);")
br := conn.SendBatch(context.Background(), batch)
if _, err := br.Exec(); err != nil {
return C.CString(fmt.Sprintf("executing DDL batch returned error: %v", err.Error()))
}
return nil
}
//export TestDdlBatchInTransaction
func TestDdlBatchInTransaction(connString string) *C.char {
ctx := context.Background()
conn, err := pgx.Connect(ctx, connString)
if err != nil {
return C.CString(err.Error())
}
defer func() { _ = conn.Close(ctx) }()
// Start a transaction and then try to execute a DDL batch.
tx, err := conn.Begin(ctx)
batch := &pgx.Batch{}
batch.Queue("CREATE SEQUENCE IF NOT EXISTS seq_merchants bit_reversed_positive")
batch.Queue("CREATE TABLE IF NOT EXISTS merchants (" +
" merchant_id varchar(36) DEFAULT spanner.generate_uuid() NOT NULL," +
" seq_id bigint DEFAULT nextval('seq_merchants')," +
" name varchar(255) NOT NULL," +
" created timestamptz DEFAULT CURRENT_TIMESTAMP," +
" created_by varchar(36)," +
" modified timestamptz DEFAULT CURRENT_TIMESTAMP," +
" modified_by varchar(36)," +
" PRIMARY KEY(merchant_id)" +
")")
batch.Queue("CREATE UNIQUE INDEX idx_uq_email ON users(email);")
br := conn.SendBatch(context.Background(), batch)
_, err = br.Exec()
if err == nil {
return C.CString("missing expected error for DDL batch in transaction")
}
// The batch execution should return an error indicating that DDL batches are not supported in transactions.
if g, w := err.Error(), "ERROR: DDL statements are not allowed in mixed batches or transactions. (SQLSTATE 25000)"; g != w {
return C.CString(fmt.Sprintf("error mismatch\n Got: %v\nWant: %v", g, w))
}
_ = tx.Rollback(ctx)
return nil
}
func insertBatch(batch *pgx.Batch, connString string, batchSize int) error {
sql := "INSERT INTO all_types (col_bigint, col_bool, col_bytea, col_float8, col_int, col_numeric, col_timestamptz, col_date, col_varchar, col_jsonb) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)"
numeric := pgtype.Numeric{}
for i := 0; i < batchSize; i++ {
_ = numeric.Scan(strconv.Itoa(i) + ".123")
var timestamptz interface{}
var date interface{}
// TODO: Remove this when the backend supports Zulu timestamp/date literals.
if strings.Contains(connString, "prefer_simple_protocol=true") {
date = fmt.Sprintf("2022-04-%02d", i+1)
timestamptz = fmt.Sprintf("2022-03-24 %02d:39:10.123456000+00", i)
} else {
date = &pgtype.Date{}
_ = date.(*pgtype.Date).Scan(fmt.Sprintf("2022-04-%02d", i+1))
timestamptz, _ = time.Parse(time.RFC3339Nano, fmt.Sprintf("2022-03-24T%02d:39:10.123456000Z", i))
}
batch.Queue(sql, 100+i, i%2 == 0, []byte(strconv.Itoa(i)+"test_bytes"), 3.14+float64(i), i, numeric, timestamptz, date, "test_string"+strconv.Itoa(i), fmt.Sprintf("{\"key\": \"value%v\"}", i))
}
return nil
}
//export TestWrongDialect
func TestWrongDialect(connString string) *C.char {
ctx := context.Background()
conn, err := pgx.Connect(ctx, connString)
if err != nil {
return C.CString(fmt.Sprintf("failed to connect to PG: %v", err))
}
defer func() { _ = conn.Close(ctx) }()
return nil
}
//export TestCopyIn
func TestCopyIn(connString string) *C.char {
ctx := context.Background()
conn, err := pgx.Connect(ctx, connString)
if err != nil {
return C.CString(err.Error())
}
defer func() { _ = conn.Close(ctx) }()
numeric := pgtype.Numeric{}
_ = numeric.Scan("6.626")
timestamptz, _ := time.Parse(time.RFC3339Nano, "2022-03-24T12:39:10.123456000Z")
date := pgtype.Date{}
_ = date.Scan("2022-07-01")
jsonb := []byte(("{\"key\": \"value\"}"))
rows := [][]interface{}{
{1, true, []byte{1, 2, 3}, float32(3.14), 3.14, 10, numeric, timestamptz, date, "test", jsonb},
{2, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil},
}
count, err := conn.CopyFrom(
ctx,
pgx.Identifier{"all_types"},
[]string{"col_bigint", "col_bool", "col_bytea", "col_float4", "col_float8", "col_int", "col_numeric", "col_timestamptz", "col_date", "col_varchar", "col_jsonb"},
pgx.CopyFromRows(rows),
)
if err != nil {
return C.CString(fmt.Sprintf("failed to execute COPY statement: %v", err))
}
if g, w := count, int64(2); g != w {
return C.CString(fmt.Sprintf("rows affected mismatch:\n Got: %v\nWant: %v", g, w))
}
return nil
}
//export TestReadWriteTransaction
func TestReadWriteTransaction(connString string) *C.char {
ctx := context.Background()
conn, err := pgx.Connect(ctx, connString)
if err != nil {
return C.CString(err.Error())
}
defer func() { _ = conn.Close(ctx) }()
tx, err := conn.BeginTx(ctx, pgx.TxOptions{})
if err != nil {
return C.CString(fmt.Sprintf("failed to begin transaction: %v", err.Error()))
}
// Execute a query in a read/write transaction.
var value int64
err = conn.QueryRow(ctx, "SELECT 1").Scan(&value)
if err != nil {
return C.CString(err.Error())
}
if g, w := value, int64(1); g != w {
return C.CString(fmt.Sprintf("value mismatch\n Got: %v\nWant: %v", g, w))
}
sql := "INSERT INTO all_types (col_bigint, col_bool, col_bytea, col_float8, col_int, col_numeric, col_timestamptz, col_date, col_varchar, col_jsonb) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)"
numeric := pgtype.Numeric{}
_ = numeric.Scan("6.626")
timestamptz, _ := time.Parse(time.RFC3339Nano, "2022-03-24T07:39:10.123456789+01:00")
var tag pgconn.CommandTag
date := pgtype.Date{}
_ = date.Scan("2022-04-02")
for _, id := range []int64{10, 20} {
if strings.Contains(connString, "prefer_simple_protocol=true") {
// Simple mode will format the date as '2022-04-02 00:00:00Z', which is not supported by the
// backend yet.
tag, err = tx.Exec(ctx, sql, id, true, []byte("test_bytes"), 3.14, 1, numeric, timestamptz, "2022-04-02", "test_string", "{\"key\": \"value\"}")
} else {
tag, err = tx.Exec(ctx, sql, id, true, []byte("test_bytes"), 3.14, 1, numeric, timestamptz, date, "test_string", "{\"key\": \"value\"}")
}
if err != nil {
return C.CString(fmt.Sprintf("failed to execute insert statement: %v", err))
}
if !tag.Insert() {
return C.CString("statement was not recognized as an insert")
}
if g, w := tag.RowsAffected(), int64(1); g != w {
return C.CString(fmt.Sprintf("rows affected mismatch:\n Got: %v\nWant: %v", g, w))
}
}
if err := tx.Commit(ctx); err != nil {
return C.CString(fmt.Sprintf("failed to commit transaction: %v", err))
}
return nil
}
//export TestReadOnlyTransaction
func TestReadOnlyTransaction(connString string) *C.char {
ctx := context.Background()
conn, err := pgx.Connect(ctx, connString)
if err != nil {
return C.CString(err.Error())
}
defer func() { _ = conn.Close(ctx) }()
tx, err := conn.BeginTx(ctx, pgx.TxOptions{AccessMode: pgx.ReadOnly})
if err != nil {
return C.CString(fmt.Sprintf("failed to begin read-only transaction: %v", err.Error()))
}
for _, i := range []int{1, 2} {
var value int64
err = tx.QueryRow(ctx, fmt.Sprintf("SELECT %d", i)).Scan(&value)
if err != nil {
return C.CString(err.Error())
}
if g, w := value, int64(i); g != w {
return C.CString(fmt.Sprintf("value mismatch\n Got: %v\nWant: %v", g, w))
}
}
if err := tx.Commit(ctx); err != nil {
return C.CString(fmt.Sprintf("failed to commit read-only transaction: %v", err.Error()))
}
return nil
}
//export TestReadWriteTransactionIsolationLevelSerializable
func TestReadWriteTransactionIsolationLevelSerializable(connString string) *C.char {
ctx := context.Background()
conn, err := pgx.Connect(ctx, connString)
if err != nil {
return C.CString(err.Error())
}
defer func() { _ = conn.Close(ctx) }()
tx, err := conn.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.Serializable})
if err != nil {
return C.CString(fmt.Sprintf("failed to begin transaction: %v", err.Error()))
}
var value int64
err = tx.QueryRow(ctx, "SELECT 1").Scan(&value)
if err != nil {
return C.CString(err.Error())
}
if g, w := value, int64(1); g != w {
return C.CString(fmt.Sprintf("value mismatch\n Got: %v\nWant: %v", g, w))
}
if err := tx.Commit(ctx); err != nil {
return C.CString(fmt.Sprintf("failed to commit transaction: %v", err))
}
return nil
}
//export TestReadWriteTransactionIsolationLevelRepeatableRead
func TestReadWriteTransactionIsolationLevelRepeatableRead(connString string) *C.char {
ctx := context.Background()
conn, err := pgx.Connect(ctx, connString)
if err != nil {
return C.CString(err.Error())
}
defer func() { _ = conn.Close(ctx) }()
tx, err := conn.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead})
if err != nil {
return C.CString(fmt.Sprintf("failed to begin transaction: %v", err.Error()))
}
var value int64
err = tx.QueryRow(ctx, "SELECT 1").Scan(&value)
if err != nil {