How do I do table locking in GORM(go-gorm)?
I found a way to do row locking, but could not find a way to do table locking.
How do I do table locking in GORM(go-gorm)?
I found a way to do row locking, but could not find a way to do table locking.
You could use this code according to gorm.io docs:
Row-Level Lock Modes, FOR UPDATE
db.Clauses(clause.Locking{Strength: "UPDATE"}).Find(&users)
// SELECT * FROM `users` FOR UPDATE
Also, you could use other lock mode instead of UPDATE, like: KEY SHARE, SHARE, NO KEY UPDATE.
Table-Level Lock Modes
For locking a table, as far as I can see there is no option with Gorm right now, because Gorm always put FOR, when merging Clauses. but you can use a raw query to achieve what you want:
db.Exec("LOCK TABLE table_name_here IN ACCESS EXCLUSIVE MODE")
// LOCK [ TABLE ] [ ONLY ] name [ * ] [, ...] [ IN lockmode MODE ] [ NOWAIT ]
where lockmode is one of:
ACCESS SHARE | ROW SHARE | ROW EXCLUSIVE | SHARE UPDATE EXCLUSIVE
| SHARE | SHARE ROW EXCLUSIVE | EXCLUSIVE | ACCESS EXCLUSIVE
More info on Postgres locks here
Add options
You can use Options to add any option that you want, this will be appear after the Strength.
db.Clauses(clause.Locking{
Strength: "UPDATE",
Options: "NOWAIT",
}).Find(&users)
// SELECT * FROM `users` FOR UPDATE NOWAIT