How do I do table locking in GORM(Golang)?

huangapple go评论84阅读模式
英文:

How do I do table locking in GORM(Golang)?

问题

在GORM(go-gorm)中如何进行表锁定?

我找到了一种进行行锁定的方法,但是找不到进行表锁定的方法。

英文:

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.

答案1

得分: 3

你可以根据gorm.io的文档使用以下代码:

行级锁模式,FOR UPDATE

db.Clauses(clause.Locking{Strength: "UPDATE"}).Find(&users)
// SELECT * FROM `users` FOR UPDATE

此外,你还可以使用其他锁模式,例如:KEY SHARE, SHARE, NO KEY UPDATE.

表级锁模式

目前我所知,Gorm没有提供直接锁定表的选项,因为在合并Clauses时,Gorm总是会添加FOR关键字。但你可以使用原始查询来实现你想要的效果:

db.Exec("LOCK TABLE table_name_here IN ACCESS EXCLUSIVE MODE")
// LOCK [ TABLE ] [ ONLY ] name [ * ] [, ...] [ IN lockmode MODE ] [ NOWAIT ]

其中lockmode可以是以下之一:

ACCESS SHARE | ROW SHARE | ROW EXCLUSIVE | SHARE UPDATE EXCLUSIVE
| SHARE | SHARE ROW EXCLUSIVE | EXCLUSIVE | ACCESS EXCLUSIVE

关于Postgres锁的更多信息,请参考这里

添加选项

你可以使用Options来添加任何你想要的选项,这些选项将出现在Strength之后。

db.Clauses(clause.Locking{
  Strength: "UPDATE",
  Options: "NOWAIT",
}).Find(&users)
// SELECT * FROM `users` FOR UPDATE NOWAIT

如何解锁:

当你使用Strength: "UPDATE"时,这意味着表正在锁定(FOR UPDATE),并且在更新后将被解锁。

其他一些更新包括:

  • Strength: "SHARE"

英文:

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

How to unlock:

When you are using Strength: "UPDATE", it means the table is Locking (FOR UPDATE) And it will be unlock after updating.

Some other updates are:

  • Strength: "SHARE"

huangapple
  • 本文由 发表于 2022年5月6日 22:18:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/72142999.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定