-
Notifications
You must be signed in to change notification settings - Fork 64
/
reflect.go
434 lines (371 loc) · 12 KB
/
reflect.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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
package reindexer
import (
"fmt"
"reflect"
"strconv"
"strings"
"unsafe"
"github.com/restream/reindexer/v3/bindings"
"github.com/restream/reindexer/v3/cjson"
"github.com/restream/reindexer/v3/jsonschema"
)
const (
CollateNone = bindings.CollateNone
CollateASCII = bindings.CollateASCII
CollateUTF8 = bindings.CollateUTF8
CollateNumeric = bindings.CollateNumeric
CollateCustom = bindings.CollateCustom
)
var collateModes = map[string]int{
"collate_ascii": CollateASCII,
"collate_utf8": CollateUTF8,
"collate_numeric": CollateNumeric,
"collate_custom": CollateCustom,
}
type indexOptions struct {
isArray bool
isAppenable bool
isDense bool
isPk bool
isSparse bool
rtreeType string
isUuid bool
isJoined bool
isComposite bool
}
func parseRxTags(field reflect.StructField) (idxName string, idxType string, expireAfter string, idxSettings []string) {
tagsSlice := strings.SplitN(field.Tag.Get("reindex"), ",", 3)
var idxOpts string
idxName, idxType, expireAfter, idxOpts = tagsSlice[0], "", "", ""
if len(tagsSlice) > 1 {
idxType = tagsSlice[1]
}
if len(tagsSlice) > 2 {
if idxType == "ttl" {
expireAfter = strings.SplitN(tagsSlice[2], "=", 2)[1]
} else {
idxOpts = tagsSlice[2]
}
}
idxSettings = cjson.SplitFieldOptions(idxOpts)
return
}
func parseIndexes(st reflect.Type, joined *map[string][]int) (indexDefs []bindings.IndexDef, err error) {
if err = parseIndexesImpl(&indexDefs, st, false, "", "", joined, nil); err != nil {
return nil, err
}
return indexDefs, nil
}
func parseSchema(st reflect.Type) *bindings.SchemaDef {
reflector := &jsonschema.Reflector{}
reflector.FieldIsInScheme = func(f reflect.StructField) bool {
_, _, _, idxSettings := parseRxTags(f)
if parseByKeyWord(&idxSettings, "joined") || parseByKeyWord(&idxSettings, "composite") {
return false
}
return true
}
reflector.DoNotReference = true
reflector.FullyQualifyTypeNames = true
if schema := reflector.ReflectFromType(st); schema != nil {
schemaDef := bindings.SchemaDef(*schema)
return &schemaDef
}
return nil
}
func parseIndexesImpl(indexDefs *[]bindings.IndexDef, st reflect.Type, subArray bool, reindexBasePath, jsonBasePath string, joined *map[string][]int, parsed *map[string]bool) (err error) {
if len(jsonBasePath) != 0 && !strings.HasSuffix(jsonBasePath, ".") {
jsonBasePath = jsonBasePath + "."
}
if len(reindexBasePath) != 0 && !strings.HasSuffix(reindexBasePath, ".") {
reindexBasePath = reindexBasePath + "."
}
if st.Kind() == reflect.Ptr {
st = st.Elem()
}
isParsed, parsed := cjson.IsStructParsed(st, parsed)
if isParsed {
return nil
}
for i := 0; i < st.NumField(); i++ {
field := st.Field(i)
t := field.Type
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
// Get and parse tags
jsonTag := strings.Split(field.Tag.Get("json"), ",")[0]
if len(jsonTag) == 0 && !field.Anonymous {
jsonTag = field.Name
}
jsonPath := jsonBasePath + jsonTag
idxName, idxType, expireAfter, idxSettings := parseRxTags(field)
if idxName == "-" {
continue
}
reindexPath := reindexBasePath + idxName
opts := parseOpts(&idxSettings)
if t.Kind() == reflect.Slice || t.Kind() == reflect.Array || subArray {
opts.isArray = true
}
if opts.isPk && strings.TrimSpace(idxName) == "" {
return fmt.Errorf("no index name is specified for primary key in field '%s'; jsonpath: '%s'", field.Name, jsonPath)
}
if idxType == "rtree" {
if t.Kind() != reflect.Array || t.Len() != 2 || t.Elem().Kind() != reflect.Float64 {
return fmt.Errorf("'rtree' index allowed only for [2]float64 or reindexer.Point field type (index name: '%s', field name: '%s', jsonpath: '%s')",
reindexPath, field.Name, jsonPath)
}
}
if jsonTag == "-" && !opts.isComposite && !opts.isJoined {
if reindexTag := field.Tag.Get("reindex"); reindexTag != "" {
return fmt.Errorf("non-composite/non-joined field ('%s'), marked with `json:-` can not have explicit reindex tags, but it does ('%s')", field.Name, reindexTag)
}
continue
}
if !opts.isComposite && !field.IsExported() {
if reindexTag := field.Tag.Get("reindex"); reindexTag != "" {
return fmt.Errorf("unexported non-composite field ('%s') can not have reindex tags, but it does ('%s')", field.Name, reindexTag)
}
continue
}
if opts.isComposite {
if t.Kind() != reflect.Struct || t.NumField() != 0 {
return fmt.Errorf("'composite' tag allowed only on empty on structs: Invalid tags '%v' on field '%s'",
strings.SplitN(field.Tag.Get("reindex"), ",", 3), field.Name)
}
indexDef := makeIndexDef(parseCompositeName(reindexPath), parseCompositeJsonPaths(reindexPath), idxType, "composite", opts, CollateNone, "", parseExpireAfter(expireAfter))
if err := indexDefAppend(indexDefs, indexDef, opts.isAppenable); err != nil {
return err
}
} else if t.Kind() == reflect.Struct {
if opts.isJoined {
return fmt.Errorf("joined index must be a slice of structs/pointers, but it is a single struct (index name: '%s', field name: '%s', jsonpath: '%s')",
reindexPath, field.Name, jsonPath)
}
if err := parseIndexesImpl(indexDefs, t, subArray, reindexPath, jsonPath, joined, parsed); err != nil {
return err
}
} else if (t.Kind() == reflect.Slice || t.Kind() == reflect.Array) &&
(t.Elem().Kind() == reflect.Struct || (t.Elem().Kind() == reflect.Ptr && t.Elem().Elem().Kind() == reflect.Struct)) {
// Check if field nested slice of struct
if opts.isJoined && len(idxName) > 0 {
(*joined)[idxName] = st.Field(i).Index
} else if err := parseIndexesImpl(indexDefs, t.Elem(), true, reindexPath, jsonPath, joined, parsed); err != nil {
return err
}
} else if len(idxName) > 0 {
collateMode, sortOrderLetters := parseCollate(&idxSettings)
var fieldType string
if idxType == "rtree" {
fieldType = "point"
} else if fieldType, err = getFieldType(t); err != nil {
return err
}
if opts.isUuid {
if fieldType != "string" {
return fmt.Errorf("UUID index is not applicable with '%v' field, only with 'string' (index name: '%s', field name: '%s', jsonpath: '%s')",
fieldType, reindexPath, field.Name, jsonPath)
}
fieldType = "uuid"
}
if opts.isJoined {
return fmt.Errorf("joined index must be a slice of objects/pointers, but it is a scalar value (index name: '%s', field name: '%s', jsonpath: '%s')",
reindexPath, field.Name, jsonPath)
}
indexDef := makeIndexDef(reindexPath, []string{jsonPath}, idxType, fieldType, opts, collateMode, sortOrderLetters, parseExpireAfter(expireAfter))
if err := indexDefAppend(indexDefs, indexDef, opts.isAppenable); err != nil {
return err
}
}
if len(idxSettings) > 0 {
return fmt.Errorf("unknown index settings are found: '%v'", idxSettings)
}
}
return nil
}
func parseOpts(idxSettingsBuf *[]string) indexOptions {
newIdxSettingsBuf := make([]string, 0)
var opts indexOptions
opts.rtreeType = "rstar"
for _, idxSetting := range *idxSettingsBuf {
switch idxSetting {
case "pk":
opts.isPk = true
case "dense":
opts.isDense = true
case "sparse":
opts.isSparse = true
case "appendable":
opts.isAppenable = true
case "linear", "quadratic", "greene", "rstar":
opts.rtreeType = idxSetting
case "uuid":
opts.isUuid = true
case "joined":
opts.isJoined = true
case "composite":
opts.isComposite = true
default:
newIdxSettingsBuf = append(newIdxSettingsBuf, idxSetting)
}
}
*idxSettingsBuf = newIdxSettingsBuf
return opts
}
func parseCompositeName(indexName string) string {
indexConents := strings.Split(indexName, "=")
if len(indexConents) > 1 {
indexName = indexConents[1]
}
return indexName
}
func parseCompositeJsonPaths(indexName string) []string {
indexConents := strings.Split(indexName, "=")
return strings.Split(indexConents[0], "+")
}
func parseCollate(idxSettingsBuf *[]string) (int, string) {
newIdxSettingsBuf := make([]string, 0)
collateMode := CollateNone
var sortOrderLetters string
for _, idxSetting := range *idxSettingsBuf {
// split by "=" for k-v collate setting
kvIdxSettings := strings.SplitN(idxSetting, "=", 2)
if newCollateMode, ok := collateModes[kvIdxSettings[0]]; ok {
if collateMode != CollateNone {
panic(fmt.Errorf("collate mode is already set to '%d'. Misunderstanding '%s'", collateMode, idxSetting))
}
collateMode = newCollateMode
if len(kvIdxSettings) == 2 {
sortOrderLetters = kvIdxSettings[1]
}
continue
}
newIdxSettingsBuf = append(newIdxSettingsBuf, idxSetting)
}
*idxSettingsBuf = newIdxSettingsBuf
return collateMode, sortOrderLetters
}
func parseExpireAfter(str string) int {
expireAfter := 0
if len(str) > 0 {
var err error
expireAfter, err = strconv.Atoi(str)
if err != nil {
panic(fmt.Errorf("'ExpireAfter' should be an integer value"))
}
}
return expireAfter
}
func parseByKeyWord(idxSettingsBuf *[]string, keyWord string) bool {
newIdxSettingsBuf := make([]string, 0)
isPresented := false
for _, idxSetting := range *idxSettingsBuf {
if strings.Compare(idxSetting, keyWord) == 0 {
isPresented = true
continue
}
newIdxSettingsBuf = append(newIdxSettingsBuf, idxSetting)
}
*idxSettingsBuf = newIdxSettingsBuf
return isPresented
}
func getFieldType(t reflect.Type) (string, error) {
switch t.Kind() {
case reflect.Bool:
return "bool", nil
case reflect.Int8, reflect.Int32, reflect.Int16,
reflect.Uint8, reflect.Uint32, reflect.Uint16:
return "int", nil
case reflect.Int, reflect.Uint:
if unsafe.Sizeof(int(0)) == unsafe.Sizeof(int64(0)) {
return "int64", nil
} else {
return "int", nil
}
case reflect.Int64, reflect.Uint64:
return "int64", nil
case reflect.String:
return "string", nil
case reflect.Float32, reflect.Float64:
return "double", nil
case reflect.Struct:
return "composite", nil
case reflect.Array, reflect.Slice, reflect.Ptr:
return getFieldType(t.Elem())
}
return "", errInvalidReflection
}
func getJoinedField(val reflect.Value, joined map[string][]int, name string) (ret reflect.Value) {
if idx, ok := joined[name]; ok {
ret = reflect.Indirect(reflect.Indirect(val).FieldByIndex(idx))
}
return ret
}
func makeIndexDef(index string, jsonPaths []string, indexType, fieldType string, opts indexOptions, collateMode int, sortOrder string, expireAfter int) bindings.IndexDef {
cm := ""
switch collateMode {
case bindings.CollateASCII:
cm = "ascii"
case bindings.CollateUTF8:
cm = "utf8"
case bindings.CollateNumeric:
cm = "numeric"
case bindings.CollateCustom:
cm = "custom"
}
return bindings.IndexDef{
Name: index,
JSONPaths: jsonPaths,
IndexType: indexType,
FieldType: fieldType,
IsArray: opts.isArray,
IsPK: opts.isPk,
IsDense: opts.isDense,
IsSparse: opts.isSparse,
CollateMode: cm,
SortOrder: sortOrder,
ExpireAfter: expireAfter,
RTreeType: opts.rtreeType,
}
}
func indexDefAppend(indexDefs *[]bindings.IndexDef, indexDef bindings.IndexDef, isAppendable bool) error {
name := indexDef.Name
var foundIndexPos int
var foundIndexDef bindings.IndexDef
indexDefExists := false
for pos, indexDef := range *indexDefs {
if (*indexDefs)[pos].Name == name {
indexDefExists = true
foundIndexDef = indexDef
foundIndexPos = pos
break
}
}
if !indexDefExists {
*indexDefs = append(*indexDefs, indexDef)
return nil
}
if indexDef.IndexType != foundIndexDef.IndexType {
return fmt.Errorf("index '%s' has another type: found index def is '%+v' and new index def is '%+v'", name, foundIndexDef, indexDef)
}
if len(indexDef.JSONPaths) > 0 && indexDef.IndexType != "composite" {
jsonPaths := foundIndexDef.JSONPaths
isPresented := false
for _, jsonPath := range jsonPaths {
if jsonPath == indexDef.JSONPaths[0] {
isPresented = true
break
}
}
if !isPresented {
if !isAppendable {
return fmt.Errorf("index '%s' is not appendable. Attempt to create array index with multiple JSON-paths: %v", name, indexDef.JSONPaths)
}
foundIndexDef.JSONPaths = append(foundIndexDef.JSONPaths, indexDef.JSONPaths[0])
}
foundIndexDef.IsArray = true
(*indexDefs)[foundIndexPos] = foundIndexDef
}
return nil
}