xgorm

package
v1.0.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 28, 2020 License: Apache-2.0 Imports: 1 Imported by: 0

README

gorm 的辅助类

Transact 用来简化事务的写法。

Example

func (s *withdrawService) Create(withdraw *entity.Withdraw, uid uint, params *request.Withdraw) error {
  mutex := s.redsync.NewMutex(fmt.Sprintf("user-wallet-%d", uid))
  if err := mutex.Lock(); err != nil {
    return err
  }
  defer mutex.Unlock()

  // 这里可以调用 Transact 方法,将需要在事务中运行的过程传入
  return xgorm.Transact(s.db, func(tx *gorm.DB) error {
    var wallet entity.Wallet
    if err := tx.Where("user_id = ?", uid).First(&wallet).Error; err != nil {
      return err
    }

    if wallet.Money < params.Amount {
      return consts.ErrBalanceNotEnough
    }

    if err := tx.Model(&wallet).Where("user_id = ?", uid).UpdateColumn("money", gorm.Expr("money - ?", params.Amount)).Error; err != nil {
      return err
    }

    if err := copier.Copy(withdraw, params); err != nil {
      return err
    }

    if err := tx.Create(&withdraw).Error; err != nil {
      return err
    }
    return nil
  })
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Transact

func Transact(db *gorm.DB, txFunc func(*gorm.DB) error) (err error)

http://hopehook.com/2017/08/21/golang_transaction/

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL