Sha256: 0c84211a0fa5963bd6fc901ea9a26195c989ef0af9f9a9de3a90d8a0e7d29ae1

Contents?: true

Size: 1.9 KB

Versions: 1

Compression:

Stored size: 1.9 KB

Contents

require 'active_record/connection_adapters/mysql2_adapter'

module ActiveRecord
  module ConnectionHandling
    def pedant_mysql2_connection(config)
      config = config.symbolize_keys

      config[:username] = 'root' if config[:username].nil?

      if Mysql2::Client.const_defined? :FOUND_ROWS
        config[:flags] = Mysql2::Client::FOUND_ROWS
      end

      client = Mysql2::Client.new(config)
      options = [config[:host], config[:username], config[:password], config[:database], config[:port], config[:socket], 0]
      ActiveRecord::ConnectionAdapters::PedantMysql2Adapter.new(client, logger, options, config)
    rescue Mysql2::Error => error
      if error.message.include?("Unknown database") && defined?(ActiveRecord::NoDatabaseError)
        raise ActiveRecord::NoDatabaseError.new(error.message)
      else
        raise
      end
    end
  end
end

class MysqlWarning < StandardError

  attr_reader :code, :level, :query

  def initialize(message, code, level, query)
    super(message)
    @code = code
    @level = level
    @query = query
  end
end

class ActiveRecord::ConnectionAdapters::PedantMysql2Adapter < ActiveRecord::ConnectionAdapters::Mysql2Adapter
  alias_method :exec_delete_without_pedant, :exec_delete

  def execute(sql, name = nil)
    value = super
    log_warnings(sql)
    value
  end

  def exec_delete(sql, name, binds)
    exec_delete_without_pedant(to_sql(sql, binds), name, binds)
    affected_rows = @connection.affected_rows
    log_warnings(sql)
    affected_rows
  end

  alias :exec_update :exec_delete

  private

  def log_warnings(sql)
    return unless @connection.warning_count > 0

    result = @connection.query('SHOW WARNINGS')
    result.each do |level, code, message|
      warning = MysqlWarning.new(message, code, level, sql)
      ::PedantMysql2.warn(warning)
    end
  end
end

if ActiveRecord::VERSION::MAJOR == 3
  ActiveRecord::Base.extend(ActiveRecord::ConnectionHandling)
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
activerecord-pedantmysql2-adapter-1.1.1 lib/active_record/connection_adapters/pedant_mysql2_adapter.rb