版本:v1.25.12
参考 #6105 中的方法进行设置后,使用 Find 查询依然无法触发 ErrRecordNotFound 错误
gormDB, err := gorm.Open(mysql.New(mysql.Config{Conn: db}), &gorm.Config{SkipDefaultTransaction: true, QueryFields: true})
if err != nil {
log.Fatal(err)
return
}
gormDB.Statement.RaiseErrorOnNotFound = true
// gormDB = gormDB.WithContext(gormDB.Statement.Context)
// err is ErrRecordNotFound
err := gormDB.Where("price > 100").Find(&r).Error
当取消注解 gormDB = gormDB.WithContext(gormDB.Statement.Context)
后可以正常生效。
func (db *DB) getInstance() *DB {
if db.clone > 0 {
tx := &DB{Config: db.Config, Error: db.Error}
if db.clone == 1 {
// clone with new statement
tx.Statement = &Statement{
DB: tx,
ConnPool: db.Statement.ConnPool,
Context: db.Statement.Context,
Clauses: map[string]clause.Clause{},
Vars: make([]interface{}, 0, 8),
SkipHooks: db.Statement.SkipHooks,
}
if db.Config.PropagateUnscoped {
tx.Statement.Unscoped = db.Statement.Unscoped
}
} else {
// with clone statement
tx.Statement = db.Statement.clone()
tx.Statement.DB = tx
}
return tx
}
return db
}
参考上面源码发现在调用getInstance()
如果 clone
为 1, 则不直接进行 Statement.clone()
而是生成一个新的 Statement
,这将导致设置的 RaiseErrorOnNotFound
被忽略,是否可以考虑在clone为1时,也带上 RaiseErrorOnNotFound 设置呢?如下:
if db.clone == 1 {
// clone with new statement
tx.Statement = &Statement{
DB: tx,
ConnPool: db.Statement.ConnPool,
Context: db.Statement.Context,
Clauses: map[string]clause.Clause{},
Vars: make([]interface{}, 0, 8),
SkipHooks: db.Statement.SkipHooks,
RaiseErrorOnNotFound: db.Statement.RaiseErrorOnNotFound,
}
if db.Config.PropagateUnscoped {
tx.Statement.Unscoped = db.Statement.Unscoped
}
}