-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresult.go
More file actions
81 lines (71 loc) · 1.66 KB
/
result.go
File metadata and controls
81 lines (71 loc) · 1.66 KB
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
package sqlfunc
import (
"reflect"
"strings"
)
/*
Scannable is an interface that can be implemented by query result struct, to
avoid the performance overhead of reflection.
When result struct implements [Scannable] interface, sqlfunc calls Dest to get
corresponding dests for columns.
Example:
type UserResult struct{
Foo string
Bar int
}
func (r *UserResult) Dest(columns []string) (dest []any) {
for _, column := range columns {
switch column {
case "foo":
dest = append(dest, &r.Foo)
case "bar":
dest = append(dest, &r.Bar)
default:
dest = append(dest, sqlfunc.Void{})
}
}
return
}
*/
type Scannable interface {
// Dest returns scanning dest for columns.
Dest(columns []string) (dest []any)
}
const (
_TagKey = "sql"
)
var (
_StructMappingCache = map[reflect.Type]map[string]string{}
)
func getStructMapping(rt reflect.Type) map[string]string {
mapping, found := _StructMappingCache[rt]
if !found {
mapping = make(map[string]string)
for i := range rt.NumField() {
ft := rt.Field(i)
if desc, found := ft.Tag.Lookup(_TagKey); found {
if strings.ContainsRune(desc, ',') {
props := strings.Split(desc, ",")
mapping[props[0]] = ft.Name
} else {
mapping[desc] = ft.Name
}
} else {
column := pascalToSnake(ft.Name)
mapping[column] = ft.Name
}
}
// Put mapping to cache
_StructMappingCache[rt] = mapping
}
return mapping
}
// preprocessResult initializes mapping cache to result type
func preprocessResult[R any]() {
if pt := reflect.TypeFor[*R](); pt.AssignableTo(_TypeScannable) {
return
}
if rt := reflect.TypeFor[R](); rt.Kind() == reflect.Struct {
getStructMapping(rt)
}
}