-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathses.go
640 lines (597 loc) · 16.4 KB
/
ses.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
// Copyright 2014 Rana Ian. All rights reserved.
// Use of this source code is governed by The MIT License
// found in the accompanying LICENSE file.
package ora
/*
#include <oci.h>
#include <stdlib.h>
*/
import "C"
import (
"bytes"
"container/list"
"fmt"
"strings"
"sync"
"unsafe"
)
type SesCfg struct {
Username string
Password string
StmtCfg *StmtCfg
}
// NewSrvCfg creates a SrvCfg with default values.
func NewSesCfg() *SesCfg {
c := &SesCfg{}
c.StmtCfg = NewStmtCfg()
return c
}
// LogSesCfg represents Ses logging configuration values.
type LogSesCfg struct {
// Close determines whether the Ses.Close method is logged.
//
// The default is true.
Close bool
// PrepAndExe determines whether the Ses.PrepAndExe method is logged.
//
// The default is true.
PrepAndExe bool
// PrepAndQry determines whether the Ses.PrepAndQry method is logged.
//
// The default is true.
PrepAndQry bool
// Prep determines whether the Ses.Prep method is logged.
//
// The default is true.
Prep bool
// Ins determines whether the Ses.Ins method is logged.
//
// The default is true.
Ins bool
// Upd determines whether the Ses.Upd method is logged.
//
// The default is true.
Upd bool
// Sel determines whether the Ses.Sel method is logged.
//
// The default is true.
Sel bool
// StartTx determines whether the Ses.StartTx method is logged.
//
// The default is true.
StartTx bool
// Ping determines whether the Ses.Ping method is logged.
//
// The default is true.
Ping bool
// Break determines whether the Ses.Break method is logged.
//
// The default is true.
Break bool
}
// NewLogSesCfg creates a LogSesCfg with default values.
func NewLogSesCfg() LogSesCfg {
c := LogSesCfg{}
c.Close = true
c.PrepAndExe = true
c.PrepAndQry = true
c.Prep = true
c.Ins = true
c.Upd = true
c.Sel = true
c.StartTx = true
c.Ping = true
c.Break = true
return c
}
// Ses is an Oracle session associated with a server.
type Ses struct {
id uint64
cfg SesCfg
mu sync.Mutex
srv *Srv
ocisvcctx *C.OCISvcCtx
ocises *C.OCISession
isLocked bool
openStmts *stmtList
openTxs *txList
}
// Close ends a session on an Oracle server.
//
// Any open statements associated with the session are closed.
//
// Calling Close will cause Ses.IsOpen to return false. Once closed, a session
// cannot be re-opened. Call Srv.OpenSes to open a new session.
func (ses *Ses) Close() (err error) {
ses.srv.openSess.remove(ses)
return ses.close()
}
// close ends a session on an Oracle server.
// does not remove Ses from Srv.openSess
func (ses *Ses) close() (err error) {
ses.mu.Lock()
defer ses.mu.Unlock()
ses.log(_drv.cfg.Log.Ses.Close)
err = ses.checkClosed()
if err != nil {
return errE(err)
}
errs := _drv.listPool.Get().(*list.List)
defer func() {
if value := recover(); value != nil {
errs.PushBack(errR(value))
}
ses.srv = nil
ses.ocisvcctx = nil
ses.ocises = nil
ses.openStmts.clear()
ses.openTxs.clear()
_drv.sesPool.Put(ses)
multiErr := newMultiErrL(errs)
if multiErr != nil {
err = errE(*multiErr)
}
errs.Init()
_drv.listPool.Put(errs)
}()
// close transactions
// close does not rollback or commit any transactions
// Expect user to make explicit Commit or Rollback.
// Any open transactions will be timedout by the server
// if not explicitly committed or rolledback.
ses.openTxs.closeAll(errs)
ses.openStmts.closeAll(errs) // close statements
// close session
// OCISessionEnd invalidates oci session handle; no need to free session.ocises
r := C.OCISessionEnd(
ses.ocisvcctx, //OCISvcCtx *svchp,
ses.srv.env.ocierr, //OCIError *errhp,
ses.ocises, //OCISession *usrhp,
C.OCI_DEFAULT) //ub4 mode );
if r == C.OCI_ERROR {
errs.PushBack(errE(ses.srv.env.ociError()))
}
return nil
}
// PrepAndExe prepares and executes a SQL statement returning the number of rows
// affected and a possible error.
func (ses *Ses) PrepAndExe(sql string, params ...interface{}) (rowsAffected uint64, err error) {
defer func() {
if value := recover(); value != nil {
err = errR(value)
}
}()
ses.log(_drv.cfg.Log.Ses.PrepAndExe)
err = ses.checkClosed()
if err != nil {
return 0, errE(err)
}
stmt, err := ses.Prep(sql)
defer func() {
if stmt != nil {
err0 := stmt.Close()
if err == nil { // don't overwrite original err
err = err0
}
}
}()
if err != nil {
return 0, errE(err)
}
rowsAffected, err = stmt.Exe(params...)
if err != nil {
return rowsAffected, errE(err)
}
return rowsAffected, nil
}
// PrepAndQry prepares a SQL statement and queries an Oracle server returning
// an *Rset and a possible error.
//
// If an error occurs during Prep or Qry a nil *Rset will be returned.
//
// The *Stmt internal to this method is automatically closed when the *Rset
// retrieves all rows or returns an error.
func (ses *Ses) PrepAndQry(sql string, params ...interface{}) (rset *Rset, err error) {
ses.log(_drv.cfg.Log.Ses.PrepAndQry)
err = ses.checkClosed()
if err != nil {
return nil, errE(err)
}
stmt, err := ses.Prep(sql)
if err != nil {
defer stmt.Close()
return nil, errE(err)
}
rset, err = stmt.Qry(params...)
if err != nil {
defer stmt.Close()
return nil, errE(err)
}
rset.autoClose = true
return rset, nil
}
// Prep prepares a sql statement returning a *Stmt and possible error.
func (ses *Ses) Prep(sql string, gcts ...GoColumnType) (stmt *Stmt, err error) {
ses.mu.Lock()
defer ses.mu.Unlock()
defer func() {
if value := recover(); value != nil {
err = errR(value)
}
}()
ses.log(_drv.cfg.Log.Ses.Prep, sql)
err = ses.checkClosed()
if err != nil {
return nil, errE(err)
}
// allocate statement handle
upOciStmt, err := ses.srv.env.allocOciHandle(C.OCI_HTYPE_STMT)
if err != nil {
return nil, errE(err)
}
ocistmt := (*C.OCIStmt)(upOciStmt)
cSql := C.CString(sql) // prepare sql text with statement handle
defer C.free(unsafe.Pointer(cSql))
r := C.OCIStmtPrepare2(
ses.ocisvcctx, // OCISvcCtx *svchp,
&ocistmt, // OCIStmt *stmtp,
ses.srv.env.ocierr, // OCIError *errhp,
(*C.OraText)(unsafe.Pointer(cSql)), // const OraText *stmt,
C.ub4(len(sql)), // ub4 stmt_len,
nil, // const OraText *key,
C.ub4(0), // ub4 keylen,
C.OCI_NTV_SYNTAX, // ub4 language,
C.OCI_DEFAULT) // ub4 mode );
if r == C.OCI_ERROR {
return nil, errE(ses.srv.env.ociError())
}
// set stmt struct
stmt = _drv.stmtPool.Get().(*Stmt)
stmt.ses = ses
stmt.ocistmt = (*C.OCIStmt)(ocistmt)
stmtCfg := ses.cfg.StmtCfg
if stmtCfg == nil {
stmtCfg = NewStmtCfg()
}
if !ses.srv.dbIsUTF8 && stmtCfg.stringPtrBufferSize > 1000 {
stmtCfg.stringPtrBufferSize = 1000
}
stmt.cfg = *stmtCfg
stmt.sql = sql
stmt.gcts = gcts
if stmt.id == 0 {
stmt.id = _drv.stmtId.nextId()
}
err = stmt.attr(unsafe.Pointer(&stmt.stmtType), 4, C.OCI_ATTR_STMT_TYPE) // determine statement type
if err != nil {
return nil, errE(err)
}
ses.openStmts.add(stmt)
return stmt, nil
}
// Ins composes, prepares and executes a sql INSERT statement returning a
// possible error.
//
// Ins offers convenience when specifying a long list of sql columns.
//
// Ins expects at least two column name-value pairs where the last pair will be
// a part of a sql RETURNING clause. The last column name is expected to be an
// identity column returning an Oracle-generated value. The last value specified
// to the variadic parameter 'columnPairs' is expected to be a pointer capable
// of receiving the identity value.
func (ses *Ses) Ins(tbl string, columnPairs ...interface{}) (err error) {
ses.log(_drv.cfg.Log.Ses.Ins)
err = ses.checkClosed()
if err != nil {
return errE(err)
}
if tbl == "" {
return errF("tbl is empty.")
}
if len(columnPairs) < 2 {
return errF("Parameter 'columnPairs' expects at least 2 column name-value pairs.")
}
if len(columnPairs)%2 != 0 {
return errF("Variadic parameter 'columnPairs' received an odd number of elements. Parameter 'columnPairs' expects an even number of elements.")
}
// build INSERT statement, params slice
params := make([]interface{}, len(columnPairs)/2)
buf := new(bytes.Buffer)
buf.WriteString("INSERT INTO ")
buf.WriteString(tbl)
buf.WriteString(" (")
lastColName := ""
for p := 0; p < len(params); p++ {
n := p * 2
columnName, ok := columnPairs[n].(string)
if !ok {
return errF("Variadic parameter 'columnPairs' expected an element at index %v to be of type string", n)
}
if p == len(params)-1 {
lastColName = columnName
} else {
buf.WriteString(columnName)
if p < len(params)-2 {
buf.WriteString(", ")
}
}
params[p] = columnPairs[n+1]
}
buf.WriteString(") VALUES (")
for n := 1; n < len(params); n++ {
buf.WriteString(fmt.Sprintf(":%v", n))
if n < len(params)-1 {
buf.WriteString(", ")
}
}
buf.WriteString(")")
buf.WriteString(" RETURNING ")
buf.WriteString(lastColName)
buf.WriteString(" INTO :RET_VAL")
stmt, err := ses.Prep(buf.String()) // prep
defer stmt.Close()
if err != nil {
return errE(err)
}
_, err = stmt.Exe(params...) // exe
if err != nil {
return errE(err)
}
return nil
}
// Upd composes, prepares and executes a sql UPDATE statement returning a
// possible error.
//
// Upd offers convenience when specifying a long list of sql columns.
func (ses *Ses) Upd(tbl string, columnPairs ...interface{}) (err error) {
ses.log(_drv.cfg.Log.Ses.Upd)
err = ses.checkClosed()
if err != nil {
return errE(err)
}
if tbl == "" {
return errF("tbl is empty.")
}
if len(columnPairs) < 2 {
return errF("Parameter 'columnPairs' expects at least 2 column name-value pairs.")
}
if len(columnPairs)%2 != 0 {
return errF("Variadic parameter 'columnPairs' received an odd number of elements. Parameter 'columnPairs' expects an even number of elements.")
}
// build UPDATE statement, params slice
params := make([]interface{}, len(columnPairs)/2)
buf := new(bytes.Buffer)
buf.WriteString("UPDATE ")
buf.WriteString(tbl)
buf.WriteString(" SET ")
lastColName := ""
for p := 0; p < len(params); p++ {
n := p * 2
columnName, ok := columnPairs[n].(string)
if !ok {
return errF("Variadic parameter 'columnPairs' expected an element at index %v to be of type string", n)
}
if p == len(params)-1 {
lastColName = columnName
} else {
buf.WriteString(columnName)
buf.WriteString(fmt.Sprintf(" = :%v", p+1))
if p < len(params)-2 {
buf.WriteString(", ")
}
}
params[p] = columnPairs[n+1]
}
buf.WriteString(" WHERE ")
buf.WriteString(lastColName)
buf.WriteString(" = :WHERE_VAL")
stmt, err := ses.Prep(buf.String()) // prep
defer func() {
err = stmt.Close()
if err != nil {
err = errE(err)
}
}()
if err != nil {
return errE(err)
}
_, err = stmt.Exe(params...) // exe
if err != nil {
return errE(err)
}
return nil
}
// Sel composes, prepares and queries a sql SELECT statement returning an *ora.Rset
// and possible error.
//
// Sel offers convenience when specifying a long list of sql columns with
// non-default GoColumnTypes.
//
// Specify a sql FROM clause with one or more pairs of sql column
// name-GoColumnType pairs. The FROM clause may have additional SQL clauses
// such as WHERE, HAVING, etc.
func (ses *Ses) Sel(sqlFrom string, columnPairs ...interface{}) (rset *Rset, err error) {
ses.log(_drv.cfg.Log.Ses.Sel)
err = ses.checkClosed()
if err != nil {
return nil, errE(err)
}
if len(columnPairs) == 0 {
return nil, errF("No column name-type pairs specified.")
}
if len(columnPairs)%2 != 0 {
return nil, errF("Variadic parameter 'columnPairs' received an odd number of elements. Parameter 'columnPairs' expects an even number of elements.")
}
// build select statement, gcts
gcts := make([]GoColumnType, len(columnPairs)/2)
buf := new(bytes.Buffer)
buf.WriteString("SELECT ")
for n := 0; n < len(columnPairs); n += 2 {
columnName, ok := columnPairs[n].(string)
if !ok {
return nil, errF("Variadic parameter 'columnPairs' expected an element at index %v to be of type string", n)
}
gct, ok := columnPairs[n+1].(GoColumnType)
if !ok {
return nil, errF("Variadic parameter 'columnPairs' expected an element at index %v to be of type ora.GoColumnType", n+1)
}
buf.WriteString(columnName)
if n != len(columnPairs)-2 {
buf.WriteRune(',')
}
buf.WriteRune(' ')
gcts[n/2] = gct
}
// add FROM keyword?
fromIndex := strings.Index(strings.ToUpper(sqlFrom), "FROM")
if fromIndex < 0 {
buf.WriteString("FROM ")
}
buf.WriteString(sqlFrom)
// prep
stmt, err := ses.Prep(buf.String(), gcts...)
if err != nil {
defer stmt.Close()
return nil, errE(err)
}
// qry
rset, err = stmt.Qry()
if err != nil {
defer stmt.Close()
return nil, errE(err)
}
rset.autoClose = true
return rset, nil
}
// StartTx starts an Oracle transaction returning a *Tx and possible error.
func (ses *Ses) StartTx() (tx *Tx, err error) {
ses.mu.Lock()
defer ses.mu.Unlock()
ses.log(_drv.cfg.Log.Ses.StartTx)
err = ses.checkClosed()
if err != nil {
return nil, errE(err)
}
// start transaction
// the number of seconds the transaction can be inactive
// before it is automatically terminated by the system.
// TODO: add timeout config value
var timeout C.uword = C.uword(60)
r := C.OCITransStart(
ses.ocisvcctx, //OCISvcCtx *svchp,
ses.srv.env.ocierr, //OCIError *errhp,
timeout, //uword timeout,
C.OCI_TRANS_NEW) //ub4 flags );
if r == C.OCI_ERROR {
return nil, errE(ses.srv.env.ociError())
}
tx = _drv.txPool.Get().(*Tx) // set *Tx
tx.ses = ses
if tx.id == 0 {
tx.id = _drv.txId.nextId()
}
ses.openTxs.add(tx)
return tx, nil
}
// Ping returns nil when an Oracle server is contacted; otherwise, an error.
func (ses *Ses) Ping() (err error) {
ses.mu.Lock()
defer ses.mu.Unlock()
ses.log(_drv.cfg.Log.Ses.Ping)
err = ses.checkClosed()
if err != nil {
return errE(err)
}
r := C.OCIPing(
ses.ocisvcctx, //OCISvcCtx *svchp,
ses.srv.env.ocierr, //OCIError *errhp,
C.OCI_DEFAULT) //ub4 mode );
if r == C.OCI_ERROR {
return errE(ses.srv.env.ociError())
}
return nil
}
// Break stops the currently running OCI function.
func (ses *Ses) Break() (err error) {
ses.mu.Lock()
defer ses.mu.Unlock()
ses.log(_drv.cfg.Log.Ses.Break)
err = ses.checkClosed()
if err != nil {
return errE(err)
}
r := C.OCIBreak(unsafe.Pointer(ses.ocisvcctx), ses.srv.env.ocierr)
if r == C.OCI_ERROR {
return errE(ses.srv.env.ociError())
}
return nil
}
// NumStmt returns the number of open Oracle statements.
func (ses *Ses) NumStmt() int {
ses.mu.Lock()
defer ses.mu.Unlock()
return ses.openStmts.len()
}
// NumTx returns the number of open Oracle transactions.
func (ses *Ses) NumTx() int {
ses.mu.Lock()
defer ses.mu.Unlock()
return ses.openTxs.len()
}
// SetCfg applies the specified cfg to the Ses.
//
// Open Stmts do not observe the specified cfg.
func (ses *Ses) SetCfg(cfg SesCfg) {
ses.mu.Lock()
defer ses.mu.Unlock()
ses.cfg = cfg
}
// Cfg returns the Ses's cfg.
func (ses *Ses) Cfg() *SesCfg {
ses.mu.Lock()
defer ses.mu.Unlock()
return &ses.cfg
}
// IsOpen returns true when a session is open; otherwise, false.
//
// Calling Close will cause Ses.IsOpen to return false. Once closed, a session
// cannot be re-opened. Call Srv.OpenSes to open a new session.
func (ses *Ses) IsOpen() bool {
ses.mu.Lock()
defer ses.mu.Unlock()
return ses.checkClosed() == nil
}
// checkClosed returns an error if Ses is closed. No locking occurs.
func (ses *Ses) checkClosed() error {
if ses == nil || ses.ocises == nil {
return er("Ses is closed.")
}
return ses.srv.checkClosed()
}
// sysName returns a string representing the Ses.
func (ses *Ses) sysName() string {
if ses == nil {
return "E_S_S_"
}
return ses.srv.sysName() + fmt.Sprintf("S%v", ses.id)
}
// log writes a message with an Ses system name and caller info.
func (ses *Ses) log(enabled bool, v ...interface{}) {
if enabled {
if len(v) == 0 {
_drv.cfg.Log.Logger.Infof("%v %v", ses.sysName(), callInfo(1))
} else {
_drv.cfg.Log.Logger.Infof("%v %v %v", ses.sysName(), callInfo(1), fmt.Sprint(v...))
}
}
}
// log writes a formatted message with an Ses system name and caller info.
func (ses *Ses) logF(enabled bool, format string, v ...interface{}) {
if enabled {
if len(v) == 0 {
_drv.cfg.Log.Logger.Infof("%v %v", ses.sysName(), callInfo(1))
} else {
_drv.cfg.Log.Logger.Infof("%v %v %v", ses.sysName(), callInfo(1), fmt.Sprintf(format, v...))
}
}
}