-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.go
74 lines (69 loc) · 1.76 KB
/
query.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
package hive
import (
"context"
hv "github.com/beltran/gohive"
"reflect"
)
func Query(ctx context.Context, cursor *hv.Cursor, fieldsIndex map[string]int, results interface{}, sql string) error {
cursor.Exec(ctx, sql)
if cursor.Err != nil {
return cursor.Err
}
modelType := reflect.TypeOf(results).Elem().Elem()
tb, er3 := Scan(cursor, modelType, fieldsIndex)
if er3 != nil {
return er3
}
for _, element := range tb {
appendToArray(results, element)
}
return nil
}
func appendToArray(arr interface{}, item interface{}) interface{} {
arrValue := reflect.ValueOf(arr)
elemValue := reflect.Indirect(arrValue)
itemValue := reflect.ValueOf(item)
if itemValue.Kind() == reflect.Ptr {
itemValue = reflect.Indirect(itemValue)
}
elemValue.Set(reflect.Append(elemValue, itemValue))
return arr
}
func Scan(cursors *hv.Cursor, modelType reflect.Type, fieldsIndex map[string]int) (t []interface{}, err error) {
if fieldsIndex == nil {
fieldsIndex, err = GetColumnIndexes(modelType)
if err != nil {
return
}
}
columns, mcols, er0 := GetColumns(cursors)
if er0 != nil {
return nil, er0
}
ctx := context.Background()
for cursors.HasMore(ctx) {
initModel := reflect.New(modelType).Interface()
r, _ := StructScan(initModel, columns, fieldsIndex)
fieldPointers := cursors.RowMap(ctx)
if cursors.Err != nil {
return t, cursors.Err
}
for _, c := range columns {
if colm, ok := mcols[c]; ok {
if v, ok := fieldPointers[colm]; ok {
if v != nil {
v = reflect.Indirect(reflect.ValueOf(v)).Interface()
if fieldValue, ok := r[c]; ok && !IsZeroOfUnderlyingType(v) {
err1 := ConvertAssign(fieldValue, v)
if err1 != nil {
return nil, err1
}
}
}
}
}
}
t = append(t, initModel)
}
return
}