PostgreSQL 运行 是否对只读事务进行了一些性能优化

Does PostgreSQL run some performance optimizations for read-only transactions

根据reference documentation,READ ONLY 事务标志除了允许 DEFERRABLE 事务外还有用吗?

SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY;

The DEFERRABLE transaction property has no effect unless the transaction is also SERIALIZABLE and READ ONLY. When all three of these properties are selected for a transaction, the transaction may block when first acquiring its snapshot, after which it is able to run without the normal overhead of a SERIALIZABLE transaction and without any risk of contributing to or being canceled by a serialization failure. This mode is well suited for long-running reports or backups.

数据库引擎是否为只读事务运行其他优化?

总结 Nick Barnes 和 Craig Ringer 在问题评论中的评论:

  1. READ_ONLY 标志不一定提供任何优化
  2. 设置 READ_ONLY 标志的主要好处是确保不会修改任何元组

事实上,确实如此。我这里直接引用源码注释:

/*
 * Check if we have just become "RO-safe". If we have, immediately release
 * all locks as they're not needed anymore. This also resets
 * MySerializableXact, so that subsequent calls to this function can exit
 * quickly.
 *
 * A transaction is flagged as RO_SAFE if all concurrent R/W transactions
 * commit without having conflicts out to an earlier snapshot, thus
 * ensuring that no conflicts are possible for this transaction.
 */