forked from vesoft-inc/nebula-go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
session.go
382 lines (359 loc) · 9.99 KB
/
session.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
/*
*
* Copyright (c) 2020 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License.
*
*/
package nebula_go
import (
"fmt"
"sync"
"github.com/facebook/fbthrift/thrift/lib/go/thrift"
"github.com/vesoft-inc/nebula-go/v3/nebula"
graph "github.com/vesoft-inc/nebula-go/v3/nebula/graph"
)
type timezoneInfo struct {
offset int32
name []byte
}
type Session struct {
sessionID int64
connection *connection
connPool *ConnectionPool
log Logger
mu sync.Mutex
timezoneInfo
}
func (session *Session) reconnectWithExecuteErr(err error) error {
// Reconnect only if the tranport is closed
err2, ok := err.(thrift.TransportException)
if !ok {
return err
}
if err2.TypeID() != thrift.END_OF_FILE {
return err
}
if _err := session.reConnect(); _err != nil {
return fmt.Errorf("failed to reconnect, %s", _err.Error())
}
session.log.Info(fmt.Sprintf("Successfully reconnect to host: %s, port: %d",
session.connection.severAddress.Host, session.connection.severAddress.Port))
return nil
}
func (session *Session) executeWithReconnect(f func() (interface{}, error)) (interface{}, error) {
resp, err := f()
if err == nil {
return resp, nil
}
if err2 := session.reconnectWithExecuteErr(err); err2 != nil {
return nil, err2
}
// Execute with the new connetion
return f()
}
// ExecuteWithParameter returns the result of the given query as a ResultSet
func (session *Session) ExecuteWithParameter(stmt string, params map[string]interface{}) (*ResultSet, error) {
session.mu.Lock()
defer session.mu.Unlock()
if session.connection == nil {
return nil, fmt.Errorf("failed to execute: Session has been released")
}
paramsMap := make(map[string]*nebula.Value)
for k, v := range params {
nv, er := value2Nvalue(v)
if er != nil {
return nil, er
}
paramsMap[k] = nv
}
execFunc := func() (interface{}, error) {
resp, err := session.connection.executeWithParameter(session.sessionID, stmt, paramsMap)
if err != nil {
return nil, err
}
resSet, err := genResultSet(resp, session.timezoneInfo)
if err != nil {
return nil, err
}
return resSet, nil
}
resp, err := session.executeWithReconnect(execFunc)
if err != nil {
return nil, err
}
return resp.(*ResultSet), err
}
// Execute returns the result of the given query as a ResultSet
func (session *Session) Execute(stmt string) (*ResultSet, error) {
return session.ExecuteWithParameter(stmt, map[string]interface{}{})
}
// ExecuteJson returns the result of the given query as a json string
// Date and Datetime will be returned in UTC
// JSON struct:
// {
// "results":[
// {
// "columns":[
// ],
// "data":[
// {
// "row":[
// "row-data"
// ],
// "meta":[
// "metadata"
// ]
// }
// ],
// "latencyInUs":0,
// "spaceName":"",
// "planDesc ":{
// "planNodeDescs":[
// {
// "name":"",
// "id":0,
// "outputVar":"",
// "description":{
// "key":""
// },
// "profiles":[
// {
// "rows":1,
// "execDurationInUs":0,
// "totalDurationInUs":0,
// "otherStats":{}
// }
// ],
// "branchInfo":{
// "isDoBranch":false,
// "conditionNodeId":-1
// },
// "dependencies":[]
// }
// ],
// "nodeIndexMap":{},
// "format":"",
// "optimize_time_in_us":0
// },
// "comment ":""
// }
// ],
// "errors":[
// {
// "code": 0,
// "message": ""
// }
// ]
// }
func (session *Session) ExecuteJson(stmt string) ([]byte, error) {
return session.ExecuteJsonWithParameter(stmt, map[string]interface{}{})
}
// ExecuteJson returns the result of the given query as a json string
// Date and Datetime will be returned in UTC
// JSON struct:
// {
// "results":[
// {
// "columns":[
// ],
// "data":[
// {
// "row":[
// "row-data"
// ],
// "meta":[
// "metadata"
// ]
// }
// ],
// "latencyInUs":0,
// "spaceName":"",
// "planDesc ":{
// "planNodeDescs":[
// {
// "name":"",
// "id":0,
// "outputVar":"",
// "description":{
// "key":""
// },
// "profiles":[
// {
// "rows":1,
// "execDurationInUs":0,
// "totalDurationInUs":0,
// "otherStats":{}
// }
// ],
// "branchInfo":{
// "isDoBranch":false,
// "conditionNodeId":-1
// },
// "dependencies":[]
// }
// ],
// "nodeIndexMap":{},
// "format":"",
// "optimize_time_in_us":0
// },
// "comment ":""
// }
// ],
// "errors":[
// {
// "code": 0,
// "message": ""
// }
// ]
// }
func (session *Session) ExecuteJsonWithParameter(stmt string, params map[string]interface{}) ([]byte, error) {
session.mu.Lock()
defer session.mu.Unlock()
if session.connection == nil {
return nil, fmt.Errorf("failed to execute: Session has been released")
}
paramsMap := make(map[string]*nebula.Value)
for k, v := range params {
nv, er := value2Nvalue(v)
if er != nil {
return nil, er
}
paramsMap[k] = nv
}
execFunc := func() (interface{}, error) {
resp, err := session.connection.ExecuteJsonWithParameter(session.sessionID, stmt, paramsMap)
if err != nil {
return nil, err
}
return resp, nil
}
resp, err := session.executeWithReconnect(execFunc)
if err != nil {
return nil, err
}
return resp.([]byte), err
}
func (session *Session) reConnect() error {
newconnection, err := session.connPool.getIdleConn()
if err != nil {
err = fmt.Errorf(err.Error())
return err
}
// Release connection to pool
session.connPool.release(session.connection)
session.connection = newconnection
return nil
}
// Release logs out and releases connetion hold by session.
// The connection will be added into the activeConnectionQueue of the connection pool
// so that it could be reused.
func (session *Session) Release() {
if session == nil {
return
}
session.mu.Lock()
defer session.mu.Unlock()
if session.connection == nil {
session.log.Warn("Session has been released")
return
}
if err := session.connection.signOut(session.sessionID); err != nil {
session.log.Warn(fmt.Sprintf("Sign out failed, %s", err.Error()))
}
// Release connection to pool
session.connPool.release(session.connection)
session.connection = nil
}
func (session *Session) GetSessionID() int64 {
return session.sessionID
}
func IsError(resp *graph.ExecutionResponse) bool {
return resp.GetErrorCode() != nebula.ErrorCode_SUCCEEDED
}
// construct Slice to nebula.NList
func slice2Nlist(list []interface{}) (*nebula.NList, error) {
sv := []*nebula.Value{}
var ret nebula.NList
for _, item := range list {
nv, er := value2Nvalue(item)
if er != nil {
return nil, er
}
sv = append(sv, nv)
}
ret.Values = sv
return &ret, nil
}
// construct map to nebula.NMap
func map2Nmap(m map[string]interface{}) (*nebula.NMap, error) {
var ret nebula.NMap
kvs := map[string]*nebula.Value{}
for k, v := range m {
nv, err := value2Nvalue(v)
if err != nil {
return nil, err
}
kvs[k] = nv
}
ret.Kvs = kvs
return &ret, nil
}
// construct go-type to nebula.Value
func value2Nvalue(any interface{}) (value *nebula.Value, err error) {
value = nebula.NewValue()
if v, ok := any.(bool); ok {
value.BVal = &v
} else if v, ok := any.(int); ok {
ival := int64(v)
value.IVal = &ival
} else if v, ok := any.(float64); ok {
if v == float64(int64(v)) {
iv := int64(v)
value.IVal = &iv
} else {
value.FVal = &v
}
} else if v, ok := any.(float32); ok {
if v == float32(int64(v)) {
iv := int64(v)
value.IVal = &iv
} else {
fval := float64(v)
value.FVal = &fval
}
} else if v, ok := any.(string); ok {
value.SVal = []byte(v)
} else if any == nil {
nval := nebula.NullType___NULL__
value.NVal = &nval
} else if v, ok := any.([]interface{}); ok {
nv, er := slice2Nlist([]interface{}(v))
if er != nil {
err = er
}
value.LVal = nv
} else if v, ok := any.(map[string]interface{}); ok {
nv, er := map2Nmap(map[string]interface{}(v))
if er != nil {
err = er
}
value.MVal = nv
} else if v, ok := any.(nebula.Value); ok {
value = &v
} else if v, ok := any.(nebula.Date); ok {
value.SetDVal(&v)
} else if v, ok := any.(nebula.DateTime); ok {
value.SetDtVal(&v)
} else if v, ok := any.(nebula.Duration); ok {
value.SetDuVal(&v)
} else if v, ok := any.(nebula.Time); ok {
value.SetTVal(&v)
} else if v, ok := any.(nebula.Geography); ok {
value.SetGgVal(&v)
} else {
// unsupport other Value type, use this function carefully
err = fmt.Errorf("Only support convert boolean/float/int/string/map/list to nebula.Value but %T", any)
}
return
}