RailsActiveRecordmysql2适配器,默认使用PreparedStatement

Rails ActiveRecord mysql2 adapter, use PreparedStatement by default

PreparedStatement 对 mysql2 的支持已添加到版本 0.4.0 中,根据此 link
根据版本 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)

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

如果没有,我还没有尝试过,但是否可以使用 Sequel 实现此目的,以及将现有应用程序从 MySQL2 迁移到 Sequel 有多复杂.

Mysql2 < 5 的 ActiveRecord,不支持启用 prepared_statement
的可配置参数 来自 ActiveRecord 4.2.6

的代码片段

connection_adapters/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

ActiveRecord with Mysql2 = 5.2.1 适配器支持可配置参数以启用 prepared_statement 来自 ActiveRecord 5.2.1

的代码片段

connection_adapters/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