This commit is contained in:
李子铭 2025-03-20 16:06:13 +08:00
parent 3eb170f4bd
commit f469b36833
4 changed files with 7 additions and 13 deletions

View File

@ -15,12 +15,6 @@ func NewDb(db *GormDb) *Db {
} }
} }
type contextTxKey struct{} func (d *Db) DB(_ context.Context) *gorm.DB {
func (d *Db) DB(ctx context.Context) *gorm.DB {
tx, ok := ctx.Value(contextTxKey{}).(*gorm.DB)
if ok {
return tx
}
return d.db.Client return d.db.Client
} }

View File

@ -35,8 +35,8 @@ func Test_db(t *testing.T) {
go func() { go func() {
defer wg.Done() defer wg.Done()
var order model.Order var m model.Product
tx := gormDb.First(&order) tx := gormDb.Model(model.Product{}).Where(model.Product{ProductNo: "001"}).Find(&m)
if tx.Error != nil { if tx.Error != nil {
if errors.Is(tx.Error, gorm.ErrRecordNotFound) { if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
t.Errorf("未找到记录") t.Errorf("未找到记录")

View File

@ -87,7 +87,7 @@ func (p *OrderRepoImpl) GetByOutBizNo(ctx context.Context, t vo.OrderType, outBi
tx := p.DB(ctx).Where(model.Order{Type: t.GetValue(), OutBizNo: outBizNo}).Find(&info) tx := p.DB(ctx).Where(model.Order{Type: t.GetValue(), OutBizNo: outBizNo}).Find(&info)
if tx.Error != nil { if tx.Error != nil {
return nil, fmt.Errorf("db fail %w", tx.Error) return nil, fmt.Errorf("order db fail %w", tx.Error)
} }
if tx.RowsAffected == 0 { if tx.RowsAffected == 0 {
@ -103,7 +103,7 @@ func (p *OrderRepoImpl) GetByID(ctx context.Context, id uint64) (*bo.OrderBo, er
tx := p.DB(ctx).Where(model.Order{ID: id}).Find(&info) tx := p.DB(ctx).Where(model.Order{ID: id}).Find(&info)
if tx.Error != nil { if tx.Error != nil {
return nil, fmt.Errorf("db fail %w", tx.Error) return nil, fmt.Errorf("order db fail %w", tx.Error)
} }
if tx.RowsAffected == 0 { if tx.RowsAffected == 0 {
@ -119,7 +119,7 @@ func (p *OrderRepoImpl) GetByOrderNo(ctx context.Context, orderNo string) (*bo.O
tx := p.DB(ctx).Where(model.Order{OrderNo: orderNo}).Find(&info) tx := p.DB(ctx).Where(model.Order{OrderNo: orderNo}).Find(&info)
if tx.Error != nil { if tx.Error != nil {
return nil, fmt.Errorf("db fail %w", tx.Error) return nil, fmt.Errorf("order db fail %w", tx.Error)
} }
if tx.RowsAffected == 0 { if tx.RowsAffected == 0 {

View File

@ -32,7 +32,7 @@ func (r *ProductRepoImpl) GetByPNO(ctx context.Context, PNO string) (*bo.Product
tx := r.DB(ctx).Where(model.Product{ProductNo: PNO}).Find(&item) tx := r.DB(ctx).Where(model.Product{ProductNo: PNO}).Find(&item)
if tx.Error != nil { if tx.Error != nil {
return nil, fmt.Errorf("db fail %w", tx.Error) return nil, fmt.Errorf("product db fail %w", tx.Error)
} }
if tx.RowsAffected == 0 { if tx.RowsAffected == 0 {