Sha256: cc216a605816484de464d6146e37606ac65ae75eb9672e16ed744e047a10ddf1

Contents?: true

Size: 1.19 KB

Versions: 2

Compression:

Stored size: 1.19 KB

Contents

module ActiveRecordSlave
  # Select Methods
  SELECT_METHODS = [:select, :select_all, :select_one, :select_rows, :select_value, :select_values]

  # In case in the future we are forced to intercept connection#execute if the
  # above select methods are not sufficient
  #   SQL_READS = /\A\s*(SELECT|WITH|SHOW|CALL|EXPLAIN|DESCRIBE)/i

  module InstanceMethods
    SELECT_METHODS.each do |select_method|
      # Database Adapter method #exec_query is called for every select call
      # Replace #exec_query with one that calls the slave connection instead
      eval <<-METHOD
      def #{select_method}(sql, name = nil, *args)
        return super if active_record_slave_read_from_master?

        ActiveRecordSlave.read_from_master do
          Slave.connection.#{select_method}(sql, "Slave: \#{name || 'SQL'}", *args)
        end
      end
      METHOD
    end

    # Returns whether to read from the master database
    def active_record_slave_read_from_master?
      # Read from master when forced by thread variable, or
      # in a transaction and not ignoring transactions
      ActiveRecordSlave.read_from_master? ||
        (open_transactions > 0) && !ActiveRecordSlave.ignore_transactions?
    end

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
active_record_slave-1.4.0 lib/active_record_slave/instance_methods.rb
active_record_slave-1.3.0 lib/active_record_slave/instance_methods.rb