-
Notifications
You must be signed in to change notification settings - Fork 102
/
z_test.go
5224 lines (4844 loc) · 137 KB
/
z_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
// Copyright 2020 Tamás Gulácsi
//
//
// SPDX-License-Identifier: UPL-1.0 OR Apache-2.0
package godror_test
import (
"bytes"
"context"
"crypto/sha256"
"database/sql"
"database/sql/driver"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"math/rand"
"os"
"os/user"
"path/filepath"
"reflect"
"runtime"
"runtime/debug"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/go-logfmt/logfmt"
"github.com/godror/godror/slog"
"github.com/google/go-cmp/cmp"
"golang.org/x/sync/errgroup"
godror "github.com/godror/godror"
"github.com/godror/godror/dsn"
)
var (
testDb *sql.DB
testSystemDb *sql.DB
tl = &testLogger{}
logger *slog.Logger
clientVersion, serverVersion godror.VersionInfo
testConStr string
testSystemConStr string
)
var tblSuffix string
var Verbose bool
const maxSessions = 16
const useDefaultFetchValue = -99
// TestMain is called instead of the separate Test functions,
// to allow setup and teardown.
func TestMain(m *testing.M) {
tearDown := setUp()
rc := m.Run()
tearDown()
os.Exit(rc)
}
func setUp() func() {
Verbose, _ = strconv.ParseBool(os.Getenv("VERBOSE"))
hsh := sha256.New()
bi, ok := debug.ReadBuildInfo()
if ok && bi != nil {
ok = json.NewEncoder(hsh).Encode(*bi) == nil
}
if !ok {
hsh.Write([]byte(runtime.Version()))
}
tblSuffix = fmt.Sprintf("_%x", hsh.Sum(nil)[:4])
if Verbose {
tl.enc = logfmt.NewEncoder(os.Stderr)
logger = slog.New(slog.NewTextHandler(tl, &slog.HandlerOptions{Level: slog.LevelDebug}))
} else {
logger = slog.New(slog.NewTextHandler(tl, nil))
}
slog.SetDefault(logger)
if tzName := os.Getenv("GODROR_TIMEZONE"); tzName != "" {
var err error
if time.Local, err = time.LoadLocation(tzName); err != nil {
panic(fmt.Errorf("unknown GODROR_TIMEZONE=%q: %w", tzName, err))
}
}
var tearDown []func()
eDSN := os.Getenv("GODROR_TEST_DSN")
{
uid, _ := user.Current()
fmt.Printf("eDSN=%s\nOSuser=%v\n", eDSN, uid)
}
var configDir string
if eDSN == "" {
wd, err := os.Getwd()
if err != nil {
panic(err)
}
wd = filepath.Join(wd, "contrib", "free.db")
tempDir, err := os.MkdirTemp("", "godror_drv_test-")
if err != nil {
panic(err)
}
tearDown = append(tearDown, func() { os.RemoveAll(tempDir) })
for _, nm := range []string{"tnsnames.ora", "cwallet.sso", "ewallet.p12"} {
var sfh *os.File
if sfh, err = os.Open(filepath.Join(wd, nm)); err != nil {
panic(err)
}
dfh, err := os.Create(filepath.Join(tempDir, nm))
if err != nil {
sfh.Close()
panic(err)
}
_, err = io.Copy(dfh, sfh)
sfh.Close()
dfh.Close()
if err != nil {
panic(err)
}
}
b, err := os.ReadFile(filepath.Join(wd, "sqlnet.ora"))
if err != nil {
panic(err)
}
if err = os.WriteFile(
filepath.Join(tempDir, "sqlnet.ora"),
bytes.Replace(b,
[]byte(`DIRECTORY="?/network/admin"`),
[]byte(`DIRECTORY="`+wd+`"`), 1),
0644,
); err != nil {
panic(err)
}
fn := filepath.Join(wd, "env.sh")
fmt.Println("Using default database for tests: ", fn)
fmt.Printf("export TNS_ADMIN=%q\n", wd)
os.Setenv("TNS_ADMIN", tempDir)
configDir = tempDir
if b, err = os.ReadFile(fn); err != nil {
fmt.Println(err)
} else {
const prefix = "export GODROR_TEST_"
for _, line := range bytes.Split(b, []byte{'\n'}) {
if !bytes.HasPrefix(line, []byte(prefix)) {
continue
}
line = line[len(prefix):]
i := bytes.IndexByte(line, '=')
if i < 0 {
continue
}
k, v := string(line[:i]), string(line[i+1:])
os.Setenv("GODROR_TEST_"+k, v)
switch k {
case "DSN":
eDSN = v
}
}
}
}
P, err := dsn.Parse(eDSN)
if err != nil {
panic(fmt.Errorf("parse %q: %w", eDSN, err))
}
// fmt.Println("parsed:", P)
P.CommonParams.Logger = logger
P.CommonParams.EnableEvents = true
P.CommonParams.ConfigDir = configDir
if P.ConnParams.ConnClass == "" {
P.ConnParams.ConnClass = "TestClassName"
}
P.ConnParams.ShardingKey = []interface{}{"gold", []byte("silver"), int(42)}
P.PoolParams.MinSessions = 2
if P.PoolParams.MaxSessions <= 1 || P.PoolParams.MaxSessions > maxSessions {
P.PoolParams.MaxSessions = maxSessions
}
P.PoolParams.SessionIncrement = 1
P.PoolParams.WaitTimeout = 5 * time.Second
P.PoolParams.MaxLifeTime = 5 * time.Minute
P.PoolParams.SessionTimeout = 1 * time.Minute
fmt.Printf("export GODROR_TEST_DSN=%q\n", P.StringWithPassword())
if strings.HasSuffix(strings.ToUpper(P.Username), " AS SYSDBA") {
P.IsSysDBA, P.Username = true, P.Username[:len(P.Username)-10]
}
testConStr = P.StringWithPassword()
if testDb = sql.OpenDB(godror.NewConnector(P)); err != nil {
panic(fmt.Errorf("connect to %s: %w", testConStr, err))
}
tearDown = append(tearDown, func() { testDb.Close() })
ctx, cancel := context.WithTimeout(testContext("init"), 30*time.Second)
defer cancel()
if eSysDSN := os.Getenv("GODROR_TEST_SYSTEM_DSN"); eSysDSN != "" {
PSystem := P
if ps, err := dsn.Parse(eSysDSN); err != nil {
panic(fmt.Errorf("sysdsn: %q: %w", eSysDSN, err))
} else {
PSystem = ps
PSystem.CommonParams.EnableEvents = true
PSystem.CommonParams.ConfigDir = configDir
PSystem.ConnParams.ConnClass = P.ConnParams.ConnClass
PSystem.ConnParams.ShardingKey = P.ConnParams.ShardingKey
PSystem.PoolParams = P.PoolParams
}
testSystemConStr = PSystem.StringWithPassword()
}
if b, err := strconv.ParseBool(os.Getenv("DO_NOT_CONNECT")); b && err == nil {
return func() {}
}
fmt.Println("#", P.String())
fmt.Println("Version:", godror.Version)
if err = godror.Raw(ctx, testDb, func(cx godror.Conn) error {
if clientVersion, err = cx.ClientVersion(); err != nil {
return err
}
fmt.Println("Client:", clientVersion.String(), "Timezone:", time.Local.String())
if serverVersion, err = cx.ServerVersion(); err != nil {
return err
}
dbTZ := cx.Timezone()
fmt.Println("Server:", serverVersion.String(), "Timezone:", dbTZ.String())
return nil
}); err != nil {
panic(err)
}
go func() {
for range time.NewTicker(time.Second).C {
runtime.GC()
}
}()
statTicks = make(chan time.Time)
statTicker = time.NewTicker(60 * time.Second)
go func() {
for t := range statTicker.C {
statTicks <- t
}
}()
testDb.SetMaxOpenConns(maxSessions)
if P.StandaloneConnection {
testDb.SetMaxIdleConns(maxSessions / 2)
testDb.SetConnMaxLifetime(10 * time.Minute)
go func() {
for range statTicks {
fmt.Fprintf(os.Stderr, "testDb: %+v\n", testDb.Stats())
}
}()
} else {
// Disable Go db connection pooling
testDb.SetMaxIdleConns(0)
testDb.SetConnMaxLifetime(0)
go func() {
for range statTicks {
ctx, cancel := context.WithTimeout(testContext("poolStats"), time.Second)
godror.Raw(ctx, testDb, func(c godror.Conn) error {
poolStats, err := c.GetPoolStats()
fmt.Fprintf(os.Stderr, "testDb: %+v: %s %v\n", testDb.Stats(), poolStats, err)
return err
})
cancel()
}
}()
}
return func() {
for i := len(tearDown) - 1; i >= 0; i-- {
tearDown[i]()
}
}
}
var statTicker *time.Ticker
var statTicks chan time.Time
func PrintConnStats() {
if statTicks != nil {
select {
case statTicks <- time.Now():
default:
}
}
}
func StopConnStats() {
if statTicker != nil {
statTicker.Stop()
}
}
func testContext(name string) context.Context {
ctx := godror.ContextWithTraceTag(context.Background(), godror.TraceTag{Module: "Test" + name})
if Verbose {
logger.Info("testContext", "name", name)
ctx = godror.ContextWithLogger(ctx, logger)
}
return ctx
}
var bufPool = sync.Pool{New: func() interface{} { return bytes.NewBuffer(make([]byte, 0, 1024)) }}
type testLogger struct {
enc *logfmt.Encoder
Ts []*testing.T
beHelped []*testing.T
mu sync.RWMutex
}
func (tl *testLogger) Write(p []byte) (int, error) {
s := string(p)
for _, t := range tl.Ts {
t.Helper()
t.Log(s)
}
return len(p), nil
}
func (tl *testLogger) Enabled(context.Context, slog.Level) bool { return true }
func (tl *testLogger) Handle(ctx context.Context, r slog.Record) error {
for _, t := range tl.Ts {
t.Helper()
t.Log(r.Message)
}
return nil
}
func (tl *testLogger) WithAttrs(attrs []slog.Attr) slog.Handler { return tl }
func (tl *testLogger) WithGroup(name string) slog.Handler { return tl }
func (tl *testLogger) Log(args ...interface{}) error {
if tl.enc != nil {
for i := 1; i < len(args); i += 2 {
switch args[i].(type) {
case string, fmt.Stringer:
default:
args[i] = fmt.Sprintf("%+v", args[i])
}
}
tl.mu.Lock()
tl.enc.Reset()
tl.enc.EncodeKeyvals(args...)
tl.enc.EndRecord()
tl.mu.Unlock()
}
return tl.GetLog()(args)
}
func (tl *testLogger) GetLog() func(keyvals ...interface{}) error {
return func(keyvals ...interface{}) error {
buf := bufPool.Get().(*bytes.Buffer)
defer bufPool.Put(buf)
buf.Reset()
if len(keyvals)%2 != 0 {
keyvals = append(append(make([]interface{}, 0, len(keyvals)+1), "msg"), keyvals...)
}
for i := 0; i < len(keyvals); i += 2 {
fmt.Fprintf(buf, "%s=%#v ", keyvals[i], keyvals[i+1])
}
tl.mu.Lock()
for _, t := range tl.beHelped {
t.Helper()
}
tl.beHelped = tl.beHelped[:0]
tl.mu.Unlock()
tl.mu.RLock()
defer tl.mu.RUnlock()
for _, t := range tl.Ts {
t.Helper()
t.Log(buf.String())
}
return nil
}
}
func (tl *testLogger) enableLogging(t *testing.T) func() {
tl.mu.Lock()
tl.Ts = append(tl.Ts, t)
tl.beHelped = append(tl.beHelped, t)
tl.mu.Unlock()
return func() {
tl.mu.Lock()
defer tl.mu.Unlock()
for i, f := range tl.Ts {
if f == t {
tl.Ts[i] = tl.Ts[0]
tl.Ts = tl.Ts[1:]
break
}
}
for i, f := range tl.beHelped {
if f == t {
tl.beHelped[i] = tl.beHelped[0]
tl.beHelped = tl.beHelped[1:]
break
}
}
}
}
func TestDescribeQuery(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(testContext("DescribeQuery"), 10*time.Second)
defer cancel()
const qry = "SELECT * FROM user_tab_cols"
cols, err := godror.DescribeQuery(ctx, testDb, qry)
if err != nil {
t.Fatal(fmt.Errorf("%s: %w", qry, err))
}
t.Log(cols)
}
func TestParseOnly(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(testContext("ParseOnly"), 10*time.Second)
defer cancel()
tbl := "test_not_exist" + tblSuffix
cnt := func() int {
var cnt int64
if err := testDb.QueryRowContext(ctx,
"SELECT COUNT(0) FROM user_tables WHERE table_name = UPPER('"+tbl+"')").Scan(&cnt); //nolint:gas
err != nil {
t.Fatal(err)
}
return int(cnt)
}
if cnt() != 0 {
if _, err := testDb.ExecContext(ctx, "DROP TABLE "+tbl); err != nil {
t.Error(err)
}
}
if _, err := testDb.ExecContext(ctx, "CREATE TABLE "+tbl+"(t VARCHAR2(1))", godror.ParseOnly()); err != nil {
t.Fatal(err)
}
if got := cnt(); got != 1 {
t.Errorf("got %d, wanted 0", got)
}
}
func TestInputArray(t *testing.T) {
t.Parallel()
defer tl.enableLogging(t)()
ctx, cancel := context.WithTimeout(testContext("InputArray"), 10*time.Second)
defer cancel()
pkg := strings.ToUpper("test_in_pkg" + tblSuffix)
qry := `CREATE OR REPLACE PACKAGE ` + pkg + ` AS
TYPE int_tab_typ IS TABLE OF BINARY_INTEGER INDEX BY PLS_INTEGER;
TYPE num_tab_typ IS TABLE OF NUMBER INDEX BY PLS_INTEGER;
TYPE vc_tab_typ IS TABLE OF VARCHAR2(100) INDEX BY PLS_INTEGER;
TYPE dt_tab_typ IS TABLE OF DATE INDEX BY PLS_INTEGER;
TYPE ids_tab_typ IS TABLE OF INTERVAL DAY TO SECOND INDEX BY PLS_INTEGER;
--TYPE lob_tab_typ IS TABLE OF CLOB INDEX BY PLS_INTEGER;
FUNCTION in_int(p_int IN int_tab_typ) RETURN VARCHAR2;
FUNCTION in_num(p_num IN num_tab_typ) RETURN VARCHAR2;
FUNCTION in_vc(p_vc IN vc_tab_typ) RETURN VARCHAR2;
FUNCTION in_dt(p_dt IN dt_tab_typ) RETURN VARCHAR2;
FUNCTION in_ids(p_dur IN ids_tab_typ) RETURN VARCHAR2;
END;
`
testDb.Exec("DROP PACKAGE " + pkg)
t.Log("package", pkg)
if _, err := testDb.ExecContext(ctx, qry); err != nil {
t.Fatal(err, qry)
}
defer testDb.Exec("DROP PACKAGE " + pkg)
qry = `CREATE OR REPLACE PACKAGE BODY ` + pkg + ` AS
FUNCTION in_int(p_int IN int_tab_typ) RETURN VARCHAR2 IS
v_idx PLS_INTEGER;
v_res VARCHAR2(32767);
BEGIN
v_idx := p_int.FIRST;
WHILE v_idx IS NOT NULL LOOP
v_res := v_res||v_idx||':'||p_int(v_idx)||CHR(10);
v_idx := p_int.NEXT(v_idx);
END LOOP;
RETURN(v_res);
END;
FUNCTION in_num(p_num IN num_tab_typ) RETURN VARCHAR2 IS
v_idx PLS_INTEGER;
v_res VARCHAR2(32767);
BEGIN
v_idx := p_num.FIRST;
WHILE v_idx IS NOT NULL LOOP
v_res := v_res||v_idx||':'||p_num(v_idx)||CHR(10);
v_idx := p_num.NEXT(v_idx);
END LOOP;
RETURN(v_res);
END;
FUNCTION in_vc(p_vc IN vc_tab_typ) RETURN VARCHAR2 IS
v_idx PLS_INTEGER;
v_res VARCHAR2(32767);
BEGIN
v_idx := p_vc.FIRST;
WHILE v_idx IS NOT NULL LOOP
v_res := v_res||v_idx||':'||p_vc(v_idx)||CHR(10);
v_idx := p_vc.NEXT(v_idx);
END LOOP;
RETURN(v_res);
END;
FUNCTION in_dt(p_dt IN dt_tab_typ) RETURN VARCHAR2 IS
v_idx PLS_INTEGER;
v_res VARCHAR2(32767);
BEGIN
v_idx := p_dt.FIRST;
WHILE v_idx IS NOT NULL LOOP
v_res := v_res||v_idx||':'||TO_CHAR(p_dt(v_idx), 'YYYY-MM-DD"T"HH24:MI:SS')||CHR(10);
v_idx := p_dt.NEXT(v_idx);
END LOOP;
RETURN(v_res);
END;
FUNCTION in_ids(p_dur IN ids_tab_typ) RETURN VARCHAR2 IS
V_idx PLS_INTEGER;
v_res VARCHAR2(32767);
BEGIN
v_idx := p_dur.FIRST;
WHILE v_idx IS NOT NULL LOOP
v_res := v_res||v_idx||':'||TO_CHAR(p_dur(v_idx), 'YYYY-MM-DD"T"HH24:MI:SS')||CHR(10);
v_idx := p_dur.NEXT(v_idx);
END LOOP;
RETURN(v_res);
END;
END;
`
if _, err := testDb.ExecContext(ctx, qry); err != nil {
t.Fatal(err, qry)
}
compileErrors, err := godror.GetCompileErrors(ctx, testDb, false)
if err != nil {
t.Fatal(err)
}
if len(compileErrors) != 0 {
t.Logf("compile errors: %v", compileErrors)
for _, ce := range compileErrors {
if strings.Contains(ce.Error(), pkg) {
t.Fatal(ce)
}
}
}
serverTZ := time.Local
if err = godror.Raw(ctx, testDb, func(conn godror.Conn) error {
serverTZ = conn.Timezone()
return nil
}); err != nil {
t.Fatal(err)
}
tx, err := testDb.BeginTx(ctx, nil)
if err != nil {
t.Fatal(err)
}
defer tx.Rollback()
qry = "ALTER SESSION SET time_zone = 'UTC'"
if _, err = tx.ExecContext(ctx, qry); err != nil {
t.Fatal(fmt.Errorf("%s: %w", qry, err))
}
epoch := time.Date(2017, 11, 20, 12, 14, 21, 0, time.UTC)
epochPlus := epoch.AddDate(0, -6, 0)
const timeFmt = "2006-01-02T15:04:05"
_ = epoch
for name, tC := range map[string]struct {
In interface{}
Want string
}{
// "int_0":{In:[]int32{}, Want:""},
"num_0": {In: []godror.Number{}, Want: ""},
"vc_0": {In: []string{}, Want: ""},
"dt_0": {In: []time.Time{}, Want: ""},
"dt_00": {In: []godror.NullTime{}, Want: ""},
"num_3": {
In: []godror.Number{"1", "2.72", "-3.14"},
Want: "1:1\n2:2.72\n3:-3.14\n",
},
"vc_3": {
In: []string{"a", "", "cCc"},
Want: "1:a\n2:\n3:cCc\n",
},
"dt_2": {
In: []time.Time{epoch, epochPlus},
Want: ("1:" + epoch.In(serverTZ).Format(timeFmt) + "\n" +
"2:" + epochPlus.In(serverTZ).Format(timeFmt) + "\n"),
},
"dt_02": {
In: []godror.NullTime{{Valid: true, Time: epoch},
{Valid: true, Time: epochPlus}},
Want: ("1:" + epoch.In(serverTZ).Format(timeFmt) + "\n" +
"2:" + epochPlus.In(serverTZ).Format(timeFmt) + "\n"),
},
// "ids_1": { In: []time.Duration{32 * time.Second}, Want: "1:32s\n", },
} {
typ := strings.SplitN(name, "_", 2)[0]
qry := "BEGIN :1 := " + pkg + ".in_" + typ + "(:2); END;"
var res string
if _, err := tx.ExecContext(ctx, qry, godror.PlSQLArrays,
sql.Out{Dest: &res}, tC.In,
); err != nil {
t.Error(fmt.Errorf("%q. %s %+v: %w", name, qry, tC.In, err))
}
t.Logf("%q. %q", name, res)
if typ == "num" {
res = strings.Replace(res, ",", ".", -1)
}
if res != tC.Want {
t.Errorf("%q. got %q, wanted %q.", name, res, tC.Want)
}
}
}
func TestDbmsOutput(t *testing.T) {
defer tl.enableLogging(t)()
ctx, cancel := context.WithTimeout(testContext("DbmsOutput"), 10*time.Second)
defer cancel()
conn, err := testDb.Conn(ctx)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
if err := godror.EnableDbmsOutput(ctx, conn); err != nil {
t.Fatal(err)
}
txt := `árvíztűrő tükörfúrógép`
qry := "BEGIN DBMS_OUTPUT.PUT_LINE('" + txt + "'); END;"
if _, err := conn.ExecContext(ctx, qry); err != nil {
t.Fatal(err)
}
var buf bytes.Buffer
if err := godror.ReadDbmsOutput(ctx, &buf, conn); err != nil {
t.Error(err)
}
t.Log(buf.String())
if buf.String() != txt+"\n" {
t.Errorf("got\n%q, wanted\n%q", buf.String(), txt+"\n")
}
}
func TestInOutArray(t *testing.T) {
t.Parallel()
defer tl.enableLogging(t)()
ctx, cancel := context.WithTimeout(testContext("InOutArray"), 20*time.Second)
defer cancel()
pkg := strings.ToUpper("test_pkg" + tblSuffix)
qry := `CREATE OR REPLACE PACKAGE ` + pkg + ` AS
TYPE int_tab_typ IS TABLE OF BINARY_INTEGER INDEX BY PLS_INTEGER;
TYPE num_tab_typ IS TABLE OF NUMBER INDEX BY PLS_INTEGER;
TYPE vc_tab_typ IS TABLE OF VARCHAR2(100) INDEX BY PLS_INTEGER;
TYPE dt_tab_typ IS TABLE OF DATE INDEX BY PLS_INTEGER;
TYPE lob_tab_typ IS TABLE OF CLOB INDEX BY PLS_INTEGER;
PROCEDURE inout_int(p_int IN OUT int_tab_typ);
PROCEDURE inout_num(p_num IN OUT num_tab_typ);
PROCEDURE inout_vc(p_vc IN OUT vc_tab_typ);
PROCEDURE inout_dt(p_dt IN OUT dt_tab_typ);
PROCEDURE p2(
--p_int IN OUT int_tab_typ,
p_num IN OUT num_tab_typ, p_vc IN OUT vc_tab_typ, p_dt IN OUT dt_tab_typ);
END;
`
if _, err := testDb.ExecContext(ctx, qry); err != nil {
t.Fatal(err, qry)
}
defer testDb.Exec("DROP PACKAGE " + pkg)
qry = `CREATE OR REPLACE PACKAGE BODY ` + pkg + ` AS
PROCEDURE inout_int(p_int IN OUT int_tab_typ) IS
v_idx PLS_INTEGER;
BEGIN
DBMS_OUTPUT.PUT_LINE('p_int.COUNT='||p_int.COUNT||' FIRST='||p_int.FIRST||' LAST='||p_int.LAST);
v_idx := p_int.FIRST;
WHILE v_idx IS NOT NULL LOOP
p_int(v_idx) := NVL(p_int(v_idx) * 2, 1);
v_idx := p_int.NEXT(v_idx);
END LOOP;
p_int(NVL(p_int.LAST, 0)+1) := p_int.COUNT;
END;
PROCEDURE inout_num(p_num IN OUT num_tab_typ) IS
v_idx PLS_INTEGER;
BEGIN
DBMS_OUTPUT.PUT_LINE('p_num.COUNT='||p_num.COUNT||' FIRST='||p_num.FIRST||' LAST='||p_num.LAST);
v_idx := p_num.FIRST;
WHILE v_idx IS NOT NULL LOOP
p_num(v_idx) := NVL(p_num(v_idx) / 2, 0.5);
v_idx := p_num.NEXT(v_idx);
END LOOP;
p_num(NVL(p_num.LAST, 0)+1) := p_num.COUNT;
END;
PROCEDURE inout_vc(p_vc IN OUT vc_tab_typ) IS
v_idx PLS_INTEGER;
BEGIN
DBMS_OUTPUT.PUT_LINE('p_vc.COUNT='||p_vc.COUNT||' FIRST='||p_vc.FIRST||' LAST='||p_vc.LAST);
v_idx := p_vc.FIRST;
WHILE v_idx IS NOT NULL LOOP
p_vc(v_idx) := NVL(p_vc(v_idx) ||' +', '-');
v_idx := p_vc.NEXT(v_idx);
END LOOP;
p_vc(NVL(p_vc.LAST, 0)+1) := p_vc.COUNT;
END;
PROCEDURE inout_dt(p_dt IN OUT dt_tab_typ) IS
v_idx PLS_INTEGER;
BEGIN
DBMS_OUTPUT.PUT_LINE('p_dt.COUNT='||p_dt.COUNT||' FIRST='||p_dt.FIRST||' LAST='||p_dt.LAST);
v_idx := p_dt.FIRST;
WHILE v_idx IS NOT NULL LOOP
DBMS_OUTPUT.PUT_LINE(v_idx||'='||TO_CHAR(p_dt(v_idx), 'YYYY-MM-DD HH24:MI:SS'));
p_dt(v_idx) := NVL(p_dt(v_idx) + 1, TRUNC(SYSDATE)-v_idx);
v_idx := p_dt.NEXT(v_idx);
END LOOP;
p_dt(NVL(p_dt.LAST, 0)+1) := TRUNC(SYSDATE);
DBMS_OUTPUT.PUT_LINE('p_dt.COUNT='||p_dt.COUNT||' FIRST='||p_dt.FIRST||' LAST='||p_dt.LAST);
END;
PROCEDURE p2(
--p_int IN OUT int_tab_typ,
p_num IN OUT num_tab_typ,
p_vc IN OUT vc_tab_typ,
p_dt IN OUT dt_tab_typ
--, p_lob IN OUT lob_tab_typ
) IS
BEGIN
--inout_int(p_int);
inout_num(p_num);
inout_vc(p_vc);
inout_dt(p_dt);
--p_lob := NULL;
END p2;
END;
`
if _, err := testDb.ExecContext(ctx, qry); err != nil {
t.Fatal(err, qry)
}
compileErrors, err := godror.GetCompileErrors(ctx, testDb, false)
if err != nil {
t.Fatal(err)
}
if len(compileErrors) != 0 {
t.Logf("compile errors: %v", compileErrors)
for _, ce := range compileErrors {
if strings.Contains(ce.Error(), pkg) {
t.Fatal(ce)
}
}
}
intgr := []int32{3, 1, 4, 0, 0}[:3]
intgrWant := []int32{3 * 2, 1 * 2, 4 * 2, 3}
_ = intgrWant
num := []godror.Number{"3.14", "-2.48", ""}[:2]
numWant := []godror.Number{"1.57", "-1.24", "2"}
vc := []string{"string", "bring", ""}[:2]
vcWant := []string{"string +", "bring +", "2"}
var today time.Time
qry = "SELECT TRUNC(SYSDATE) FROM DUAL"
if testDb.QueryRowContext(ctx, qry).Scan(&today); err != nil {
t.Fatal(err)
}
dt := []time.Time{
time.Date(2017, 6, 18, 7, 5, 51, 0, time.Local),
{},
today.Add(-2 * 24 * time.Hour),
today,
}
dt[1] = dt[0].Add(24 * time.Hour)
dtWant := make([]time.Time, len(dt))
for i, d := range dt {
if i < len(dt)-1 {
// p_dt(v_idx) := NVL(p_dt(v_idx) + 1, TRUNC(SYSDATE)-v_idx);
dtWant[i] = d.AddDate(0, 0, 1)
} else {
// p_dt(NVL(p_dt.LAST, 0)+1) := TRUNC(SYSDATE);
dtWant[i] = d
}
}
dt = dt[:len(dt)-1]
conn, err := testDb.Conn(ctx)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
if _, err = conn.ExecContext(ctx, "ALTER SESSION SET time_zone = local"); err != nil {
t.Fatal(err)
}
godror.EnableDbmsOutput(ctx, conn)
opts := []cmp.Option{
cmp.Comparer(func(x, y time.Time) bool { return x.Equal(y) }),
}
for _, tC := range []struct {
In, Want interface{}
Name string
}{
{Name: "vc", In: vc, Want: vcWant},
{Name: "num", In: num, Want: numWant},
{Name: "dt", In: dt, Want: dtWant},
// {Name: "int", In: intgr, Want: intgrWant},
{Name: "vc-1", In: vc[:1], Want: []string{"string +", "1"}},
{Name: "vc-0", In: vc[:0], Want: []string{"0"}},
} {
tC := tC
t.Run("inout_"+tC.Name, func(t *testing.T) {
t.Logf("%s=%s", tC.Name, tC.In)
nm := strings.SplitN(tC.Name, "-", 2)[0]
qry = "BEGIN " + pkg + ".inout_" + nm + "(:1); END;"
dst := copySlice(tC.In)
if _, err := conn.ExecContext(ctx, qry,
godror.PlSQLArrays,
sql.Out{Dest: dst, In: true},
); err != nil {
t.Fatalf("%s\n%#v\n%+v", qry, dst, err)
}
got := reflect.ValueOf(dst).Elem().Interface()
if nm == "dt" {
t.Logf("\nin =%v\ngot=%v\nwt= %v", tC.In, got, tC.Want)
}
if cmp.Equal(got, tC.Want, opts...) {
return
}
t.Errorf("%s: %s", tC.Name, cmp.Diff(printSlice(tC.Want), printSlice(got)))
var buf bytes.Buffer
if err := godror.ReadDbmsOutput(ctx, &buf, conn); err != nil {
t.Error(err)
}
t.Log("OUTPUT:", buf.String())
})
}
// lob := []godror.Lob{godror.Lob{IsClob: true, Reader: strings.NewReader("abcdef")}}
t.Run("p2", func(t *testing.T) {
if _, err := conn.ExecContext(ctx,
"BEGIN "+pkg+".p2(:1, :2, :3); END;",
godror.PlSQLArrays,
// sql.Out{Dest: &intgr, In: true},
sql.Out{Dest: &num, In: true},
sql.Out{Dest: &vc, In: true},
sql.Out{Dest: &dt, In: true},
// sql.Out{Dest: &lob, In: true},
); err != nil {
t.Fatal(err)
}
t.Logf("int=%#v num=%#v vc=%#v dt=%#v", intgr, num, vc, dt)
// if d := cmp.Diff(intgr, intgrWant); d != "" {
// t.Errorf("int: %s", d)
// }
if d := cmp.Diff(num, numWant); d != "" {
t.Errorf("num: %s", d)
}
if d := cmp.Diff(vc, vcWant); d != "" {
t.Errorf("vc: %s", d)
}
if !cmp.Equal(dt, dtWant, opts...) {
if d := cmp.Diff(dt, dtWant); d != "" {
t.Errorf("dt: %s", d)
}
}
})
}
func TestOutParam(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(testContext("OutParam"), 10*time.Second)
defer cancel()
conn, err := testDb.Conn(ctx)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
if _, err = conn.ExecContext(ctx, "ALTER SESSION SET time_zone = local"); err != nil {
t.Fatal(err)
}
pkg := strings.ToUpper("test_p1" + tblSuffix)
qry := `CREATE OR REPLACE PROCEDURE
` + pkg + `(p_int IN OUT INTEGER, p_num IN OUT NUMBER, p_vc IN OUT VARCHAR2, p_dt IN OUT DATE, p_lob IN OUT CLOB)
IS
BEGIN
p_int := NVL(p_int * 2, 1);
p_num := NVL(p_num / 2, 0.5);
p_vc := NVL(p_vc ||' +', '-');
p_dt := NVL(p_dt + 1, SYSDATE);
p_lob := NULL;
END;`
if _, err = conn.ExecContext(ctx, qry); err != nil {
t.Fatal(err, qry)
}
defer testDb.Exec("DROP PROCEDURE " + pkg)
qry = "BEGIN " + pkg + "(:1, :2, :3, :4, :5); END;"
stmt, err := conn.PrepareContext(ctx, qry)
if err != nil {
t.Fatal(fmt.Errorf("%s: %w", qry, err))
}
defer stmt.Close()
var intgr int = 3
num := godror.Number("3.14")
var vc string = "string"
var dt time.Time = time.Date(2017, 6, 18, 7, 5, 51, 0, time.Local)
var lob godror.Lob = godror.Lob{IsClob: true, Reader: strings.NewReader("abcdef")}
if _, err := stmt.ExecContext(ctx,
sql.Out{Dest: &intgr, In: true},
sql.Out{Dest: &num, In: true},
sql.Out{Dest: &vc, In: true},
sql.Out{Dest: &dt, In: true},
sql.Out{Dest: &lob, In: true},
); err != nil {
t.Fatal(fmt.Errorf("%s: %w", qry, err))
}
t.Logf("int=%#v num=%#v vc=%#v dt=%#v", intgr, num, vc, dt)
if intgr != 6 {
t.Errorf("int: got %d, wanted %d", intgr, 6)
}
if num != "1.57" {
t.Errorf("num: got %q, wanted %q", num, "1.57")
}
if vc != "string +" {
t.Errorf("vc: got %q, wanted %q", vc, "string +")
}
}
func TestSelectRefCursor(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(testContext("SelectRefCursor"), 10*time.Second)
defer cancel()
rows, err := testDb.QueryContext(ctx, "SELECT CURSOR(SELECT object_name, object_type, object_id, created FROM all_objects WHERE ROWNUM <= 10) FROM DUAL")
if err != nil {
t.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var sub driver.Rows
if err := rows.Scan(&sub); err != nil {
sub.Close()
t.Fatal(err)
}
defer sub.Close()
t.Logf("%[1]T %[1]p", sub)
cols := sub.(driver.RowsColumnTypeScanType).Columns()
t.Log("Columns", cols)
dests := make([]driver.Value, len(cols))
for {
if err := sub.Next(dests); err != nil {
if err == io.EOF {
break
}
sub.Close()
t.Error(err)
break
}
// fmt.Println(dests)
t.Log(dests)
}
sub.Close()
}
// Test the Finalizers
runtime.GC()
}
func TestSelectRefCursorWrap(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(testContext("SelectRefCursorWrap"), 10*time.Second)
defer cancel()
rows, err := testDb.QueryContext(ctx, "SELECT CURSOR(SELECT object_name, object_type, object_id, created FROM all_objects WHERE ROWNUM <= 10) FROM DUAL")
if err != nil {
t.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var intf driver.Rows
if err := rows.Scan(&intf); err != nil {
t.Error(err)