Debian Codegraph @

struct.go

raw symbols SCIP
1 // Copyright 2016 Qiang Xue. All rights reserved.
2 // Use of this source code is governed by a MIT-style
3 // license that can be found in the LICENSE file.
4
5 package dbx
6
7 import (
8 "database/sql"
9 "reflect"
10 "regexp"
11 "strings"
12 "sync"
13 )
14
15 type (
16 // FieldMapFunc converts a struct field name into a DB column name.
17 FieldMapFunc func(string) string
18
19 // TableMapFunc converts a sample struct into a DB table name.
20 TableMapFunc func(a interface{}) string
21
22 structInfo struct {
23 nameMap map[string]*fieldInfo // mapping from struct field names to field infos
24 dbNameMap map[string]*fieldInfo // mapping from db column names to field infos
25 pkNames []string // struct field names representing PKs
26 }
27
28 structValue struct {
29 *structInfo
30 value reflect.Value // the struct value
31 tableName string // the db table name for the struct
32 }
33
34 fieldInfo struct {
35 name string // field name
36 dbName string // db column name
37 path []int // index path to the struct field reflection
38 }
39
40 structInfoMapKey struct {
41 t reflect.Type
42 m reflect.Value
43 }
44 )
45
46 var (
47 // DbTag is the name of the struct tag used to specify the column name for the associated struct field
48 DbTag = "db"
49
50 fieldRegex = regexp.MustCompile(`([^A-Z_])([A-Z])`)
51 scannerType = reflect.TypeOf((*sql.Scanner)(nil)).Elem()
52 postScannerType = reflect.TypeOf((*PostScanner)(nil)).Elem()
53 structInfoMap = make(map[structInfoMapKey]*structInfo)
54 muStructInfoMap sync.Mutex
55 )
56
57 // PostScanner is an optional interface used by ScanStruct.
58 type PostScanner interface {
59 // PostScan executes right after the struct has been populated
60 // with the DB values, allowing you to further normalize or validate
61 // the loaded data.
62 PostScan() error
63 }
64
65 // DefaultFieldMapFunc maps a field name to a DB column name.
66 // The mapping rule set by this method is that words in a field name will be separated by underscores
67 // and the name will be turned into lower case. For example, "FirstName" maps to "first_name", and "MyID" becomes "my_id".
68 // See DB.FieldMapper for more details.
69 func DefaultFieldMapFunc(f string) string {
70 return strings.ToLower(fieldRegex.ReplaceAllString(f, "${1}_$2"))
71 }
72
73 func getStructInfo(a reflect.Type, mapper FieldMapFunc) *structInfo {
74 muStructInfoMap.Lock()
75 defer muStructInfoMap.Unlock()
76
77 key := structInfoMapKey{a, reflect.ValueOf(mapper)}
78 if si, ok := structInfoMap[key]; ok {
79 return si
80 }
81
82 si := &structInfo{
83 nameMap: map[string]*fieldInfo{},
84 dbNameMap: map[string]*fieldInfo{},
85 }
86 si.build(a, make([]int, 0), "", "", mapper)
87 structInfoMap[key] = si
88
89 return si
90 }
91
92 func newStructValue(model interface{}, fieldMapFunc FieldMapFunc, tableMapFunc TableMapFunc) *structValue {
93 value := reflect.ValueOf(model)
94 if value.Kind() != reflect.Ptr || value.Elem().Kind() != reflect.Struct || value.IsNil() {
95 return nil
96 }
97
98 return &structValue{
99 structInfo: getStructInfo(reflect.TypeOf(model).Elem(), fieldMapFunc),
100 value: value.Elem(),
101 tableName: tableMapFunc(model),
102 }
103 }
104
105 // pk returns the primary key values indexed by the corresponding primary key column names.
106 func (s *structValue) pk() map[string]interface{} {
107 if len(s.pkNames) == 0 {
108 return nil
109 }
110 return s.columns(s.pkNames, nil)
111 }
112
113 // columns returns the struct field values indexed by their corresponding DB column names.
114 func (s *structValue) columns(include, exclude []string) map[string]interface{} {
115 v := make(map[string]interface{}, len(s.nameMap))
116 if len(include) == 0 {
117 for _, fi := range s.nameMap {
118 v[fi.dbName] = fi.getValue(s.value)
119 }
120 } else {
121 for _, attr := range include {
122 if fi, ok := s.nameMap[attr]; ok {
123 v[fi.dbName] = fi.getValue(s.value)
124 }
125 }
126 }
127 if len(exclude) > 0 {
128 for _, name := range exclude {
129 if fi, ok := s.nameMap[name]; ok {
130 delete(v, fi.dbName)
131 }
132 }
133 }
134 return v
135 }
136
137 // getValue returns the field value for the given struct value.
138 func (fi *fieldInfo) getValue(a reflect.Value) interface{} {
139 for _, i := range fi.path {
140 a = a.Field(i)
141 if a.Kind() == reflect.Ptr {
142 if a.IsNil() {
143 return nil
144 }
145 a = a.Elem()
146 }
147 }
148 return a.Interface()
149 }
150
151 // getField returns the reflection value of the field for the given struct value.
152 func (fi *fieldInfo) getField(a reflect.Value) reflect.Value {
153 i := 0
154 for ; i < len(fi.path)-1; i++ {
155 a = indirect(a.Field(fi.path[i]))
156 }
157 return a.Field(fi.path[i])
158 }
159
160 func (si *structInfo) build(a reflect.Type, path []int, namePrefix, dbNamePrefix string, mapper FieldMapFunc) {
161 n := a.NumField()
162 for i := 0; i < n; i++ {
163 field := a.Field(i)
164 tag := field.Tag.Get(DbTag)
165
166 // only handle anonymous or exported fields
167 if !field.Anonymous && field.PkgPath != "" || tag == "-" {
168 continue
169 }
170
171 path2 := make([]int, len(path), len(path)+1)
172 copy(path2, path)
173 path2 = append(path2, i)
174
175 ft := field.Type
176 if ft.Kind() == reflect.Ptr {
177 ft = ft.Elem()
178 }
179
180 name := field.Name
181 dbName, isPK := parseTag(tag)
182 if dbName == "" && !field.Anonymous {
183 if mapper != nil {
184 dbName = mapper(field.Name)
185 } else {
186 dbName = field.Name
187 }
188 }
189 if field.Anonymous {
190 name = ""
191 }
192
193 if isNestedStruct(ft) {
194 // dive into non-scanner struct
195 si.build(ft, path2, concat(namePrefix, name), concat(dbNamePrefix, dbName), mapper)
196 } else if dbName != "" {
197 // non-anonymous scanner or struct field
198 fi := &fieldInfo{
199 name: concat(namePrefix, name),
200 dbName: concat(dbNamePrefix, dbName),
201 path: path2,
202 }
203 // a field in an anonymous struct may be shadowed
204 if _, ok := si.nameMap[fi.name]; !ok || len(path2) < len(si.nameMap[fi.name].path) {
205 si.nameMap[fi.name] = fi
206 si.dbNameMap[fi.dbName] = fi
207 if isPK {
208 si.pkNames = append(si.pkNames, fi.name)
209 }
210 }
211 }
212 }
213 if len(si.pkNames) == 0 {
214 if _, ok := si.nameMap["ID"]; ok {
215 si.pkNames = append(si.pkNames, "ID")
216 } else if _, ok := si.nameMap["Id"]; ok {
217 si.pkNames = append(si.pkNames, "Id")
218 }
219 }
220 }
221
222 func isNestedStruct(t reflect.Type) bool {
223 if t.PkgPath() == "time" && t.Name() == "Time" {
224 return false
225 }
226 return t.Kind() == reflect.Struct && !reflect.PtrTo(t).Implements(scannerType)
227 }
228
229 func parseTag(tag string) (string, bool) {
230 if tag == "pk" {
231 return "", true
232 }
233 if strings.HasPrefix(tag, "pk,") {
234 return tag[3:], true
235 }
236 return tag, false
237 }
238
239 func concat(s1, s2 string) string {
240 if s1 == "" {
241 return s2
242 } else if s2 == "" {
243 return s1
244 } else {
245 return s1 + "." + s2
246 }
247 }
248
249 // indirect dereferences pointers and returns the actual value it points to.
250 // If a pointer is nil, it will be initialized with a new value.
251 func indirect(v reflect.Value) reflect.Value {
252 for v.Kind() == reflect.Ptr {
253 if v.IsNil() {
254 v.Set(reflect.New(v.Type().Elem()))
255 }
256 v = v.Elem()
257 }
258 return v
259 }
260
261 // GetTableName implements the default way of determining the table name corresponding to the given model struct
262 // or slice of structs. To get the actual table name for a model, you should use DB.TableMapFunc() instead.
263 // Do not call this method in a model's TableName() method because it will cause infinite loop.
264 func GetTableName(a interface{}) string {
265 if tm, ok := a.(TableModel); ok {
266 v := reflect.ValueOf(a)
267 if v.Kind() == reflect.Ptr && v.IsNil() {
268 a = reflect.New(v.Type().Elem()).Interface()
269 return a.(TableModel).TableName()
270 }
271 return tm.TableName()
272 }
273 t := reflect.TypeOf(a)
274 if t.Kind() == reflect.Ptr {
275 t = t.Elem()
276 }
277 if t.Kind() == reflect.Slice {
278 return GetTableName(reflect.Zero(t.Elem()).Interface())
279 }
280 return DefaultFieldMapFunc(t.Name())
281 }