I expect that can got gorm.ErrRecordNotFound
If no record is found when using pointer to slice. And after trace code I noted that https://github.com/jinzhu/gorm/blob/master/callback_query.go#L87-L89 add isSlice
bool value to block error setting.
So how can I got no database record found when I using pointer to slice? Thx.
} else if scope.db.RowsAffected == 0 && !isSlice {
scope.Err(ErrRecordNotFound)
}
go version
)?Latest
sqlite
package main
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"fmt"
)
type Product struct {
gorm.Model
Code string
Price uint
}
func main() {
db, _ := gorm.Open("sqlite3", "test.db")
defer db.Close()
// Migrate the schema
db.AutoMigrate(&Product{})
// Create
db.Create(&Product{Code: "L1212", Price: 1000})
var products []Product
// No record can be found
if err:= db.Where(map[string]interface{}{"code": ""}).Find(&products).Error;err!=nil {
if err == gorm.ErrRecordNotFound {
//expect getting ErrRecordNotFound error
fmt.Print("ErrRecordNotFound")
}
}
}
After I search issue I found https://github.com/jinzhu/gorm/issues/228#issuecomment-281573321 Find a slice won't return error, bug find a struct will.
Can add this to document or consider that make behavior consistency?
This is totally unexpected; find on a slice should also return the error.
An example of how real code would look like right now:
var originalRecords []*Record
err := db.
Joins("JOIN records ON records.ext_id = external.id").
Where(`external."key" = ?`, key).
Find(&originalRecords).Error
if err != nil {
return nil, err
}
if len(originalRecords) == 0 {
return nil, gorm.ErrRecordNotFound
}
return originalRecords, nil
Merged #2015 ,close it.
Most helpful comment
After I search issue I found https://github.com/jinzhu/gorm/issues/228#issuecomment-281573321
Find a slice won't return error, bug find a struct will.
Can add this to document or consider that make behavior consistency?