Sha256: 74e55bea99ae7ea0b4cd6c982ad9d32c76dbc182b8c20535d218317d6bd20ac8

Contents?: true

Size: 1.79 KB

Versions: 3

Compression:

Stored size: 1.79 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] 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
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
yam-db-charmer-1.7.4.10 lib/db_charmer/sharding.rb
yam-db-charmer-1.7.4.9 lib/db_charmer/sharding.rb
yam-db-charmer-1.7.4.8 lib/db_charmer/sharding.rb