Module: DbCharmer::ActiveRecord::DbMagic

Defined in:
lib/db_charmer/active_record/db_magic.rb

Defined Under Namespace

Classes: DatabaseDetectConnection

Instance Method Summary collapse

Instance Method Details

#create_true_method(method_name) ⇒ Object



45
46
47
48
49
50
51
52
53
# File 'lib/db_charmer/active_record/db_magic.rb', line 45

def create_true_method(method_name)
  unless self.respond_to?(method_name.to_sym)
    (class << self; self; end).instance_eval do
      define_method method_name.to_sym do
        true
      end
    end
  end
end

#db_magic(opt = {}) ⇒ Object



5
6
7
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
38
39
40
41
42
43
# File 'lib/db_charmer/active_record/db_magic.rb', line 5

def db_magic(opt = {})

  # define a method that can be used to check if
  # a model is extended by db_charmer
  create_true_method(:db_charmer_extended)
    
  # Make sure we could use our connections management here
  hijack_connection!

  if DbCharmer.rails3?
    self.extend(DbCharmer::ActiveRecord::RelationMethod) unless self.respond_to?(:relation_with_db_charmer)
  end

  # Should requested connections exist in the config?
  should_exist = opt.has_key?(:should_exist) ? opt[:should_exist] : DbCharmer.connections_should_exist?

  # Main connection management
  setup_connection_magic(opt[:connection], should_exist)

  # Set up slaves pool
  opt[:slaves] ||= []
  opt[:slaves] = [ opt[:slaves] ].flatten
  opt[:slaves] << opt[:slave] if opt[:slave]

  # Forced reads are enabled for all models by default, could be disabled by the user
  forced_slave_reads = opt.has_key?(:force_slave_reads) ? opt[:force_slave_reads] : true

  # Setup all the slaves related magic if needed
  setup_slaves_magic(opt[:slaves], forced_slave_reads, should_exist)

  # Setup inheritance magic
  setup_children_magic(opt)

  # Setup sharding if needed
  if opt[:sharded]
    raise ArgumentError, "Can't use sharding on a model with slaves!" if opt[:slaves].any?
    setup_sharding_magic(opt[:sharded])
  end
end

#exist_pg_database?(server_config, db_name) ⇒ Boolean

given the a db server config and a db name returns true if db_name exists

Returns:

  • (Boolean)


61
62
63
64
65
66
67
68
69
70
# File 'lib/db_charmer/active_record/db_magic.rb', line 61

def exist_pg_database?(server_config, db_name)
  config_no_db_name = server_config.clone
  config_no_db_name['database'] = nil
  DatabaseDetectConnection.establish_connection(config_no_db_name)
  server_connection = DatabaseDetectConnection.connection
  sql = "SELECT datname FROM pg_database WHERE datname='#{db_name}'"
  existing_dbs = server_connection.execute(sql)
  server_connection.disconnect!
  existing_dbs.first ? true : false
end