func (p *SettingDao) Set(db *gorm.DB, key string, val interface{}, enc bool) error { dt, err := web.ToBits(val) if err != nil { db.Rollback() return err } if enc { dt, err = p.Aes.Encode(dt) if err != nil { db.Rollback() return err } } st := Setting{ID: key} var cn int db.Model(st).Count(&cn) if cn == 0 { st.Val = dt db.Create(&st) } else { db.Model(&st).Updates(Setting{Val: dt}) } return nil }
// Transactional executes the given function in a transaction. If todo returns an error, the transaction is rolled back func Transactional(db *gorm.DB, todo func(tx *gorm.DB) error) error { var tx *gorm.DB tx = db.Begin() if tx.Error != nil { return tx.Error } if err := todo(tx); err != nil { tx.Rollback() return errs.WithStack(err) } tx.Commit() return tx.Error }