GORM Playground Link
https://github.com/go-gorm/playground/pull/573
run test code below can reproduce this
Do I miss something configuration of gorm.Config, which cause this problem or what is the best practice to use ErrRecordNotFound ?
package main
import (
"errors"
"fmt"
"log"
"strings"
"gorm.io/driver/sqlite"
// "gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/schema"
)
type Records struct {
RID int `gorm:"primaryKey"`
Name string
Price float64
}
type MyStrategy struct {
schema.NamingStrategy
}
func (s MyStrategy) ColumnName(table, column string) string {
return strings.ToLower(column)
}
func main() {
db, err := gorm.Open(sqlite.Open("gorm1.db"), &gorm.Config{
NamingStrategy: MyStrategy{},
})
if err != nil {
log.Fatalln(err)
}
r := []*Records{}
if !db.Migrator().HasTable(r) {
if err := db.Migrator().CreateTable(r); err != nil {
log.Fatalln(err)
} else {
fmt.Println("create table ok")
records := make([]Records, 5)
for i := range records {
records[i] = Records{RID: i + 1, Name: fmt.Sprintf("name-%v", i), Price: float64(i) + 1.2}
}
fmt.Println(&records)
db.Create(&records)
fmt.Println("after insert", &records)
}
} else { // has table, do query and then update
gormDb := db.Where("price > 100").Find(&r)
fmt.Println("rows =", gormDb.RowsAffected, gormDb.Error)
// FIXME
if errors.Is(gormDb.Error, gorm.ErrRecordNotFound) {
fmt.Println("record not found")
}
// query
var result []Records
gormDb.Scan(&result)
for _, r := range result {
fmt.Printf("item %v %v, %v\n", r.RID, r.Name, r.Price)
}
}
}
Comment From: github-actions[bot]
The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.io ✨ Search Before Asking ✨
Comment From: black-06
Find will not raise err on not found. Use First / Take / Last instead.
If you must use Find, you can do with:
db.Statement.RaiseErrorOnNotFound = true
// err is ErrRecordNotFound
err := db.Where("price > 100").Find(&r).Error
Note: It will also raise ErrRecordNotFound when association is empty.
Comment From: haarts
I also just ran into this. I know the issue is closed. I have one small question though: why doesn't it raise that error?
Comment From: a631807682
I also just ran into this. I know the issue is closed. I have one small question though: why doesn't it raise that error?
The difference is whether to query for one record or multiple records. When querying one record, we need to determine whether the data exists, because the value may be nil or an empty struct at this time.
Comment From: alessandroargentieri
@guest6379 I've rewritten your example to let it work the way you expected. As suggested by the other comments, you should expect 1 result only to have the NotFoundError:
package main
import (
"errors"
"fmt"
"log"
"strings"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/schema"
)
// gorm model
type Record struct {
RID int `gorm:"primaryKey"`
Name string
Price float64
}
type MyStrategy struct {
schema.NamingStrategy
}
func (s MyStrategy) ColumnName(table, column string) string {
return strings.ToLower(column)
}
func main() {
db, err := gorm.Open(sqlite.Open("gorm1.db"), &gorm.Config{
NamingStrategy: MyStrategy{},
})
if err != nil {
log.Fatalln(err)
}
if !db.Migrator().HasTable(&Record{}) {
fmt.Println("no table 'records' present: creating...")
if err := db.Migrator().CreateTable(&Record{}); err != nil {
log.Fatalln(err)
} else {
fmt.Println("table 'records' created")
fmt.Println("preparing records to be inserted in the 'records' table...")
records := make([]Record, 5)
for i := range records {
records[i] = Record{RID: i + 1, Name: fmt.Sprintf("name-%v", i), Price: float64(i) + 1.2}
}
//fmt.Println(records)
db.Create(&records)
fmt.Printf("records inserted in the 'records' table:\n %+v\n", records)
}
} else { // has table, do query and then update
fmt.Println("'records' table found. Querying...")
fmt.Println("SELECT * FROM records WHERE price > 100;")
records := []Record{}
result := db.Where("price > ?", 100).Find(&records)
fmt.Println("rows =", result.RowsAffected, result.Error)
fmt.Println("SELECT * FROM records WHERE rid = 10;")
record := Record{}
result = db.First(&record, 10)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
fmt.Println("record not found")
} else {
fmt.Println(result.Error)
}
} else {
fmt.Println(record)
}
}
}