在Postgres和GO中强制执行“锁定”操作

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

Force a "lock" with Postgres and GO

问题

我是新手Postgres,所以这可能很明显(或者非常困难,我不确定)。

我想要强制一个表或行在一段时间内被“锁定”,这将导致第二个操作“等待”。

我正在使用golang和“github.com/lib/pq”与数据库进行交互。

我需要这样做的原因是因为我正在开发一个监控PostgreSQL的项目。谢谢任何帮助。

英文:

I am new to Postgres so this may be obvious (or very difficult, I am not sure).

I would like to force a table or row to be "locked" for at least a few seconds at a time. Which will cause a second operation to "wait".

I am using golang with "github.com/lib/pq" to interact with the database.

The reason I need this is because I am working on a project that monitors postgresql. Thanks for any help.

答案1

得分: 7

你也可以使用select ... for update来锁定一行或多行数据,以确保在事务期间保持锁定状态。

基本上,它的用法如下:

begin;
select * from foo where quatloos = 100 for update;
update foo set feens = feens + 1 where quatloos = 100;
commit;

这将对foo表中quatloos等于100的行执行独占的行级锁定。任何试图访问这些行的其他事务将被阻塞,直到执行commit或rollback以释放select for update的锁定。

理想情况下,这些锁定应该尽可能短暂。

参考文档:https://www.postgresql.org/docs/current/static/explicit-locking.html

英文:

You can also use select ... for update to lock a row or rows for the length of the transaction.

Basically, it's like:

begin;
select * from foo where quatloos = 100 for update;
update foo set feens = feens + 1 where quatloos = 100;
commit;

This will execute an exclusive row-level lock on foo table rows where quatloos = 100. Any other transaction attempting to access those rows will be blocked until commit or rollback has been issued once the select for update has run.

Ideally, these locks should live as short as possible.

See: https://www.postgresql.org/docs/current/static/explicit-locking.html

huangapple
  • 本文由 发表于 2017年8月25日 01:17:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/45867537.html
匿名

发表评论

匿名网友

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

确定