-
Notifications
You must be signed in to change notification settings - Fork 102
/
stmt.go
3586 lines (3374 loc) · 92.8 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 2017, 2020 The Godror Authors
//
//
// SPDX-License-Identifier: UPL-1.0 OR Apache-2.0
package godror
/*
#include <stdlib.h>
#include "dpiImpl.h"
const int sizeof_dpiData = sizeof(void);
void godror_setFromString(dpiVar *dv, uint32_t pos, const _GoString_ value) {
uint32_t length;
length = _GoStringLen(value);
if( length == 0 ) {
return;
}
dpiVar_setFromBytes(dv, pos, _GoStringPtr(value), length);
}
*/
import "C"
import (
"bytes"
"context"
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"io"
"reflect"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unsafe"
"github.com/godror/godror/slog"
"github.com/godror/knownpb/timestamppb"
)
const printStack = false
// NullTime is an alias for sql.NullTime
type NullTime = sql.NullTime
var nullTime interface{} = nil
type stmtOptions struct {
boolString boolString
fetchArraySize int // zero means DefaultFetchArraySize
prefetchCount int // zero means DefaultPrefetchCount, -1 is zero.
arraySize int
callTimeout time.Duration
execMode C.dpiExecMode
plSQLArrays bool
lobAsReader bool
nullDateAsZeroTime bool
deleteFromCache bool
numberAsString bool
numberAsFloat64 bool
}
type boolString struct {
True, False string
}
func (bs boolString) IsZero() bool { return bs.True == "" && bs.False == "" }
func (bs boolString) MaxLen() int {
n := len(bs.True)
if m := len(bs.False); m > n {
return m
}
return n
}
func (bs boolString) ToString(b bool) string {
if b {
return bs.True
}
return bs.False
}
func (bs boolString) FromString(s string) bool {
return s == bs.True && bs.True != "" || bs.True == "" && s != bs.False
}
func (o stmtOptions) BoolString() boolString { return o.boolString }
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) PrefetchCount() int {
switch n := o.prefetchCount; {
case n == 0:
return DefaultPrefetchCount
case n < 0:
return 0
default:
return n
}
}
func (o stmtOptions) FetchArraySize() int {
n := o.fetchArraySize
if n <= 0 {
return DefaultFetchArraySize
}
return n
}
func (o stmtOptions) PlSQLArrays() bool { return o.plSQLArrays }
func (o stmtOptions) ClobAsString() bool { return !o.lobAsReader }
func (o stmtOptions) LobAsReader() bool { return o.lobAsReader }
func (o stmtOptions) NullDate() interface{} {
if o.nullDateAsZeroTime {
return time.Time{}
}
return nullTime
}
func (o stmtOptions) DeleteFromCache() bool { return o.deleteFromCache }
func (o stmtOptions) NumberAsString() bool { return o.numberAsString }
func (o stmtOptions) NumberAsFloat64() bool { return o.numberAsFloat64 }
// Option holds statement options.
//
// Use it "naked", without sql.Named!
type Option func(*stmtOptions)
// BoolToString is an option that governs convertsion from bool to string in the database.
// This is for converting from bool to string, from outside of the database
// (which does not have a BOOL(EAN) column (SQL) type, only a BOOLEAN PL/SQL type).
//
// This will be used only with DML statements and when the PlSQLArrays Option is not used.
//
// For the other way around, use an sql.Scanner that converts from string to bool. For example:
//
// type Booler bool
// var _ sql.Scanner = Booler{}
// func (b Booler) Scan(src interface{}) error {
// switch src := src.(type) {
// case int: *b = x == 1
// case string: *b = x == "Y" || x == "T" // or any string your database model treats as truth value
// default: return fmt.Errorf("unknown scanner source %T", src)
// }
// return nil
// }
//
// Such a type cannot be included in this package till we can inject the truth strings into the scanner method.
func BoolToString(trueVal, falseVal string) Option {
return func(o *stmtOptions) { o.boolString = boolString{True: trueVal, False: falseVal} }
}
// 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.
//
// Use it "naked", without sql.Named!
var PlSQLArrays Option = func(o *stmtOptions) { o.plSQLArrays = true }
// FetchRowCount is DEPRECATED, use FetchArraySize.
//
// It returns an option to set the rows to be fetched, overriding DefaultFetchRowCount.
//
// Use it "naked", without sql.Named!
func FetchRowCount(rowCount int) Option { return FetchArraySize(rowCount) }
// FetchArraySize returns an option to set the rows to be fetched, overriding DefaultFetchRowCount.
//
// For choosing FetchArraySize and PrefetchCount, see https://cx-oracle.readthedocs.io/en/latest/user_guide/tuning.html#choosing-values-for-arraysize-and-prefetchrows
//
// Use it "naked", without sql.Named!
func FetchArraySize(rowCount int) Option {
return func(o *stmtOptions) {
if rowCount > 0 {
o.fetchArraySize = rowCount
} else {
o.fetchArraySize = 0
}
}
}
// PrefetchCount returns an option to set the rows to be fetched, overriding DefaultPrefetchCount.
//
// For choosing FetchArraySize and PrefetchCount, see https://cx-oracle.readthedocs.io/en/latest/user_guide/tuning.html#choosing-values-for-arraysize-and-prefetchrows
//
// WARNING: If you will take a REF CURSOR, the driver will start prefetching, so if you give that cursor to a stored procedure, that won't see the prefetched rows!
//
// Use it "naked", without sql.Named!
func PrefetchCount(rowCount int) Option {
return func(o *stmtOptions) {
if rowCount > 0 {
o.prefetchCount = rowCount
} else {
o.prefetchCount = -1
}
}
}
// ArraySize returns an option to set the array size to be used, overriding DefaultArraySize.
//
// Use it "naked", without sql.Named!
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.
//
// Use it "naked", without sql.Named!
func ParseOnly() Option {
return parseOnly
}
func describeOnly(o *stmtOptions) { o.execMode = C.DPI_MODE_EXEC_DESCRIBE_ONLY }
// ClobAsString returns an option to force fetching CLOB columns as strings.
//
// Deprecated: CLOBs are returned as string by default - for CLOB, use LobAsReader.
// EXCEPT for Object attributes, those are returned as-is - as lobReader.
//
// Use it "naked", without sql.Named!
func ClobAsString() Option { return func(o *stmtOptions) { o.lobAsReader = false } }
// 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!
//
// EXCEPT for Object attributes, those are returned as-is - as lobReader.
//
// Use it "naked", without sql.Named!
func LobAsReader() Option { return func(o *stmtOptions) { o.lobAsReader = 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 }
}
// NullDateAsZeroTime is an option to return NULL DATE columns as time.Time{} instead of nil.
// If you must Scan into time.Time (cannot use sql.NullTime), this may help.
func NullDateAsZeroTime() Option { return func(o *stmtOptions) { o.nullDateAsZeroTime = true } }
// DeleteFromCache is an option to delete the statement from the statement cache.
func DeleteFromCache() Option { return func(o *stmtOptions) { o.deleteFromCache = true } }
// NumberAsString is an option to return numbers as string, not Number.
func NumberAsString() Option { return func(o *stmtOptions) { o.numberAsString = true } }
// NumberAsFloat64 is an option to return numbers as float64, not Number (which is a string).
func NumberAsFloat64() Option { return func(o *stmtOptions) { o.numberAsFloat64 = true } }
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 {
ctx context.Context
*conn
dpiStmt *C.dpiStmt
query string
columns []Column
isSlice []bool
gets []dataGetter
dests []interface{}
data [][]C.dpiData
vars []*C.dpiVar
varInfos []varInfo
stmtOptions
arrLen int
dpiStmtInfo C.dpiStmtInfo
sync.Mutex
}
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.closeNotLocking()
}
func (st *statement) closeNotLocking() error {
if st == nil || st.dpiStmt == nil {
return nil
}
c, dpiStmt, vars := st.conn, st.dpiStmt, st.vars
st.vars = nil
st.isSlice = nil
st.query = ""
st.data = nil
st.varInfos = nil
st.gets = nil
st.dests = nil
st.columns = nil
st.dpiStmt = nil
st.conn = nil
st.dpiStmtInfo = C.dpiStmtInfo{}
st.ctx = nil
if logger := getLogger(context.TODO()); logger != nil {
logger.Debug("statement.closeNotLocking", "st", fmt.Sprintf("%p", st), "refCount", dpiStmt.refCount)
if printStack {
var a [4096]byte
stack := a[:runtime.Stack(a[:], false)]
logger.Debug("closeNotLocking", "stack", string(stack))
}
}
for _, v := range vars[:cap(vars)] {
if v != nil {
C.dpiVar_release(v)
}
}
if dpiStmt.refCount > 0 {
C.dpiStmt_release(dpiStmt)
}
if c == nil {
return driver.ErrBadConn
}
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)
}
func newDoneCh() (<-chan struct{}, func()) {
done := make(chan struct{})
var once sync.Once
return done, func() { once.Do(func() { close(done) }) }
}
// 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) (driver.Result, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
logger := st.conn.getLogger(ctx)
if logger != nil {
logger.Debug("ExecContext", "stmt", fmt.Sprintf("%p", st), "args", fmt.Sprintf("%#v", args))
}
st.Lock()
defer st.Unlock()
if st.conn == nil {
return nil, driver.ErrBadConn
}
st.ctx = ctx
if st.dpiStmt == nil && st.query == getConnection {
*(args[0].Value.(sql.Out).Dest.(*interface{})) = st.conn
return driver.ResultNoRows, nil
}
st.conn.mu.RLock()
defer st.conn.mu.RUnlock()
// HandleDeadline for all ODPI calls called below
done, closeDone := newDoneCh()
defer closeDone()
if err := st.handleDeadline(ctx, done); err != nil {
return nil, err
}
var err error
closeIfBadConn := func(err error) error {
closeDone()
if err == nil {
return nil
}
c := st.conn
if err = maybeBadConn(err, c); err == driver.ErrBadConn {
_ = st.closeNotLocking()
}
return err
}
// bind variables
if err = st.bindVars(args, logger); 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
}
if st.DeleteFromCache() {
C.dpiStmt_deleteFromCache(st.dpiStmt)
}
// execute
var f func() C.int
many := !st.PlSQLArrays() && st.arrLen > 0
if many {
f = func() C.int { return C.dpiStmt_executeMany(st.dpiStmt, mode, C.uint32_t(st.arrLen)) }
} else {
f = func() C.int { return C.dpiStmt_execute(st.dpiStmt, mode, nil) }
}
for i := 0; i < 3; i++ {
if logger != nil {
logger.Debug("dpiStmt_execute", "st", fmt.Sprintf("%p", st.dpiStmt), "many", many, "mode", mode, "len", st.arrLen)
}
if err = st.checkExec(f); err == nil {
break
}
if ctxErr := ctx.Err(); ctxErr != nil {
return nil, ctxErr
}
if !isInvalidErr(err) {
break
}
}
if err != nil {
return nil, closeIfBadConn(err) //fmt.Errorf("dpiStmt_execute(mode=%d arrLen=%d): %w", mode, arrLen, err))
}
if logger != nil {
logger.Debug("get/set", "gets", st.gets, "dests", st.dests)
}
for i, get := range st.gets {
if get == nil {
continue
}
i := i
if st.dpiStmtInfo.isReturning == 1 {
var n C.uint32_t
data := &st.data[i][0]
if err := st.checkExec(func() C.int { return C.dpiVar_getReturnedData(st.vars[i], 0, &n, &data) }); err != nil {
return nil, closeIfBadConn(fmt.Errorf("%d.getReturnedData: %w", i, err))
}
if n == 0 {
st.data[i] = st.data[i][:0]
} else {
st.data[i] = unsafe.Slice(data, n)
}
}
dest := st.dests[i]
if !st.isSlice[i] {
if err := get(dest, st.data[i]); err != nil {
if logger != nil {
logger.Error("get", "i", i, "error", err)
}
return nil, closeIfBadConn(fmt.Errorf("%d. get[%d]: %w", i, 0, err))
}
if logger != nil {
logger.Debug("get-not-slice", "i", i, "dest", dest)
}
continue
}
var n C.uint32_t = 1
if err := st.checkExec(func() C.int { return C.dpiVar_getNumElementsInArray(st.vars[i], &n) }); err != nil {
if logger != nil {
logger.Error("getNumElementsInArray", "i", i, "error", err)
}
return nil, closeIfBadConn(fmt.Errorf("%d.getNumElementsInArray: %w", i, err))
}
//fmt.Printf("i=%d dest=%T %#v\n", i, dest, dest)
if err := get(dest, st.data[i][:n]); err != nil {
if logger != nil {
logger.Error("get", "i", i, "n", n, "error", err)
}
return nil, closeIfBadConn(fmt.Errorf("%d. get: %w", i, err))
}
}
var count C.uint64_t
if st.checkExec(func() C.int { return C.dpiStmt_getRowCount(st.dpiStmt, &count) }) != nil {
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
}
st.Lock()
defer st.Unlock()
if st.conn == nil {
return nil, driver.ErrBadConn
}
st.conn.mu.RLock()
defer st.conn.mu.RUnlock()
return st.queryContextNotLocked(ctx, args)
}
func (st *statement) queryContextNotLocked(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
st.ctx = ctx
logger := st.conn.getLogger(ctx)
switch st.query {
case getConnection:
if logger != nil {
logger.Debug("QueryContext", "args", args)
}
return &directRow{conn: st.conn, query: st.query, result: []interface{}{st.conn}}, nil
case wrapResultset:
if logger != nil {
logger.Debug("QueryContext", "args", args)
}
return args[0].Value.(driver.Rows), nil
}
done, closeDone := newDoneCh()
defer closeDone()
if err := st.handleDeadline(ctx, done); err != nil {
return nil, err
}
var err error
closeIfBadConn := func(err error) error {
closeDone()
if err == nil {
return nil
}
c := st.conn
if err = maybeBadConn(err, c); err == driver.ErrBadConn {
_ = st.closeNotLocking()
}
return err
}
// HandleDeadline for all ODPI calls called below
//fmt.Printf("QueryContext(%+v)\n", args)
// bind variables
if err = st.bindVars(args, logger); 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
}
// set Prefetch Parameters before execute
C.dpiStmt_setFetchArraySize(st.dpiStmt, C.uint32_t(st.FetchArraySize()))
C.dpiStmt_setPrefetchRows(st.dpiStmt, C.uint32_t(st.PrefetchCount()))
// execute
var colCount C.uint32_t
f := func() C.int { return C.dpiStmt_execute(st.dpiStmt, mode, &colCount) }
for i := 0; i < 3; i++ {
if err = st.checkExec(f); err == nil {
break
}
if ctxErr := ctx.Err(); ctxErr != nil {
return nil, ctxErr
}
if !isInvalidErr(err) {
break
}
}
if err != nil {
return nil, closeIfBadConn(fmt.Errorf("dpiStmt_execute: %w", 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 {
logger := getLogger(context.TODO())
if logger != nil {
logger.Debug("NumInput", "stmt", fmt.Sprintf("%p", st), "dpiStmt", fmt.Sprintf("%p", st.dpiStmt), "query", st.query)
}
if st.query == wrapResultset {
return 1
}
if st.dpiStmt == nil {
switch st.query {
case getConnection, wrapResultset:
return 1
}
return 0
}
st.Lock()
defer st.Unlock()
var cnt C.uint32_t
if err := st.checkExec(func() C.int { return C.dpiStmt_getBindCount(st.dpiStmt, &cnt) }); err != nil {
if logger != nil {
logger.Error("getBindCount", "error", err)
}
if st.conn == nil {
panic(driver.ErrBadConn)
}
panic(err)
}
if cnt < 2 { // 1 can't decrease...
if logger != nil {
logger.Info("NumInput", "count", cnt, "stmt", fmt.Sprintf("%p", st))
}
return int(cnt)
}
var prevColon bool
var mayHaveBoundName bool
for _, r := range st.query {
if r == ':' {
prevColon = true
continue
}
if prevColon {
prevColon = false
if 'a' <= r && r <= 'z' || 'A' <= r && r <= 'Z' {
mayHaveBoundName = true
break
}
}
}
if !mayHaveBoundName {
return int(cnt)
}
names := make([]*C.char, int(cnt))
lengths := make([]C.uint32_t, int(cnt))
if err := st.checkExec(func() C.int { return C.dpiStmt_getBindNames(st.dpiStmt, &cnt, &names[0], &lengths[0]) }); err != nil {
if logger != nil {
logger.Error("getBindNames", "error", err)
}
if st.conn == nil {
panic(driver.ErrBadConn)
}
panic(err)
}
if logger != nil {
logger.Debug("NumInput", "count", cnt, "stmt", fmt.Sprintf("%p", st))
}
// return the number of *unique* arguments
return int(cnt)
}
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, logger *slog.Logger) error {
if logger != nil {
logger.Debug("enter bindVars", "st", fmt.Sprintf("%p", st), "args", fmt.Sprintf("%#v", args))
}
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 false && 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 logger != nil {
logger.Debug("bindVars", "i", i, "in", info.isIn, "out", info.isOut, "value", fmt.Sprintf("%[1]p %[1]T %#[1]v", 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 fmt.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 logger != nil {
logger.Debug("bindVars", "doManyCount", doManyCount, "arrLen", st.arrLen, "doExecMany", doExecMany, "minArrLen", "maxArrLen")
}
runtime.LockOSThread()
defer runtime.UnlockOSThread()
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 fmt.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 logger != nil {
logger.Debug("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 fmt.Errorf("maximum array size allowed is %d", maxArraySize)
}
mustAllocate := st.vars[i] == nil || st.data[i] == nil
if !mustAllocate && st.varInfos[i] != vi {
C.dpiVar_release(st.vars[i])
mustAllocate = true
}
if mustAllocate {
if st.vars[i], st.data[i], err = st.newVar(vi); err != nil {
return fmt.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 logger != nil {
logger.Debug("dpiVar_setNumElementsInArray", "i", i, "n", 0)
}
if err := st.checkExecNoLOT(func() C.int { return C.dpiVar_setNumElementsInArray(dv, C.uint32_t(0)) }); err != nil {
return fmt.Errorf("setNumElementsInArray[%d](%d): %w", i, 0, err)
}
}
continue
}
if !st.isSlice[i] {
if logger != nil {
logger.Debug("set", "i", i, "value", fmt.Sprintf("%T=%#v", value, value))
}
if err := info.set(dv, data[:1], value); err != nil {
return fmt.Errorf("set(data[%d][%d], %#v (%T)): %w", i, 0, value, value, err)
}
continue
}
if st.PlSQLArrays() {
n = rv.Len()
if logger != nil {
logger.Debug("dpiVar_setNumElementsInArray", "i", i, "n", n)
}
if err := st.checkExecNoLOT(func() C.int { return C.dpiVar_setNumElementsInArray(dv, C.uint32_t(n)) }); err != nil {
return fmt.Errorf("%+v.setNumElementsInArray[%d](%d): %w", dv, i, n, err)
}
}
//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 {
i, v := i, v
if err := st.checkExecNoLOT(func() C.int { return C.dpiStmt_bindByPos(st.dpiStmt, C.uint32_t(i+1), v) }); err != nil {
return fmt.Errorf("bindByPos[%d]: %w", i, err)
}
}
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)
err := st.checkExecNoLOT(func() C.int { return C.dpiStmt_bindByName(st.dpiStmt, cName, C.uint32_t(len(name)), st.vars[i]) })
C.free(unsafe.Pointer(cName))
if err != nil {
return fmt.Errorf("bindByName[%q]: %w", name, err)
}
}
return nil
}
func (st *statement) bindVarTypeSwitch(info *argInfo, get *dataGetter, value interface{}) (interface{}, error) {
nilPtr := false
logger := getLogger(context.TODO())
if logger != nil {
defer func() {
logger.Debug("bindVarTypeSwitch", "info", info, "value", fmt.Sprintf("[%T]%#v", value, value))
}()
}
vlr, isValuer := value.(driver.Valuer)
switch value.(type) {
case *driver.Rows, *Object, *timestamppb.Timestamp:
default:
if rv := reflect.ValueOf(value); rv.Kind() == reflect.Ptr {
if nilPtr = rv.IsNil(); nilPtr {
info.set = dataSetNull
value = reflect.Zero(rv.Type().Elem()).Interface()
} else {
value = rv.Elem().Interface()
if !isValuer {
vlr, isValuer = value.(driver.Valuer)
}
}
}
}
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