gorm/callback_query.go

78 lines
1.5 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"
"time"
)
2014-01-26 08:49:10 +04:00
func Query(scope *Scope) {
2014-01-28 05:25:30 +04:00
defer scope.Trace(time.Now())
var (
isSlice bool
anyRecordFound bool
destType reflect.Type
)
var dest = reflect.Indirect(reflect.ValueOf(scope.Value))
2014-01-28 05:48:44 +04:00
if value, ok := scope.Get("gorm:query_destination"); ok {
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()
} 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(value))
if field.IsValid() {
values = append(values, field.Addr().Interface())
} else {
var ignore interface{}
values = append(values, &ignore)
}
}
scope.Err(rows.Scan(values...))
if isSlice {
dest.Set(reflect.Append(dest, elem))
}
}
if !anyRecordFound && !isSlice {
scope.Err(RecordNotFound)
}
}
2014-01-26 08:49:10 +04:00
}
func AfterQuery(scope *Scope) {
scope.CallMethod("AfterFind")
}
func init() {
DefaultCallback.Query().Register("query", Query)
DefaultCallback.Query().Register("after_query", AfterQuery)
}