From 40ee326cac59ffba1234d48dfbb62ea633c4d3c6 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Tue, 23 Mar 2021 21:48:58 +0800 Subject: [PATCH] More clear for Get with nil (#1879) Resolve #1844 Reviewed-on: https://gitea.com/xorm/xorm/pulls/1879 Co-authored-by: Lunny Xiao Co-committed-by: Lunny Xiao --- integrations/session_get_test.go | 16 ++++++++++++++++ session_get.go | 6 ++++++ 2 files changed, 22 insertions(+) diff --git a/integrations/session_get_test.go b/integrations/session_get_test.go index e4d9f82e..99db98fc 100644 --- a/integrations/session_get_test.go +++ b/integrations/session_get_test.go @@ -6,11 +6,13 @@ package integrations import ( "database/sql" + "errors" "fmt" "strconv" "testing" "time" + "xorm.io/xorm" "xorm.io/xorm/contexts" "xorm.io/xorm/schemas" @@ -750,3 +752,17 @@ func TestGetViaMapCond(t *testing.T) { assert.NoError(t, err) 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) +} diff --git a/session_get.go b/session_get.go index afedcd1f..6e65ea2f 100644 --- a/session_get.go +++ b/session_get.go @@ -16,6 +16,10 @@ import ( "xorm.io/xorm/schemas" ) +var ( + ErrObjectIsNil = errors.New("object should not be nil") +) + // Get retrieve one record from database, bean's non-empty fields // will be as conditions 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") } else if beanValue.Elem().Kind() == reflect.Ptr { 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 {