Sha256: b53114d2f23eec89c64577adc6bb2af9742d85a489d59e6900d188a00ee77825

Contents?: true

Size: 1.87 KB

Versions: 2

Compression:

Stored size: 1.87 KB

Contents

module DbCharmer
  module Sharding
    autoload :Connection, 'db_charmer/sharding/connection'
    autoload :StubConnection, 'db_charmer/sharding/stub_connection'
    autoload :Method, 'db_charmer/sharding/method'

    @@sharded_connections = {}

    def self.register_connection(config)
      name = config[:name] or raise ArgumentError, "No :name in connection!"
      @@sharded_connections[name] = DbCharmer::Sharding::Connection.new(config)

      # Enable multi-db migrations
      if @@sharded_connections[name].sharder.is_a?(DbCharmer::Sharding::Method::DbBlockSchemaMap)
        ::ActiveRecord::Base.extend(DbCharmer::Sharding::Method::SchemaTableNamePrefix)
      end
    end

    # name is the is the sharded_connection name passed to db_magic in the model
    def self.sharded_connection(name)
      @@sharded_connections[name.to_sym] or raise ArgumentError, "Invalid sharded connection name!"
    end

    # Return the DbCharmer::Sharding::Connection that matches name
    # name is the the connection name calculated in the sharder for a specific database
    def self.sharded_connection_by_connection_name(name)
      connection = @@sharded_connections.detect do |c|
        c[1].config[:connection] == name.to_sym
      end
      connection[1] if connection
    end

    def self.sharder_for_connection_name(sharder_name)
      connection = sharded_connection(sharder_name)
      return connection.sharder if connection
    end

    # Return shard record for the given config hash.
    # connection_config is the config hash taken from a PostgreSQLAdapter instance.
    def self.shard_for_connection_name(connection_config)
      sharder = sharder_for_connection_name(connection_config[:sharder_name])
      return unless sharder
      sharder.shard_class.where(:id => connection_config[:shard_id]).first
    end

    def self.reset_connections
      @@sharded_connections = {}
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
yam-db-charmer-1.7.4.14 lib/db_charmer/sharding.rb
yam-db-charmer-1.7.4.13 lib/db_charmer/sharding.rb