Skip to content

Commit e6a132b

Browse files
committed
KeyFieldsDetector. Move query-related logic to own Query class
1 parent 83c6abb commit e6a132b

File tree

1 file changed

+24
-7
lines changed

1 file changed

+24
-7
lines changed

lib/dynamoid/criteria/key_fields_detector.rb

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,30 @@
33
module Dynamoid #:nodoc:
44
module Criteria
55
class KeyFieldsDetector
6+
7+
class Query
8+
def initialize(query_hash)
9+
@query_hash = query_hash
10+
@fields_with_operator = query_hash.keys.map(&:to_s)
11+
@fields = query_hash.keys.map(&:to_s).map { |s| s.split('.').first }
12+
end
13+
14+
def contain?(field_name)
15+
@fields.include?(field_name.to_s)
16+
end
17+
18+
def contain_with_eq_operator?(field_name)
19+
@fields_with_operator.include?(field_name.to_s)
20+
end
21+
end
22+
23+
624
attr_reader :hash_key, :range_key, :index_name
725

826
def initialize(query, source)
927
@query = query
1028
@source = source
29+
@query = Query.new(query)
1130

1231
detect_keys
1332
end
@@ -19,22 +38,20 @@ def key_present?
1938
private
2039

2140
def detect_keys
22-
query_keys = @query.keys.collect { |k| k.to_s.split('.').first }
23-
2441
# See if querying based on table hash key
25-
if @query.keys.map(&:to_s).include?(@source.hash_key.to_s)
42+
if @query.contain_with_eq_operator?(@source.hash_key)
2643
@hash_key = @source.hash_key
2744

2845
# Use table's default range key
29-
if query_keys.include?(@source.range_key.to_s)
46+
if @query.contain?(@source.range_key)
3047
@range_key = @source.range_key
3148
return
3249
end
3350

3451
# See if can use any local secondary index range key
3552
# Chooses the first LSI found that can be utilized for the query
3653
@source.local_secondary_indexes.each do |_, lsi|
37-
next unless query_keys.include?(lsi.range_key.to_s)
54+
next unless @query.contain?(lsi.range_key)
3855

3956
@range_key = lsi.range_key
4057
@index_name = lsi.name
@@ -49,8 +66,8 @@ def detect_keys
4966
# But only do so if projects ALL attributes otherwise we won't
5067
# get back full data
5168
@source.global_secondary_indexes.each do |_, gsi|
52-
next unless @query.keys.map(&:to_s).include?(gsi.hash_key.to_s) && gsi.projected_attributes == :all
53-
next if @hash_key.present? && !query_keys.include?(gsi.range_key.to_s)
69+
next unless @query.contain_with_eq_operator?(gsi.hash_key) && gsi.projected_attributes == :all
70+
next if @hash_key.present? && !@query.contain?(gsi.range_key)
5471

5572
@hash_key = gsi.hash_key
5673
@range_key = gsi.range_key

0 commit comments

Comments
 (0)