简体   繁体   English

查询中的锁顺序(PostgreSQL)

[英]Order of locks in query (postgresql)

Database has table X and tables An, Bn, Cn, Dn that inherits from X. 数据库具有表X和从X继承的表An,Bn,Cn,Dn。

Process 1 queries periodically data from X. 进程1定期查询来自X的数据。

Process 2 updates data in child tables. 进程2更新子表中的数据。 For example, to update tables An and Bn it creates new tables Am and Bm, loads data into them, locks in access exclusive An, Bn, drops An and Bn and alters Am and Bm to inherit X. 例如,要更新表An和Bn,它将创建新表Am和Bm,将数据加载到表中,锁定访问互斥的An,Bn,删除An和Bn,并更改Am和Bm以继承X。

The problem is that when process 1 execute query (for example select * from X ) it locks tables An, Bn, Cn, Dn in shared mode, and order of locking is unknown. 问题在于,当进程1执行查询(例如, select * from X )时,它将以共享模式锁定表An,Bn,Cn,Dn,并且锁定顺序未知。 If process 1 locks Bn, then process 2 locks An we have deadlock. 如果进程1锁定Bn,则进程2锁定An,则出现死锁。

Are there any info about order of locking tables in queries in postgresql (without explicit locking)? 是否有有关PostgreSQL查询中锁定表顺序的信息(无显式锁定)? Or may be other solutions are possible? 还是可能有其他解决方案?

I know you said without explicit locking, but honestly your best bet here is explicit locking. 我知道您说的没有显式锁定,但老实说,您最好的选择显式锁定。 As the first statement in both batches have a lock command that locks the tables that you will use. 由于这两个批处理中的第一条语句都有一个lock命令,该命令将锁定您将要使用的表。 The most important part about this is that both lock commands must lock the tables in the same order, otherwise you will run into deadlocks again anyways. 与此有关的最重要的部分是,两个lock命令必须以相同的顺序锁定表,否则无论如何您将再次陷入死锁。

After this make sure both batches run as fast as possible since you're taking table level locks ... you don't want to hold them any longer than you must. 在此之后,请确保两个批处理都尽可能快地运行,因为您要使用表级别的锁……您不想持有它们的时间超过了必须的时间。

Are there any info about order of locking tables in queries in postgresql (without explicit locking)? 是否有有关PostgreSQL查询中锁定表顺序的信息(无显式锁定)? Or may be other solutions are possible? 还是可能有其他解决方案?

Normally postgresql' mvcc implementation would shield you against many types of deadlocks. 通常,PostgreSQL的mvcc实现会使您免受许多类型的死锁的困扰。 See http://www.postgresql.org/files/developer/transactions.pdf for more details. 有关更多详细信息,请参见http://www.postgresql.org/files/developer/transactions.pdf

Though, one common solution is to just handle the deadlocks, that is, if your query fails due to a deadlock, try again.? 但是,一种常见的解决方案是仅处理死锁,也就是说,如果查询由于死锁而失败,请重试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM