gorm/callback_query.go

87 lines
1.7 KiB
Go
Raw Normal View History

2014-01-26 08:49:10 +04:00
package gorm
2014-01-28 05:25:30 +04:00
import (
"reflect"
2014-07-04 04:19:11 +04:00
"strings"
2014-01-28 05:25:30 +04:00
)
2014-01-26 08:49:10 +04:00
func Query(scope *Scope) {
defer scope.Trace(NowFunc())
2014-01-28 05:25:30 +04:00
var (
isSlice bool
2014-07-08 06:45:31 +04:00
isPtr bool
2014-01-28 05:25:30 +04:00
anyRecordFound bool
destType reflect.Type
)
2014-07-30 10:58:00 +04:00
var dest = scope.IndirectValue()
if value, ok := scope.InstanceGet("gorm:query_destination"); ok {
2014-01-28 05:48:44 +04:00
dest = reflect.Indirect(reflect.ValueOf(value))
}
2014-01-28 05:25:30 +04:00
if dest.Kind() == reflect.Slice {
isSlice = true
destType = dest.Type().Elem()
2014-07-08 06:45:31 +04:00
if destType.Kind() == reflect.Ptr {
isPtr = true
destType = destType.Elem()
}
2014-01-28 05:25:30 +04:00
} else {
scope.Search = scope.Search.clone().limit(1)
}
2014-01-28 05:48:44 +04:00
scope.prepareQuerySql()
2014-01-28 05:25:30 +04:00
if !scope.HasError() {
rows, err := scope.DB().Query(scope.Sql, scope.SqlVars...)
if scope.Err(err) != nil {
return
}
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 {
field := elem.FieldByName(SnakeToUpperCamel(strings.ToLower(value)))
2014-01-28 05:25:30 +04:00
if field.IsValid() {
values = append(values, field.Addr().Interface())
} else {
var ignore interface{}
values = append(values, &ignore)
}
}
scope.Err(rows.Scan(values...))
if isSlice {
2014-07-08 06:45:31 +04:00
if isPtr {
dest.Set(reflect.Append(dest, elem.Addr()))
} else {
dest.Set(reflect.Append(dest, elem))
}
2014-01-28 05:25:30 +04:00
}
}
if !anyRecordFound {
2014-01-28 05:25:30 +04:00
scope.Err(RecordNotFound)
}
}
2014-01-26 08:49:10 +04:00
}
func AfterQuery(scope *Scope) {
scope.CallMethod("AfterFind")
}
func init() {
2014-01-29 06:28:20 +04:00
DefaultCallback.Query().Register("gorm:query", Query)
DefaultCallback.Query().Register("gorm:after_query", AfterQuery)
2014-01-26 08:49:10 +04:00
}