More clear for Get with nil (#1879)

Resolve #1844

Reviewed-on: https://gitea.com/xorm/xorm/pulls/1879
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-committed-by: Lunny Xiao <xiaolunwen@gmail.com>
This commit is contained in:
Lunny Xiao 2021-03-23 21:48:58 +08:00
parent 9286f29576
commit 40ee326cac
2 changed files with 22 additions and 0 deletions

View File

@ -6,11 +6,13 @@ package integrations
import ( import (
"database/sql" "database/sql"
"errors"
"fmt" "fmt"
"strconv" "strconv"
"testing" "testing"
"time" "time"
"xorm.io/xorm"
"xorm.io/xorm/contexts" "xorm.io/xorm/contexts"
"xorm.io/xorm/schemas" "xorm.io/xorm/schemas"
@ -750,3 +752,17 @@ func TestGetViaMapCond(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
assert.False(t, has) assert.False(t, has)
} }
func TestGetNil(t *testing.T) {
type GetNil struct {
Id int64
}
assert.NoError(t, PrepareEngine())
assertSync(t, new(GetNil))
var gn *GetNil
has, err := testEngine.Get(gn)
assert.True(t, errors.Is(err, xorm.ErrObjectIsNil))
assert.False(t, has)
}

View File

@ -16,6 +16,10 @@ import (
"xorm.io/xorm/schemas" "xorm.io/xorm/schemas"
) )
var (
ErrObjectIsNil = errors.New("object should not be nil")
)
// Get retrieve one record from database, bean's non-empty fields // Get retrieve one record from database, bean's non-empty fields
// will be as conditions // will be as conditions
func (session *Session) Get(bean interface{}) (bool, error) { func (session *Session) Get(bean interface{}) (bool, error) {
@ -37,6 +41,8 @@ func (session *Session) get(bean interface{}) (bool, error) {
return false, errors.New("needs a pointer to a value") return false, errors.New("needs a pointer to a value")
} else if beanValue.Elem().Kind() == reflect.Ptr { } else if beanValue.Elem().Kind() == reflect.Ptr {
return false, errors.New("a pointer to a pointer is not allowed") return false, errors.New("a pointer to a pointer is not allowed")
} else if beanValue.IsNil() {
return false, ErrObjectIsNil
} }
if beanValue.Elem().Kind() == reflect.Struct { if beanValue.Elem().Kind() == reflect.Struct {