Sha256: 84cd7d8787bf6d53601789fc70059067a83672aae1d5e08fb853fb4082f94573

Contents?: true

Size: 1.75 KB

Versions: 1

Compression:

Stored size: 1.75 KB

Contents

module DbCharmer
  module ActiveRecord
    module Sharding

      def self.extended(model)
        model.cattr_accessor(:sharded_connection)
      end

      def shard_for(key, proxy_target = nil, &block)
        raise ArgumentError, "No sharded connection configured!" unless sharded_connection
        conn = sharded_connection.sharder.shard_for_key(key)
        on_db(conn, proxy_target, &block)
      end

      # The block passed to this function should return an object responding to key_field
      def create_with_allocated_shard(key_field = :id, &block)
        group = sharded_connection.sharder.least_loaded_group
        shard_info = shard_info_by_group_id(group_id)
        conn = shard_connection_config(shard_info, group.id)
        key_obj = on_db(conn, proxy_target, &block)
        allocate_new_block_for_key_on_group(key_obj.send(key_field), group)
        key_obj
      end

      # Run on default shard (if supported by the sharding method)
      def on_default_shard(proxy_target = nil, &block)
        raise ArgumentError, "No sharded connection configured!" unless sharded_connection

        if sharded_connection.support_default_shard?
          shard_for(:default, proxy_target, &block)
        else
          raise ArgumentError, "This model's sharding method does not support default shard"
        end
      end

      # Enumerate shards
      def on_each_shard(proxy_target = nil, &block)
        raise ArgumentError, "No sharded connection configured!" unless sharded_connection

        conns = sharded_connection.shard_connections
        raise ArgumentError, "This model's sharding method does not support shards enumeration" unless conns

        conns.each do |conn|
          on_db(conn, proxy_target, &block)
        end
      end

    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

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