Reputation: 11
I want to update a record while returning a field from the record. If I don't return in the same command there might be concurrency issues that is why I want it to be an atomic operation. Can somebody guide me as to how to achieve this in Gorm?
Upvotes: 0
Views: 1536
Reputation: 61
You can use func (*DB) BeginTx
to start a transaction and when you are done with calculation or updates, you can use func (s *DB) Commit() *DB
to update transaction. It will lock the table to ensure atomic operation(In case of error use Rollback).
For more Information of this function use this link: https://godoc.org/github.com/jinzhu/gorm#DB.BeginTx
For example(Sample Golang Code):
db, err := mysql.SharedStore().BeginTx()
if err != nil {
return nil, err
}
defer func() { _ = db.Rollback() }()
//calculations
db.CommitTx()
Upvotes: 2