gorm/callback_query.go

90 lines
1.9 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 (
"errors"
"fmt"
2014-01-28 05:25:30 +04:00
"reflect"
)
2014-01-26 08:49:10 +04:00
func Query(scope *Scope) {
2016-01-13 09:58:30 +03:00
defer scope.trace(NowFunc())
2014-01-28 05:25:30 +04:00
var (
2016-01-13 11:53:04 +03:00
isSlice bool
isPtr bool
destType reflect.Type
2014-01-28 05:25:30 +04:00
)
if orderBy, ok := scope.Get("gorm:order_by_primary_key"); ok {
if primaryKey := scope.PrimaryKey(); primaryKey != "" {
scope.Search.Order(fmt.Sprintf("%v.%v %v", scope.QuotedTableName(), scope.Quote(primaryKey), orderBy))
}
}
2015-04-17 13:27:20 +03:00
var dest = scope.IndirectValue()
2015-05-19 11:58:33 +03:00
if value, ok := scope.Get("gorm:query_destination"); ok {
2015-04-17 13:27:20 +03:00
dest = reflect.Indirect(reflect.ValueOf(value))
}
if kind := dest.Kind(); kind == reflect.Slice {
2014-01-28 05:25:30 +04:00
isSlice = true
destType = dest.Type().Elem()
dest.Set(reflect.MakeSlice(dest.Type(), 0, 0))
2015-06-24 08:56:30 +03:00
2014-07-08 06:45:31 +04:00
if destType.Kind() == reflect.Ptr {
isPtr = true
destType = destType.Elem()
}
} else if kind != reflect.Struct {
scope.Err(errors.New("unsupported destination, should be slice or struct"))
return
2014-01-28 05:25:30 +04:00
}
2014-01-28 05:48:44 +04:00
scope.prepareQuerySql()
2014-01-28 05:25:30 +04:00
if !scope.HasError() {
2015-02-26 07:35:33 +03:00
rows, err := scope.SqlDB().Query(scope.Sql, scope.SqlVars...)
2015-01-28 06:16:29 +03:00
scope.db.RowsAffected = 0
2014-01-28 05:25:30 +04:00
if scope.Err(err) != nil {
return
}
2015-02-17 15:19:47 +03:00
defer rows.Close()
2014-01-28 05:25:30 +04:00
2015-02-01 18:19:29 +03:00
columns, _ := rows.Columns()
2014-01-28 05:25:30 +04:00
for rows.Next() {
2015-02-17 03:34:01 +03:00
scope.db.RowsAffected++
2015-01-28 06:16:29 +03:00
2014-01-28 05:25:30 +04:00
elem := dest
if isSlice {
elem = reflect.New(destType).Elem()
}
2014-08-28 14:25:05 +04:00
fields := scope.New(elem.Addr().Interface()).Fields()
2016-01-13 11:53:04 +03:00
scope.scan(rows, columns, fields)
2015-01-19 10:50:21 +03:00
2014-01-28 05:25:30 +04:00
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
}
}
2016-01-13 11:53:04 +03:00
if scope.db.RowsAffected == 0 && !isSlice {
2014-01-28 05:25:30 +04:00
scope.Err(RecordNotFound)
}
}
2014-01-26 08:49:10 +04:00
}
func AfterQuery(scope *Scope) {
2015-02-24 11:28:15 +03:00
scope.CallMethodWithErrorCheck("AfterFind")
2014-01-26 08:49:10 +04:00
}
func init() {
2014-01-29 06:28:20 +04:00
DefaultCallback.Query().Register("gorm:query", Query)
DefaultCallback.Query().Register("gorm:after_query", AfterQuery)
DefaultCallback.Query().Register("gorm:preload", Preload)
2014-01-26 08:49:10 +04:00
}