Module: ActiveRecordMysqlRepl::Database::Connection

Defined in:
lib/active_record_mysql_repl/database/connection.rb

Constant Summary collapse

MAX_RETRY =
3

Class Method Summary collapse

Class Method Details

.connect(db_config, port) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/active_record_mysql_repl/database/connection.rb', line 8

def self.connect(db_config, port)
  conn = {
    adapter: "mysql2",
    host: "127.0.0.1",
    port: port,
    username: db_config.user,
    password: db_config.password,
    database: db_config.database
  }

  ActiveRecord::Base.logger = Logger.new($stdout)
  ActiveRecord::Base.establish_connection(conn)

  puts "Ensureing connection to #{db_config.database} on port 127.0.0.1:#{port}".gray

  tables = nil
  (1..MAX_RETRY - 1).to_a.each do |time|
    tables = ActiveRecord::Base.connection.tables
  rescue => e
    puts "#{e}, Retry #{time}/#{MAX_RETRY}".red
    sleep time * time
    next
  end

  if tables.blank?
    raise "Retred #{MAX_RETRY} times, but failed to connect to database."
  end

  yield if block_given?
end