【问题标题】:Rails ActiveRecord mysql2 adapter, use PreparedStatement by defaultRails ActiveRecord mysql2 适配器,默认使用 PreparedStatement
【发布时间】:2019-03-10 13:37:22
【问题描述】:

根据link
,版本 0.4.0 中已经添加了对 mysql2 的 PreparedStatement 支持 根据 0.5.2 版中的以下详细信息,它仍然没有在内部的所有 ORM 查询中使用准备好的语句:

Shipment.where(order_id: 78987898789)<br>
Shipment.where('order_id = ?', 56789876)

Mysql 日志:

2019-03-10T13:20:01.722848Z  1072 Query SELECT `shipments`.* FROM `shipments` WHERE `shipments`.`order_id` = 78987898789<br>
2019-03-10T13:22:27.748687Z  1072 Query SELECT `shipments`.* FROM `shipments` WHERE (order_id = 56789876)

有没有办法为所有 ORM 查询启用/禁用它? (就像 PostgreSQL 适配器 ref)。启用它是否会对整体应用程序性能产生不利影响?

如果没有,我还没有尝试过,但是否可以使用Sequel 来实现这一点,以及将现有应用程序从 MySQL2 迁移到 Sequel 有多复杂。

【问题讨论】:

    标签: ruby-on-rails ruby activerecord sequel mysql2


    【解决方案1】:

    Mysql2 来自 ActiveRecord 4.2.6 的代码 sn-p

    connection_adapter/mysql2_adapter.rb

    module ConnectionAdapters
    class Mysql2Adapter < AbstractMysqlAdapter
      ADAPTER_NAME = 'Mysql2'.freeze
    
      def initialize(connection, logger, connection_options, config)
        super
        @prepared_statements = false # No configurable param, default set to false
        configure_connection
      end
      ...
    end
    

    带有 Mysql2 = 5.2.1 适配器的 ActiveRecord 支持可配置参数以启用prepared_statement 来自 ActiveRecord 5.2.1 的代码 sn-p

    connection_adapter/mysql2_adapter.rb

    module ConnectionAdapters
    class Mysql2Adapter < AbstractMysqlAdapter
      ADAPTER_NAME = "Mysql2".freeze
    
      include MySQL::DatabaseStatements
    
      def initialize(connection, logger, connection_options, config)
        super
        @prepared_statements = false unless config.key?(:prepared_statements)
        configure_connection
      end
      ...
    end
    

    因此,在 ActiveRecord 5.2.1 中,只需在 database.yml 中添加以下行即可启用prepared_statements

    prepared_statements: true

    【讨论】:

      猜你喜欢
      • 2012-04-09
      • 2013-03-15
      • 1970-01-01
      • 2011-09-18
      • 2023-03-30
      • 2012-04-04
      • 2021-07-17
      • 2020-06-09
      • 2013-07-19
      相关资源
      最近更新 更多