-
Notifications
You must be signed in to change notification settings - Fork 1
/
callback_query.go
117 lines (101 loc) · 2.47 KB
/
callback_query.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
package gorm
import (
"reflect"
"strings"
"time"
)
func getColumnMap(destType reflect.Type) map[string]string {
colToFieldMap := make(map[string]string)
if destType != nil && destType.Kind() == reflect.Struct {
for i := 0; i < destType.NumField(); i++ {
field := destType.Field(i)
if field.Anonymous {
embeddedStructFields := getColumnMap(field.Type)
for k, v := range embeddedStructFields {
colToFieldMap[k] = v
}
continue
}
fieldName := field.Name
dbColumnName := ToSnake(fieldName)
settings := parseTagSetting(destType.Field(i).Tag.Get("gorm"))
if colName, ok := settings["COLUMN"]; ok && colName != "" {
dbColumnName = colName
}
colToFieldMap[dbColumnName] = fieldName
}
}
return colToFieldMap
}
func Query(scope *Scope) {
defer scope.Trace(time.Now())
var (
isSlice bool
isPtr bool
anyRecordFound bool
destType reflect.Type
)
var dest = scope.IndirectValue()
if value, ok := scope.Get("gorm:query_destination"); ok {
dest = reflect.Indirect(reflect.ValueOf(value))
}
if dest.Kind() == reflect.Slice {
isSlice = true
destType = dest.Type().Elem()
if destType.Kind() == reflect.Ptr {
isPtr = true
destType = destType.Elem()
}
} else {
scope.Search = scope.Search.clone().limit(1)
}
scope.prepareQuerySql()
if !scope.HasError() {
rows, err := scope.DB().Query(scope.Sql, scope.SqlVars...)
if scope.Err(err) != nil {
return
}
colToFieldMap := getColumnMap(destType)
defer rows.Close()
for rows.Next() {
anyRecordFound = true
elem := dest
if isSlice {
elem = reflect.New(destType).Elem()
}
columns, _ := rows.Columns()
var values []interface{}
for _, value := range columns {
fieldName, ok := colToFieldMap[value]
if !ok {
fieldName = SnakeToUpperCamel(strings.ToLower(value))
}
field := elem.FieldByName(fieldName)
if field.IsValid() {
values = append(values, field.Addr().Interface())
} else {
var ignore interface{}
values = append(values, &ignore)
}
}
scope.Err(rows.Scan(values...))
if isSlice {
if isPtr {
dest.Set(reflect.Append(dest, elem.Addr()))
} else {
dest.Set(reflect.Append(dest, elem))
}
}
}
if !anyRecordFound {
scope.Err(RecordNotFound)
}
}
}
func AfterQuery(scope *Scope) {
scope.CallMethod("AfterFind")
}
func init() {
DefaultCallback.Query().Register("gorm:query", Query)
DefaultCallback.Query().Register("gorm:after_query", AfterQuery)
}