lib/dynamoid/criteria/chain.rb in dynamoid-0.4.1 vs lib/dynamoid/criteria/chain.rb in dynamoid-0.5.0

- old
+ new

@@ -95,20 +95,11 @@ # # @return [Array] an array of the found records. # # @since 0.2.0 def records_with_index - ids = if index.range_key? - Dynamoid::Adapter.query(index.table_name, index_query).collect{|r| r[:ids]}.inject(Set.new) {|set, result| set + result} - else - results = Dynamoid::Adapter.read(index.table_name, index_query[:hash_value], consistent_opts) - if results - results[:ids] - else - [] - end - end + ids = ids_from_index if ids.nil? || ids.empty? [] else ids = ids.to_a @@ -119,12 +110,26 @@ ids = ids.take(@limit) if @limit Array(source.find(ids, consistent_opts)) end end + # Returns the Set of IDs from the index table. + # + # @return [Set] a Set containing the IDs from the index. + def ids_from_index + if index.range_key? + Dynamoid::Adapter.query(index.table_name, index_query.merge(consistent_opts)).inject(Set.new) do |all, record| + all + Set.new(record[:ids]) + end + else + results = Dynamoid::Adapter.read(index.table_name, index_query[:hash_value], consistent_opts) + results ? results[:ids] : [] + end + end + def records_with_range - Dynamoid::Adapter.query(source.table_name, range_query).collect {|hash| source.new(hash).tap { |r| r.new_record = false } } + Dynamoid::Adapter.query(source.table_name, range_query).collect {|hash| source.from_database(hash) } end # If the query does not match an index, we'll manually scan the associated table to find results. # # @return [Array] an array of the found records. @@ -134,11 +139,15 @@ if Dynamoid::Config.warn_on_scan Dynamoid.logger.warn 'Queries without an index are forced to use scan and are generally much slower than indexed queries!' Dynamoid.logger.warn "You can index this query by adding this to #{source.to_s.downcase}.rb: index [#{source.attributes.sort.collect{|attr| ":#{attr}"}.join(', ')}]" end - Dynamoid::Adapter.scan(source.table_name, query, query_opts).collect {|hash| source.new(hash).tap { |r| r.new_record = false } } + if @consistent_read + raise Dynamoid::Errors::InvalidQuery, 'Consistent read is not supported by SCAN operation' + end + + Dynamoid::Adapter.scan(source.table_name, query, query_opts).collect {|hash| source.from_database(hash) } end # Format the provided query so that it can be used to query results from DynamoDB. # # @return [Hash] a hash with keys of :hash_value and :range_value @@ -199,10 +208,10 @@ query.keys.collect{|k| k.to_s.split('.').first} end def range? return false unless source.range_key - query_keys == ['id'] || (query_keys.to_set == ['id', source.range_key.to_s].to_set) + query_keys == [source.hash_key.to_s] || (query_keys.to_set == [source.hash_key.to_s, source.range_key.to_s].to_set) end def start_key key = { :hash_key_element => { 'S' => @start.hash_key } } if range_key = @start.class.range_key