【问题标题】:Regularly seeing PG::InFailedSqlTransaction error when deploying rails app to heroku将 Rails 应用程序部署到 Heroku 时经常看到 PG::InFailedSqlTransaction 错误
【发布时间】:2016-09-10 02:27:59
【问题描述】:

每当我们部署 Rails/Postgres 应用并且迁移是部署的一部分时,我们都会收到以下错误:

PG::InFailedSqlTransaction: 错误: 当前事务被中止, 命令在事务块结束前被忽略

PG::FeatureNotSupported: 错误:缓存的计划不能改变结果 输入

有问题的 SQL 事务通常是不同的。

我想知道在我们部署时是否有办法防止这种情况发生?

【问题讨论】:

    标签: postgresql ruby-on-rails-4 heroku


    【解决方案1】:

    原因:

    准备好的报表被兑现以提高绩效。 每当在相关表的架构发生更改后使用准备好的语句时,您会得到:

    PG::FeatureNotSupported: ERROR: cached plan must not change result type
    

    PG 的适配器通常会通过优雅地DEALLOCATEing 准备好的语句来恢复。

    但是,如果错误发生在事务中,则事务已经失败。 DEALLOCATE 语句在同一个事务中运行,因此被回滚。 所以连接留下了一个不起作用的兑现准备好的语句。

    解决方案:

    • 升级到 Rails 5.0.4+ 问题已解决there
    • 在运行迁移时不要运行任何 Rails 进程。如果您想要零停机时间部署,则不适用。适用,但如果您有多个应用程序访问同一个数据库,则不方便。
    • Disable prepared statements 一共。可能会或可能不会导致性能下降:

      # config/database.yml
      
      production:
        prepared_statements: false
      
    • following monkey patch 添加到ActiveRecord::Base(稍作修改的版本):

      # config/initializers/rails_recoverable_transactions.rb
      
      raise "Remove monkey patch in #{__FILE__}" if Rails::VERSION::MAJOR > 4
      
      module TransactionRecoverable
        module ClassMethods
          def transaction(*args)
            super(*args) do
              yield
            end
          rescue PG::InFailedSqlTransaction
            connection.rollback_db_transaction
            connection.clear_cache!
      
            super(*args) do
              yield
            end
          end
        end
      end
      
      class << ActiveRecord::Base
        prepend TransactionRecoverable::ClassMethods
      end
      

    这样可以确保如果您在事务中遇到上述错误,首先关闭事务,然后清除缓存,然后重试事务一次。如果出于某种原因您不想重试事务,您可以删除 rescue 块内的 super 调用。

    【讨论】:

    • 感谢您的回答,如果我不想重试而是 raise 我应该用 raise 替换救援块内的 super 调用还是不需要?
    • @flylib 事实上,如果你想提高,只需将 super 调用替换为相关的 raise
    猜你喜欢
    • 1970-01-01
    • 2015-09-22
    • 2015-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-25
    相关资源
    最近更新 更多