-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenv.go
378 lines (345 loc) · 9.76 KB
/
env.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
// 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 (
"container/list"
"fmt"
"strings"
"sync"
"unsafe"
)
// EnvCfg configures a new Env.
type EnvCfg struct {
// StmtCfg configures new Stmts.
StmtCfg *StmtCfg
}
// NewEnvCfg creates a EnvCfg with default values.
func NewEnvCfg() *EnvCfg {
c := &EnvCfg{}
c.StmtCfg = NewStmtCfg()
return c
}
// LogEnvCfg represents Env logging configuration values.
type LogEnvCfg struct {
// Close determines whether the Env.Close method is logged.
//
// The default is true.
Close bool
// OpenSrv determines whether the Env.OpenSrv method is logged.
//
// The default is true.
OpenSrv bool
// OpenCon determines whether the Env.OpenCon method is logged.
//
// The default is true.
OpenCon bool
}
// NewLogEnvCfg creates a LogEnvCfg with default values.
func NewLogEnvCfg() LogEnvCfg {
c := LogEnvCfg{}
c.Close = true
c.OpenSrv = true
c.OpenCon = true
return c
}
// Env represents an Oracle environment.
type Env struct {
id uint64
cfg EnvCfg
mu sync.Mutex
ocienv *C.OCIEnv
ocierr *C.OCIError
errBuf [512]C.char
ociHndMu sync.Mutex
openSrvs *srvList
openCons *conList
}
// Close disconnects from servers and resets optional fields.
func (env *Env) Close() (err error) {
env.mu.Lock()
defer env.mu.Unlock()
env.log(_drv.cfg.Log.Env.Close)
err = env.checkClosed()
if err != nil {
return errE(err)
}
errs := _drv.listPool.Get().(*list.List)
defer func() {
if value := recover(); value != nil {
errs.PushBack(errR(value))
}
_drv.openEnvs.remove(env)
env.ocienv = nil
env.ocierr = nil
env.openSrvs.clear()
env.openCons.clear()
_drv.envPool.Put(env)
multiErr := newMultiErrL(errs)
if multiErr != nil {
err = errE(*multiErr)
}
errs.Init()
_drv.listPool.Put(errs)
}()
env.openCons.closeAll(errs)
env.openSrvs.closeAll(errs)
// Free oci environment handle and all oci child handles
// The oci error handle is released as a child of the environment handle
err = env.freeOciHandle(unsafe.Pointer(env.ocienv), C.OCI_HTYPE_ENV)
if err != nil {
return errE(err)
}
return nil
}
// OpenSrv connects to an Oracle server returning a *Srv and possible error.
func (env *Env) OpenSrv(cfg *SrvCfg) (srv *Srv, err error) {
env.mu.Lock()
defer env.mu.Unlock()
env.log(_drv.cfg.Log.Env.OpenSrv)
err = env.checkClosed()
if err != nil {
return nil, errE(err)
}
if cfg == nil {
return nil, er("Parameter 'cfg' may not be nil.")
}
// allocate server handle
ocisrv, err := env.allocOciHandle(C.OCI_HTYPE_SERVER)
if err != nil {
return nil, errE(err)
}
// attach to server
cDblink := C.CString(cfg.Dblink)
defer C.free(unsafe.Pointer(cDblink))
r := C.OCIServerAttach(
(*C.OCIServer)(ocisrv), //OCIServer *srvhp,
env.ocierr, //OCIError *errhp,
(*C.OraText)(unsafe.Pointer(cDblink)), //const OraText *dblink,
C.sb4(len(cfg.Dblink)), //sb4 dblink_len,
C.OCI_DEFAULT) //ub4 mode);
if r == C.OCI_ERROR {
return nil, errE(env.ociError())
}
srv = _drv.srvPool.Get().(*Srv) // set *Srv
srv.env = env
srv.ocisrv = (*C.OCIServer)(ocisrv)
if srv.id == 0 {
srv.id = _drv.srvId.nextId()
}
srv.cfg = *cfg
if srv.cfg.StmtCfg == nil && srv.env.cfg.StmtCfg != nil {
srv.cfg.StmtCfg = &(*srv.env.cfg.StmtCfg) // copy by value so that user may change independently
}
env.openSrvs.add(srv)
return srv, nil
}
var (
conCharset = make(map[string]string, 2)
conCharsetMu sync.Mutex
)
// OpenCon starts an Oracle session on a server returning a *Con and possible error.
//
// The connection string has the form username/password@dblink e.g., scott/tiger@orcl
// dblink is a connection identifier such as a net service name,
// full connection identifier, or a simple connection identifier.
// The dblink may be defined in the client machine's tnsnames.ora file.
func (env *Env) OpenCon(str string) (con *Con, err error) {
// do not lock; calls to env.OpenSrv will lock
env.log(_drv.cfg.Log.Env.OpenCon)
err = env.checkClosed()
if err != nil {
return nil, errE(err)
}
// parse connection string
var username string
var password string
var dblink string
str = strings.TrimSpace(str)
if strings.HasPrefix(str, "/@") {
dblink = str[2:]
} else {
str = strings.Replace(str, "/", " / ", 1)
str = strings.Replace(str, "@", " @ ", 1)
_, err := fmt.Sscanf(str, "%s / %s @ %s", &username, &password, &dblink)
if err != nil {
return nil, errE(err)
}
}
srvCfg := NewSrvCfg()
srvCfg.Dblink = dblink
srv, err := env.OpenSrv(srvCfg) // open Srv
if err != nil {
return nil, errE(err)
}
sesCfg := NewSesCfg()
sesCfg.Username = username
sesCfg.Password = password
sesCfg.StmtCfg = srv.env.cfg.StmtCfg // sqlPkg StmtCfg has been configured for database/sql package
ses, err := srv.OpenSes(sesCfg) // open Ses
if err != nil {
return nil, errE(err)
}
con = _drv.conPool.Get().(*Con) // set *Con
con.env = env
con.srv = srv
con.ses = ses
if con.id == 0 {
con.id = _drv.conId.nextId()
}
conCharsetMu.Lock()
defer conCharsetMu.Unlock()
if cs, ok := conCharset[dblink]; ok {
srv.dbIsUTF8 = cs == "AL32UTF8"
return con, nil
}
if rset, err := ses.PrepAndQry(
`SELECT property_value FROM database_properties WHERE property_name = 'NLS_CHARACTERSET'`,
); err != nil {
//Log.Errorf("E%vS%vS%v] Determine database characterset: %v",
// env.id, con.id, ses.id, err)
} else if rset != nil && rset.Next() && len(rset.Row) == 1 {
//Log.Infof("E%vS%vS%v] Database characterset=%q",
// env.id, con.id, ses.id, rset.Row[0])
if cs, ok := rset.Row[0].(string); ok {
conCharset[dblink] = cs
con.srv.dbIsUTF8 = cs == "AL32UTF8"
}
}
env.openCons.add(con)
return con, nil
}
// NumSrv returns the number of open Oracle servers.
func (env *Env) NumSrv() int {
env.mu.Lock()
defer env.mu.Unlock()
return env.openSrvs.len()
}
// NumCon returns the number of open Oracle connections.
func (env *Env) NumCon() int {
env.mu.Lock()
defer env.mu.Unlock()
return env.openCons.len()
}
// SetCfg applies the specified cfg to the Env.
//
// Open Srvs do not observe the specified cfg.
func (env *Env) SetCfg(cfg *EnvCfg) {
env.mu.Lock()
defer env.mu.Unlock()
env.cfg = *cfg
}
// Cfg returns the Env's cfg.
func (env *Env) Cfg() *EnvCfg {
env.mu.Lock()
defer env.mu.Unlock()
return &env.cfg
}
// IsOpen returns true when the environment is open; otherwise, false.
//
// Calling Close will cause IsOpen to return false. Once closed, the environment
// may be re-opened by calling Open.
func (env *Env) IsOpen() bool {
env.mu.Lock()
defer env.mu.Unlock()
return env.ocienv != nil
}
// checkClosed returns an error if Env is closed. No locking occurs.
func (env *Env) checkClosed() error {
if env == nil || env.ocienv == nil {
return er("Env is closed.")
}
return nil
}
// sysName returns a string representing the Env.
func (env *Env) sysName() string {
return fmt.Sprintf("E%v", env.id)
}
// log writes a message with an Env system name and caller info.
func (env *Env) log(enabled bool, v ...interface{}) {
if enabled {
if len(v) == 0 {
_drv.cfg.Log.Logger.Infof("%v %v", env.sysName(), callInfo(1))
} else {
_drv.cfg.Log.Logger.Infof("%v %v %v", env.sysName(), callInfo(1), fmt.Sprint(v...))
}
}
}
// log writes a formatted message with an Env system name and caller info.
func (env *Env) logF(enabled bool, format string, v ...interface{}) {
if enabled {
if len(v) == 0 {
_drv.cfg.Log.Logger.Infof("%v %v", env.sysName(), callInfo(1))
} else {
_drv.cfg.Log.Logger.Infof("%v %v %v", env.sysName(), callInfo(1), fmt.Sprintf(format, v...))
}
}
}
// allocateOciHandle allocates an oci handle. No locking occurs.
func (env *Env) allocOciHandle(handleType C.ub4) (unsafe.Pointer, error) {
env.ociHndMu.Lock()
defer env.ociHndMu.Unlock()
// OCIHandleAlloc returns: OCI_SUCCESS, OCI_INVALID_HANDLE
var handle unsafe.Pointer
r := C.OCIHandleAlloc(
unsafe.Pointer(env.ocienv), //const void *parenth,
&handle, //void **hndlpp,
handleType, //ub4 type,
C.size_t(0), //size_t xtramem_sz,
nil) //void **usrmempp
if r == C.OCI_INVALID_HANDLE {
return nil, er("Unable to allocate handle")
}
return handle, nil
}
// freeOciHandle deallocates an oci handle. No locking occurs.
func (env *Env) freeOciHandle(ociHandle unsafe.Pointer, handleType C.ub4) error {
env.ociHndMu.Lock()
defer env.ociHndMu.Unlock()
// OCIHandleFree returns: OCI_SUCCESS, OCI_INVALID_HANDLE, or OCI_ERROR
r := C.OCIHandleFree(
ociHandle, //void *hndlp,
handleType) //ub4 type );
if r == C.OCI_INVALID_HANDLE {
return er("Unable to free handle")
} else if r == C.OCI_ERROR {
return errE(env.ociError())
}
return nil
}
// setOciAttribute sets an attribute value on a handle or descriptor. No locking occurs.
func (env *Env) setAttr(
target unsafe.Pointer,
targetType C.ub4,
attribute unsafe.Pointer,
attributeSize C.ub4,
attributeType C.ub4) (err error) {
r := C.OCIAttrSet(
target, //void *trgthndlp,
targetType, //ub4 trghndltyp,
attribute, //void *attributep,
attributeSize, //ub4 size,
attributeType, //ub4 attrtype,
env.ocierr) //OCIError *errhp );
if r == C.OCI_ERROR {
return errE(env.ociError())
}
return nil
}
// getOciError gets an error returned by an Oracle server. No locking occurs.
func (env *Env) ociError() error {
var errcode C.sb4
C.OCIErrorGet(
unsafe.Pointer(env.ocierr),
1, nil,
&errcode,
(*C.OraText)(unsafe.Pointer(&env.errBuf[0])),
C.ub4(len(env.errBuf)),
C.OCI_HTYPE_ERROR)
return er(C.GoString(&env.errBuf[0]))
}