As I was reading the docs, I came across this line:
GORM perform write (create/update/delete) operations run inside a transaction to ensure data consistency, you can disable it during initialization if it is not required
Source: https://gorm.io/docs/transactions.html
I am to perform some update operations on the db using the lock clause. I was wondering if I need to take care of the transaction myself or I can assume the before mentioned statement to be true in this case? Thanks
I am trying to update my payments database from multiple go routines. I need this to be concurrency safe. Can anyone confirm if my assumption is true? Or I need to perform synchronization? Thanks
func updatePayment(......) {
result := db.DB.Model(Payment{
TransactionState: TransactionInitiated,
}).First(Payment{
Id: orderId,
}).Clauses(clause.Locking{
Strength: clause.LockingStrengthUpdate,
}).Updates(Payment{
TransactionState: TransactionCompleted,
Status: status,
PaymentMethod: method,
})
}
go updatePayment(.....)
If you use PostgreSQL then it will locks rows until update is successfull more detail, and PostgreSQL also treats all comand as being executed in transaction if you dont start BEGIN command
PostgreSQL actually treats every SQL statement as being executed within a transaction. If you do not issue a BEGIN command, then each individual statement has an implicit BEGIN and (if successful) COMMIT wrapped around it. A group of statements surrounded by BEGIN and COMMIT is sometimes called a transaction block. more detail
so your code is safe if you only do update operation, for example:
UPDATE payments
SET transaction_state = 'TransactionCompleted',
status = '<status>',
payment_method = '<method>'
WHERE id = '<orderId>'