Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: keep result as nil when record not found & dest is nil #6958

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion callbacks.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,8 @@ func (p *processor) Execute(db *DB) *DB {
if stmt.Dest != nil {
stmt.ReflectValue = reflect.ValueOf(stmt.Dest)
for stmt.ReflectValue.Kind() == reflect.Ptr {
if stmt.ReflectValue.IsNil() && stmt.ReflectValue.CanAddr() {
stmt.DestIsNil = stmt.ReflectValue.IsNil()
if stmt.DestIsNil && stmt.ReflectValue.CanAddr() {
stmt.ReflectValue.Set(reflect.New(stmt.ReflectValue.Type().Elem()))
}

Expand Down
4 changes: 4 additions & 0 deletions scan.go
Original file line number Diff line number Diff line change
Expand Up @@ -342,5 +342,9 @@ func Scan(rows Rows, db *DB, mode ScanMode) {

if db.RowsAffected == 0 && db.Statement.RaiseErrorOnNotFound && db.Error == nil {
db.AddError(ErrRecordNotFound)
if db.Statement.DestIsNil {
// reset dest to nil
reflect.ValueOf(db.Statement.Dest).Elem().Set(reflect.Zero(reflect.ValueOf(db.Statement.Dest).Elem().Type()))
}
}
}
1 change: 1 addition & 0 deletions statement.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ type Statement struct {
Model interface{}
Unscoped bool
Dest interface{}
DestIsNil bool
ReflectValue reflect.Value
Clauses map[string]clause.Clause
BuildClauses []string
Expand Down
8 changes: 8 additions & 0 deletions tests/query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,14 @@ func TestFind(t *testing.T) {
}
})

t.Run("KeepResultAsNil", func(t *testing.T) {
var first *User
if err := DB.Where("name = ?", "find not found").First(&first).Error; err != nil {
AssertEqual(t, err, gorm.ErrRecordNotFound)
AssertEqual(t, first, nil)
}
})

var models []User
if err := DB.Where("name in (?)", []string{"find"}).Find(&models).Error; err != nil || len(models) != 3 {
t.Errorf("errors happened when query find with in clause: %v, length: %v", err, len(models))
Expand Down
Loading