-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Use db transactions #10
Comments
Do you mean to encapsulate all common database operations (CRUD) into See: Which way is better? |
When using database transactions, we usually do database operations like this: func CreateAnimals(db *gorm.DB) error {
// Note the use of tx as the database handle once you are within a transaction
tx := db.Begin()
defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()
if err := tx.Error; err != nil {
return err
}
if err := tx.Create(&Animal{Name: "Giraffe"}).Error; err != nil {
tx.Rollback()
return err
}
if err := tx.Create(&Animal{Name: "Lion"}).Error; err != nil {
tx.Rollback()
return err
}
return tx.Commit().Error
} https://gorm.io/docs/transactions.html#A-Specific-Example That means we use a seperate m := model.GetModel()
defer m.Close()
err = m.CreateSomething()
if err != nil {
m.Abort() // rollback
ErrHandle()
}
err = m.AddSomeRelation()
if err != nil {
m.Abort() // rollback
ErrHandle()
}
err = m.Commit() // if there's no err, then commit
// .... var db *gorm.DB
type model struct {
tx *gorm.DB
context context.Context
cancel context.CancelFunc
}
func GetModel() *model {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
m := &model{
tx: db.Begin().WithContext(ctx),
context: ctx,
cancel: cancel,
}
return m
}
func (m *model) Close() {
if r := recover(); r != nil {
m.tx.Rollback()
}
m.cancel()
}
func (m *model) Abort() {
m.tx.Rollback()
m.cancel()
} When there's no tx to use, I believe it's reasonable and also more convenient to do CRUD separately. But when using tx, maybe it's better to encapsulate it into Model. 🤔 |
Understood. Thank you. |
NGB/internal/model/model.go
Lines 11 to 15 in f8ca797
You can encapsulate db transactions in
Model
The text was updated successfully, but these errors were encountered: