-
Notifications
You must be signed in to change notification settings - Fork 1
/
stmt.go
2082 lines (1949 loc) · 50.4 KB
/
stmt.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 2019 Tamás Gulácsi
//
// SPDX-License-Identifier: UPL-1.0
package oracledb
/*
#include <stdlib.h>
#include "dpiImpl.h"
const int sizeof_dpiData = sizeof(void);
*/
import "C"
import (
"context"
"database/sql"
"database/sql/driver"
"fmt"
"io"
"reflect"
"strconv"
"strings"
"sync"
"time"
"unsafe"
errors "golang.org/x/xerrors"
)
type stmtOptions struct {
fetchRowCount int
arraySize int
callTimeout time.Duration
execMode C.dpiExecMode
plSQLArrays bool
lobAsReader bool
magicTypeConversion bool
numberAsString bool
}
func (o stmtOptions) ExecMode() C.dpiExecMode {
if o.execMode == 0 {
return C.DPI_MODE_EXEC_DEFAULT
}
return o.execMode
}
func (o stmtOptions) ArraySize() int {
if o.arraySize <= 0 {
return DefaultArraySize
} else if o.arraySize > 1<<16 {
return 1 << 16
}
return o.arraySize
}
func (o stmtOptions) FetchRowCount() int {
if o.fetchRowCount <= 0 {
return DefaultFetchRowCount
}
return o.fetchRowCount
}
func (o stmtOptions) PlSQLArrays() bool { return o.plSQLArrays }
func (o stmtOptions) LobAsReader() bool { return o.lobAsReader }
func (o stmtOptions) MagicTypeConversion() bool { return o.magicTypeConversion }
func (o stmtOptions) NumberAsString() bool { return o.numberAsString }
// Option holds statement options.
type Option func(*stmtOptions)
// PlSQLArrays is to signal that the slices given in arguments of Exec to
// be left as is - the default is to treat them as arguments for ExecMany.
var PlSQLArrays Option = func(o *stmtOptions) { o.plSQLArrays = true }
// FetchRowCount returns an option to set the rows to be fetched, overriding DefaultFetchRowCount.
func FetchRowCount(rowCount int) Option {
if rowCount <= 0 {
return nil
}
return func(o *stmtOptions) { o.fetchRowCount = rowCount }
}
// ArraySize returns an option to set the array size to be used, overriding DefaultArraySize.
func ArraySize(arraySize int) Option {
if arraySize <= 0 {
return nil
}
return func(o *stmtOptions) { o.arraySize = arraySize }
}
func parseOnly(o *stmtOptions) { o.execMode = C.DPI_MODE_EXEC_PARSE_ONLY }
// ParseOnly returns an option to set the ExecMode to only Parse.
func ParseOnly() Option {
return parseOnly
}
func describeOnly(o *stmtOptions) { o.execMode = C.DPI_MODE_EXEC_DESCRIBE_ONLY }
// LobAsReader is an option to set query columns of CLOB/BLOB to be returned as a Lob.
//
// LOB as a reader and writer is not the most performant at all. Yes, OCI
// and ODPI-C provide a way to retrieve this data directly. Effectively,
// all you need to do is tell ODPI-C that you want a "long string" or "long
// raw" returned. You can do that by telling ODPI-C you want a variable
// with oracleTypeNum=DPI_ORACLE_TYPE_LONG_VARCHAR or
// DPI_ORACLE_TYPE_LONG_RAW and nativeTypeNum=DPI_NATIVE_TYPE_BYTES. ODPI-C
// will handle all of the dynamic fetching and allocation that is required.
// :-) You can also use DPI_ORACLE_TYPE_VARCHAR and DPI_ORACLE_TYPE_RAW as
// long as you set the size > 32767 -- whichever way you wish to use.
//
// With the use of LOBs, there is one round-trip to get the LOB locators,
// then a round-trip for each read() that is performed. If you request the
// length there is another round-trip required. So if you fetch 100 rows
// with 2 CLOB columns, that means you get 401 round-trips. Using
// string/[]bytes directly means only one round trip. So you can see that
// if your database is remote with high latency you can have a significant
// performance penalty!
func LobAsReader() Option { return func(o *stmtOptions) { o.lobAsReader = true } }
// MagicTypeConversion returns an option to force converting named scalar types (e.g. "type underlying int64") to their scalar underlying type.
func MagicTypeConversion() Option {
return func(o *stmtOptions) { o.magicTypeConversion = true }
}
// NumberAsString returns an option to return numbers as string, not Number.
func NumberAsString() Option {
return func(o *stmtOptions) { o.numberAsString = true }
}
// CallTimeout sets the round-trip timeout (OCI_ATTR_CALL_TIMEOUT).
//
// See https://docs.oracle.com/en/database/oracle/oracle-database/18/lnoci/handle-and-descriptor-attributes.html#GUID-D8EE68EB-7E38-4068-B06E-DF5686379E5E
func CallTimeout(d time.Duration) Option {
return func(o *stmtOptions) { o.callTimeout = d }
}
const minChunkSize = 1 << 16
var _ = driver.Stmt((*statement)(nil))
var _ = driver.StmtQueryContext((*statement)(nil))
var _ = driver.StmtExecContext((*statement)(nil))
var _ = driver.NamedValueChecker((*statement)(nil))
type statement struct {
stmtOptions
columns []Column
isSlice []bool
gets []dataGetter
dests []interface{}
data [][]C.dpiData
vars []*C.dpiVar
varInfos []varInfo
query string
sync.Mutex
arrLen int
*conn
dpiStmt *C.dpiStmt
isReturning bool
}
type dataGetter func(v interface{}, data []C.dpiData) error
// Close closes the statement.
//
// As of Go 1.1, a Stmt will not be closed if it's in use
// by any queries.
func (st *statement) Close() error {
if st == nil {
return nil
}
st.Lock()
defer st.Unlock()
return st.close(false)
}
func (st *statement) close(keepDpiStmt bool) error {
if st == nil {
return nil
}
c, dpiStmt, vars := st.conn, st.dpiStmt, st.vars
st.isSlice = nil
st.query = ""
st.data = nil
st.vars = nil
st.varInfos = nil
st.gets = nil
st.dests = nil
st.columns = nil
st.dpiStmt = nil
st.conn = nil
for _, v := range vars[:cap(vars)] {
if v != nil {
C.dpiVar_release(v)
}
}
if !keepDpiStmt {
var si C.dpiStmtInfo
if dpiStmt != nil &&
C.dpiStmt_getInfo(dpiStmt, &si) != C.DPI_FAILURE && // this is just to check the validity of dpiStmt, to avoid SIGSEGV
C.dpiStmt_release(dpiStmt) != C.DPI_FAILURE {
return nil
}
}
if c == nil {
return driver.ErrBadConn
}
if err := c.getError(); err != nil {
return errors.Errorf("statement/dpiStmt_release: %w", err)
}
return nil
}
// Exec executes a query that doesn't return rows, such
// as an INSERT or UPDATE.
//
// Deprecated: Drivers should implement StmtExecContext instead (or additionally).
func (st *statement) Exec(args []driver.Value) (driver.Result, error) {
nargs := make([]driver.NamedValue, len(args))
for i, arg := range args {
nargs[i].Ordinal = i + 1
nargs[i].Value = arg
}
return st.ExecContext(context.Background(), nargs)
}
// Query executes a query that may return rows, such as a
// SELECT.
//
// Deprecated: Drivers should implement StmtQueryContext instead (or additionally).
func (st *statement) Query(args []driver.Value) (driver.Rows, error) {
nargs := make([]driver.NamedValue, len(args))
for i, arg := range args {
nargs[i].Ordinal = i + 1
nargs[i].Value = arg
}
return st.QueryContext(context.Background(), nargs)
}
// ExecContext executes a query that doesn't return rows, such as an INSERT or UPDATE.
//
// ExecContext must honor the context timeout and return when it is canceled.
//
// Cancelation/timeout is honored, execution is broken, but you may have to disable out-of-bound execution - see https://github.com/oracle/odpi/issues/116 for details.
func (st *statement) ExecContext(ctx context.Context, args []driver.NamedValue) (res driver.Result, err error) {
if err = ctx.Err(); err != nil {
return nil, err
}
Log := ctxGetLog(ctx)
closeIfBadConn := func(err error) error {
if err != nil && err == driver.ErrBadConn {
if Log != nil {
Log("error", err)
}
st.close(false)
st.conn.close(true)
}
return err
}
st.Lock()
defer st.Unlock()
if st.dpiStmt == nil && st.query == getConnection {
*(args[0].Value.(sql.Out).Dest.(*interface{})) = st.conn
return driver.ResultNoRows, nil
}
st.isReturning = false
st.conn.RLock()
defer st.conn.RUnlock()
// bind variables
if err = st.bindVars(args, Log); err != nil {
return nil, closeIfBadConn(err)
}
mode := st.ExecMode()
//fmt.Printf("%p.%p: inTran? %t\n%s\n", st.conn, st, st.inTransaction, st.query)
if !st.inTransaction {
mode |= C.DPI_MODE_EXEC_COMMIT_ON_SUCCESS
}
st.setCallTimeout(ctx)
done := make(chan error, 1)
// execute
go func() {
defer close(done)
Loop:
for i := 0; i < 3; i++ {
if err = ctx.Err(); err != nil {
done <- err
return
}
if !st.PlSQLArrays() && st.arrLen > 0 {
if Log != nil {
Log("C", "dpiStmt_executeMany", "mode", mode, "len", st.arrLen)
}
if C.dpiStmt_executeMany(st.dpiStmt, mode, C.uint32_t(st.arrLen)) == C.DPI_FAILURE {
if err = ctx.Err(); err == nil {
err = st.getError()
}
}
} else {
var colCount C.uint32_t
if Log != nil {
Log("C", "dpiStmt_execute", "mode", mode, "colCount", colCount)
}
if C.dpiStmt_execute(st.dpiStmt, mode, &colCount) == C.DPI_FAILURE {
if err = ctx.Err(); err == nil {
err = st.getError()
}
}
}
if Log != nil {
Log("msg", "st.Execute", "error", err)
}
if err == nil {
var info C.dpiStmtInfo
if C.dpiStmt_getInfo(st.dpiStmt, &info) == C.DPI_FAILURE {
err = errors.Errorf("getInfo: %w", st.getError())
}
st.isReturning = info.isReturning != 0
return
}
var cdr interface{ Code() int }
if !errors.As(err, &cdr) {
break
}
switch code := cdr.Code(); code {
// ORA-04068: "existing state of packages has been discarded"
case 4061, 4065, 4068:
if Log != nil {
Log("msg", "retry", "ora", code)
}
continue Loop
}
break
}
if err == nil {
done <- nil
return
}
done <- maybeBadConn(errors.Errorf("dpiStmt_execute(mode=%d arrLen=%d): %w", mode, st.arrLen, err), nil)
}()
select {
case err = <-done:
if err != nil {
return nil, closeIfBadConn(err)
}
case <-ctx.Done():
// select again to avoid race condition if both are done
select {
case err = <-done:
if err != nil {
return nil, closeIfBadConn(err)
}
case <-ctx.Done():
if Log != nil {
Log("msg", "BREAK statement")
}
_ = st.Break()
st.close(false)
if err := st.conn.Close(); err != nil {
return nil, err
}
return nil, ctx.Err()
}
}
if Log != nil {
Log("gets", st.gets, "dests", st.dests)
}
for i, get := range st.gets {
if get == nil {
continue
}
if st.isReturning {
var n C.uint32_t
data := &st.data[i][0]
if C.dpiVar_getReturnedData(st.vars[i], 0, &n, &data) == C.DPI_FAILURE {
err = st.getError()
return nil, errors.Errorf("%d.getReturnedData: %w", i, closeIfBadConn(err))
}
if n == 0 {
st.data[i] = st.data[i][:0]
} else {
st.data[i] = (*(*[maxArraySize]C.dpiData)(unsafe.Pointer(data)))[:int(n):int(n)]
}
}
dest := st.dests[i]
if !st.isSlice[i] {
if err = get(dest, st.data[i]); err != nil {
if Log != nil {
Log("get", i, "error", err)
}
return nil, errors.Errorf("%d. get[%d]: %w", i, 0, closeIfBadConn(err))
}
continue
}
var n C.uint32_t = 1
if C.dpiVar_getNumElementsInArray(st.vars[i], &n) == C.DPI_FAILURE {
err = st.getError()
if Log != nil {
Log("msg", "getNumElementsInArray", "i", i, "error", err)
}
return nil, errors.Errorf("%d.getNumElementsInArray: %w", i, closeIfBadConn(err))
}
//fmt.Printf("i=%d dest=%T %#v\n", i, dest, dest)
if err = get(dest, st.data[i][:n]); err != nil {
if Log != nil {
Log("msg", "get", "i", i, "n", n, "error", err)
}
return nil, errors.Errorf("%d. get: %w", i, closeIfBadConn(err))
}
}
var count C.uint64_t
if C.dpiStmt_getRowCount(st.dpiStmt, &count) == C.DPI_FAILURE {
return nil, nil
}
return driver.RowsAffected(count), nil
}
// QueryContext executes a query that may return rows, such as a SELECT.
//
// QueryContext must honor the context timeout and return when it is canceled.
//
// Cancelation/timeout is honored, execution is broken, but you may have to disable out-of-bound execution - see https://github.com/oracle/odpi/issues/116 for details.
func (st *statement) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
Log := ctxGetLog(ctx)
closeIfBadConn := func(err error) error {
if err != nil && err == driver.ErrBadConn {
if Log != nil {
Log("error", err)
}
st.close(false)
st.conn.close(true)
}
return err
}
st.Lock()
defer st.Unlock()
st.isReturning = false
st.conn.RLock()
defer st.conn.RUnlock()
switch st.query {
case getConnection:
if Log != nil {
Log("msg", "QueryContext", "args", args)
}
return &directRow{conn: st.conn, query: st.query, result: []interface{}{st.conn}}, nil
case wrapResultset:
if Log != nil {
Log("msg", "QueryContext", "args", args)
}
return args[0].Value.(driver.Rows), nil
}
//fmt.Printf("QueryContext(%+v)\n", args)
// bind variables
if err := st.bindVars(args, Log); err != nil {
return nil, closeIfBadConn(err)
}
mode := st.ExecMode()
//fmt.Printf("%p.%p: inTran? %t\n%s\n", st.conn, st, st.inTransaction, st.query)
if !st.inTransaction {
mode |= C.DPI_MODE_EXEC_COMMIT_ON_SUCCESS
}
// execute
var colCount C.uint32_t
done := make(chan error, 1)
go func() {
var err error
defer close(done)
for i := 0; i < 3; i++ {
if err = ctx.Err(); err != nil {
done <- err
return
}
st.setCallTimeout(ctx)
if C.dpiStmt_execute(st.dpiStmt, mode, &colCount) != C.DPI_FAILURE {
break
}
if err = ctx.Err(); err == nil {
err = st.getError()
if c, ok := err.(interface{ Code() int }); ok && c.Code() != 4068 {
break
}
}
}
if err == nil {
done <- nil
return
}
done <- maybeBadConn(errors.Errorf("dpiStmt_execute: %w", err), nil)
}()
select {
case err := <-done:
if err != nil {
return nil, closeIfBadConn(err)
}
case <-ctx.Done():
select {
case err := <-done:
if err != nil {
return nil, closeIfBadConn(err)
}
case <-ctx.Done():
if Log != nil {
Log("msg", "BREAK query")
}
_ = st.Break()
st.close(false)
if err := st.conn.Close(); err != nil {
return nil, err
}
return nil, ctx.Err()
}
}
rows, err := st.openRows(int(colCount))
return rows, closeIfBadConn(err)
}
// NumInput returns the number of placeholder parameters.
//
// If NumInput returns >= 0, the sql package will sanity check
// argument counts from callers and return errors to the caller
// before the statement's Exec or Query methods are called.
//
// NumInput may also return -1, if the driver doesn't know
// its number of placeholders. In that case, the sql package
// will not sanity check Exec or Query argument counts.
func (st *statement) NumInput() int {
if st.query == wrapResultset {
return 1
}
if st.dpiStmt == nil {
switch st.query {
case getConnection, wrapResultset:
return 1
}
return 0
}
if !go10 {
return -1
}
st.Lock()
defer st.Unlock()
var cnt C.uint32_t
//defer func() { fmt.Printf("%p.NumInput=%d (%q)\n", st, cnt, st.query) }()
if C.dpiStmt_getBindCount(st.dpiStmt, &cnt) == C.DPI_FAILURE {
return -1
}
if cnt < 2 { // 1 can't decrease...
return int(cnt)
}
names := make([]*C.char, int(cnt))
lengths := make([]C.uint32_t, int(cnt))
if C.dpiStmt_getBindNames(st.dpiStmt, &cnt, &names[0], &lengths[0]) == C.DPI_FAILURE {
return -1
}
//fmt.Printf("%p.NumInput=%d\n", st, cnt)
// return the number of *unique* arguments
return int(cnt)
}
func (st *statement) setCallTimeout(ctx context.Context) {
if st.callTimeout != 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, st.callTimeout)
_ = cancel
}
st.conn.setCallTimeout(ctx)
}
type argInfo struct {
objType *C.dpiObjectType
set dataSetter
bufSize int
typ C.dpiOracleTypeNum
natTyp C.dpiNativeTypeNum
isIn, isOut bool
}
// bindVars binds the given args into new variables.
func (st *statement) bindVars(args []driver.NamedValue, Log logFunc) error {
if Log != nil {
Log("enter", "bindVars", "args", args)
}
for i, v := range st.vars[:cap(st.vars)] {
if v != nil {
C.dpiVar_release(v)
st.vars[i], st.varInfos[i] = nil, varInfo{}
}
}
var named bool
if cap(st.vars) < len(args) {
st.vars = make([]*C.dpiVar, len(args))
} else {
st.vars = st.vars[:len(args)]
}
if cap(st.varInfos) < len(args) {
st.varInfos = make([]varInfo, len(args))
} else {
st.varInfos = st.varInfos[:len(args)]
}
if cap(st.data) < len(args) {
st.data = make([][]C.dpiData, len(args))
} else {
st.data = st.data[:len(args)]
}
if cap(st.gets) < len(args) {
st.gets = make([]dataGetter, len(args))
} else {
st.gets = st.gets[:len(args)]
}
if cap(st.dests) < len(args) {
st.dests = make([]interface{}, len(args))
} else {
st.dests = st.dests[:len(args)]
}
if cap(st.isSlice) < len(args) {
st.isSlice = make([]bool, len(args))
} else {
st.isSlice = st.isSlice[:len(args)]
}
rArgs := make([]reflect.Value, len(args))
minArrLen, maxArrLen := -1, -1
st.arrLen = minArrLen
maxArraySize := st.ArraySize()
infos := make([]argInfo, len(args))
//fmt.Printf("bindVars %d\n", len(args))
for i, a := range args {
st.gets[i] = nil
st.dests[i] = nil
if !named {
named = a.Name != ""
}
info := &(infos[i])
info.isIn = true
value := a.Value
if out, ok := value.(sql.Out); ok {
if !st.PlSQLArrays() && st.arrLen > 1 {
st.arrLen = maxArraySize
}
info.isIn, info.isOut = out.In, true
value = out.Dest
}
st.dests[i] = value
rv := reflect.ValueOf(value)
if info.isOut {
if rv.IsNil() {
fmt.Printf("%d. v=%T %#v kind=%s\n", i, value, value, reflect.ValueOf(value).Kind())
}
if rv.Kind() == reflect.Ptr {
rv = rv.Elem()
value = rv.Interface()
}
}
st.isSlice[i] = false
rArgs[i] = rv
if rv.Kind() == reflect.Ptr {
// deref in rArgs, but NOT value!
rArgs[i] = rv.Elem()
}
if _, isByteSlice := value.([]byte); !isByteSlice {
st.isSlice[i] = rArgs[i].Kind() == reflect.Slice
if !st.PlSQLArrays() && st.isSlice[i] {
n := rArgs[i].Len()
if minArrLen == -1 || n < minArrLen {
minArrLen = n
}
if maxArrLen == -1 || n > maxArrLen {
maxArrLen = n
}
}
}
if Log != nil {
Log("msg", "bindVars", "i", i, "in", info.isIn, "out", info.isOut, "value", fmt.Sprintf("%T %#v", st.dests[i], st.dests[i]))
}
}
if maxArrLen > maxArraySize {
if st.arrLen == maxArraySize {
st.arrLen = maxArrLen
}
maxArraySize = maxArrLen
}
doManyCount := 1
doExecMany := !st.PlSQLArrays()
if doExecMany {
if minArrLen != -1 && minArrLen != maxArrLen {
return errors.Errorf("PlSQLArrays is not set, but has different lengthed slices (min=%d < %d=max)", minArrLen, maxArrLen)
}
st.arrLen = minArrLen
if doExecMany = st.arrLen > 1; doExecMany {
doManyCount = st.arrLen
}
}
if Log != nil {
Log("doManyCount", doManyCount, "arrLen", st.arrLen, "doExecMany", doExecMany, "minArrLen", "maxArrLen")
}
for i := range args {
info := &(infos[i])
value := st.dests[i]
var err error
if value, err = st.bindVarTypeSwitch(info, &(st.gets[i]), value); err != nil {
return errors.Errorf("%d. arg: %w", i+1, err)
}
var rv reflect.Value
if st.isSlice[i] {
rv = reflect.ValueOf(value)
}
n := doManyCount
if st.PlSQLArrays() && st.isSlice[i] {
n = rv.Len()
if info.isOut {
n = rv.Cap()
}
}
if Log != nil {
Log("msg", "newVar", "i", i, "plSQLArrays", st.PlSQLArrays(), "typ", int(info.typ), "natTyp", int(info.natTyp), "sliceLen", n, "bufSize", info.bufSize, "isSlice", st.isSlice[i])
}
//i, st.PlSQLArrays(), info.typ, info.natTyp dataSliceLen, info.bufSize)
vi := varInfo{
IsPLSArray: st.PlSQLArrays() && st.isSlice[i],
Typ: info.typ, NatTyp: info.natTyp,
SliceLen: n, BufSize: info.bufSize,
ObjectType: info.objType,
}
if vi.IsPLSArray && vi.SliceLen > maxArraySize {
return errors.Errorf("maximum array size allowed is %d", maxArraySize)
}
if st.vars[i] == nil || st.data[i] == nil || st.varInfos[i] != vi {
if st.vars[i], st.data[i], err = st.newVar(vi); err != nil {
return errors.Errorf("%d: %w", i, err)
}
st.varInfos[i] = vi
}
// Have to setNumElementsInArray for the actual lengths for PL/SQL arrays
dv, data := st.vars[i], st.data[i]
if !info.isIn {
if st.PlSQLArrays() {
if Log != nil {
Log("C", "dpiVar_setNumElementsInArray", "i", i, "n", 0)
}
if C.dpiVar_setNumElementsInArray(dv, C.uint32_t(0)) == C.DPI_FAILURE {
return errors.Errorf("setNumElementsInArray[%d](%d): %w", i, 0, st.getError())
}
}
continue
}
if !st.isSlice[i] {
if Log != nil {
Log("msg", "set", "i", i, "value", fmt.Sprintf("%T=%#v", value, value))
}
if err := info.set(dv, data[:1], value); err != nil {
return errors.Errorf("set(data[%d][%d], %#v (%T)): %w", i, 0, value, value, err)
}
continue
}
if st.PlSQLArrays() {
n = rv.Len()
if Log != nil {
Log("C", "dpiVar_setNumElementsInArray", "i", i, "n", n)
}
if C.dpiVar_setNumElementsInArray(dv, C.uint32_t(n)) == C.DPI_FAILURE {
return errors.Errorf("%+v.setNumElementsInArray[%d](%d): %w", dv, i, n, st.getError())
}
}
//fmt.Println("n:", len(st.data[i]))
if err := info.set(dv, data, value); err != nil {
return err
}
}
if !named {
for i, v := range st.vars {
//if Log != nil {Log("C", "dpiStmt_bindByPos", "dpiStmt", st.dpiStmt, "i", i, "v", v) }
if C.dpiStmt_bindByPos(st.dpiStmt, C.uint32_t(i+1), v) == C.DPI_FAILURE {
return errors.Errorf("bindByPos[%d]: %w", i, st.getError())
}
}
return nil
}
for i, a := range args {
name := a.Name
if name == "" {
name = strconv.Itoa(a.Ordinal)
}
//fmt.Printf("bindByName(%q)\n", name)
cName := C.CString(name)
res := C.dpiStmt_bindByName(st.dpiStmt, cName, C.uint32_t(len(name)), st.vars[i])
C.free(unsafe.Pointer(cName))
if res == C.DPI_FAILURE {
return errors.Errorf("bindByName[%q]: %w", name, st.getError())
}
}
return nil
}
func (st *statement) bindVarTypeSwitch(info *argInfo, get *dataGetter, value interface{}) (interface{}, error) {
nilPtr := false
if Log != nil {
Log("msg", "bindVarTypeSwitch", "info", info, "value", fmt.Sprintf("[%T]%v", value, value))
}
vlr, isValuer := value.(driver.Valuer)
switch value.(type) {
case *driver.Rows:
default:
var magic bool
rv := reflect.ValueOf(value)
kind := rv.Kind()
if kind != reflect.Ptr {
if magic = st.MagicTypeConversion(); magic {
if isValuer {
var err error
if value, err = vlr.Value(); err != nil {
return value, errors.Errorf("arg.Value(): %w", err)
}
return st.bindVarTypeSwitch(info, get, value)
}
}
} else {
if nilPtr = rv.IsNil(); nilPtr {
info.set = dataSetNull
value = reflect.Zero(rv.Type().Elem()).Interface()
} else {
value = rv.Elem().Interface()
}
}
if magic {
switch kind {
case reflect.Bool,
reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64,
reflect.Float32, reflect.Float64,
reflect.String:
default:
magic = false
}
}
if magic {
switch rv.Type().Name() {
case "bool",
"int", "int8", "int16", "int32", "int64",
"uint", "uint8", "uint16", "uint32", "uint64",
"float32", "float64",
"string":
// nothing to do
magic = false
default:
}
}
if magic {
switch kind {
case reflect.Bool:
value = rv.Bool()
case reflect.Int:
value = int(rv.Int())
case reflect.Int8:
value = int8(rv.Int())
case reflect.Int16:
value = int16(rv.Int())
case reflect.Int32:
value = int32(rv.Int())
case reflect.Int64:
value = rv.Int()
case reflect.Uint:
value = uint(rv.Uint())
case reflect.Uint16:
value = uint16(rv.Uint())
case reflect.Uint32:
value = uint32(rv.Uint())
case reflect.Uint64:
value = rv.Uint()
case reflect.Float32:
value = float32(rv.Float())
case reflect.Float64:
value = rv.Float()
case reflect.String:
value = rv.String()
}
}
}
switch v := value.(type) {
case Lob, []Lob:
info.typ, info.natTyp = C.DPI_ORACLE_TYPE_BLOB, C.DPI_NATIVE_TYPE_LOB
var isClob bool
switch v := v.(type) {
case Lob:
isClob = v.IsClob
case []Lob:
isClob = len(v) > 0 && v[0].IsClob
}
if isClob {
info.typ = C.DPI_ORACLE_TYPE_CLOB
}
info.set = st.dataSetLOB
if info.isOut {
*get = st.dataGetLOB
}
case *driver.Rows:
info.typ, info.natTyp = C.DPI_ORACLE_TYPE_STMT, C.DPI_NATIVE_TYPE_STMT
info.set = dataSetNull
if info.isOut {
*get = st.dataGetStmt
}
case int, []int:
info.typ, info.natTyp = C.DPI_ORACLE_TYPE_NUMBER, C.DPI_NATIVE_TYPE_INT64
if !nilPtr {
info.set = dataSetNumber
if info.isOut {
*get = dataGetNumber
}
}
case int32, []int32:
info.typ, info.natTyp = C.DPI_ORACLE_TYPE_NATIVE_INT, C.DPI_NATIVE_TYPE_INT64
if !nilPtr {
info.set = dataSetNumber
if info.isOut {
*get = dataGetNumber
}
}
case int64, []int64, sql.NullInt64, []sql.NullInt64:
info.typ, info.natTyp = C.DPI_ORACLE_TYPE_NUMBER, C.DPI_NATIVE_TYPE_INT64
if !nilPtr {
info.set = dataSetNumber
if info.isOut {
*get = dataGetNumber
}
}
case uint, []uint:
info.typ, info.natTyp = C.DPI_ORACLE_TYPE_NUMBER, C.DPI_NATIVE_TYPE_UINT64
if !nilPtr {
info.set = dataSetNumber
if info.isOut {
*get = dataGetNumber
}
}
case uint32, []uint32:
info.typ, info.natTyp = C.DPI_ORACLE_TYPE_NATIVE_UINT, C.DPI_NATIVE_TYPE_UINT64
if !nilPtr {
info.set = dataSetNumber
if info.isOut {
*get = dataGetNumber
}
}
case uint64, []uint64:
info.typ, info.natTyp = C.DPI_ORACLE_TYPE_NUMBER, C.DPI_NATIVE_TYPE_UINT64
if !nilPtr {
info.set = dataSetNumber
if info.isOut {
*get = dataGetNumber
}
}
case float32, []float32:
info.typ, info.natTyp = C.DPI_ORACLE_TYPE_NATIVE_FLOAT, C.DPI_NATIVE_TYPE_FLOAT
if !nilPtr {
info.set = dataSetNumber
if info.isOut {
*get = dataGetNumber
}
}
case float64, []float64:
info.typ, info.natTyp = C.DPI_ORACLE_TYPE_NATIVE_DOUBLE, C.DPI_NATIVE_TYPE_DOUBLE
if !nilPtr {
info.set = dataSetNumber
if info.isOut {
*get = dataGetNumber