forked from go-goracle/goracle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconn.go
532 lines (490 loc) · 14.6 KB
/
conn.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
// Copyright 2017 Tamás Gulácsi
//
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package goracle
/*
#include <stdlib.h>
#include "dpiImpl.h"
*/
import "C"
import (
"context"
"database/sql"
"database/sql/driver"
"strings"
"sync"
"time"
"unsafe"
"github.com/pkg/errors"
)
const getConnection = "--GET_CONNECTION--"
const wrapResultset = "--WRAP_RESULTSET--"
// The maximum capacity is limited to (2^32 / sizeof(dpiData))-1 to remain compatible
// with 32-bit platforms. The size of a `C.dpiData` is 32 Byte on a 64-bit system, `C.dpiSubscrMessageTable` is 40 bytes.
// So this is 2^25.
// See https://github.com/go-goracle/goracle/issues/73#issuecomment-401281714
const maxArraySize = (1<<30)/C.sizeof_dpiSubscrMessageTable - 1
var _ = driver.Conn((*conn)(nil))
var _ = driver.ConnBeginTx((*conn)(nil))
var _ = driver.ConnPrepareContext((*conn)(nil))
var _ = driver.Pinger((*conn)(nil))
type conn struct {
sync.RWMutex
dpiConn *C.dpiConn
connParams ConnectionParams
inTransaction bool
Client, Server VersionInfo
setTT TraceTag
currentUser string
*drv
}
func (c *conn) getError() error {
if c == nil || c.drv == nil {
return driver.ErrBadConn
}
return c.drv.getError()
}
func (c *conn) Break() error {
c.RLock()
defer c.RUnlock()
if Log != nil {
Log("msg", "Break", "dpiConn", c.dpiConn)
}
if C.dpiConn_breakExecution(c.dpiConn) == C.DPI_FAILURE {
return errors.Wrap(c.getError(), "Break")
}
return nil
}
// Ping checks the connection's state.
//
// WARNING: as database/sql calls database/sql/driver.Open when it needs
// a new connection, but does not provide this Context,
// if the Open stalls (unreachable / firewalled host), the
// database/sql.Ping may return way after the Context.Deadline!
func (c *conn) Ping(ctx context.Context) error {
if err := ctx.Err(); err != nil {
return err
}
if err := c.ensureContextUser(ctx); err != nil {
return err
}
c.RLock()
defer c.RUnlock()
done := make(chan error, 1)
go func() {
defer close(done)
failure := C.dpiConn_ping(c.dpiConn) == C.DPI_FAILURE
if failure {
done <- maybeBadConn(errors.Wrap(c.getError(), "Ping"))
return
}
done <- nil
}()
select {
case err := <-done:
return err
case <-ctx.Done():
// select again to avoid race condition if both are done
select {
case err := <-done:
return err
default:
_ = c.Break()
return driver.ErrBadConn
}
}
}
// Prepare returns a prepared statement, bound to this connection.
func (c *conn) Prepare(query string) (driver.Stmt, error) {
return c.PrepareContext(context.Background(), query)
}
// Close invalidates and potentially stops any current
// prepared statements and transactions, marking this
// connection as no longer in use.
//
// Because the sql package maintains a free pool of
// connections and only calls Close when there's a surplus of
// idle connections, it shouldn't be necessary for drivers to
// do their own connection caching.
func (c *conn) Close() error {
if c == nil {
return nil
}
c.Lock()
defer c.Unlock()
c.setTraceTag(TraceTag{})
dpiConn := c.dpiConn
c.dpiConn = nil
if dpiConn == nil {
return nil
}
// Just to be sure, break anything in progress.
done := make(chan struct{})
go func() {
select {
case <-done:
case <-time.After(10 * time.Second):
C.dpiConn_breakExecution(dpiConn)
}
}()
rc := C.dpiConn_release(dpiConn)
close(done)
var err error
if rc == C.DPI_FAILURE {
err = errors.Wrap(c.getError(), "Close")
}
return err
}
// Begin starts and returns a new transaction.
//
// Deprecated: Drivers should implement ConnBeginTx instead (or additionally).
func (c *conn) Begin() (driver.Tx, error) {
return c.BeginTx(context.Background(), driver.TxOptions{})
}
// BeginTx starts and returns a new transaction.
// If the context is canceled by the user the sql package will
// call Tx.Rollback before discarding and closing the connection.
//
// This must check opts.Isolation to determine if there is a set
// isolation level. If the driver does not support a non-default
// level and one is set or if there is a non-default isolation level
// that is not supported, an error must be returned.
//
// This must also check opts.ReadOnly to determine if the read-only
// value is true to either set the read-only transaction property if supported
// or return an error if it is not supported.
func (c *conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
var todo []string
if opts.ReadOnly {
todo = append(todo, "READ ONLY")
} else {
todo = append(todo, "READ WRITE")
}
switch level := sql.IsolationLevel(opts.Isolation); level {
case sql.LevelDefault:
case sql.LevelReadCommitted:
todo = append(todo, "ISOLATION LEVEL READ COMMITTED")
case sql.LevelSerializable:
todo = append(todo, "ISOLATION LEVEL SERIALIZABLE")
default:
return nil, errors.Errorf("%v isolation level is not supported", sql.IsolationLevel(opts.Isolation))
}
for _, qry := range todo {
qry = "SET TRANSACTION " + qry
stmt, err := c.PrepareContext(ctx, qry)
if err == nil {
//fmt.Println(qry)
_, err = stmt.Exec(nil) //nolint:typecheck,megacheck
stmt.Close()
}
if err != nil {
return nil, maybeBadConn(errors.Wrap(err, qry))
}
}
c.RLock()
inTran := c.inTransaction
c.RUnlock()
if inTran {
return nil, errors.New("already in transaction")
}
c.Lock()
c.inTransaction = true
c.Unlock()
if tt, ok := ctx.Value(traceTagCtxKey).(TraceTag); ok {
c.Lock()
c.setTraceTag(tt)
c.Unlock()
}
return c, nil
}
// PrepareContext returns a prepared statement, bound to this connection.
// context is for the preparation of the statement,
// it must not store the context within the statement itself.
func (c *conn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
if err := c.ensureContextUser(ctx); err != nil {
return nil, err
}
if tt, ok := ctx.Value(traceTagCtxKey).(TraceTag); ok {
c.Lock()
c.setTraceTag(tt)
c.Unlock()
}
if query == getConnection {
if Log != nil {
Log("msg", "PrepareContext", "shortcut", query)
}
return &statement{conn: c, query: query}, nil
}
cSQL := C.CString(query)
defer func() {
C.free(unsafe.Pointer(cSQL))
}()
c.RLock()
defer c.RUnlock()
var dpiStmt *C.dpiStmt
if C.dpiConn_prepareStmt(c.dpiConn, 0, cSQL, C.uint32_t(len(query)), nil, 0,
(**C.dpiStmt)(unsafe.Pointer(&dpiStmt)),
) == C.DPI_FAILURE {
return nil, maybeBadConn(errors.Wrap(c.getError(), "Prepare: "+query))
}
return &statement{conn: c, dpiStmt: dpiStmt, query: query}, nil
}
func (c *conn) Commit() error {
return c.endTran(true)
}
func (c *conn) Rollback() error {
return c.endTran(false)
}
func (c *conn) endTran(isCommit bool) error {
c.Lock()
c.inTransaction = false
var err error
//msg := "Commit"
if isCommit {
if C.dpiConn_commit(c.dpiConn) == C.DPI_FAILURE {
err = errors.Wrap(c.getError(), "Commit")
}
} else {
//msg = "Rollback"
if C.dpiConn_rollback(c.dpiConn) == C.DPI_FAILURE {
err = errors.Wrap(c.getError(), "Rollback")
}
}
c.Unlock()
//fmt.Printf("%p.%s\n", c, msg)
return err
}
type varInfo struct {
IsPLSArray bool
Typ C.dpiOracleTypeNum
NatTyp C.dpiNativeTypeNum
SliceLen, BufSize int
ObjectType *C.dpiObjectType
}
func (c *conn) newVar(vi varInfo) (*C.dpiVar, []C.dpiData, error) {
if c == nil || c.dpiConn == nil {
return nil, nil, errors.New("connection is nil")
}
isArray := C.int(0)
if vi.IsPLSArray {
isArray = 1
}
if vi.SliceLen < 1 {
vi.SliceLen = 1
}
var dataArr *C.dpiData
var v *C.dpiVar
if Log != nil {
Log("C", "dpiConn_newVar", "conn", c.dpiConn, "typ", int(vi.Typ), "natTyp", int(vi.NatTyp), "sliceLen", vi.SliceLen, "bufSize", vi.BufSize, "isArray", isArray, "objType", vi.ObjectType, "v", v)
}
if C.dpiConn_newVar(
c.dpiConn, vi.Typ, vi.NatTyp, C.uint32_t(vi.SliceLen),
C.uint32_t(vi.BufSize), 1,
isArray, vi.ObjectType,
&v, &dataArr,
) == C.DPI_FAILURE {
return nil, nil, errors.Wrapf(c.getError(), "newVar(typ=%d, natTyp=%d, sliceLen=%d, bufSize=%d)", vi.Typ, vi.NatTyp, vi.SliceLen, vi.BufSize)
}
// https://github.com/golang/go/wiki/cgo#Turning_C_arrays_into_Go_slices
/*
var theCArray *C.YourType = C.getTheArray()
length := C.getTheArrayLength()
slice := (*[maxArraySize]C.YourType)(unsafe.Pointer(theCArray))[:length:length]
*/
data := ((*[maxArraySize]C.dpiData)(unsafe.Pointer(dataArr)))[:vi.SliceLen:vi.SliceLen]
return v, data, nil
}
var _ = driver.Tx((*conn)(nil))
func (c *conn) ServerVersion() (VersionInfo, error) {
return c.Server, nil
}
func (c *conn) init() error {
if c.Server.Version != 0 {
return nil
}
var err error
if c.Client, err = c.drv.ClientVersion(); err != nil {
return err
}
var v C.dpiVersionInfo
var release *C.char
var releaseLen C.uint32_t
if C.dpiConn_getServerVersion(c.dpiConn, &release, &releaseLen, &v) == C.DPI_FAILURE {
return errors.Wrap(c.getError(), "getServerVersion")
}
c.Server.set(&v)
c.Server.ServerRelease = C.GoStringN(release, C.int(releaseLen))
return nil
}
func (c *conn) setCallTimeout(ctx context.Context) {
if c.Client.Version < 18 {
return
}
var ms C.uint32_t
if dl, ok := ctx.Deadline(); ok {
ms = C.uint32_t(time.Until(dl) / time.Millisecond)
}
// force it to be 0 (disabled)
C.dpiConn_setCallTimeout(c.dpiConn, ms)
}
func maybeBadConn(err error) error {
if err == nil {
return nil
}
if cd, ok := errors.Cause(err).(interface {
Code() int
}); ok {
// Yes, this is copied from rana/ora, but I've put it there, so it's mine. @tgulacsi
switch cd.Code() {
case 0:
if strings.Contains(err.Error(), " DPI-1002: ") {
return driver.ErrBadConn
}
// cases by experience:
// ORA-12170: TNS:Connect timeout occurred
// ORA-12528: TNS:listener: all appropriate instances are blocking new connections
// ORA-12545: Connect failed because target host or object does not exist
// ORA-24315: illegal attribute type
// ORA-28547: connection to server failed, probable Oracle Net admin error
case 12170, 12528, 12545, 24315, 28547:
//cases from https://github.com/oracle/odpi/blob/master/src/dpiError.c#L61-L94
case 22, // invalid session ID; access denied
28, // your session has been killed
31, // your session has been marked for kill
45, // your session has been terminated with no replay
378, // buffer pools cannot be created as specified
602, // internal programming exception
603, // ORACLE server session terminated by fatal error
609, // could not attach to incoming connection
1012, // not logged on
1041, // internal error. hostdef extension doesn't exist
1043, // user side memory corruption
1089, // immediate shutdown or close in progress
1092, // ORACLE instance terminated. Disconnection forced
2396, // exceeded maximum idle time, please connect again
3113, // end-of-file on communication channel
3114, // not connected to ORACLE
3122, // attempt to close ORACLE-side window on user side
3135, // connection lost contact
3136, // inbound connection timed out
12153, // TNS:not connected
12537, // TNS:connection closed
12547, // TNS:lost contact
12570, // TNS:packet reader failure
12583, // TNS:no reader
27146, // post/wait initialization failed
28511, // lost RPC connection
56600: // an illegal OCI function call was issued
return driver.ErrBadConn
}
}
return err
}
func (c *conn) setTraceTag(tt TraceTag) error {
if c.dpiConn == nil {
return nil
}
//fmt.Fprintf(os.Stderr, "setTraceTag %s\n", tt)
var err error
for nm, vv := range map[string][2]string{
"action": {c.setTT.Action, tt.Action},
"module": {c.setTT.Module, tt.Module},
"info": {c.setTT.ClientInfo, tt.ClientInfo},
"identifier": {c.setTT.ClientIdentifier, tt.ClientIdentifier},
"op": {c.setTT.DbOp, tt.DbOp},
} {
if vv[0] == vv[1] {
continue
}
v := vv[1]
var s *C.char
if v != "" {
s = C.CString(v)
}
var rc C.int
switch nm {
case "action":
rc = C.dpiConn_setAction(c.dpiConn, s, C.uint32_t(len(v)))
case "module":
rc = C.dpiConn_setModule(c.dpiConn, s, C.uint32_t(len(v)))
case "info":
rc = C.dpiConn_setClientInfo(c.dpiConn, s, C.uint32_t(len(v)))
case "identifier":
rc = C.dpiConn_setClientIdentifier(c.dpiConn, s, C.uint32_t(len(v)))
case "op":
rc = C.dpiConn_setDbOp(c.dpiConn, s, C.uint32_t(len(v)))
}
if rc == C.DPI_FAILURE && err == nil {
err = errors.Wrap(c.getError(), nm)
}
if s != nil {
C.free(unsafe.Pointer(s))
}
}
c.setTT = tt
return err
}
const traceTagCtxKey = ctxKey("tracetag")
// ContextWithTraceTag returns a context with the specified TraceTag, which will
// be set on the session used.
func ContextWithTraceTag(ctx context.Context, tt TraceTag) context.Context {
return context.WithValue(ctx, traceTagCtxKey, tt)
}
// TraceTag holds tracing information for the session. It can be set on the session
// with ContextWithTraceTag.
type TraceTag struct {
// ClientIdentifier - specifies an end user based on the logon ID, such as HR.HR
ClientIdentifier string
// ClientInfo - client-specific info
ClientInfo string
// DbOp - database operation
DbOp string
// Module - specifies a functional block, such as Accounts Receivable or General Ledger, of an application
Module string
// Action - specifies an action, such as an INSERT or UPDATE operation, in a module
Action string
}
const userpwCtxKey = ctxKey("userPw")
// ContextWithUserPassw returns a context with the specified user and password,
// to be used with heterogeneous pools.
func ContextWithUserPassw(ctx context.Context, user, password string) context.Context {
return context.WithValue(ctx, userpwCtxKey, [2]string{user, password})
}
func (c *conn) ensureContextUser(ctx context.Context) error {
if !c.connParams.HeterogeneousPool {
return nil
}
var up [2]string
var ok bool
if up, ok = ctx.Value(userpwCtxKey).([2]string); !ok || up[0] == c.currentUser {
return nil
}
if c.dpiConn != nil {
if err := c.Close(); err != nil {
return driver.ErrBadConn
}
}
c.Lock()
defer c.Unlock()
if err := c.acquireConn(up[0], up[1]); err != nil {
return err
}
return c.init()
}