Class: Rails::Sharding::Core

Inherits:
Object
  • Object
show all
Defined in:
lib/rails/sharding/core.rb

Class Method Summary collapse

Class Method Details

.configurations(environment = Rails.env) ⇒ Object



26
27
28
29
30
31
# File 'lib/rails/sharding/core.rb', line 26

def self.configurations(environment=Rails.env)
  @@db_configs ||= YAML.load_file(Config.shards_config_file)
  @@db_configs[environment]
rescue Errno::ENOENT => e
  raise Errors::ConfigNotFoundError, Config.shards_config_file.to_s + ' file was not found'
end

.reset_configurations_cacheObject



33
34
35
# File 'lib/rails/sharding/core.rb', line 33

def self.reset_configurations_cache
  @@db_configs = nil
end

.setupObject

Method that should be called on a rails initializer



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/rails/sharding/core.rb', line 50

def self.setup
  if block_given?
    yield Config
  end

  if Config.establish_all_connections_on_setup
    # Establishes connections with all shards specified in config/shards.yml
    ConnectionHandler.establish_all_connections
  end

  if Config.extend_active_record_scope
    # includes the #using_shard method to all AR scopes
    ActiveRecordExtensions.extend_active_record_scope
  end
end

.shard_groupsObject



41
42
43
# File 'lib/rails/sharding/core.rb', line 41

def self.shard_groups
  self.configurations.keys
end

.shard_names(shard_group) ⇒ Object



45
46
47
# File 'lib/rails/sharding/core.rb', line 45

def self.shard_names(shard_group)
  self.configurations[shard_group.to_s].keys
end

.test_configurationsObject



37
38
39
# File 'lib/rails/sharding/core.rb', line 37

def self.test_configurations
  self.configurations('test')
end

.using_shard(shard_group, shard_name) ⇒ Object

Opens a block where all queries will be directed to the selected shard



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/rails/sharding/core.rb', line 12

def self.using_shard(shard_group, shard_name)
  raise 'Cannot nest using_shard blocks' if ShardThreadRegistry.connecting_to_shard?

  ShardThreadRegistry.current_shard_group = shard_group
  ShardThreadRegistry.current_shard_name = shard_name
  yield
ensure
  # Releases connections in case user left some connection in the reserved state
  # (by calling retrieve_connection instead of with_connection). Also, using
  # normal activerecord queries leaves a connection in the reserved state
  ConnectionHandler.connection_pool(*ShardThreadRegistry.current_shard_group_and_name).release_connection
  ShardThreadRegistry.connect_back_to_master!
end