Sha256: 3baa5f9f94d9bc25b64fa2459172232a008b5f8c5e9bb9dfb601237fde435ce6

Contents?: true

Size: 1.3 KB

Versions: 2

Compression:

Stored size: 1.3 KB

Contents

module ActiveRecord
  # Support parallel execution with each shard and deal with AR connection
  # management in parallel execution.
  module ShardFor
    class AllShardsInParallel
      # @param [Array<Class>] An array of shard model class
      # @param [Expeditor::Service] service
      def initialize(shards, service:)
        @shards = shards
        @service = service
      end

      # @yield [Class] A shard model class
      # @return [Array] A result
      # @example
      #   User.all_shards_in_parallel.map(&:count).reduce(&:+)
      def map
        return [] unless block_given?

        commands = @shards.map do |m|
          Expeditor::Command.new(service: @service) { m.connection_pool.with_connection { yield m } }
        end
        commands.each(&:start)
        commands.map(&:get)
      end

      # @yield [Class] A shard model class
      # @return [Array] A result
      # @example
      #   User.all_shards_in_parallel.flat_map {|m| m.where(age: 1) }
      def flat_map(&block)
        map(&block).flatten
      end

      # @yield [Class] A shard model class
      # @return [ActiveRecord::ShardFor::AllShardsInParallel]
      # @example
      #   User.all_shards_in_parallel.each {|m| puts m.count }
      def each(&block)
        map(&block) if block_given?
        self
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
activerecord-shard_for-0.7.0 lib/activerecord/shard_for/all_shards_in_parallel.rb
activerecord-shard_for-0.6.1 lib/activerecord/shard_for/all_shards_in_parallel.rb