More clear for Get with nil #1879

Merged
lunny merged 1 commits from lunny/clear_error into master 2021-03-23 13:48:58 +00:00
2 changed files with 22 additions and 0 deletions

View File

@ -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)
}

View File

@ -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 {