-
Notifications
You must be signed in to change notification settings - Fork 3
/
driver_test.go
1415 lines (1282 loc) · 34.3 KB
/
driver_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 cli_test
import (
"context"
"database/sql"
"database/sql/driver"
"encoding/hex"
"fmt"
"io/ioutil"
"math"
"os"
"reflect"
"strings"
"testing"
"time"
_ "github.com/asifjalil/cli"
)
type testDB struct {
*sql.DB
}
func getDB2Error(sqlerr error) (int, string, bool) {
type sqlcode interface {
SQLCode() int
SQLState() string
}
if err, ok := sqlerr.(sqlcode); ok {
return err.SQLCode(), err.SQLState(), ok
}
return 0, "", false
}
func newTestDB() (*testDB, error) {
config := struct {
database string
uid string
pwd string
}{
database: "sample",
uid: "",
pwd: "",
}
if os.Getenv("DATABASE_NAME") != "" {
config.database = os.Getenv("DATABASE_NAME")
}
if os.Getenv("DATABASE_USER") != "" {
config.uid = os.Getenv("DATABASE_USER")
}
if os.Getenv("DATABASE_PASSWORD") != "" {
config.pwd = os.Getenv("DATABASE_PASSWORD")
}
connStr := fmt.Sprintf("DATABASE = %s; UID = %s; PWD = %s;",
config.database, config.uid, config.pwd)
if os.Getenv("DATABASE_DSN") != "" {
connStr = os.Getenv("DATABASE_DSN")
}
db, err := sql.Open("cli", connStr)
if err != nil {
return nil, err
}
return &testDB{db}, nil
}
func (db *testDB) close() {
db.DB.Close()
}
func TestScan(t *testing.T) {
var (
s1 string
s2 sql.NullString
i1 int
f1 float64
)
db, err := newTestDB()
if err != nil {
die(t, "failed because %v", err)
}
defer db.close()
err = db.QueryRowContext(context.Background(), "values('hello', NULL, 12345, 12345.6789)").Scan(&s1,
&s2, &i1, &f1)
switch {
case err != nil:
die(t, "error: %v", err)
case s1 != "hello" || s2.String != "" || i1 != 12345 ||
f1 != 12345.6789:
die(t, "Expected: s1:\"hello\", s2:\"\", i1: 12345, f1: 12345.6789|Got: s1:%s, s2:%s, i1: %d, f1: %f",
s1, s2.String, i1, f1)
default:
info(t, "All Ok!")
}
}
func TestTimeStamp(t *testing.T) {
// Database timestamp accuracy is up to a microsecond or 6 digits.
// But Go timestamp accuracy is up to a nanosecond or 9 digits.
// So the last 3 digits in 9 digits must be 0.
ts := time.Date(2009, time.November, 10, 23, 6, 29, 10011001000, time.UTC)
db, err := newTestDB()
if err != nil {
die(t, "failed to create db object: %v", err)
}
defer db.close()
// start transaction
tx, err := db.Begin()
if err != nil {
die(t, "transaction begin failed because: %v", err)
}
// insert value
_, err = tx.Exec(`INSERT INTO in_tray(received, source, subject, note_text)
VALUES(?, ?, ?, ?)`, ts, "TEST", nil, nil)
if err != nil {
die(t, "insert failed because %v", err)
}
_, err = tx.ExecContext(context.Background(), `INSERT INTO in_tray(received, source, subject, note_text)
VALUES(?, ?, ?, ?)`, ts, "TEST", nil, nil)
if err != nil {
die(t, "insert failed because %v", err)
}
// check that the data is in the table
var db_ts time.Time
err = tx.QueryRow("SELECT received FROM in_tray WHERE source = ?",
"TEST").Scan(&db_ts)
switch {
case err == sql.ErrNoRows:
die(t, "No new timestamp in table IN_TRAY - insert didn't work")
case err != nil:
die(t, "insert into IN_TRAY failed because %v", err)
default:
// Timestamps are stored as is but without the timezone information.
// When a timestamp is returned from the database, the driver/Go assumes
// local timezone.
info(t, "database timestamp with local timezone: %v", db_ts)
// In this case we used UTC, so change the local timezone to UTC.
db_ts = time.Date(db_ts.Year(),
db_ts.Month(),
db_ts.Day(),
db_ts.Hour(),
db_ts.Minute(),
db_ts.Second(),
db_ts.Nanosecond(),
time.UTC)
if !ts.Equal(db_ts) {
die(t, "Expected: %v| Got: %v", ts, db_ts)
}
}
// cleanup
err = tx.Rollback()
if err != nil {
die(t, "rollback failed because %v", err)
}
}
func TestXML(t *testing.T) {
testCases := []struct {
qry string
val string
got string
}{
{qry: `SELECT info FROM Customer c
WHERE XMLEXISTS('$INFO//addr[pcode-zip = $zip]'
passing c.INFO as "d",
CAST(? AS VARCHAR(128)) AS "zip") `, val: "M6W 1E6"},
{qry: `SELECT XMLQUERY ('$d/customerinfo/addr' passing c.INFO as "d")
FROM Customer as c
WHERE XMLEXISTS('$d//addr[city=$cityName]'
passing c.INFO as "d",
CAST (? AS VARCHAR(128)) AS "cityName")`, val: "Aurora"},
}
db, err := newTestDB()
if err != nil {
t.Fatal(err)
}
defer db.close()
for i, tc := range testCases {
t.Run(fmt.Sprintf("Testcase %d", i), func(t *testing.T) {
err := db.QueryRow(tc.qry, tc.val).Scan(&tc.got)
switch {
case err == sql.ErrNoRows:
t.Log("No rows for query: ", tc.qry)
case err != nil:
t.Error(err)
default:
t.Log(tc.got)
}
})
}
}
// for issue #8
func TestLgXML(t *testing.T) {
tabname := "testxml"
delFile := "_TEST/large.del"
xmlFile := "_TEST/large.xml"
createStmt := fmt.Sprintf("CREATE TABLE %s (Col1 XML)", tabname)
dropStmt := fmt.Sprintf("DROP TABLE %s", tabname)
queryStmt := fmt.Sprintf("SELECT col1 FROM %s", tabname)
if home := os.Getenv("DATABASE_HOMEDIR"); home != "" {
delFile = home + "/" + delFile
} else if dir, err := os.Getwd(); err != nil {
die(t, "failed to lookup current directory: %v", err)
} else {
delFile = dir + "/" + delFile
}
if dir, err := os.Getwd(); err != nil {
die(t, "failed to lookup current directory: %v", err)
} else {
xmlFile = dir + "/" + xmlFile
}
b, err := ioutil.ReadFile(xmlFile)
if err != nil {
die(t, "Failed to read xml from file %s: %v", xmlFile, err)
}
wantXML := string(b)
importStmt := fmt.Sprintf("CALL SYSPROC.ADMIN_CMD('IMPORT FROM %s"+
" OF DEL XMLPARSE PRESERVE WHITESPACE REPLACE INTO %s')", delFile, tabname)
db, err := newTestDB()
if err != nil {
die(t, "Failed to connect to database: %v", err)
}
defer db.close()
// create test table
_, err = db.Exec(createStmt)
if err != nil {
die(t, "Failed to create table %s: %v", tabname, err)
}
defer func() {
db.Exec(dropStmt)
}()
// load xml data
_, err = db.Exec(importStmt)
if err != nil {
die(t, "Failed to run %q: %v", importStmt, err)
}
var gotXML string
err = db.QueryRow(queryStmt).Scan(&gotXML)
gotXML += "\n"
switch {
case err == sql.ErrNoRows:
die(t, "Expected 1 row; Found 0")
case err != nil:
die(t, "error: %v", err)
case wantXML != gotXML:
ioutil.WriteFile("want_xml.txt", []byte(wantXML), 0644)
ioutil.WriteFile("got_xml.txt", []byte(gotXML), 0644)
t.Error("wantXML doesn't match gotXML")
default:
info(t, "All OK")
}
}
func TestLob(t *testing.T) {
testCases := []struct {
qry string
val []string
got []byte
}{
{qry: `SELECT picture
FROM emp_photo
WHERE empno = ? AND photo_format = ?`, val: []string{"000140", "bitmap"}},
{qry: `SELECT resume
FROM emp_resume
WHERE empno = ? AND resume_format = ?`, val: []string{"000140", "ascii"}},
}
db, err := newTestDB()
if err != nil {
t.Fatal(err)
}
defer db.close()
for i, tc := range testCases {
t.Run(fmt.Sprintf("Testcase %d", i), func(t *testing.T) {
err := db.QueryRow(tc.qry, tc.val[0], tc.val[1]).Scan(&tc.got)
switch {
case err == sql.ErrNoRows:
t.Log("No match for query: ", tc.qry)
case err != nil:
t.Error(err)
default:
t.Logf("Got a LOB value of %d bytes!", len(tc.got))
}
})
}
}
func TestRowsColumnTypes(t *testing.T) {
testCases := []struct {
qry string
colTypes []string
colNullables []bool
colIsVarLengths []bool
colScales []int64
}{
{qry: `SELECT current timestamp, current date, current time, ' A ', 100, 1.101, cast(NULL as INT), cast(NULL as DECFLOAT)
FROM sysibm.sysdummy1`,
colTypes: []string{"TIMESTAMP", "DATE", "TIME", "VARCHAR", "INTEGER", "DECIMAL", "INTEGER", "DECFLOAT"},
colNullables: []bool{false, false, false, false, false, false, true, true},
colIsVarLengths: []bool{false, false, false, true, false, false, false, false},
colScales: []int64{6, 0, 0, 0, 0, 3, 0, 0},
},
}
db, err := newTestDB()
if err != nil {
t.Fatal(err)
}
defer db.close()
for i, tc := range testCases {
t.Run(fmt.Sprintf("Testcase %d", i), func(t *testing.T) {
rows, err := db.QueryContext(context.Background(), tc.qry)
if err != nil {
t.Fatalf("Query: %v", err)
}
ct, err := rows.ColumnTypes()
if err != nil {
t.Fatalf("ColumnTypes: %v", err)
}
for i := range ct {
colType := ct[i].DatabaseTypeName()
if colType != tc.colTypes[i] {
t.Error("Expected ColType: ", tc.colTypes[i], ", Got ColType: ", colType)
}
nullable, _ := ct[i].Nullable()
if nullable != tc.colNullables[i] {
t.Error("Expected Col Nullability: ", tc.colNullables[i], ", Got Col Nullability: ", nullable)
}
length, isVarLength := ct[i].Length()
if isVarLength != tc.colIsVarLengths[i] {
t.Error("For column type ", colType, " Expected variable length to be: ", tc.colIsVarLengths[i], ", Got variable length to be: ", isVarLength)
}
precision, scale, _ := ct[i].DecimalSize()
t.Log("Type: ", ct[i].DatabaseTypeName(), ", length(precision): ", length, "(", precision, "), scale: ", scale)
if scale != tc.colScales[i] {
t.Error("Expected Col Scale: ", tc.colScales[i], ", Got Col Scale: ", scale)
}
}
})
}
}
func TestQueryTimeout(t *testing.T) {
var rc int
db, err := newTestDB()
if err != nil {
t.Fatal(err)
}
defer db.close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// The test works if a separate connecton puts a exclusive lock on a table.
// For example: db2 +c "LOCK TABLE asif.ACT IN EXCLUSIVE MODE"
// Then count the number of rows.
// err = db.QueryRowContext(ctx, "select count(*) from asif.ACT").Scan(&rc)
// The test doesn't work with SLEEP C UDF.
// With the C udf SLEEP function DB2 CLI driver doesn't respond to SQLCancel.
// err = db.QueryRowContext(ctx, "VALUES(SLEEP(60))").Scan(&rc)
// Use a CPU intensive, naive SQL based sleep function instead.
err = db.QueryRowContext(ctx, "CALL SLEEP_PROC(60)").Scan(&rc)
switch {
case err != nil:
if sqlcode, sqlstate, ok := getDB2Error(err); ok {
switch {
case sqlstate == "42884" || sqlcode == -1646:
t.Skip("SLEEP function is missing. Skip the test.")
case sqlstate == "HY008":
t.Log("All Ok!")
default:
t.Errorf("Unexpected CLI error: %s\n", err)
}
} else {
t.Errorf("Expected CLI error with SQLCode and SqlState; instead got this error: %s\n", err)
}
default:
t.Log("Expected the query to fail, but it didn't.")
}
}
func TestQueryCancel(t *testing.T) {
var rc int
db, err := newTestDB()
if err != nil {
t.Fatal(err)
}
defer db.close()
ctx, cancel := context.WithCancel(context.Background())
// use a goroutine to cancel the query in 5 seconds
go func(cancel context.CancelFunc) {
time.Sleep(5 * time.Second)
cancel()
}(cancel)
err = db.QueryRowContext(ctx, "CALL SLEEP_PROC(60)").Scan(&rc)
switch {
case err != nil:
if sqlcode, sqlstate, ok := getDB2Error(err); ok {
switch {
case sqlstate == "42884" || sqlcode == -1646:
t.Skip("SLEEP function is missing. Skip the test.")
case sqlstate == "HY008":
t.Log("Query was cancelled as expected.")
default:
t.Errorf("Unexpected CLI error: %s\n", err)
}
} else if err == context.Canceled {
// The goroutine may have cancelled the context before the query even started.
t.Log("Context was cancelled before the query even started. That's expected also.")
} else {
t.Errorf("Expected CLI error with SQLCode and SqlState; instead got this error: %s\n", err)
}
default:
t.Log("Expected the query to fail, but it didn't.")
}
}
func TestTxPrepare(t *testing.T) {
db, err := newTestDB()
if err != nil {
t.Fatal(err)
}
defer db.close()
tx, err := db.BeginTx(context.Background(), nil)
if err != nil {
die(t, "%s", err)
}
stmt, err := tx.PrepareContext(context.Background(), "select 11 from abcd")
if err == nil {
stmt.Close()
die(t, "Expected PrepareContext to fail with SQL0204N and SQLSTATE=42704")
}
info(t, "%s", err)
tx.Commit()
}
func TestTxContext(t *testing.T) {
db, err := newTestDB()
if err != nil {
t.Fatal(err)
}
defer db.close()
opts := sql.TxOptions{
Isolation: sql.LevelDefault,
ReadOnly: true,
}
tx, err := db.BeginTx(context.Background(), &opts)
if err != nil {
t.Fatal(err)
}
stmt, err := tx.PrepareContext(context.Background(), "select count(*) from syscat.tables")
if err != nil {
t.Fatal(err)
}
rows, err := stmt.Query()
if err != nil {
t.Fatal(err)
}
rows.Close()
stmt.Close()
tx.Commit()
}
func TestDouble(t *testing.T) {
db, err := newTestDB()
if err != nil {
t.Fatal(err)
}
defer db.close()
tests := []struct {
name string
val sql.NullString // need to use string to pass smallest/larget double
want sql.NullFloat64
}{
{
name: "null value",
val: sql.NullString{String: "", Valid: false},
want: sql.NullFloat64{Float64: 0, Valid: false},
},
{
name: "zero value",
val: sql.NullString{String: "0.0", Valid: true},
want: sql.NullFloat64{Float64: 0.0, Valid: true},
},
{
name: "negative zero value",
val: sql.NullString{String: "-0.0", Valid: true},
want: sql.NullFloat64{Float64: -0.0, Valid: true},
},
{
name: "smallest positive",
val: sql.NullString{String: "+2.225E-307", Valid: true},
want: sql.NullFloat64{Float64: +2.225E-307, Valid: true},
},
{
name: "largest positive",
val: sql.NullString{String: "+1.79769E+308", Valid: true},
want: sql.NullFloat64{Float64: +1.79769E+308, Valid: true},
},
{
name: "smallest negative",
val: sql.NullString{String: "-1.79769E+308", Valid: true},
want: sql.NullFloat64{Float64: -1.79769E+308, Valid: true},
},
{
name: "largest negative",
val: sql.NullString{String: "-2.225E-307", Valid: true},
want: sql.NullFloat64{Float64: -2.225E-307, Valid: true},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var got sql.NullFloat64
err := db.QueryRow("VALUES (CAST (? AS DOUBLE))", tt.val).Scan(&got)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(tt.want, got) {
t.Errorf("want %f, got %f", tt.want.Float64, got.Float64)
}
})
}
}
func TestDecFloat(t *testing.T) {
db, err := newTestDB()
if err != nil {
t.Fatal(err)
}
defer db.close()
tests := []struct {
name string
val sql.NullString // need to use string to pass smallest/larget decfloat
want sql.NullFloat64
}{
{
name: "null value",
val: sql.NullString{String: "", Valid: false},
want: sql.NullFloat64{Float64: 0, Valid: false},
},
{
name: "zero value",
val: sql.NullString{String: "0.0", Valid: true},
want: sql.NullFloat64{Float64: 0.0, Valid: true},
},
{
name: "negative zero value",
val: sql.NullString{String: "-0.0", Valid: true},
want: sql.NullFloat64{Float64: -0.0, Valid: true},
},
{
name: "smallest positive",
val: sql.NullString{String: "5e-324", Valid: true},
want: sql.NullFloat64{Float64: math.SmallestNonzeroFloat64, Valid: true},
},
{
name: "largest positive",
val: sql.NullString{String: "1.7976931348623157e+308", Valid: true},
want: sql.NullFloat64{Float64: math.MaxFloat64, Valid: true},
},
{
name: "smallest negative",
val: sql.NullString{String: "-5e-324", Valid: true},
want: sql.NullFloat64{Float64: -math.SmallestNonzeroFloat64, Valid: true},
},
{
name: "largest negative",
val: sql.NullString{String: "-1.7976931348623157e+308", Valid: true},
want: sql.NullFloat64{Float64: -math.MaxFloat64, Valid: true},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var got sql.NullFloat64
err := db.QueryRow("VALUES (CAST (? AS DECFLOAT))", tt.val).Scan(&got)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(tt.want, got) {
t.Errorf("want %f, got %f", tt.want.Float64, got.Float64)
}
})
}
}
func TestInt(t *testing.T) {
db, err := newTestDB()
if err != nil {
t.Fatal(err)
}
defer db.close()
tests := []struct {
name string
want sql.NullInt64
}{
{
name: "null value",
want: sql.NullInt64{Int64: 0, Valid: false},
},
{
name: "zero value",
want: sql.NullInt64{Int64: 0, Valid: true},
},
{
name: "negative zero value",
want: sql.NullInt64{Int64: -0, Valid: true},
},
{
name: "smallest",
want: sql.NullInt64{Int64: -2147483648, Valid: true},
},
{
name: "largest",
want: sql.NullInt64{Int64: 2147483647, Valid: true},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var got sql.NullInt64
err := db.QueryRow("VALUES (CAST (? AS INT))", tt.want).Scan(&got)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(tt.want, got) {
t.Errorf("wanted %v, got %v", tt.want, got)
}
})
}
}
func TestBigInt(t *testing.T) {
db, err := newTestDB()
if err != nil {
t.Fatal(err)
}
defer db.close()
tests := []struct {
name string
want sql.NullInt64
}{
{
name: "null value",
want: sql.NullInt64{Int64: 0, Valid: false},
},
{
name: "zero value",
want: sql.NullInt64{Int64: 0, Valid: true},
},
{
name: "negative zero value",
want: sql.NullInt64{Int64: -0, Valid: true},
},
{
name: "smallest",
want: sql.NullInt64{Int64: -9223372036854775808, Valid: true},
},
{
name: "largest",
want: sql.NullInt64{Int64: 9223372036854775807, Valid: true},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var got sql.NullInt64
err := db.QueryRow("VALUES (CAST (? AS BIGINT))", tt.want).Scan(&got)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(tt.want, got) {
t.Errorf("wanted %v, got %v", tt.want, got)
}
})
}
}
func TestString(t *testing.T) {
password := "Pac1f1c"
db, err := newTestDB()
if err != nil {
t.Fatal(err)
}
defer db.close()
_, err = db.Exec("CREATE TABLE STRINGS(COL1 VARCHAR(50) FOR BIT DATA)")
if err != nil {
t.Fatal(err)
}
defer func() {
db.Exec("DROP TABLE STRINGS")
}()
tests := []struct {
name string
want sql.NullString
}{
{
name: "null value",
want: sql.NullString{String: "", Valid: false},
},
{
name: "empty value",
want: sql.NullString{String: "", Valid: true},
},
{
name: "unicode value",
want: sql.NullString{String: "Hello, 世界", Valid: true},
},
{
name: "alphanumeric value",
want: sql.NullString{String: " 289-46-8832 AB ", Valid: true},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var got sql.NullString
err := db.QueryRow(`SELECT DECRYPT_CHAR(COL1, ?) FROM FINAL TABLE (
INSERT INTO STRINGS VALUES ENCRYPT(?, ?)
)`, password, tt.want, password).Scan(&got)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(tt.want, got) {
t.Errorf("wanted %q, got %q\n", tt.want.String, got.String)
}
})
}
}
// for issue #2
// Empty character strings from the db get represented as a byte-slice with all 0s.
func TestEmptyString(t *testing.T) {
db, err := newTestDB()
if err != nil {
t.Fatal(err)
}
defer db.close()
var emptyString string
err = db.QueryRow("SELECT '' FROM sysibm.sysdummy1").Scan(&emptyString)
if err != nil {
t.Fatal(err)
}
if emptyString != "" {
t.Fatalf("Expected '' got %v\n", emptyString)
}
if len([]byte(emptyString)) > 0 {
t.Fatalf("Expected empty byte slice but got %v\n", []byte(emptyString))
}
}
type NullByte struct {
Byte []byte
Valid bool
}
func (nb *NullByte) Scan(value interface{}) error {
if value == nil {
nb.Byte, nb.Valid = nil, false
return nil
}
if _, ok := value.([]byte); !ok {
return fmt.Errorf("Unsupported value type %T in NullByte.Scan", value)
}
nb.Valid = true
bv := value.([]byte)
if nb.Byte == nil {
nb.Byte = make([]byte, len(bv))
}
copy(nb.Byte, bv)
return nil
}
func (nb NullByte) Value() (driver.Value, error) {
if !nb.Valid {
return nil, nil
}
return nb.Byte, nil
}
func (nb NullByte) String() string {
if !nb.Valid {
return "-"
}
return string(nb.Byte)
}
// for issue #2
// Empty VarBinary causes panic.
func TestVarBinary(t *testing.T) {
db, err := newTestDB()
if err != nil {
t.Fatal(err)
}
defer db.close()
_, err = db.Exec(`CREATE TABLE binaries
( NAME varchar(64)
, PASSWORDHASH varbinary(255))`)
if err != nil {
t.Fatal(err)
}
defer func() {
db.Exec("DROP TABLE binaries")
}()
tests := []struct {
name string
want NullByte
}{
{
name: "null varbinary",
want: NullByte{Byte: nil, Valid: false},
},
{
name: "empty varbinary",
want: NullByte{Byte: []byte(""), Valid: true},
},
{
name: "regular varbinary",
want: NullByte{Byte: []byte("myhint\t"), Valid: true},
},
{
name: "unicode varbinary",
want: NullByte{Byte: []byte("Hello, 世界 \n"), Valid: true},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var got sql.NullString
err := db.QueryRow(`SELECT HEX(PASSWORDHASH) FROM FINAL TABLE
(INSERT INTO binaries (NAME, PASSWORDHASH) VALUES (?, ?))`, "ABCD", tt.want).Scan(&got)
if err != nil {
t.Error(err)
}
decoded, err := hex.DecodeString(got.String)
if err != nil {
t.Fatal(err)
}
if string(tt.want.Byte) != string(decoded) {
t.Errorf("want %q, got %q\n", tt.want.Byte, decoded)
} else {
t.Logf("want %q, got %q\n", tt.want.Byte, decoded)
}
})
}
}
// Tests that INOUT option works with DB2 Stored Procedure.
func TestSPInOut(t *testing.T) {
db, err := newTestDB()
if err != nil {
t.Fatal(err)
}
defer db.close()
// for real data type test use float32 instead of float64
var f32 float32 = 1.99999
ts := time.Date(2009, time.November, 10, 23, 6, 29, 10011001000, time.UTC)
createSp := `CREATE OR REPLACE PROCEDURE test_inout(
INOUT p_a %s)
LANGUAGE SQL
SPECIFIC test_inout
BEGIN
SET p_a = p_a ;
END
`
callSp := "call test_inout(?)"
dropSp := "drop procedure test_inout"
tests := []struct {
paramType string
want sql.Out
got sql.Out
}{
{
paramType: "int",
want: sql.Out{Dest: &sql.NullInt64{Valid: false}, In: true},
got: sql.Out{Dest: &sql.NullInt64{Valid: false}, In: true},
},
{
paramType: "int",
want: sql.Out{Dest: &sql.NullInt64{Int64: -2147483648, Valid: true}, In: true},
got: sql.Out{Dest: &sql.NullInt64{Int64: -2147483648, Valid: true}, In: true},
},
{
paramType: "int",
want: sql.Out{Dest: &sql.NullInt64{Int64: 2147483647, Valid: true}, In: true},
got: sql.Out{Dest: &sql.NullInt64{Int64: 2147483647, Valid: true}, In: true},
},
{
paramType: "bigint",
want: sql.Out{Dest: &sql.NullInt64{Int64: -9223372036854775808, Valid: true}, In: true},
got: sql.Out{Dest: &sql.NullInt64{Int64: -9223372036854775808, Valid: true}, In: true},
},
{
paramType: "bigint",
want: sql.Out{Dest: &sql.NullInt64{Int64: 9223372036854775807, Valid: true}, In: true},
got: sql.Out{Dest: &sql.NullInt64{Int64: 9223372036854775807, Valid: true}, In: true},
},
{
paramType: "varchar(1000)",
want: sql.Out{Dest: &sql.NullString{Valid: false}, In: true},
got: sql.Out{Dest: &sql.NullString{Valid: false}, In: true},
},
{
paramType: "varchar(1000)",
want: sql.Out{Dest: &sql.NullString{String: "", Valid: true}, In: true},
got: sql.Out{Dest: &sql.NullString{String: "", Valid: true}, In: true},
},
{
paramType: "varchar(1000)",
want: sql.Out{Dest: &sql.NullString{String: "Hello World", Valid: true}, In: true},
got: sql.Out{Dest: &sql.NullString{String: "Hello World", Valid: true}, In: true},
},
{
paramType: "double",
want: sql.Out{Dest: &sql.NullFloat64{Valid: false}, In: true},
got: sql.Out{Dest: &sql.NullFloat64{Valid: false}, In: true},
},
{
paramType: "double",
want: sql.Out{Dest: &sql.NullFloat64{Float64: 1.999999, Valid: true}, In: true},
got: sql.Out{Dest: &sql.NullFloat64{Float64: 1.999999, Valid: true}, In: true},
},
{
paramType: "double",
want: sql.Out{Dest: &sql.NullFloat64{Float64: -1.999999, Valid: true}, In: true},
got: sql.Out{Dest: &sql.NullFloat64{Float64: -1.999999, Valid: true}, In: true},
},
{
paramType: "float",
want: sql.Out{Dest: &sql.NullFloat64{Float64: 1.999999, Valid: true}, In: true},
got: sql.Out{Dest: &sql.NullFloat64{Float64: 1.999999, Valid: true}, In: true},
},
{
paramType: "float",
want: sql.Out{Dest: &sql.NullFloat64{Float64: -1.999999, Valid: true}, In: true},
got: sql.Out{Dest: &sql.NullFloat64{Float64: -1.999999, Valid: true}, In: true},
},
{
paramType: "real",
want: sql.Out{Dest: &f32, In: true},
got: sql.Out{Dest: &f32, In: true},
},
{
paramType: "decfloat",
want: sql.Out{Dest: &sql.NullFloat64{Valid: false}, In: true},
got: sql.Out{Dest: &sql.NullFloat64{Valid: false}, In: true},
},
{
paramType: "decfloat",
want: sql.Out{Dest: &sql.NullFloat64{Float64: 1.999999, Valid: true}, In: true},
got: sql.Out{Dest: &sql.NullFloat64{Float64: 1.999999, Valid: true}, In: true},