-
Notifications
You must be signed in to change notification settings - Fork 4
/
eval.go
302 lines (268 loc) · 6.85 KB
/
eval.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
package twowaysql
import (
"bytes"
"database/sql"
"fmt"
"reflect"
"strings"
"time"
"unicode"
"github.com/future-architect/tagscanner/runtimescan"
)
// Eval returns converted query and bind value.
// inputParams takes a tagged struct. Tags must be in the form `map:"tag_name"`.
// The return value is expected to be used to issue queries to the database
func Eval(inputQuery string, inputParams interface{}) (string, []interface{}, error) {
mapParams := map[string]interface{}{}
if inputParams != nil {
if err := encode(mapParams, inputParams); err != nil {
return "", nil, err
}
} else {
mapParams = nil
}
tokens, err := tokenize(inputQuery)
if err != nil {
return "", nil, err
}
generatedTokens, err := parseCondition(tokens, mapParams)
if err != nil {
return "", nil, err
}
convertedQuery, params, err := build(generatedTokens, mapParams)
if err != nil {
return "", nil, err
}
return arrangeWhiteSpace(convertedQuery), params, nil
}
func build(tokens []token, inputParams map[string]interface{}) (string, []interface{}, error) {
var b strings.Builder
params := make([]interface{}, 0, len(tokens))
for _, token := range tokens {
if token.kind == tkBind {
if elem, ok := inputParams[token.value]; ok {
switch elemTyp := elem.(type) {
case []string:
token.str = bindLiterals(token.str, len(elemTyp))
for _, value := range elemTyp {
params = append(params, value)
}
case []int:
token.str = bindLiterals(token.str, len(elemTyp))
for _, value := range elemTyp {
params = append(params, value)
}
case [][]interface{}:
token.str = bindTable(token.str, len(elemTyp), len(elemTyp[0]))
for _, rows := range elemTyp {
for _, columns := range rows {
params = append(params, columns)
}
}
default:
params = append(params, elem)
}
} else {
return "", nil, fmt.Errorf("no parameter that matches the bind value: %s", token.value)
}
}
b.WriteString(token.str)
}
return b.String(), params, nil
}
// ?/* ... */ -> (?, ?, ?)/* ... */みたいにする
func bindLiterals(str string, number int) string {
str = strings.TrimLeftFunc(str, func(r rune) bool {
return r != unicode.SimpleFold('/')
})
var b strings.Builder
b.WriteRune('(')
for i := 0; i < number; i++ {
b.WriteRune('?')
if i != number-1 {
b.WriteString(", ")
}
}
b.WriteRune(')')
return fmt.Sprint(b.String(), str)
}
func bindTable(str string, rowNumber, columnNumber int) string {
str = strings.TrimLeftFunc(str, func(r rune) bool {
return r != unicode.SimpleFold('/')
})
var column strings.Builder
column.WriteRune('(')
for i := 0; i < columnNumber; i++ {
column.WriteRune('?')
if i != columnNumber-1 {
column.WriteString(", ")
}
}
column.WriteRune(')')
var row strings.Builder
row.WriteRune('(')
for i := 0; i < rowNumber; i++ {
row.WriteString(column.String())
if i != rowNumber-1 {
row.WriteString(", ")
}
}
row.WriteRune(')')
return fmt.Sprint(row.String(), str)
}
// 空白が二つ以上続いていたら一つにする。=1 -> = 1のような変換はできない
// 単純な空白を想定。 -> issue: よりロバストな実装
func arrangeWhiteSpace(str string) string {
ret := ""
buff := bytes.NewBufferString(ret)
for i := 0; i < len(str); i++ {
if i < len(str)-1 && str[i] == ' ' && str[i+1] == ' ' {
continue
}
buff.WriteByte(str[i])
}
ret = buff.String()
return strings.Trim(ret, " ")
}
type encoder struct {
dest map[string]interface{}
}
func (m encoder) ParseTag(name, tagKey, tagStr, pathStr string, elemType reflect.Type) (tag interface{}, err error) {
return runtimescan.BasicParseTag(name, tagKey, tagStr, pathStr, elemType)
}
func (m *encoder) VisitField(tag, value interface{}) (err error) {
t := tag.(*runtimescan.BasicTag)
m.dest[t.Tag] = value
return nil
}
func (m encoder) EnterChild(tag interface{}) (err error) {
return nil
}
func (m encoder) LeaveChild(tag interface{}) (err error) {
return nil
}
func encode(dest map[string]interface{}, src interface{}) error {
v := reflect.ValueOf(src)
if v.Kind() == reflect.Pointer && v.Elem().Kind() == reflect.Map {
if convertToMapStringAny(v.Elem(), dest) {
return nil
}
}
if v.Kind() == reflect.Map {
if convertToMapStringAny(v, dest) {
return nil
}
}
tags := []string{"twowaysql", "db"}
if err := runtimescan.Encode(src, tags, &encoder{
dest: dest,
}); err != nil {
return err
}
// tagscanner does not support nest struct type.
encodeStructField(src, dest, tags)
return nil
}
func convertToMapStringAny(mp reflect.Value, dest map[string]interface{}) bool {
if mp.Type().Key().Kind() != reflect.String {
return false
}
for _, k := range mp.MapKeys() {
dest[k.String()] = mp.MapIndex(k).Interface()
}
return true
}
func encodeStructField(src interface{}, dest map[string]interface{}, tags []string) {
srcFieldValues := reflect.ValueOf(src)
srcFieldTyps := srcFieldValues.Type()
if srcFieldTyps.Kind() == reflect.Pointer {
srcFieldTyps = srcFieldTyps.Elem()
srcFieldValues = srcFieldValues.Elem()
}
for i := 0; i < srcFieldTyps.NumField(); i++ {
srcFieldTyp := srcFieldTyps.Field(i)
srcFieldValue := srcFieldValues.Field(i)
tagValue := getTagValue(srcFieldTyp.Tag, tags)
if srcFieldTyp.Type.Kind() != reflect.Struct {
continue
}
switch srcFieldTyp.Type.PkgPath() {
case "database/sql":
if tagValue == "" {
continue
}
encodeSQLNullTyp(srcFieldValue, dest, tagValue)
case "time":
if tagValue == "" {
continue
}
encodeTimeTyp(srcFieldValue, dest, tagValue)
default:
encodeStructField(srcFieldValue.Interface(), dest, tags)
}
}
}
func encodeSQLNullTyp(srcFieldValue reflect.Value, dest map[string]interface{}, tagValue string) {
switch v := srcFieldValue.Interface().(type) {
case sql.NullBool:
if v.Valid {
dest[tagValue] = v.Bool
} else {
dest[tagValue] = nil
}
case sql.NullByte:
// not support
return
case sql.NullFloat64:
if v.Valid {
dest[tagValue] = v.Float64
} else {
dest[tagValue] = nil
}
case sql.NullInt16:
if v.Valid {
dest[tagValue] = v.Int16
} else {
dest[tagValue] = nil
}
case sql.NullInt32:
if v.Valid {
dest[tagValue] = v.Int32
} else {
dest[tagValue] = nil
}
case sql.NullInt64:
if v.Valid {
dest[tagValue] = v.Int64
} else {
dest[tagValue] = nil
}
case sql.NullString:
if v.Valid {
dest[tagValue] = v.String
} else {
dest[tagValue] = nil
}
case sql.NullTime:
if v.Valid {
dest[tagValue] = v.Time
} else {
dest[tagValue] = nil
}
}
}
func encodeTimeTyp(srcFieldValue reflect.Value, dest map[string]interface{}, tagValue string) {
switch v := srcFieldValue.Interface().(type) {
case time.Time:
dest[tagValue] = v
}
}
func getTagValue(structTag reflect.StructTag, targetTags []string) string {
for _, t := range targetTags {
tag := structTag.Get(t)
if tag != "" {
return tag
}
}
return ""
}