【问题标题】:How is an update query on a locked database resolved in postgresql?如何在 postgresql 中解决锁定数据库的更新查询?
【发布时间】:2020-08-25 15:41:47
【问题描述】:

使用postgresql,如果用户想在数据库锁定的情况下添加新数据或更新数据库中的现有数据,他的事务如何解决?让我们考虑一下这种情况,如果我的理解有任何错误,请纠正我:

1. User 1 wants to batch update some records in the database.
2. The transaction from user 1 locks the database until all the updates are pushed.
3. User 2 wants to update something in the database, or insert some new data to the database while it is locked.
4. Based on what MVCC denotes, user 2 is shown the pre-lock version of the database.
5. User 2 inserts or updates the data.
6. User one finishes pushing its transaction and releases the database.
7. There are two versions of database now, the data is resolved.

第 7 步中的问题如何解决?我在某处读到它将获取具有最新全球时间戳的数据。但是我怎么能确定它应该保留的数据呢?如果来自用户 2 的数据优先于用户 1,但来自用户 2 的事务在用户 1 之前完成,那么如何解决这个优先级?感谢您的帮助。

【问题讨论】:

  • PostgreSQL没有数据库级锁,所以写的问题没有意义。

标签: database postgresql acid


【解决方案1】:

您不能在 PostgreSQL 中锁定数据库,但可以独占锁定表。这是您应该永远不要做的事情,因为它没有必要并且会损害并发和系统维护过程(autovacuum)。

您修改或删除的每一行都将在事务期间自动锁定。这不会影响并发会话对其他行的修改。

如果一个事务试图修改已经被另一个事务锁定的行,则第二个事务被阻塞,必须等到第一个事务完成。这样就避免了你描述的场景。

【讨论】:

  • 所以正在修改锁定行的事务将等待直到锁定被释放。那么在什么情况下会发生回滚呢?
  • 当您发出ROLLBACK 命令或数据库会话在事务仍处于打开状态时终止时会发生回滚。
猜你喜欢
  • 1970-01-01
  • 2013-03-24
  • 1970-01-01
  • 2014-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-12
  • 2020-01-29
相关资源
最近更新 更多