forked from godror/godror
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdrv.go
1390 lines (1257 loc) · 41.9 KB
/
drv.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, 2023 The Godror Authors
//
//
// SPDX-License-Identifier: UPL-1.0 OR Apache-2.0
// Package godror is a database/sql/driver for Oracle DB.
//
// The connection string for the sql.Open("godror", dataSourceName) call can be
// the simple
//
// user="login" password="password" connectString="host:port/service_name" sysdba=true
//
// with additional params (here with the defaults):
//
// sysdba=0
// sysoper=0
// poolMinSessions=1
// poolMaxSessions=1000
// poolMaxSessionsPerShard=
// poolPingInterval=
// poolIncrement=1
// connectionClass=
// standaloneConnection=0
// enableEvents=0
// heterogeneousPool=0
// externalAuth=0
// prelim=0
// poolWaitTimeout=5m
// poolSessionMaxLifetime=1h
// poolSessionTimeout=30s
// timezone=
// noTimezoneCheck=
// perSessionTimezone=
// newPassword=
// onInit="ALTER SESSION SET current_schema=my_schema"
// configDir=
// libDir=
// stmtCacheSize=
// charset=UTF-8
// noBreakOnContextCancel=
//
// These are the defaults.
// For external authentication, user and password should be empty
// with default value(0) for heterogeneousPool parameter.
// heterogeneousPool(valid for standaloneConnection=0)
// and externalAuth parameters are internally set. For Proxy
// support , sessionuser is enclosed in brackets [sessionuser].
//
// To use a heterogeneous Pool with Proxy Support ,user and password
// parameters should be non-empty and parameter heterogeneousPool should be 1.
// If user,password are empty and heterogeneousPool is set to 1,
// different user and password can be passed in subsequent queries.
//
// Many advocate that a static session pool (min=max, incr=0)
// is better, with 1-10 sessions per CPU thread.
// See https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-7DFBA826-7CC0-4D16-B19C-31D168069B54
// You may also use ConnectionParams to configure a connection.
//
// If you specify connectionClass, that'll reuse the same session pool
// without the connectionClass, but will specify it on each session acquire.
// Thus you can cluster the session pool with classes.
//
// For connectionClass usage, see https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-CE6E4DCC-92DF-4946-92B8-2BDD9845DA35
//
// If you specify server_type as POOLED in sid, DRCP is used.
// For what can be used as "sid", see https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-E5358DEA-D619-4B7B-A799-3D2F802500F1
//
// Go strings are UTF-8, so the default charset should be used unless there's a really good reason to interfere with Oracle's character set conversion.
package godror
/*
#cgo CFLAGS: -I./odpi/include -I./odpi/src -I./odpi/embed
#include "dpi.c"
*/
import "C"
import (
"context"
"crypto/sha256"
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"github.com/godror/godror/slog"
"io"
"math"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unsafe"
"github.com/godror/godror/dsn"
)
const (
// DefaultFetchArraySize is the fetch array size by default (if not changed through FetchArraySize statement option).
DefaultFetchArraySize = C.DPI_DEFAULT_FETCH_ARRAY_SIZE
// DefaultPrefetchCountis the number of prefetched rows by default (if not changed through PrefetchCount statement option).
DefaultPrefetchCount = DefaultFetchArraySize
// DefaultArraySize is the length of the maximum PL/SQL array by default (if not changed through ArraySize statement option).
DefaultArraySize = 1 << 10
baseWaitTimeout = 30 * time.Second
)
// DriverName is set on the connection to be seen in the DB
//
// It cannot be longer than 30 bytes !
var DriverName = "godror : " + Version
const (
// DpiMajorVersion is the wanted major version of the underlying ODPI-C library.
DpiMajorVersion = C.DPI_MAJOR_VERSION
// DpiMinorVersion is the wanted minor version of the underlying ODPI-C library.
DpiMinorVersion = C.DPI_MINOR_VERSION
// DpiPatchLevel is the patch level version of the underlying ODPI-C library
DpiPatchLevel = C.DPI_PATCH_LEVEL
// DpiVersionNumber is the underlying ODPI-C version as one number (Major * 10000 + Minor * 100 + Patch)
DpiVersionNumber = C.DPI_VERSION_NUMBER
// DefaultPoolMinSessions specifies the default value for minSessions for pool creation.
DefaultPoolMinSessions = dsn.DefaultPoolMinSessions
// DefaultPoolMaxSessions specifies the default value for maxSessions for pool creation.
DefaultPoolMaxSessions = dsn.DefaultPoolMaxSessions
// DefaultSessionIncrement specifies the default value for increment for pool creation.
DefaultSessionIncrement = dsn.DefaultSessionIncrement
// DefaultPoolIncrement is a deprecated name for DefaultSessionIncrement.
DefaultPoolIncrement = DefaultSessionIncrement
// DefaultConnectionClass is empty, which allows to use the poolMinSessions created as part of session pool creation for non-DRCP. For DRCP, connectionClass needs to be explicitly mentioned.
DefaultConnectionClass = dsn.DefaultConnectionClass
// NoConnectionPoolingConnectionClass is a special connection class name to indicate no connection pooling.
// It is the same as setting standaloneConnection=1
NoConnectionPoolingConnectionClass = dsn.NoConnectionPoolingConnectionClass
// DefaultSessionTimeout is the seconds before idle pool sessions get evicted
DefaultSessionTimeout = dsn.DefaultSessionTimeout
// DefaultWaitTimeout is the milliseconds to wait for a session to become available
DefaultWaitTimeout = dsn.DefaultWaitTimeout
// DefaultMaxLifeTime is the maximum time in seconds till a pooled session may exist
DefaultMaxLifeTime = dsn.DefaultMaxLifeTime
//DefaultStandaloneConnection holds the default for standaloneConnection.
DefaultStandaloneConnection = dsn.DefaultStandaloneConnection
)
// dsn is separated out for fuzzing, but keep it as "internal"
type (
ConnectionParams = dsn.ConnectionParams
CommonParams = dsn.CommonParams
ConnParams = dsn.ConnParams
PoolParams = dsn.PoolParams
Password = dsn.Password
)
// ParseConnString is deprecated, use ParseDSN.
func ParseConnString(s string) (ConnectionParams, error) { return dsn.Parse(s) }
// ParseDSN parses the given dataSourceName and returns a ConnectionParams structure for use in sql.OpenDB(godror.NewConnector(P)).
func ParseDSN(dataSourceName string) (P ConnectionParams, err error) {
return dsn.Parse(dataSourceName)
}
func NewPassword(s string) Password { return dsn.NewPassword(s) }
func freeAccessToken(accessToken *C.dpiAccessToken) {
if accessToken == nil {
return
}
if accessToken.token != nil {
C.free(unsafe.Pointer(accessToken.token))
}
if accessToken.privateKey != nil {
C.free(unsafe.Pointer(accessToken.privateKey))
}
C.free(unsafe.Pointer(accessToken))
}
var defaultDrv = &drv{}
func init() {
sql.Register("godror", defaultDrv)
// It cannot be longer than 30 bytes !
if len(DriverName) > 30 {
DriverName = DriverName[:30]
}
}
var _ driver.Driver = (*drv)(nil)
type drv struct {
dpiContext *C.dpiContext
pools map[string]*connPool
timezones map[string]locationWithOffSecs
clientVersion VersionInfo
mu sync.RWMutex
}
func NewDriver() *drv { return &drv{} }
func (d *drv) Close() error {
if d == nil {
return nil
}
d.mu.Lock()
defer d.mu.Unlock()
dpiCtx, pools := d.dpiContext, d.pools
d.dpiContext, d.pools, d.timezones = nil, nil, nil
done := make(chan error, 1)
go func() {
for _, pool := range pools {
pool.Purge()
}
done <- nil
}()
select {
case <-done:
case <-time.After(baseWaitTimeout):
}
go func() {
if C.dpiContext_destroy(dpiCtx) == C.DPI_FAILURE {
done <- fmt.Errorf("error destroying dpiContext %p", dpiCtx)
}
close(done)
}()
select {
case err := <-done:
return err
case <-time.After(baseWaitTimeout):
return fmt.Errorf("Driver.Close: %w", context.DeadlineExceeded)
}
}
type locationWithOffSecs struct {
*time.Location
offSecs int
}
type connPool struct {
dpiPool *C.dpiPool
key string
wrapTokenCallBackCtx unsafe.Pointer
params commonAndPoolParams
}
// Purge force-closes the pool's connections then closes the pool.
func (p *connPool) Purge() {
dpiPool := p.dpiPool
p.dpiPool = nil
if dpiPool != nil {
UnRegisterTokenCallback(p.wrapTokenCallBackCtx)
C.dpiPool_close(dpiPool, C.DPI_MODE_POOL_CLOSE_FORCE)
}
}
func (p *connPool) Close() error {
dpiPool := p.dpiPool
p.dpiPool = nil
if dpiPool != nil {
C.dpiPool_release(dpiPool)
}
return nil
}
func (d *drv) checkExec(f func() C.int) error {
runtime.LockOSThread()
err := d.checkExecNoLOT(f)
runtime.UnlockOSThread()
return err
}
func (d *drv) checkExecNoLOT(f func() C.int) error {
if f() != C.DPI_FAILURE {
return nil
}
return d.getError()
}
func (d *drv) init(configDir, libDir string) error {
d.mu.RLock()
ok := d.pools != nil && d.timezones != nil && d.dpiContext != nil
d.mu.RUnlock()
if ok {
return nil
}
d.mu.Lock()
defer d.mu.Unlock()
if d.pools == nil {
d.pools = make(map[string]*connPool)
}
if d.timezones == nil {
d.timezones = make(map[string]locationWithOffSecs)
}
if d.dpiContext != nil {
return nil
}
ctxParams := new(C.dpiContextCreateParams)
ctxParams.defaultDriverName, ctxParams.defaultEncoding = cDriverName, cUTF8
if !(configDir == "" && libDir == "") {
if configDir != "" {
ctxParams.oracleClientConfigDir = C.CString(configDir)
}
if libDir != "" {
ctxParams.oracleClientLibDir = C.CString(libDir)
}
}
logger := getLogger(context.TODO())
if logger != nil {
logger.Debug("dpiContext_createWithParams", "params", ctxParams)
}
runtime.LockOSThread()
defer runtime.UnlockOSThread()
var errInfo C.dpiErrorInfo
if C.dpiContext_createWithParams(C.uint(DpiMajorVersion), C.uint(DpiMinorVersion),
ctxParams,
(**C.dpiContext)(unsafe.Pointer(&d.dpiContext)), &errInfo,
) == C.DPI_FAILURE {
return fromErrorInfo(errInfo)
}
var v C.dpiVersionInfo
if C.dpiContext_getClientVersion(d.dpiContext, &v) == C.DPI_FAILURE {
return fmt.Errorf("getClientVersion: %w", d.getError())
}
d.clientVersion.set(&v)
return nil
}
// Open returns a new connection to the database.
// The name is a string in a driver-specific format.
func (d *drv) Open(s string) (driver.Conn, error) {
c, err := d.OpenConnector(s)
if err != nil {
return nil, err
}
return d.createConnFromParams(context.Background(), c.(connector).ConnectionParams)
}
func (d *drv) ClientVersion() (VersionInfo, error) {
return d.clientVersion, nil
}
// UTF-8 is a shortcut name for AL32UTF8 in ODPI-C (and not the same as the botched UTF8).
var cUTF8, cDriverName = C.CString("UTF-8"), C.CString(DriverName)
// initCommonCreateParams initializes ODPI-C common creation parameters used for creating pools and
// standalone connections. The C strings for the encoding and driver name are
// defined at the package level for convenience.
func (d *drv) initCommonCreateParams(P *C.dpiCommonCreateParams, enableEvents bool,
stmtCacheSize int, charset string, token string, privateKey string,
accessToken *C.dpiAccessToken) error {
// initialize ODPI-C structure for common creation parameters
if err := d.checkExec(func() C.int {
return C.dpiContext_initCommonCreateParams(d.dpiContext, P)
}); err != nil {
return fmt.Errorf("initCommonCreateParams: %w", err)
}
// assign encoding and national encoding
P.encoding, P.nencoding = cUTF8, cUTF8
if charset != "" {
P.encoding = C.CString(charset)
P.nencoding = P.encoding
}
// assign driver name
P.driverName = cDriverName
P.driverNameLength = C.uint32_t(len(DriverName))
// assign creation mode; always use threaded mode in order to allow
// goroutines to function without mutexing; enable events mode, if
// requested
P.createMode = C.DPI_MODE_CREATE_DEFAULT | C.DPI_MODE_CREATE_THREADED
if enableEvents {
P.createMode |= C.DPI_MODE_CREATE_EVENTS
}
if stmtCacheSize != 0 {
if stmtCacheSize < 0 {
P.stmtCacheSize = 0
} else {
P.stmtCacheSize = C.uint32_t(stmtCacheSize)
}
}
// Token Based Authentication.
if token != "" {
accessToken.token = C.CString(token)
accessToken.tokenLength = C.uint32_t(len(token))
if privateKey != "" {
accessToken.privateKey = C.CString(privateKey)
accessToken.privateKeyLength = C.uint32_t(len(privateKey))
}
P.accessToken = accessToken
}
return nil
}
// createConn creates an ODPI-C connection with the specified parameters. If a pool is
// provided, the connection is acquired from the pool; otherwise, a standalone
// connection is created.
// second return value: true = connection is new / false = connection is from pool
func (d *drv) createConn(pool *connPool, P commonAndConnParams) (*conn, bool, error) {
// initialize driver, if necessary
if err := d.init(P.ConfigDir, P.LibDir); err != nil {
return nil, false, err
}
dc, isNew, cleanup, err := d.acquireConn(pool, P)
if err != nil {
return nil, false, err
}
var poolKey string
if pool != nil {
poolKey = pool.key
}
// create connection and initialize it, if needed
c := conn{
drv: d, dpiConn: dc,
params: dsn.ConnectionParams{CommonParams: P.CommonParams, ConnParams: P.ConnParams},
poolKey: poolKey,
objTypes: make(map[string]*ObjectType),
}
logger := P.Logger
var cs *C.char
var length C.uint
for _, td := range []struct {
Name string
Dest *string
f func() C.int
}{
{"DbDomain", &c.DomainName, func() C.int { return C.dpiConn_getDbDomain(c.dpiConn, &cs, &length) }},
{"Edition", &c.Edition, func() C.int { return C.dpiConn_getEdition(c.dpiConn, &cs, &length) }},
{"DbName", &c.DBName, func() C.int { return C.dpiConn_getDbName(c.dpiConn, &cs, &length) }},
{"ServiceName", &c.ServiceName, func() C.int { return C.dpiConn_getServiceName(c.dpiConn, &cs, &length) }},
} {
if err := c.checkExec(td.f); err != nil {
if logger != nil {
logger.Error(td.Name, "error", err)
}
} else if length != 0 && cs != nil {
*td.Dest = C.GoStringN(cs, C.int(length))
}
}
if pool != nil {
c.params.PoolParams = pool.params.PoolParams
if c.params.Username == "" {
c.params.Username = pool.params.Username
}
}
ctx, cancel := context.WithTimeout(context.Background(), nvlD(c.params.WaitTimeout, time.Minute))
err = c.init(ctx, isNew, getOnInit(&c.params.CommonParams))
cancel()
if err != nil {
_ = c.closeNotLocking()
if cleanup != nil {
cleanup()
}
return nil, false, err
}
if !guardWithFinalizers.Load() {
return &c, isNew, nil
}
if !logLingeringResourceStack.Load() {
runtime.SetFinalizer(&c, func(c *conn) {
if cleanup != nil {
cleanup()
}
if c != nil && c.dpiConn != nil {
fmt.Printf("ERROR: conn %p of createConn is not Closed!\n", c)
_ = c.closeNotLocking()
}
})
} else {
var a [4096]byte
stack := a[:runtime.Stack(a[:], false)]
runtime.SetFinalizer(&c, func(c *conn) {
if cleanup != nil {
cleanup()
}
if c != nil && c.dpiConn != nil {
fmt.Printf("ERROR: conn %p of createConn is not Closed!\n%s\n", c, stack)
_ = c.closeNotLocking()
}
})
}
return &c, isNew, nil
}
func (d *drv) acquireConn(pool *connPool, P commonAndConnParams) (*C.dpiConn, bool, func(), error) {
logger := P.Logger
if logger != nil {
logger.Debug("acquireConn", "pool", pool, "connParams", P)
}
// initialize ODPI-C structure for common creation parameters; this is only
// used when a standalone connection is being created; when a connection is
// being acquired from the pool this structure is not needed
var commonCreateParamsPtr *C.dpiCommonCreateParams
var accessToken *C.dpiAccessToken
if pool == nil {
var commonCreateParams C.dpiCommonCreateParams
if P.Token != "" { // Token Authentication requested.
mem := C.malloc(C.sizeof_dpiAccessToken)
accessToken = (*C.dpiAccessToken)(mem)
accessToken.token = nil
accessToken.privateKey = nil
defer freeAccessToken(accessToken)
}
if err := d.initCommonCreateParams(&commonCreateParams, P.EnableEvents, P.StmtCacheSize,
P.Charset, P.Token, P.PrivateKey, accessToken); err != nil {
return nil, false, nil, err
}
commonCreateParamsPtr = &commonCreateParams
}
// manage strings
var cUsername, cPassword, cNewPassword, cConnectString, cConnClass *C.char
defer func() {
if cUsername != nil {
C.free(unsafe.Pointer(cUsername))
}
if cPassword != nil {
C.free(unsafe.Pointer(cPassword))
}
if cNewPassword != nil {
C.free(unsafe.Pointer(cNewPassword))
}
if cConnectString != nil {
C.free(unsafe.Pointer(cConnectString))
}
if cConnClass != nil {
C.free(unsafe.Pointer(cConnClass))
}
}()
// initialize ODPI-C structure for connection creation parameters
var connCreateParams C.dpiConnCreateParams
if err := d.checkExec(func() C.int {
return C.dpiContext_initConnCreateParams(d.dpiContext, &connCreateParams)
}); err != nil {
return nil, false, nil, fmt.Errorf("initConnCreateParams: %w", err)
}
// assign connection class
if P.ConnClass != "" {
cConnClass = C.CString(P.ConnClass)
connCreateParams.connectionClass = cConnClass
connCreateParams.connectionClassLength = C.uint32_t(len(P.ConnClass))
}
// assign new password (only relevant for standalone connections)
if pool == nil && !P.NewPassword.IsZero() {
cNewPassword = C.CString(P.NewPassword.Secret())
connCreateParams.newPassword = cNewPassword
connCreateParams.newPasswordLength = C.uint32_t(P.NewPassword.Len())
}
// assign external authentication flag (only relevant for standalone
// connections)
if pool == nil && P.Username == "" && P.Password.IsZero() {
connCreateParams.externalAuth = 1
}
// assign authorization mode
connCreateParams.authMode = C.dpiAuthMode(C.DPI_MODE_AUTH_DEFAULT)
if P.IsSysDBA {
connCreateParams.authMode |= C.DPI_MODE_AUTH_SYSDBA
}
if P.IsSysOper {
connCreateParams.authMode |= C.DPI_MODE_AUTH_SYSOPER
}
if P.IsSysASM {
connCreateParams.authMode |= C.DPI_MODE_AUTH_SYSASM
}
if P.IsPrelim {
connCreateParams.authMode |= C.DPI_MODE_AUTH_PRELIM
}
var cleanup func()
// assign sharding keys, if applicable
if len(P.ShardingKey) > 0 {
var tempData C.dpiData
mem := C.malloc(C.sizeof_dpiShardingKeyColumn *
C.size_t(len(P.ShardingKey)))
defer C.free(mem)
columns := (*[(math.MaxInt32 - 1) / C.sizeof_dpiShardingKeyColumn]C.dpiShardingKeyColumn)(mem)
tbd := make([]func(), 0, len(P.ShardingKey))
for i, value := range P.ShardingKey {
switch value := value.(type) {
case int:
columns[i].oracleTypeNum = C.DPI_ORACLE_TYPE_NUMBER
columns[i].nativeTypeNum = C.DPI_NATIVE_TYPE_INT64
C.dpiData_setInt64(&tempData, C.int64_t(value))
case string:
columns[i].oracleTypeNum = C.DPI_ORACLE_TYPE_VARCHAR
columns[i].nativeTypeNum = C.DPI_NATIVE_TYPE_BYTES
cs := C.CString(value)
tbd = append(tbd, func() { C.free(unsafe.Pointer(cs)) })
C.dpiData_setBytes(&tempData, cs, C.uint32_t(len(value)))
case []byte:
columns[i].oracleTypeNum = C.DPI_ORACLE_TYPE_RAW
columns[i].nativeTypeNum = C.DPI_NATIVE_TYPE_BYTES
cs := (*C.char)(C.CBytes(value))
tbd = append(tbd, func() { C.free(unsafe.Pointer(cs)) })
C.dpiData_setBytes(&tempData, cs, C.uint32_t(len(value)))
default:
for _, f := range tbd {
f()
}
return nil, false, nil, errors.New("unsupported data type for sharding")
}
columns[i].value = tempData.value
}
connCreateParams.shardingKeyColumns = &columns[0]
connCreateParams.numShardingKeyColumns = C.uint8_t(len(P.ShardingKey))
if len(tbd) != 0 {
cleanup = func() {
for _, f := range tbd {
f()
}
}
}
}
// if a pool was provided, assign the pool
if pool != nil {
connCreateParams.pool = pool.dpiPool
}
// setup credentials
username, password := P.Username, P.Password.Secret()
if pool != nil && !pool.params.Heterogeneous && !pool.params.ExternalAuth {
// Only for homogeneous pool force user, password as empty.
username, password = "", ""
}
if username != "" {
cUsername = C.CString(username)
}
if password != "" {
cPassword = C.CString(password)
}
if P.ConnectString != "" {
cConnectString = C.CString(P.ConnectString)
}
// create ODPI-C connection
var dc *C.dpiConn
if err := d.checkExec(func() C.int {
return C.dpiConn_create(
d.dpiContext,
cUsername, C.uint32_t(len(username)),
cPassword, C.uint32_t(len(password)),
cConnectString, C.uint32_t(len(P.ConnectString)),
commonCreateParamsPtr,
&connCreateParams, &dc,
)
}); err != nil {
if cleanup != nil {
cleanup()
}
if pool != nil {
stats, _ := d.getPoolStats(pool)
return nil, false, nil, fmt.Errorf("pool=%p stats=%s params=%+v: %w",
pool.dpiPool, stats, connCreateParams, err)
}
return nil, false, nil, fmt.Errorf("user=%q standalone params=%+v: %w",
username, connCreateParams, err)
}
//use the information from ODPI driver if new connection has been created or it is only pooled
isNew := connCreateParams.outNewSession == 1
return dc, isNew, cleanup, nil
}
// createConnFromParams creates a driver connection given pool parameters and connection
// parameters. The pool parameters are used to either create a pool or use an
// existing cached pool.
//
// If the pool parameters are nil, no pool is used and a
// standalone connection is created instead. The connection parameters are used
// to acquire a connection from the pool specified by the pool parameters or
// are used to create a standalone connection.
func (d *drv) createConnFromParams(ctx context.Context, P dsn.ConnectionParams) (*conn, error) {
var err error
var pool *connPool
if !P.IsStandalone() {
pool, err = d.getPool(commonAndPoolParams{CommonParams: P.CommonParams, PoolParams: P.PoolParams})
if err != nil {
return nil, err
}
}
conn, isNew, err := d.createConn(pool, commonAndConnParams{CommonParams: P.CommonParams, ConnParams: P.ConnParams})
if err != nil {
return conn, err
}
if P.CommonParams.InitOnNewConn && !isNew {
return conn, nil
}
onInit := getOnInit(&conn.params.CommonParams)
if onInit == nil {
return conn, err
}
ctx, cancel := context.WithTimeout(ctx, nvlD(conn.params.WaitTimeout, time.Minute))
err = onInit(ctx, conn)
cancel()
if err != nil {
conn.Close()
return nil, err
}
return conn, nil
}
// getPool get the pool to use given the set of pool parameters provided.
//
// Pools are stored in a map keyed by a string representation of the pool parameters.
// If no pool exists, a pool is created and stored in the map.
func (d *drv) getPool(P commonAndPoolParams) (*connPool, error) {
// initialize driver, if necessary
if err := d.init(P.ConfigDir, P.LibDir); err != nil {
return nil, err
}
var usernameKey string
var passwordHash [sha256.Size]byte
if !P.Heterogeneous && !P.ExternalAuth {
// skip username being part of key in heterogeneous pools
usernameKey = P.Username
passwordHash = sha256.Sum256([]byte(P.Password.Secret())) // See issue #245
}
// determine key to use for pool
poolKey := fmt.Sprintf("%s\t%x\t%s\t%d\t%d\t%d\t%s\t%s\t%s\t%t\t%t\t%t\t%s\t%d\t%s",
usernameKey, passwordHash[:4], P.ConnectString, P.MinSessions, P.MaxSessions,
P.SessionIncrement, P.WaitTimeout, P.MaxLifeTime, P.SessionTimeout,
P.Heterogeneous, P.EnableEvents, P.ExternalAuth,
P.Timezone, P.MaxSessionsPerShard, P.PingInterval,
)
logger := P.Logger
if logger != nil {
logger.Debug("getPool", "key", poolKey)
}
// if pool already exists, return it immediately; otherwise, create a new
// pool; hold the lock while the pool is looked up (and created, if needed)
// in order to ensure that multiple goroutines do not attempt to create a
// pool
d.mu.RLock()
pool, ok := d.pools[poolKey]
d.mu.RUnlock()
if ok {
return pool, nil
}
// createPool uses checkExec wich needs getError which uses RLock,
// so we cannot Lock here, thus this little race window for
// creating a pool and throwing it away.
pool, err := d.createPool(P)
if err != nil {
return nil, err
}
d.mu.Lock()
defer d.mu.Unlock()
if poolOld, ok := d.pools[poolKey]; ok {
_ = pool.Close()
return poolOld, nil
}
pool.key = poolKey
d.pools[poolKey] = pool
return pool, nil
}
// createPool creates an ODPI-C pool with the specified parameters.
//
// This is done while holding the mutex in order to ensure that
// multiple goroutines do not attempt to create the pool at the same time.
func (d *drv) createPool(P commonAndPoolParams) (*connPool, error) {
// set up common creation parameters
var commonCreateParams C.dpiCommonCreateParams
var accessToken *C.dpiAccessToken
var wrapTokenCBCtx unsafe.Pointer // cgo.handle wrapped as void* context
if P.Token != "" { // Token Based Authentication requested.
mem := C.malloc(C.sizeof_dpiAccessToken)
accessToken = (*C.dpiAccessToken)(mem)
accessToken.token = nil
accessToken.privateKey = nil
defer freeAccessToken(accessToken)
}
if err := d.initCommonCreateParams(&commonCreateParams, P.EnableEvents, P.StmtCacheSize,
P.Charset, P.Token, P.PrivateKey, accessToken); err != nil {
return nil, err
}
// initialize ODPI-C structure for pool creation parameters
var poolCreateParams C.dpiPoolCreateParams
if err := d.checkExec(func() C.int {
return C.dpiContext_initPoolCreateParams(d.dpiContext, &poolCreateParams)
}); err != nil {
return nil, fmt.Errorf("initPoolCreateParams: %w", err)
}
// assign minimum number of sessions permitted in the pool
poolCreateParams.minSessions = dsn.DefaultPoolMinSessions
if P.MinSessions >= 0 {
poolCreateParams.minSessions = C.uint32_t(P.MinSessions)
}
// assign maximum number of sessions permitted in the pool
poolCreateParams.maxSessions = dsn.DefaultPoolMaxSessions
if P.MaxSessions > 0 {
poolCreateParams.maxSessions = C.uint32_t(P.MaxSessions)
}
// assign the number of sessions to create each time more is needed
poolCreateParams.sessionIncrement = dsn.DefaultPoolIncrement
if P.SessionIncrement > 0 {
poolCreateParams.sessionIncrement = C.uint32_t(P.SessionIncrement)
}
// assign "get" mode (always used timed wait)
poolCreateParams.getMode = C.DPI_MODE_POOL_GET_TIMEDWAIT
// assign wait timeout (number of milliseconds to wait for a session to
// become available
poolCreateParams.waitTimeout = C.uint32_t(dsn.DefaultWaitTimeout / time.Millisecond)
if P.WaitTimeout > 0 {
poolCreateParams.waitTimeout = C.uint32_t(P.WaitTimeout / time.Millisecond)
}
// assign timeout (number of seconds before idle pool session are evicted
// from the pool
poolCreateParams.timeout = C.uint32_t(dsn.DefaultSessionTimeout / time.Second)
if P.SessionTimeout > 0 {
poolCreateParams.timeout = C.uint32_t(P.SessionTimeout / time.Second)
}
// assign maximum lifetime (number of seconds a pooled session may exist)
poolCreateParams.maxLifetimeSession = C.uint32_t(dsn.DefaultMaxLifeTime / time.Second)
if P.MaxLifeTime > 0 {
poolCreateParams.maxLifetimeSession = C.uint32_t(P.MaxLifeTime / time.Second)
}
// assign external authentication flag
poolCreateParams.externalAuth = C.int(b2i(P.ExternalAuth))
// assign homogeneous pool flag; default is true so need to clear the flag
// if specifically reqeuested or if external authentication is desirable
if poolCreateParams.externalAuth == 1 || P.Heterogeneous {
if P.Token == "" {
// Reset homogeneous only for non-token Authentication
poolCreateParams.homogeneous = 0
}
}
if P.TokenCB != nil {
//typedef int (*dpiAccessTokenCallback)(void *context,
// dpiAccessToken *accessToken);
wrapTokenCBCtx = RegisterTokenCallback(&poolCreateParams, P.TokenCB, P.TokenCBCtx)
}
// setup credentials
var cUsername, cPassword, cConnectString *C.char
if P.Username != "" {
cUsername = C.CString(P.Username)
defer C.free(unsafe.Pointer(cUsername))
}
if !P.Password.IsZero() {
cPassword = C.CString(P.Password.Secret())
defer C.free(unsafe.Pointer(cPassword))
}
if P.ConnectString != "" {
cConnectString = C.CString(P.ConnectString)
defer C.free(unsafe.Pointer(cConnectString))
}
// create pool
var dp *C.dpiPool
logger := P.Logger
if logger != nil && logger.Enabled(context.TODO(), slog.LevelDebug) {
logger.Debug("C.dpiPool_create",
"user", P.Username,
"ConnectString", P.ConnectString,
"common", commonCreateParams,
"pool", fmt.Sprintf("%#v", poolCreateParams))
}
if err := d.checkExec(func() C.int {
return C.dpiPool_create(
d.dpiContext,
cUsername, C.uint32_t(len(P.Username)),
cPassword, C.uint32_t(P.Password.Len()),
cConnectString, C.uint32_t(len(P.ConnectString)),
&commonCreateParams,
&poolCreateParams,
(**C.dpiPool)(unsafe.Pointer(&dp)),
)
}); err != nil {
UnRegisterTokenCallback(wrapTokenCBCtx)
return nil, fmt.Errorf("dpoPool_create user=%s extAuth=%v: %w",
P.Username, poolCreateParams.externalAuth, err)
}
// set statement cache
stmtCacheSize := C.uint32_t(40)
if P.StmtCacheSize != 0 {
if P.StmtCacheSize < 0 {
stmtCacheSize = 0
} else {
stmtCacheSize = C.uint32_t(P.StmtCacheSize)
}
}
C.dpiPool_setStmtCacheSize(dp, stmtCacheSize)
return &connPool{dpiPool: dp, params: P, wrapTokenCallBackCtx: wrapTokenCBCtx}, nil
}
// PoolStats contains Oracle session pool statistics
type PoolStats struct {
Busy, Open, Max uint32
MaxLifetime, Timeout, WaitTimeout time.Duration
}
func (s PoolStats) String() string {
return fmt.Sprintf("busy=%d open=%d max=%d maxLifetime=%s timeout=%s waitTimeout=%s",
s.Busy, s.Open, s.Max, s.MaxLifetime, s.Timeout, s.WaitTimeout)
}
func (p PoolStats) AsDBStats() sql.DBStats {
return sql.DBStats{
MaxOpenConnections: int(p.Max),
// Pool Status
OpenConnections: int(p.Open),
InUse: int(p.Busy),
Idle: int(p.Open) - int(p.Busy),
}
}
// Stats returns PoolStats of the pool.
func (d *drv) getPoolStats(p *connPool) (stats PoolStats, err error) {
if p == nil || p.dpiPool == nil {
return stats, nil
}
stats.Max = uint32(p.params.PoolParams.MaxSessions)
runtime.LockOSThread()
defer runtime.UnlockOSThread()
var u C.uint32_t
if C.dpiPool_getBusyCount(p.dpiPool, &u) != C.DPI_FAILURE {
stats.Busy = uint32(u)
}
if C.dpiPool_getOpenCount(p.dpiPool, &u) != C.DPI_FAILURE {
stats.Open = uint32(u)
}
if C.dpiPool_getMaxLifetimeSession(p.dpiPool, &u) != C.DPI_FAILURE {
stats.MaxLifetime = time.Duration(u) * time.Second
}
if C.dpiPool_getTimeout(p.dpiPool, &u) != C.DPI_FAILURE {
stats.Timeout = time.Duration(u) * time.Second
}
if C.dpiPool_getWaitTimeout(p.dpiPool, &u) != C.DPI_FAILURE {
stats.WaitTimeout = time.Duration(u) * time.Millisecond
return stats, nil
}
return stats, d.getError()
}
type commonAndConnParams struct {
dsn.CommonParams
dsn.ConnParams
}
func (P commonAndConnParams) String() string {
return P.CommonParams.String() + " " + P.ConnParams.String()
}
type commonAndPoolParams struct {
dsn.CommonParams
dsn.PoolParams
}
func (P commonAndPoolParams) String() string {
return P.CommonParams.String() + " " + P.PoolParams.String()
}
// OraErr is an error holding the ORA-01234 code and the message.
type OraErr struct {
message, funName, action, sqlState string
code, offset int
recoverable, warning bool
}
// AsOraErr returns the underlying *OraErr and whether it succeeded.
func AsOraErr(err error) (*OraErr, bool) {
var oerr *OraErr