-
Notifications
You must be signed in to change notification settings - Fork 1
/
reflect.go
297 lines (269 loc) · 7.01 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
package pan
import (
"fmt"
"reflect"
"sort"
"strings"
"sync"
"unicode"
"unicode/utf8"
)
const (
tagName = "sql_column" // The tag that will be read
)
var (
structReadCache = map[string][]string{}
structReadMutex sync.RWMutex
)
func validTag(s string) bool {
if s == "" {
return false
}
for _, c := range s {
if !unicode.IsLetter(c) && !unicode.IsDigit(c) && c != rune([]byte("_")[0]) && c != rune([]byte(".")[0]) && c != rune([]byte("-")[0]) {
return false
}
}
return true
}
func toSnake(s string) string {
if s == "" {
return ""
}
snake := ""
prevWasLower := false
buf := make([]byte, 4)
for _, c := range s {
if !unicode.IsLetter(c) && !unicode.IsDigit(c) {
continue
}
if unicode.IsLower(c) {
prevWasLower = true
} else if unicode.IsUpper(c) {
c = unicode.ToLower(c)
if prevWasLower {
snake += "_"
}
prevWasLower = false
}
n := utf8.EncodeRune(buf, c)
snake += string(buf[0:n])
}
return snake
}
func getFieldColumn(f reflect.StructField) string {
// Get the SQL column name, from the tag or infer it
field := f.Tag.Get(tagName)
if field == "-" {
return ""
}
if field == "" || !validTag(field) {
field = toSnake(f.Name)
}
return field
}
func hasFlags(list []Flag, passed ...Flag) bool {
for _, candidate := range passed {
var found bool
for _, f := range list {
if f == candidate {
found = true
break
}
}
if !found {
return false
}
}
return true
}
func decorateColumns(columns []string, table string, flags ...Flag) []string {
results := make([]string, 0, len(columns))
for _, name := range columns {
if hasFlags(flags, FlagTicked) {
name = "`" + name + "`"
} else if hasFlags(flags, FlagDoubleQuoted) {
name = `"` + name + `"`
}
if hasFlags(flags, FlagFull, FlagTicked) {
name = "`" + table + "`." + name
} else if hasFlags(flags, FlagFull, FlagDoubleQuoted) {
name = `"` + table + `".` + name
} else if hasFlags(flags, FlagFull) {
name = table + "." + name
}
results = append(results, name)
}
return results
}
// if needsValues is false, we'll attempt to use the cache and `values` will be nil
func readStruct(s SQLTableNamer, needsValues bool, flags ...Flag) (columns []string, values []interface{}) {
typ := fmt.Sprintf("%T", s)
structReadMutex.RLock()
if cached, ok := structReadCache[typ]; !needsValues && ok {
structReadMutex.RUnlock()
return decorateColumns(cached, s.GetSQLTableName(), flags...), nil
}
structReadMutex.RUnlock()
v := reflect.ValueOf(s)
t := reflect.TypeOf(s)
k := t.Kind()
for k == reflect.Interface || k == reflect.Ptr {
v = v.Elem()
t = v.Type()
k = t.Kind()
}
if k != reflect.Struct {
return
}
for i := 0; i < t.NumField(); i++ {
if t.Field(i).PkgPath != "" {
// skip unexported fields
continue
}
field := getFieldColumn(t.Field(i))
if field == "" {
continue
}
columns = append(columns, field)
if needsValues {
// Get the value of the field
value := v.Field(i).Interface()
values = append(values, value)
}
}
structReadMutex.Lock()
structReadCache[typ] = columns
structReadMutex.Unlock()
return decorateColumns(columns, s.GetSQLTableName(), flags...), values
}
// Columns returns a ColumnList containing the names of the columns
// in `s`.
func Columns(s SQLTableNamer, flags ...Flag) ColumnList {
columns, _ := readStruct(s, false, flags...)
return columns
}
// Column returns the name of the column that `property` maps to for `s`.
// `property` must be the exact name of a property on `s`, or Column will
// panic.
func Column(s SQLTableNamer, property string, flags ...Flag) string {
t := reflect.TypeOf(s)
k := t.Kind()
for k == reflect.Interface || k == reflect.Ptr {
t = reflect.ValueOf(s).Elem().Type()
k = t.Kind()
}
if k != reflect.Struct {
return ""
}
field, ok := t.FieldByName(property)
if !ok {
panic("Field not found in type: " + property)
}
columns := decorateColumns([]string{getFieldColumn(field)}, s.GetSQLTableName(), flags...)
return columns[0]
}
// ColumnValues returns the values in `s` for each column in `s`, in the
// same order `Columns` returns the names.
func ColumnValues(s SQLTableNamer) []interface{} {
_, values := readStruct(s, true)
return values
}
// SQLTableNamer is used to represent a type that corresponds to an SQL
// table. It must define the GetSQLTableName method, returning the name
// of the SQL table to store data for that type in.
type SQLTableNamer interface {
GetSQLTableName() string
}
// Table is a convenient shorthand wrapper for the GetSQLTableName method
// on `t`.
func Table(t SQLTableNamer) string {
return t.GetSQLTableName()
}
// Placeholders returns a formatted string containing `num` placeholders.
// The placeholders will be comma-separated.
func Placeholders(num int) string {
placeholders := make([]string, num)
for pos := 0; pos < num; pos++ {
placeholders[pos] = "?"
}
return strings.Join(placeholders, ", ")
}
// Scannable defines a type that can insert the results of a Query into
// the SQLTableNamer a Query was built from, and can list off the column
// names, in order, that those results represent.
type Scannable interface {
Scan(dst ...interface{}) error
Columns() ([]string, error)
}
type pointer struct {
addr interface{}
column string
sortOrder int
}
type pointers []pointer
func (p pointers) Len() int { return len(p) }
func (p pointers) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p pointers) Less(i, j int) bool { return p[i].sortOrder < p[j].sortOrder }
func getColumnAddrs(s Scannable, in []pointer) ([]interface{}, error) {
columns, err := s.Columns()
if err != nil {
return nil, err
}
var results pointers
for _, pointer := range in {
for pos, column := range columns {
if column == pointer.column {
pointer.sortOrder = pos
results = append(results, pointer)
break
}
}
}
sort.Sort(results)
i := make([]interface{}, 0, len(results))
for _, res := range results {
i = append(i, res.addr)
}
return i, nil
}
// Unmarshal reads the Scannable `s` into the variable at `d`, and returns an
// error if it is unable to. If there are more values than `d` has properties
// associated with columns, `additional` can be supplied to catch the extra values.
// The variables in `additional` must be a compatible type with and be in the same
// order as the columns of `s`.
func Unmarshal(s Scannable, dst interface{}, additional ...interface{}) error {
t := reflect.TypeOf(dst)
v := reflect.ValueOf(dst)
k := t.Kind()
for k == reflect.Interface || k == reflect.Ptr {
v = v.Elem()
t = v.Type()
k = t.Kind()
}
if k != reflect.Struct {
return s.Scan(dst)
}
props := []pointer{}
for i := 0; i < t.NumField(); i++ {
if t.Field(i).PkgPath != "" {
// skip unexported fields
continue
}
field := getFieldColumn(t.Field(i))
if field == "" {
continue
}
// Get the value of the field
props = append(props, pointer{
addr: v.Field(i).Addr().Interface(),
column: field,
})
}
addrs, err := getColumnAddrs(s, props)
if err != nil {
return err
}
addrs = append(addrs, additional...)
return s.Scan(addrs...)
}