-
-
Notifications
You must be signed in to change notification settings - Fork 212
/
statement.go
1036 lines (912 loc) · 32.8 KB
/
statement.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 oci8
// #include "oci8.go.h"
import "C"
import (
"bytes"
"context"
"database/sql"
"database/sql/driver"
"encoding/binary"
"fmt"
"strings"
"time"
"unsafe"
)
// Close closes the statement
func (stmt *Stmt) Close() error {
if stmt.closed {
return nil
}
stmt.closed = true
var result C.sword
if stmt.cacheKey == "" {
result = C.OCIStmtRelease(
stmt.stmt, // statement handle
stmt.conn.errHandle, // error handle
nil, // key to be associated with the statement in the cache
C.ub4(0), // length of the key
stmt.releaseMode, // mode
)
} else {
cacheKeyP := cString(stmt.cacheKey)
defer C.free(unsafe.Pointer(cacheKeyP))
result = C.OCIStmtRelease(
stmt.stmt, // statement handle
stmt.conn.errHandle, // error handle
cacheKeyP, // key to be associated with the statement in the cache
C.ub4(len(stmt.cacheKey)), // length of the key
stmt.releaseMode, // mode
)
}
stmt.stmt = nil
return stmt.conn.getError(result)
}
// NumInput returns the number of input
func (stmt *Stmt) NumInput() int {
return -1
}
// CheckNamedValue checks a named value
func (stmt *Stmt) CheckNamedValue(namedValue *driver.NamedValue) error {
switch namedValue.Value.(type) {
case sql.Out:
return nil
}
return driver.ErrSkip
}
// bindValues binds the values to the stmt
func (stmt *Stmt) bindValues(values []driver.Value, namedValues []driver.NamedValue) ([]bindStruct, error) {
if len(values) == 0 && len(namedValues) == 0 {
return nil, nil
}
var err error
var binds []bindStruct
var useValues bool
count := len(namedValues)
if count == 0 {
useValues = true
count = len(values)
}
for i := 0; i < count; i++ {
if stmt.ctx.Err() != nil {
freeBinds(binds)
return nil, stmt.ctx.Err()
}
var valueInterface interface{}
var sbind bindStruct
sbind.length = (*C.ub2)(C.malloc(C.sizeof_ub2))
*sbind.length = 0
sbind.indicator = (*C.sb2)(C.malloc(C.sizeof_sb2))
*sbind.indicator = 0
if useValues {
valueInterface = values[i]
} else {
valueInterface = namedValues[i].Value
}
var isOut bool
var isNill bool
sbind.out, isOut = valueInterface.(sql.Out)
if isOut {
valueInterface, err = driver.DefaultParameterConverter.ConvertValue(sbind.out.Dest)
if err != nil {
binds = append(binds, sbind)
freeBinds(binds)
return nil, err
}
switch valueInterface.(type) {
case nil:
isNill = true
valueInterface = sbind.out.Dest
switch valueInterface.(type) {
case *sql.NullBool:
valueInterface = false
case *sql.NullFloat64:
valueInterface = float64(0)
case *sql.NullInt64:
valueInterface = int64(0)
case *sql.NullString:
valueInterface = ""
}
}
}
switch value := valueInterface.(type) {
case nil:
sbind.dataType = C.SQLT_AFC
sbind.pbuf = nil
sbind.maxSize = 0
*sbind.indicator = -1 // set to null
case []byte:
if isOut {
if len(value) > 32767 {
var lobP *unsafe.Pointer
lobP, _, err = stmt.conn.ociDescriptorAlloc(C.OCI_DTYPE_LOB, 0)
if err != nil {
freeBinds(binds)
return nil, err
}
sbind.dataType = C.SQLT_BLOB
sbind.pbuf = unsafe.Pointer(lobP)
sbind.maxSize = C.sb4(sizeOfNilPointer)
*sbind.length = C.ub2(sizeOfNilPointer)
lobLocator := (**C.OCILobLocator)(sbind.pbuf)
err = stmt.conn.ociLobCreateTemporary(*lobLocator, C.SQLCS_IMPLICIT, C.OCI_TEMP_BLOB)
if err != nil {
freeBinds(binds)
return nil, err
}
err = stmt.conn.ociLobWrite(*lobLocator, C.SQLCS_IMPLICIT, value)
if err != nil {
freeBinds(binds)
return nil, err
}
} else {
sbind.dataType = C.SQLT_BIN
sbind.pbuf = unsafe.Pointer(cByteN(value, 32768))
sbind.maxSize = 32767
if sbind.out.In && !isNill {
*sbind.length = C.ub2(len(value))
} else {
*sbind.indicator = -1 // set to null
}
}
} else {
if len(value) > 32767 {
var lobP *unsafe.Pointer
lobP, _, err = stmt.conn.ociDescriptorAlloc(C.OCI_DTYPE_LOB, 0)
if err != nil {
freeBinds(binds)
return nil, err
}
sbind.dataType = C.SQLT_BLOB
sbind.pbuf = unsafe.Pointer(lobP)
sbind.maxSize = C.sb4(sizeOfNilPointer)
*sbind.length = C.ub2(sizeOfNilPointer)
lobLocator := (**C.OCILobLocator)(sbind.pbuf)
err = stmt.conn.ociLobCreateTemporary(*lobLocator, C.SQLCS_IMPLICIT, C.OCI_TEMP_BLOB)
if err != nil {
freeBinds(binds)
return nil, err
}
err = stmt.conn.ociLobWrite(*lobLocator, C.SQLCS_IMPLICIT, value)
if err != nil {
freeBinds(binds)
return nil, err
}
} else {
sbind.dataType = C.SQLT_BIN
sbind.pbuf = unsafe.Pointer(cByte(value))
sbind.maxSize = C.sb4(len(value))
*sbind.length = C.ub2(len(value))
}
}
case time.Time:
sbind.dataType = C.SQLT_TIMESTAMP_TZ
sbind.maxSize = C.sb4(sizeOfNilPointer)
*sbind.length = C.ub2(sizeOfNilPointer)
dateTimePP, err := stmt.conn.timeToOCIDateTime(&value)
if err != nil {
freeBinds(binds)
return nil, fmt.Errorf("timeToOCIDateTime for column %v - error: %v", i, err)
}
sbind.pbuf = unsafe.Pointer(dateTimePP)
case string:
if isOut {
if len(value) > 32767 {
var lobP *unsafe.Pointer
lobP, _, err = stmt.conn.ociDescriptorAlloc(C.OCI_DTYPE_LOB, 0)
if err != nil {
freeBinds(binds)
return nil, err
}
sbind.dataType = C.SQLT_CLOB
sbind.pbuf = unsafe.Pointer(lobP)
sbind.maxSize = C.sb4(sizeOfNilPointer)
*sbind.length = C.ub2(sizeOfNilPointer)
lobLocator := (**C.OCILobLocator)(sbind.pbuf)
err = stmt.conn.ociLobCreateTemporary(*lobLocator, C.SQLCS_IMPLICIT, C.OCI_TEMP_CLOB)
if err != nil {
freeBinds(binds)
return nil, err
}
err = stmt.conn.ociLobWrite(*lobLocator, C.SQLCS_IMPLICIT, []byte(value))
if err != nil {
freeBinds(binds)
return nil, err
}
} else {
sbind.dataType = C.SQLT_CHR
sbind.pbuf = unsafe.Pointer(cStringN(value, 32768))
sbind.maxSize = 32767
if sbind.out.In && !isNill {
*sbind.length = C.ub2(len(value))
} else {
*sbind.indicator = -1 // set to null
}
}
} else {
if len(value) > 32767 {
var lobP *unsafe.Pointer
lobP, _, err = stmt.conn.ociDescriptorAlloc(C.OCI_DTYPE_LOB, 0)
if err != nil {
freeBinds(binds)
return nil, err
}
sbind.dataType = C.SQLT_CLOB
sbind.pbuf = unsafe.Pointer(lobP)
sbind.maxSize = C.sb4(sizeOfNilPointer)
*sbind.length = C.ub2(sizeOfNilPointer)
lobLocator := (**C.OCILobLocator)(sbind.pbuf)
err = stmt.conn.ociLobCreateTemporary(*lobLocator, C.SQLCS_IMPLICIT, C.OCI_TEMP_CLOB)
if err != nil {
freeBinds(binds)
return nil, err
}
err = stmt.conn.ociLobWrite(*lobLocator, C.SQLCS_IMPLICIT, []byte(value))
if err != nil {
freeBinds(binds)
return nil, err
}
} else {
sbind.dataType = C.SQLT_AFC
sbind.pbuf = unsafe.Pointer(C.CString(value))
sbind.maxSize = C.sb4(len(value))
*sbind.length = C.ub2(len(value))
}
}
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr:
buffer := bytes.Buffer{}
err = binary.Write(&buffer, binary.LittleEndian, value)
if err != nil {
freeBinds(binds)
return nil, fmt.Errorf("binary read for column %v - error: %v", i, err)
}
sbind.dataType = C.SQLT_INT
sbind.pbuf = unsafe.Pointer(cByte(buffer.Bytes()))
sbind.maxSize = C.sb4(buffer.Len())
*sbind.length = C.ub2(buffer.Len())
if isOut && sbind.out.In && isNill {
*sbind.indicator = -1 // set to null
}
case float32, float64:
buffer := bytes.Buffer{}
err = binary.Write(&buffer, binary.LittleEndian, value)
if err != nil {
freeBinds(binds)
return nil, fmt.Errorf("binary read for column %v - error: %v", i, err)
}
sbind.dataType = C.SQLT_BDOUBLE
sbind.pbuf = unsafe.Pointer(cByte(buffer.Bytes()))
sbind.maxSize = C.sb4(buffer.Len())
*sbind.length = C.ub2(buffer.Len())
if isOut && sbind.out.In && isNill {
*sbind.indicator = -1 // set to null
}
case bool: // oracle does not have bool, handle as 0/1 int
sbind.dataType = C.SQLT_INT
if value {
sbind.pbuf = unsafe.Pointer(cByte([]byte{1}))
} else {
sbind.pbuf = unsafe.Pointer(cByte([]byte{0}))
}
sbind.maxSize = 1
*sbind.length = 1
if isOut && sbind.out.In && isNill {
*sbind.indicator = -1 // set to null
}
default:
if isOut {
// TODO: should this error instead of setting to null?
sbind.dataType = C.SQLT_AFC
sbind.pbuf = nil
sbind.maxSize = 0
*sbind.length = 0
*sbind.indicator = -1 // set to null
} else {
d := fmt.Sprintf("%v", value)
sbind.dataType = C.SQLT_AFC
sbind.pbuf = unsafe.Pointer(C.CString(d))
sbind.maxSize = C.sb4(len(d))
*sbind.length = C.ub2(len(d))
}
}
// add to binds now so if error will be freed by freeBinds call
binds = append(binds, sbind)
if useValues || len(namedValues[i].Name) < 1 {
err = stmt.ociBindByPos(C.ub4(i+1), &sbind)
// TODO: should we use namedValues[i]Ordinal?
} else {
err = stmt.ociBindByName([]byte(":"+namedValues[i].Name), &sbind)
}
if err != nil {
freeBinds(binds)
return nil, err
}
}
return binds, nil
}
// Query runs a query
func (stmt *Stmt) Query(values []driver.Value) (driver.Rows, error) {
stmt.ctx = context.Background()
binds, err := stmt.bindValues(values, nil)
if err != nil {
return nil, err
}
return stmt.query(binds)
}
// QueryContext runs a query with context
func (stmt *Stmt) QueryContext(ctx context.Context, namedValues []driver.NamedValue) (driver.Rows, error) {
stmt.ctx = ctx
binds, err := stmt.bindValues(nil, namedValues)
if err != nil {
return nil, err
}
return stmt.query(binds)
}
// query runs a query with context
func (stmt *Stmt) query(binds []bindStruct) (driver.Rows, error) {
defer freeBinds(binds)
var stmtType C.ub2
_, err := stmt.ociAttrGet(unsafe.Pointer(&stmtType), C.OCI_ATTR_STMT_TYPE)
if err != nil {
return nil, err
}
iter := C.ub4(1)
if stmtType == C.OCI_STMT_SELECT {
iter = 0
}
if stmt.conn.prefetchRows != 1 {
prefetchRows := stmt.conn.prefetchRows
// OCI_ATTR_PREFETCH_ROWS sets the number of top level rows to be prefetched. The default value is 1 row. Value of 0 seems to mean only prefetch memory size limits the number of rows to prefetch.
err = stmt.conn.ociAttrSet(unsafe.Pointer(stmt.stmt), C.OCI_HTYPE_STMT, unsafe.Pointer(&prefetchRows), 0, C.OCI_ATTR_PREFETCH_ROWS)
if err != nil {
return nil, err
}
}
if stmt.conn.prefetchMemory > 0 {
prefetchMemory := stmt.conn.prefetchMemory
// OCI_ATTR_PREFETCH_MEMORY sets the memory level for top level rows to be prefetched. Rows up to the specified top level row count are fetched if it occupies no more than the specified memory usage limit.
// The default value is 0, which means that memory size is not included in computing the number of rows to prefetch.
err = stmt.conn.ociAttrSet(unsafe.Pointer(stmt.stmt), C.OCI_HTYPE_STMT, unsafe.Pointer(&prefetchMemory), 0, C.OCI_ATTR_PREFETCH_MEMORY)
if err != nil {
return nil, err
}
}
mode := C.ub4(C.OCI_DEFAULT)
if !stmt.conn.inTransaction {
mode = mode | C.OCI_COMMIT_ON_SUCCESS
}
if stmt.ctx.Err() != nil {
return nil, stmt.ctx.Err()
}
done := make(chan struct{})
go stmt.conn.ociBreakDone(stmt.ctx, done)
err = stmt.ociStmtExecute(iter, mode)
close(done)
if err != nil {
return nil, err
}
var defines []defineStruct
defines, err = stmt.makeDefines()
if err != nil {
return nil, err
}
if stmt.ctx.Err() != nil {
freeDefines(defines)
return nil, stmt.ctx.Err()
}
rows := &Rows{
stmt: stmt,
defines: defines,
}
return rows, nil
}
func (stmt *Stmt) makeDefines() ([]defineStruct, error) {
var paramCountUb4 C.ub4 // number of columns in the select-list
_, err := stmt.ociAttrGet(unsafe.Pointer(¶mCountUb4), C.OCI_ATTR_PARAM_COUNT)
if err != nil {
return nil, err
}
paramCount := int(paramCountUb4)
defines := make([]defineStruct, paramCount)
for i := 0; i < paramCount; i++ {
if stmt.ctx.Err() != nil {
freeDefines(defines)
return nil, stmt.ctx.Err()
}
var param *C.OCIParam
param, err = stmt.ociParamGet(C.ub4(i + 1))
if err != nil {
freeDefines(defines)
return nil, err
}
defer C.OCIDescriptorFree(unsafe.Pointer(param), C.OCI_DTYPE_PARAM)
var dataType C.ub2 // external datatype of the column: https://docs.oracle.com/cd/E11882_01/appdev.112/e10646/oci03typ.htm#CEGIEEJI
_, err = stmt.conn.ociAttrGet(param, unsafe.Pointer(&dataType), C.OCI_ATTR_DATA_TYPE)
if err != nil {
freeDefines(defines)
return nil, err
}
var columnName *C.OraText // name of the column
var size C.ub4
size, err = stmt.conn.ociAttrGet(param, unsafe.Pointer(&columnName), C.OCI_ATTR_NAME)
if err != nil {
freeDefines(defines)
return nil, err
}
defines[i].name = cGoStringN(columnName, int(size))
var maxSize C.ub4 // Maximum size in bytes of the external data for the column. This can affect conversion buffer sizes.
_, err = stmt.conn.ociAttrGet(param, unsafe.Pointer(&maxSize), C.OCI_ATTR_DATA_SIZE)
if err != nil {
freeDefines(defines)
return nil, err
}
defines[i].length = (*C.ub2)(C.malloc(C.sizeof_ub2))
*defines[i].length = 0
defines[i].indicator = (*C.sb2)(C.malloc(C.sizeof_sb2))
*defines[i].indicator = 0
// switch on dataType
switch dataType {
case C.SQLT_AFC, C.SQLT_CHR, C.SQLT_VCS, C.SQLT_AVC:
defines[i].dataType = C.SQLT_AFC
// For a database with character set to ZHS16GBK the OCI C driver does not seem to report the correct max size, not sure exactly why.
// Doubling the max size of the buffer seems to fix the issue, not sure if there is a better fix.
defines[i].maxSize = C.sb4(maxSize * 2)
defines[i].pbuf = C.malloc(C.size_t(defines[i].maxSize))
case C.SQLT_BIN:
defines[i].dataType = C.SQLT_BIN
defines[i].maxSize = C.sb4(maxSize)
defines[i].pbuf = C.malloc(C.size_t(defines[i].maxSize))
case C.SQLT_NUM:
var precision C.sb2 // the precision
_, err = stmt.conn.ociAttrGet(param, unsafe.Pointer(&precision), C.OCI_ATTR_PRECISION)
if err != nil {
freeDefines(defines)
return nil, err
}
var scale C.sb1 // the scale (number of digits to the right of the decimal point)
_, err = stmt.conn.ociAttrGet(param, unsafe.Pointer(&scale), C.OCI_ATTR_SCALE)
if err != nil {
freeDefines(defines)
return nil, err
}
// The precision of numeric type attributes. If the precision is nonzero and scale is -127, then it is a FLOAT;
// otherwise, it is a NUMBER(precision, scale).
// When precision is 0, NUMBER(precision, scale) can be represented simply as NUMBER.
// https://docs.oracle.com/cd/E11882_01/appdev.112/e10646/oci06des.htm#LNOCI16458
// note that select sum and count both return as precision == 0 && scale == 0 so use float64 (SQLT_BDOUBLE) to handle both
if (precision == 0 && scale == 0) || scale > 0 || scale == -127 {
defines[i].dataType = C.SQLT_BDOUBLE
defines[i].maxSize = 8
defines[i].pbuf = C.malloc(C.size_t(defines[i].maxSize))
} else {
defines[i].dataType = C.SQLT_INT
defines[i].maxSize = 8
defines[i].pbuf = C.malloc(C.size_t(defines[i].maxSize))
}
case C.SQLT_INT:
defines[i].dataType = C.SQLT_INT
defines[i].maxSize = 8
defines[i].pbuf = C.malloc(C.size_t(defines[i].maxSize))
case C.SQLT_BDOUBLE, C.SQLT_IBDOUBLE, C.SQLT_BFLOAT, C.SQLT_IBFLOAT:
defines[i].dataType = C.SQLT_BDOUBLE
defines[i].maxSize = 8
defines[i].pbuf = C.malloc(C.size_t(defines[i].maxSize))
case C.SQLT_LNG:
defines[i].dataType = C.SQLT_LNG
defines[i].maxSize = 4000
defines[i].pbuf = C.malloc(C.size_t(defines[i].maxSize))
case C.SQLT_CLOB, C.SQLT_BLOB:
defines[i].dataType = dataType
defines[i].maxSize = C.sb4(sizeOfNilPointer)
var lobP *unsafe.Pointer
lobP, _, err = stmt.conn.ociDescriptorAlloc(C.OCI_DTYPE_LOB, 0)
if err != nil {
freeDefines(defines)
return nil, err
}
defines[i].pbuf = unsafe.Pointer(lobP)
case C.SQLT_TIMESTAMP, C.SQLT_DAT:
defines[i].dataType = C.SQLT_TIMESTAMP
defines[i].maxSize = C.sb4(sizeOfNilPointer)
var timestampP *unsafe.Pointer
timestampP, _, err = stmt.conn.ociDescriptorAlloc(C.OCI_DTYPE_TIMESTAMP, 0)
if err != nil {
freeDefines(defines)
return nil, err
}
defines[i].pbuf = unsafe.Pointer(timestampP)
case C.SQLT_TIMESTAMP_TZ, C.SQLT_TIMESTAMP_LTZ:
defines[i].dataType = C.SQLT_TIMESTAMP_TZ
defines[i].maxSize = C.sb4(sizeOfNilPointer)
var timestampP *unsafe.Pointer
timestampP, _, err = stmt.conn.ociDescriptorAlloc(C.OCI_DTYPE_TIMESTAMP_TZ, 0)
if err != nil {
freeDefines(defines)
return nil, err
}
defines[i].pbuf = unsafe.Pointer(timestampP)
case C.SQLT_INTERVAL_DS:
defines[i].dataType = C.SQLT_INTERVAL_DS
defines[i].maxSize = C.sb4(sizeOfNilPointer)
var intervalP *unsafe.Pointer
intervalP, _, err = stmt.conn.ociDescriptorAlloc(C.OCI_DTYPE_INTERVAL_DS, 0)
if err != nil {
freeDefines(defines)
return nil, err
}
defines[i].pbuf = unsafe.Pointer(intervalP)
case C.SQLT_INTERVAL_YM:
defines[i].dataType = C.SQLT_INTERVAL_YM
defines[i].maxSize = C.sb4(sizeOfNilPointer)
var intervalP *unsafe.Pointer
intervalP, _, err = stmt.conn.ociDescriptorAlloc(C.OCI_DTYPE_INTERVAL_YM, 0)
if err != nil {
freeDefines(defines)
return nil, err
}
defines[i].pbuf = unsafe.Pointer(intervalP)
case C.SQLT_RDD: // rowid
defines[i].dataType = C.SQLT_AFC
defines[i].maxSize = 40
defines[i].pbuf = C.malloc(C.size_t(defines[i].maxSize))
case C.SQLT_RSET: // ref cursor
defines[i].dataType = dataType
defines[i].maxSize = C.sb4(sizeOfNilPointer)
var stmtP *unsafe.Pointer
stmtP, _, err = stmt.conn.ociHandleAlloc(C.OCI_HTYPE_STMT, 0)
if err != nil {
freeDefines(defines)
return nil, err
}
defines[i].pbuf = unsafe.Pointer(stmtP)
default:
defines[i].dataType = C.SQLT_AFC
defines[i].maxSize = C.sb4(maxSize)
defines[i].pbuf = C.malloc(C.size_t(defines[i].maxSize))
}
result := C.OCIDefineByPos(
stmt.stmt, // statement handle
&defines[i].defineHandle, // pointer to a pointer to a define handle. If NULL, this call implicitly allocates the define handle.
stmt.conn.errHandle, // error handle
C.ub4(i+1), // position of this value in the select list. Positions are 1-based and are numbered from left to right.
defines[i].pbuf, // pointer to a buffer
defines[i].maxSize, // size of each valuep buffer in bytes
defines[i].dataType, // datatype
unsafe.Pointer(defines[i].indicator), // pointer to an indicator variable or array
defines[i].length, // pointer to array of length of data fetched
nil, // pointer to array of column-level return codes
C.OCI_DEFAULT, // mode - OCI_DEFAULT - This is the default mode.
)
if result != C.OCI_SUCCESS {
freeDefines(defines)
return nil, stmt.conn.getError(result)
}
}
return defines, nil
}
// getRowid returns the rowid
func (stmt *Stmt) getRowid() (string, error) {
rowidP, _, err := stmt.conn.ociDescriptorAlloc(C.OCI_DTYPE_ROWID, 0)
if err != nil {
return "", err
}
defer C.OCIDescriptorFree(*rowidP, C.OCI_DTYPE_ROWID)
// OCI_ATTR_ROWID returns the ROWID descriptor allocated with OCIDescriptorAlloc()
_, err = stmt.ociAttrGet(*rowidP, C.OCI_ATTR_ROWID)
if err != nil {
return "", err
}
rowid := cStringN("", 18)
defer C.free(unsafe.Pointer(rowid))
rowidLength := C.ub2(18)
result := C.OCIRowidToChar((*C.OCIRowid)(*rowidP), rowid, &rowidLength, stmt.conn.errHandle)
err = stmt.conn.getError(result)
if err != nil {
return "", err
}
return cGoStringN(rowid, int(rowidLength)), nil
}
// rowsAffected returns the number of rows affected
func (stmt *Stmt) rowsAffected() (int64, error) {
var rowCount C.ub4 // Number of rows processed so far after SELECT statements. For INSERT, UPDATE, and DELETE statements, it is the number of rows processed by the most recent statement. The default value is 1.
_, err := stmt.ociAttrGet(unsafe.Pointer(&rowCount), C.OCI_ATTR_ROW_COUNT)
if err != nil {
return -1, err
}
return int64(rowCount), nil
}
// Exec runs an exec query
func (stmt *Stmt) Exec(values []driver.Value) (driver.Result, error) {
stmt.ctx = context.Background()
binds, err := stmt.bindValues(values, nil)
if err != nil {
return nil, err
}
return stmt.exec(binds)
}
// ExecContext run a exec query with context
func (stmt *Stmt) ExecContext(ctx context.Context, namedValues []driver.NamedValue) (driver.Result, error) {
stmt.ctx = ctx
binds, err := stmt.bindValues(nil, namedValues)
if err != nil {
return nil, err
}
return stmt.exec(binds)
}
func (stmt *Stmt) exec(binds []bindStruct) (driver.Result, error) {
defer freeBinds(binds)
mode := C.ub4(C.OCI_DEFAULT)
if stmt.conn.inTransaction == false {
mode = mode | C.OCI_COMMIT_ON_SUCCESS
}
if stmt.ctx.Err() != nil {
return nil, stmt.ctx.Err()
}
done := make(chan struct{})
go stmt.conn.ociBreakDone(stmt.ctx, done)
err := stmt.ociStmtExecute(1, mode)
close(done)
if err != nil && err != ErrOCISuccessWithInfo {
return nil, err
}
result := Result{stmt: stmt}
result.rowsAffected, result.rowsAffectedErr = stmt.rowsAffected()
if result.rowsAffectedErr != nil || result.rowsAffected < 1 {
result.rowidErr = ErrNoRowid
} else {
result.rowid, result.rowidErr = stmt.getRowid()
}
err = stmt.outputBoundParameters(binds)
if err != nil {
return nil, err
}
return &result, nil
}
// outputBoundParameters sets bound parameters
func (stmt *Stmt) outputBoundParameters(binds []bindStruct) error {
var err error
for i, bind := range binds {
if bind.pbuf != nil {
switch dest := bind.out.Dest.(type) {
case *string:
switch {
case *bind.indicator > 0: // indicator variable is the actual length before truncation
spaces := int(*bind.indicator) - int(*bind.length)
if spaces < 0 {
return fmt.Errorf("spaces less than 0 for column %v", i)
}
*dest = C.GoStringN((*C.char)(bind.pbuf), C.int(*bind.length)) + strings.Repeat(" ", spaces)
case *bind.indicator == 0: // Normal
if bind.dataType == C.SQLT_CLOB {
lobLocator := (**C.OCILobLocator)(bind.pbuf)
var buffer []byte
buffer, err = stmt.conn.ociLobRead(*lobLocator, C.SQLCS_IMPLICIT)
if err != nil {
return err
}
*dest = string(buffer)
} else {
*dest = C.GoStringN((*C.char)(bind.pbuf), C.int(*bind.length))
}
case *bind.indicator == -1: // The selected value is null
*dest = "" // best attempt at Go nil string
case *bind.indicator == -2: // Item is greater than the length of the output variable; the item has been truncated.
*dest = C.GoStringN((*C.char)(bind.pbuf), C.int(*bind.length))
// TODO: should this be an error?
default:
return fmt.Errorf("unknown column indicator %d for column %v", *bind.indicator, i)
}
case *sql.NullString:
switch {
case *bind.indicator > 0: // indicator variable is the actual length before truncation
spaces := int(*bind.indicator) - int(*bind.length)
if spaces < 0 {
return fmt.Errorf("spaces less than 0 for column %v", i)
}
dest.String = C.GoStringN((*C.char)(bind.pbuf), C.int(*bind.length)) + strings.Repeat(" ", spaces)
dest.Valid = true
case *bind.indicator == 0: // Normal
dest.String = C.GoStringN((*C.char)(bind.pbuf), C.int(*bind.length))
dest.Valid = true
case *bind.indicator == -1: // The selected value is null
dest.String = ""
dest.Valid = false
case *bind.indicator == -2: // Item is greater than the length of the output variable; the item has been truncated.
dest.String = C.GoStringN((*C.char)(bind.pbuf), C.int(*bind.length))
dest.Valid = true
// TODO: should this be an error?
default:
return fmt.Errorf("unknown column indicator %d for column %v", *bind.indicator, i)
}
case *int:
*dest = int(getInt64(bind.pbuf))
case *int64:
*dest = getInt64(bind.pbuf)
case *int32:
*dest = int32(getInt64(bind.pbuf))
case *int16:
*dest = int16(getInt64(bind.pbuf))
case *int8:
*dest = int8(getInt64(bind.pbuf))
case *sql.NullInt64:
if *bind.indicator == -1 {
dest.Int64 = 0
dest.Valid = false
} else {
dest.Int64 = getInt64(bind.pbuf)
dest.Valid = true
}
case *uint:
*dest = uint(getUint64(bind.pbuf))
case *uint64:
*dest = getUint64(bind.pbuf)
case *uint32:
*dest = uint32(getUint64(bind.pbuf))
case *uint16:
*dest = uint16(getUint64(bind.pbuf))
case *uint8:
*dest = uint8(getUint64(bind.pbuf))
case *uintptr:
*dest = uintptr(getUint64(bind.pbuf))
case *float64:
buf := (*[8]byte)(bind.pbuf)[0:8]
var data float64
err = binary.Read(bytes.NewReader(buf), binary.LittleEndian, &data)
if err != nil {
return fmt.Errorf("binary read for column %v - error: %v", i, err)
}
*dest = data
case *float32:
// statement is using SQLT_BDOUBLE to bind
// need to read as float64 because of the 8 bits
buf := (*[8]byte)(bind.pbuf)[0:8]
var data float64
err = binary.Read(bytes.NewReader(buf), binary.LittleEndian, &data)
if err != nil {
return fmt.Errorf("binary read for column %v - error: %v", i, err)
}
*dest = float32(data)
case *sql.NullFloat64:
if *bind.indicator == -1 {
dest.Float64 = 0
dest.Valid = false
} else {
buf := (*[8]byte)(bind.pbuf)[0:8]
var data float64
err = binary.Read(bytes.NewReader(buf), binary.LittleEndian, &data)
if err != nil {
return fmt.Errorf("binary read for column %v - error: %v", i, err)
}
dest.Float64 = data
dest.Valid = true
}
case *bool:
buf := (*[1 << 30]byte)(bind.pbuf)[0:1]
*dest = buf[0] != 0
case *sql.NullBool:
if *bind.indicator == -1 {
dest.Bool = false
dest.Valid = false
} else {
buf := (*[1 << 30]byte)(bind.pbuf)[0:1]
dest.Bool = buf[0] != 0
dest.Valid = true
}
case *[]byte:
switch {
case *bind.indicator > 0: // indicator variable is the actual length before truncation
if int(*bind.indicator)-int(*bind.length) < 0 {
return fmt.Errorf("spaces less than 0 for column %v", i)
}
*dest = C.GoBytes(bind.pbuf, C.int(*bind.indicator))
case *bind.indicator == 0: // Normal
if bind.dataType == C.SQLT_BLOB {
lobLocator := (**C.OCILobLocator)(bind.pbuf)
*dest, err = stmt.conn.ociLobRead(*lobLocator, C.SQLCS_IMPLICIT)
if err != nil {
return err
}
} else {
*dest = C.GoBytes(bind.pbuf, C.int(*bind.length))
}
case *bind.indicator == -1: // The selected value is null
*dest = nil
case *bind.indicator == -2: // Item is greater than the length of the output variable; the item has been truncated.
*dest = C.GoBytes(bind.pbuf, C.int(*bind.length))
// TODO: should this be an error?
default:
return fmt.Errorf("unknown column indicator %d for column %v", *bind.indicator, i)
}
}
}
}
return nil
}
// ociParamGet calls OCIParamGet then returns OCIParam and error.
// OCIDescriptorFree must be called on returned OCIParam.
func (stmt *Stmt) ociParamGet(position C.ub4) (*C.OCIParam, error) {
var paramTemp *C.OCIParam
param := ¶mTemp
result := C.OCIParamGet(
unsafe.Pointer(stmt.stmt), // A statement handle or describe handle
C.OCI_HTYPE_STMT, // Handle type: OCI_HTYPE_STMT, for a statement handle
stmt.conn.errHandle, // An error handle
(*unsafe.Pointer)(unsafe.Pointer(param)), // A descriptor of the parameter at the position
position, // Position number in the statement handle or describe handle. A parameter descriptor will be returned for this position.
)
err := stmt.conn.getError(result)
if err != nil {
return nil, err
}
return *param, nil
}
// ociAttrGet calls OCIAttrGet with OCIStmt then returns attribute size and error.
// The attribute value is stored into passed value.
func (stmt *Stmt) ociAttrGet(value unsafe.Pointer, attributeType C.ub4) (C.ub4, error) {
var size C.ub4
result := C.OCIAttrGet(
unsafe.Pointer(stmt.stmt), // Pointer to a handle type
C.OCI_HTYPE_STMT, // The handle type: OCI_HTYPE_STMT, for a statement handle
value, // Pointer to the storage for an attribute value
&size, // The size of the attribute value
attributeType, // The attribute type: https://docs.oracle.com/cd/B19306_01/appdev.102/b14250/ociaahan.htm
stmt.conn.errHandle, // An error handle
)
return size, stmt.conn.getError(result)
}
// ociBindByName calls OCIBindByName, then returns bind handle and error.
func (stmt *Stmt) ociBindByName(name []byte, bind *bindStruct) error {
result := C.OCIBindByName(
stmt.stmt, // The statement handle
&bind.bindHandle, // The bind handle that is implicitly allocated by this call. The handle is freed implicitly when the statement handle is deallocated.
stmt.conn.errHandle, // An error handle
(*C.OraText)(&name[0]), // The placeholder, specified by its name, that maps to a variable in the statement associated with the statement handle.
C.sb4(len(name)), // The length of the name specified in placeholder, in number of bytes regardless of the encoding.
bind.pbuf, // The pointer to a data value or an array of data values of type specified in the dty parameter
bind.maxSize, // The maximum size possible in bytes of any data value for this bind variable
bind.dataType, // The data type of the values being bound
unsafe.Pointer(bind.indicator), // Pointer to an indicator variable or array
bind.length, // lengths are in bytes in general
nil, // Pointer to the array of column-level return codes
0, // A maximum array length parameter
nil, // Current array length parameter
C.OCI_DEFAULT, // The mode. Recommended to set to OCI_DEFAULT, which makes the bind variable have the same encoding as its statement.
)
return stmt.conn.getError(result)
}
// ociBindByPos calls OCIBindByPos, then returns bind handle and error.
func (stmt *Stmt) ociBindByPos(position C.ub4, bind *bindStruct) error {
result := C.OCIBindByPos(
stmt.stmt, // The statement handle
&bind.bindHandle, // The bind handle that is implicitly allocated by this call. The handle is freed implicitly when the statement handle is deallocated.