Class: ActiveRecord::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/mysql_replication_adapter.rb

Class Method Summary collapse

Class Method Details

.find_by_sql(sql, use_slave = false) ⇒ Object

Override find_by_sql so that you can tell it to selectively use a slave machine



117
118
119
120
121
122
123
# File 'lib/mysql_replication_adapter.rb', line 117

def find_by_sql(sql, use_slave = false)
  if use_slave && connection.is_a?(ConnectionAdapters::MysqlReplicationAdapter)
    connection.load_balance_query {old_find_by_sql sql}
  else
    old_find_by_sql sql
  end
end

.find_every(options) ⇒ Object

Override the standard find to check for the :use_slave option. When specified, the resulting query will be sent to a slave machine.



102
103
104
105
106
107
108
109
110
111
# File 'lib/mysql_replication_adapter.rb', line 102

def find_every(options)
  result = if options[:use_slave] && connection.is_a?(ConnectionAdapters::MysqlReplicationAdapter)
    connection.load_balance_query do
      old_find_every(options)
    end
  else
    old_find_every(options)
  end
  result
end

.mysql_replication_connection(config) ⇒ Object

Establishes a connection to the database that’s used by all Active Record objects.



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/mysql_replication_adapter.rb', line 74

def self.mysql_replication_connection(config) # :nodoc:
  config = config.symbolize_keys
  host     = config[:host]
  port     = config[:port]
  socket   = config[:socket]
  username = config[:username] ? config[:username].to_s : 'root'
  password = config[:password].to_s
  
  if config.has_key?(:database)
    database = config[:database]
  else
    raise ArgumentError, "No database specified. Missing argument: database."
  end

  require_mysql
  mysql = Mysql.init
  mysql.ssl_set(config[:sslkey], config[:sslcert], config[:sslca], config[:sslcapath], config[:sslcipher]) if config[:sslkey]

  ConnectionAdapters::MysqlReplicationAdapter.new(mysql, logger, [host, username, password, database, port, socket], config)
end

.old_find_by_sqlObject



115
# File 'lib/mysql_replication_adapter.rb', line 115

alias_method :old_find_by_sql, :find_by_sql

.old_find_everyObject



96
# File 'lib/mysql_replication_adapter.rb', line 96

alias_method :old_find_every, :find_every

.require_mysqlObject



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/mysql_replication_adapter.rb', line 54

def self.require_mysql
  # Include the MySQL driver if one hasn't already been loaded
  unless defined? Mysql
    begin
      require_library_or_gem 'mysql'
    rescue LoadError => cannot_require_mysql
      # Use the bundled Ruby/MySQL driver if no driver is already in place
      begin
        require 'active_record/vendor/mysql'
      rescue LoadError
        raise cannot_require_mysql
      end
    end
  end

  # Define Mysql::Result.all_hashes
  MysqlCompat.define_all_hashes_method!
end