-
Notifications
You must be signed in to change notification settings - Fork 16
/
proteus_function.go
206 lines (172 loc) · 5.1 KB
/
proteus_function.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
package proteus
import (
"context"
"database/sql"
"fmt"
"reflect"
"strings"
"github.com/jonbodner/proteus/logger"
"github.com/jonbodner/proteus/mapper"
"github.com/jonbodner/stackerr"
)
type Builder struct {
adapter ParamAdapter
mappers []QueryMapper
}
func NewBuilder(adapter ParamAdapter, mappers ...QueryMapper) Builder {
return Builder{
adapter: adapter,
mappers: mappers,
}
}
func (fb Builder) BuildFunction(c context.Context, f interface{}, query string, names []string) error {
//if log level is set and not in the context, use it
if _, ok := logger.LevelFromContext(c); !ok && l != logger.OFF {
rw.RLock()
c = logger.WithLevel(c, l)
rw.RUnlock()
}
// make sure that f is of the right type (pointer to function)
funcPointerType := reflect.TypeOf(f)
//must be a pointer to func
if funcPointerType.Kind() != reflect.Ptr {
return stackerr.New("not a pointer")
}
funcType := funcPointerType.Elem()
//if not a func, error out
if funcType.Kind() != reflect.Func {
return stackerr.New("not a pointer to func")
}
//validate to make sure that the function matches what we expect
hasCtx, err := validateFunction(funcType)
if err != nil {
return err
}
var nameOrderMap map[string]int
startPos := 1
if hasCtx {
startPos = 2
}
if len(names) == 0 {
nameOrderMap = buildDummyParameters(funcType.NumIn(), startPos)
} else {
nameOrderMap = buildFuncNameOrderMap(names, startPos)
}
//check to see if the query is in a QueryMapper
query, err = lookupQuery(query, fb.mappers)
if err != nil {
return err
}
implementation, err := makeImplementation(c, funcType, query, fb.adapter, nameOrderMap)
if err != nil {
return err
}
reflect.ValueOf(f).Elem().Set(reflect.MakeFunc(funcType, implementation))
return nil
}
func buildFuncNameOrderMap(names []string, startPos int) map[string]int {
out := map[string]int{}
for k, v := range names {
out[strings.TrimSpace(v)] = k + startPos
}
return out
}
type sliceTypes []reflect.Type
func (st sliceTypes) In(i int) reflect.Type {
return st[i]
}
func (fb Builder) Exec(c context.Context, e ContextExecutor, query string, params map[string]interface{}) (int64, error) {
result, err := fb.ExecResult(c, e, query, params)
if err != nil {
return 0, err
}
count, err := result.RowsAffected()
return count, err
}
func (fb Builder) ExecResult(c context.Context, e ContextExecutor, query string, params map[string]interface{}) (sql.Result, error) {
//if log level is set and not in the context, use it
if _, ok := logger.LevelFromContext(c); !ok && l != logger.OFF {
rw.RLock()
c = logger.WithLevel(c, l)
rw.RUnlock()
}
finalQuery, queryArgs, err := fb.setupDynamicQueries(c, query, params)
if err != nil {
return nil, err
}
logger.Log(c, logger.DEBUG, fmt.Sprintln("calling", finalQuery, "with params", queryArgs))
result, err := e.ExecContext(c, finalQuery, queryArgs...)
return result, err
}
func (fb Builder) Query(c context.Context, q ContextQuerier, query string, params map[string]interface{}, output interface{}) error {
//if log level is set and not in the context, use it
if _, ok := logger.LevelFromContext(c); !ok && l != logger.OFF {
rw.RLock()
c = logger.WithLevel(c, l)
rw.RUnlock()
}
// make sure that output is a pointer to something
outputPointerType := reflect.TypeOf(output)
if outputPointerType.Kind() != reflect.Ptr {
return stackerr.New("not a pointer")
}
finalQuery, queryArgs, err := fb.setupDynamicQueries(c, query, params)
if err != nil {
return err
}
logger.Log(c, logger.DEBUG, fmt.Sprintln("calling", finalQuery, "with params", queryArgs))
rows, err := q.QueryContext(c, finalQuery, queryArgs...)
if err != nil {
return err
}
sType := outputPointerType.Elem()
qZero := reflect.Zero(sType)
builder, err := mapper.MakeBuilder(c, sType)
if err != nil {
return err
}
val, err := handleMapping(c, sType, rows, builder)
if err != nil {
return err
}
outputValue := reflect.ValueOf(output).Elem()
if val == nil {
outputValue.Set(qZero)
return nil
}
outputValue.Set(reflect.ValueOf(val).Convert(sType))
return nil
}
func (fb Builder) setupDynamicQueries(c context.Context, query string, paramsAndNames map[string]interface{}) (string, []interface{}, error) {
params := make([]interface{}, 0, len(paramsAndNames))
names := make([]string, 0, len(paramsAndNames))
for k, v := range paramsAndNames {
params = append(params, v)
names = append(names, k)
}
nameOrderMap := buildFuncNameOrderMap(names, 0)
//check to see if the query is in a QueryMapper
query, err := lookupQuery(query, fb.mappers)
if err != nil {
return "", nil, err
}
st := make(sliceTypes, 0, len(params))
args := make([]reflect.Value, 0, len(params))
for _, v := range params {
st = append(st, reflect.TypeOf(v))
args = append(args, reflect.ValueOf(v))
}
fixedQuery, paramOrder, err := buildFixedQueryAndParamOrder(c, query, nameOrderMap, st, fb.adapter)
if err != nil {
return "", nil, err
}
finalQuery, err := fixedQuery.finalize(c, args)
if err != nil {
return "", nil, err
}
queryArgs, err := buildQueryArgs(c, args, paramOrder)
if err != nil {
return "", nil, err
}
return finalQuery, queryArgs, nil
}