Skip to content

Commit

Permalink
Merge pull request #456 from Dynamoid/check-missing-range-key-in-finders
Browse files Browse the repository at this point in the history
Check if required range key argument if missing in .find method
  • Loading branch information
andrykonchin committed Jun 25, 2020
2 parents a2ec742 + bf39ee3 commit 129b4bf
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
8 changes: 8 additions & 0 deletions lib/dynamoid/finders.rb
Expand Up @@ -25,6 +25,10 @@ module ClassMethods
# specified +raise_error: false+ option then +find+ will not raise the
# exception.
#
# When a document schema includes range key it always should be specified
# in +find+ method call. In case it's missing +MissingRangeKey+ exception
# will be raised.
#
# Please note that +find+ doesn't preserve order of models in result when
# passes multiple ids.
#
Expand Down Expand Up @@ -114,6 +118,8 @@ def find_by_id(id, options = {})

# @private
def _find_all(ids, options = {})
raise Errors::MissingRangeKey if range_key && ids.any? { |pk, sk| sk.nil? }

if range_key
ids = ids.map do |pk, sk|
sk_casted = TypeCasting.cast_field(sk, attributes[range_key])
Expand Down Expand Up @@ -156,6 +162,8 @@ def _find_all(ids, options = {})

# @private
def _find_by_id(id, options = {})
raise Errors::MissingRangeKey if range_key && options[:range_key].nil?

if range_key
key = options[:range_key]
key_casted = TypeCasting.cast_field(key, attributes[range_key])
Expand Down
16 changes: 16 additions & 0 deletions spec/dynamoid/finders_spec.rb
Expand Up @@ -58,6 +58,14 @@
obj = klass_with_date.create(published_on: date)
expect(klass_with_date.find(obj.id, range_key: date)).to eql(obj)
end

it 'raises MissingRangeKey when range key is not specified' do
obj = klass_with_composite_key.create(age: 12)

expect {
klass_with_composite_key.find(obj.id)
}.to raise_error(Dynamoid::Errors::MissingRangeKey)
end
end

it 'returns persisted? object' do
Expand Down Expand Up @@ -216,6 +224,14 @@
klass_with_date.find([[obj1.id, obj1.published_on], [obj2.id, obj2.published_on]])
).to match_array([obj1, obj2])
end

it 'raises MissingRangeKey when range key is not specified' do
obj1, obj2 = klass_with_composite_key.create([{ age: 1 }, { age: 2 }])

expect {
klass_with_composite_key.find([obj1.id, obj2.id])
}.to raise_error(Dynamoid::Errors::MissingRangeKey)
end
end

it 'returns persisted? objects' do
Expand Down

0 comments on commit 129b4bf

Please sign in to comment.