-
Notifications
You must be signed in to change notification settings - Fork 94
/
struct.go
243 lines (214 loc) · 5.8 KB
/
struct.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
// Copyright 2016 Qiang Xue. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package dbx
import (
"database/sql"
"reflect"
"regexp"
"strings"
"sync"
)
type (
// FieldMapFunc converts a struct field name into a DB column name.
FieldMapFunc func(string) string
structInfo struct {
nameMap map[string]*fieldInfo // mapping from struct field names to field infos
dbNameMap map[string]*fieldInfo // mapping from db column names to field infos
pkNames []string // struct field names representing PKs
}
structValue struct {
*structInfo
value reflect.Value // the struct value
tableName string // the db table name for the struct
}
fieldInfo struct {
name string // field name
dbName string // db column name
path []int // index path to the struct field reflection
}
structInfoMapKey struct {
t reflect.Type
m reflect.Value
}
)
var (
// DbTag is the name of the struct tag used to specify the column name for the associated struct field
DbTag = "db"
fieldRegex = regexp.MustCompile(`([^A-Z_])([A-Z])`)
scannerType = reflect.TypeOf((*sql.Scanner)(nil)).Elem()
structInfoMap = make(map[structInfoMapKey]*structInfo)
muStructInfoMap sync.Mutex
)
// DefaultFieldMapFunc maps a field name to a DB column name.
// The mapping rule set by this method is that words in a field name will be separated by underscores
// and the name will be turned into lower case. For example, "FirstName" maps to "first_name", and "MyID" becomes "my_id".
// See DB.FieldMapper for more details.
func DefaultFieldMapFunc(f string) string {
return strings.ToLower(fieldRegex.ReplaceAllString(f, "${1}_$2"))
}
func getStructInfo(a reflect.Type, mapper FieldMapFunc) *structInfo {
muStructInfoMap.Lock()
defer muStructInfoMap.Unlock()
key := structInfoMapKey{a, reflect.ValueOf(mapper)}
if si, ok := structInfoMap[key]; ok {
return si
}
si := &structInfo{
nameMap: map[string]*fieldInfo{},
dbNameMap: map[string]*fieldInfo{},
}
si.build(a, make([]int, 0), "", "", mapper)
structInfoMap[key] = si
return si
}
func newStructValue(model interface{}, mapper FieldMapFunc) *structValue {
value := reflect.ValueOf(model)
if value.Kind() != reflect.Ptr || value.Elem().Kind() != reflect.Struct || value.IsNil() {
return nil
}
t := reflect.TypeOf(model).Elem()
var tableName string
if tm, ok := model.(TableModel); ok {
tableName = tm.TableName()
} else {
tableName = DefaultFieldMapFunc(t.Name())
}
si := getStructInfo(t, mapper)
return &structValue{
structInfo: si,
value: value.Elem(),
tableName: tableName,
}
}
func (s *structValue) pk() map[string]interface{} {
if len(s.pkNames) == 0 {
return nil
}
return s.columns(s.pkNames, nil)
}
func (s *structValue) columns(include, exclude []string) map[string]interface{} {
v := map[string]interface{}{}
if len(include) == 0 {
for _, fi := range s.nameMap {
v[fi.dbName] = fi.getValue(s.value)
}
} else {
for _, attr := range include {
if fi, ok := s.nameMap[attr]; ok {
v[fi.dbName] = fi.getValue(s.value)
}
}
}
if len(exclude) > 0 {
for _, name := range exclude {
if fi, ok := s.nameMap[name]; ok {
delete(v, fi.dbName)
}
}
}
return v
}
// getValue returns the field value for the given struct value.
func (fi *fieldInfo) getValue(a reflect.Value) interface{} {
for _, i := range fi.path {
a = a.Field(i)
if a.Kind() == reflect.Ptr {
if a.IsNil() {
return nil
}
a = a.Elem()
}
}
return a.Interface()
}
// getField returns the reflection value of the field for the given struct value.
func (fi *fieldInfo) getField(a reflect.Value) reflect.Value {
i := 0
for ; i < len(fi.path)-1; i++ {
a = indirect(a.Field(fi.path[i]))
}
return a.Field(fi.path[i])
}
func (si *structInfo) build(a reflect.Type, path []int, namePrefix, dbNamePrefix string, mapper FieldMapFunc) {
n := a.NumField()
for i := 0; i < n; i++ {
field := a.Field(i)
tag := field.Tag.Get(DbTag)
// only handle anonymous or exported fields
if !field.Anonymous && field.PkgPath != "" || tag == "-" {
continue
}
path2 := make([]int, len(path), len(path)+1)
copy(path2, path)
path2 = append(path2, i)
ft := field.Type
if ft.Kind() == reflect.Ptr {
ft = ft.Elem()
}
name := field.Name
dbName, isPK := parseTag(tag)
if dbName == "" && !field.Anonymous {
if mapper != nil {
dbName = mapper(field.Name)
} else {
dbName = field.Name
}
}
if field.Anonymous {
name = ""
}
if ft.Kind() == reflect.Struct && !reflect.PtrTo(ft).Implements(scannerType) {
// dive into non-scanner struct
si.build(ft, path2, concat(namePrefix, name), concat(dbNamePrefix, dbName), mapper)
} else if dbName != "" {
// non-anonymous scanner or struct field
fi := &fieldInfo{
name: concat(namePrefix, name),
dbName: concat(dbNamePrefix, dbName),
path: path2,
}
si.nameMap[fi.name] = fi
si.dbNameMap[fi.dbName] = fi
if isPK {
si.pkNames = append(si.pkNames, fi.name)
}
}
}
if len(si.pkNames) == 0 {
if _, ok := si.nameMap["ID"]; ok {
si.pkNames = append(si.pkNames, "ID")
} else if _, ok := si.nameMap["Id"]; ok {
si.pkNames = append(si.pkNames, "Id")
}
}
}
func parseTag(tag string) (string, bool) {
if tag == "pk" {
return "", true
}
if strings.HasPrefix(tag, "pk,") {
return tag[3:], true
}
return tag, false
}
func concat(s1, s2 string) string {
if s1 == "" {
return s2
} else if s2 == "" {
return s1
} else {
return s1 + "." + s2
}
}
// indirect dereferences pointers and returns the actual value it points to.
// If a pointer is nil, it will be initialized with a new value.
func indirect(v reflect.Value) reflect.Value {
for v.Kind() == reflect.Ptr {
if v.IsNil() {
v.Set(reflect.New(v.Type().Elem()))
}
v = v.Elem()
}
return v
}