gorm/callback_query.go
jnfeinstein 0d6f01d340 Create empty slice when records are not found.
There is a gotcha in golang (go figure!) resulting from the
difference between a nil slice and an empty slice. While the length
of both are 0, the JSON encoder will interpret the nil slice as
'null' and the empty slice as '[]'. Other libraries (i.e. ActiveRecord)
will return an empty array when no values are found. I have found
that this translates into better client-side code, since you don't
have to protect against null arrays.

See 'http://danott.co/posts/json-marshalling-empty-slices-to-empty-arrays-in-go.html'
for more information.
2014-11-22 02:19:40 -08:00

102 lines
2.2 KiB
Go

package gorm
import (
"fmt"
"reflect"
)
func Query(scope *Scope) {
defer scope.Trace(NowFunc())
var (
isSlice bool
isPtr bool
anyRecordFound bool
destType reflect.Type
)
var dest = scope.IndirectValue()
if value, ok := scope.InstanceGet("gorm:query_destination"); ok {
dest = reflect.Indirect(reflect.ValueOf(value))
}
if orderBy, ok := scope.InstanceGet("gorm:order_by_primary_key"); ok {
if primaryKey := scope.PrimaryKey(); primaryKey != "" {
scope.Search = scope.Search.clone().order(fmt.Sprintf("%v.%v %v", scope.QuotedTableName(), primaryKey, orderBy))
}
}
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
}
defer rows.Close()
for rows.Next() {
anyRecordFound = true
elem := dest
if isSlice {
elem = reflect.New(destType).Elem()
}
columns, _ := rows.Columns()
var values []interface{}
fields := scope.New(elem.Addr().Interface()).Fields()
for _, value := range columns {
if field, ok := fields[value]; ok {
values = append(values, field.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 {
if isSlice && dest.IsNil() {
var emptySliceType reflect.Type
if isPtr {
emptySliceType = reflect.SliceOf(reflect.PtrTo(destType))
} else {
emptySliceType = reflect.SliceOf(destType)
}
dest.Set(reflect.MakeSlice(emptySliceType, 0, 0))
}
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)
}