/
NodeForEach.go
102 lines (97 loc) · 2.34 KB
/
NodeForEach.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
package ast
import (
"bytes"
"reflect"
)
//foreach 节点
type NodeForEach struct {
childs []Node
t NodeType
collection string
index string
item string
open string
close string
separator string
}
func (it *NodeForEach) Type() NodeType {
return NForEach
}
func (it *NodeForEach) Eval(env map[string]interface{}) ([]byte, error) {
if it.collection == "" {
panic(`[GoMybatis] collection value can not be "" in <foreach collection=""> !`)
}
var tempSql bytes.Buffer
var datas = env[it.collection]
var collectionValue = reflect.ValueOf(datas)
if collectionValue.Kind() != reflect.Slice && collectionValue.Kind() != reflect.Map {
panic(`[GoMybatis] collection value must be a slice or map !`)
}
var collectionValueLen = collectionValue.Len()
if collectionValueLen == 0 {
return nil, nil
}
if it.index == "" {
it.index = "index"
}
if it.item == "" {
it.item = "item"
}
switch collectionValue.Kind() {
case reflect.Map:
var mapKeys = collectionValue.MapKeys()
var collectionKeyLen = len(mapKeys)
if collectionKeyLen == 0 {
return nil, nil
}
var tempArgMap = env
for _, keyValue := range mapKeys {
var key = keyValue.Interface()
var collectionItem = collectionValue.MapIndex(keyValue)
if it.item != "" {
tempArgMap[it.item] = collectionItem.Interface()
}
tempArgMap[it.index] = key
var r, err = DoChildNodes(it.childs, tempArgMap)
if err != nil {
return nil, err
}
if r != nil {
tempSql.Write(r)
}
tempSql.WriteString(it.separator)
delete(tempArgMap, it.item)
}
break
case reflect.Slice:
var tempArgMap = env
for i := 0; i < collectionValueLen; i++ {
var collectionItem = collectionValue.Index(i)
if it.item != "" {
tempArgMap[it.item] = collectionItem.Interface()
}
if it.index != "" {
tempArgMap[it.index] = i
}
var r, err = DoChildNodes(it.childs, tempArgMap)
if err != nil {
return nil, err
}
if r != nil {
tempSql.Write(r)
}
tempSql.WriteString(it.separator)
delete(tempArgMap, it.item)
}
break
}
var newTempSql bytes.Buffer
var tempSqlString = bytes.Trim(tempSql.Bytes(), it.separator)
tempSql.Reset()
newTempSql.WriteString(it.open)
newTempSql.Write(tempSqlString)
newTempSql.WriteString(it.close)
var newTempSqlBytes = newTempSql.Bytes()
newTempSql.Reset()
return newTempSqlBytes, nil
}