diff --git a/lib/dynamoid/transactions/mutation.rb b/lib/dynamoid/transactions/mutation.rb index a91b5f25..1cb75bae 100644 --- a/lib/dynamoid/transactions/mutation.rb +++ b/lib/dynamoid/transactions/mutation.rb @@ -910,6 +910,14 @@ def destroy(model) # Since DynamoDB limits the total number of actions per transaction, # each model created via +#import+ consumes one action from this limit. # + # There are the following differences between transactional and + # non-transactional +#import+: + # - transactional +#import+ checks primary key uniqueness and rolls back + # the transaction, raising + # +Aws::DynamoDB::Errors::TransactionCanceledException+, when a primary + # key already exists (non-transactional +#import+ overwrites existing + # items with the same key) + # # @param model_class [Class] a model class # @param array_of_attributes [Array] attributes of models # @return [Array] created models diff --git a/lib/dynamoid/transactions/mutation/builders/put_request_builder.rb b/lib/dynamoid/transactions/mutation/builders/put_request_builder.rb new file mode 100644 index 00000000..d4cfc61a --- /dev/null +++ b/lib/dynamoid/transactions/mutation/builders/put_request_builder.rb @@ -0,0 +1,37 @@ +# frozen_string_literal: true + +module Dynamoid + module Transactions + class Mutation + # @private + module Builders + class PutRequestBuilder + def initialize(model_class, item) + @model_class = model_class + @item = item + end + + def request + # Require primary key not to exist yet so existing items are never overwritten. + expression_attribute_names = { '#_h' => @model_class.hash_key } + condition = 'attribute_not_exists(#_h)' + + if @model_class.range_key? + expression_attribute_names['#_r'] = @model_class.range_key + condition += ' AND attribute_not_exists(#_r)' + end + + { + put: { + item: @item, + table_name: @model_class.table_name, + condition_expression: condition, + expression_attribute_names: expression_attribute_names + } + } + end + end + end + end + end +end diff --git a/lib/dynamoid/transactions/mutation/import.rb b/lib/dynamoid/transactions/mutation/import.rb index c5df8801..c27cf1d0 100644 --- a/lib/dynamoid/transactions/mutation/import.rb +++ b/lib/dynamoid/transactions/mutation/import.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true require_relative 'base' +require_relative 'builders/put_request_builder' module Dynamoid module Transactions @@ -65,12 +66,7 @@ def action_requests attributes_dumped = Dynamoid::Dumping.dump_attributes(model.attributes, @model_class.attributes) attributes_dumped = sanitize_item(attributes_dumped) - { - put: { - item: attributes_dumped, - table_name: @model_class.table_name - } - } + Builders::PutRequestBuilder.new(@model_class, attributes_dumped).request end end diff --git a/lib/dynamoid/transactions/mutation/save.rb b/lib/dynamoid/transactions/mutation/save.rb index 5c41f1b7..039a9bdb 100644 --- a/lib/dynamoid/transactions/mutation/save.rb +++ b/lib/dynamoid/transactions/mutation/save.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true require_relative 'base' +require_relative 'builders/put_request_builder' require_relative 'builders/update_request_builder' module Dynamoid @@ -118,23 +119,7 @@ def action_request_to_create attributes_dumped = Dynamoid::Dumping.dump_attributes(@model.attributes, @model_class.attributes) attributes_dumped = sanitize_item(attributes_dumped) - # require primary key not to exist yet - expression_attribute_names = { '#_h' => @model_class.hash_key } - condition = 'attribute_not_exists(#_h)' - - if @model_class.range_key? - expression_attribute_names['#_r'] = @model_class.range_key - condition += ' AND attribute_not_exists(#_r)' - end - - { - put: { - item: attributes_dumped, - table_name: @model_class.table_name, - condition_expression: condition, - expression_attribute_names: expression_attribute_names - } - } + Builders::PutRequestBuilder.new(@model_class, attributes_dumped).request end def action_request_to_update diff --git a/spec/dynamoid/persistence/import_spec.rb b/spec/dynamoid/persistence/import_spec.rb index 993f3bec..333650dd 100644 --- a/spec/dynamoid/persistence/import_spec.rb +++ b/spec/dynamoid/persistence/import_spec.rb @@ -474,5 +474,18 @@ end end end + + # see https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ReservedWords.html + it 'allows reserved words as partition key and sort key' do + klass = new_class(partition_key: { name: :order, type: :string }) do + range :connection, :string + field :city + end + klass.create_table + + objects = klass.import([{ order: 'order-1', connection: 'conn-1', city: 'Chicago' }]) + + expect(objects[0].reload.city).to eql 'Chicago' + end end end diff --git a/spec/dynamoid/transactions/mutation/import_spec.rb b/spec/dynamoid/transactions/mutation/import_spec.rb index 247f98a4..bf35d17e 100644 --- a/spec/dynamoid/transactions/mutation/import_spec.rb +++ b/spec/dynamoid/transactions/mutation/import_spec.rb @@ -519,4 +519,127 @@ end end end + + context 'with not unique primary key' do + let(:klass_with_composite_key) do + new_class do + range :age, :integer + field :city + end + end + + context 'with simple key' do + before do + klass.create_table + end + + it 'rolls back the transaction and does not overwrite existing item' do + existing = klass.create!(id: '10', city: 'Chicago') + imported = nil + + expect do + described_class.execute do |t| + imported = t.import(klass, [{ id: '20', city: 'Boston' }, { id: '10', city: 'New York' }]) + end + end.to raise_error(Aws::DynamoDB::Errors::TransactionCanceledException) + + expect(klass.count).to eq 1 + expect(existing.reload.city).to eq 'Chicago' + expect(imported).to all(satisfy { |m| !m.persisted? && m.changed? }) + end + + it 'runs after_rollback callbacks when primary key already exists' do + klass_with_callback = new_class do + field :city + after_rollback { ScratchPad << "after_rollback #{id}" } + end + klass_with_callback.create_table + klass_with_callback.create!(id: '10', city: 'Chicago') + ScratchPad.record [] + + expect do + described_class.execute do |t| + t.import(klass_with_callback, [{ id: '20', city: 'Boston' }, { id: '10', city: 'New York' }]) + end + end.to raise_error(Aws::DynamoDB::Errors::TransactionCanceledException) + + expect(ScratchPad.recorded).to contain_exactly('after_rollback 20', 'after_rollback 10') + end + + it 'rolls back the transaction when duplicate keys are passed in the same call' do + # DynamoDB Local raises TransactionCanceledException, whereas AWS DynamoDB + # raises ValidationException when a transaction includes multiple operations on the same item. + expect do + described_class.execute do |t| + t.import(klass, [{ id: '10', city: 'Chicago' }, { id: '10', city: 'New York' }]) + end + end.to raise_error(Aws::Errors::ServiceError) + + expect(klass.count).to eq 0 + end + end + + context 'with composite key' do + before do + klass_with_composite_key.create_table + end + + it 'rolls back the transaction and does not overwrite existing item with same hash and range keys' do + existing = klass_with_composite_key.create!(id: '10', age: 42, city: 'Chicago') + + expect do + described_class.execute do |t| + t.import(klass_with_composite_key, [ + { id: '20', age: 30, city: 'Boston' }, + { id: '10', age: 42, city: 'New York' } + ]) + end + end.to raise_error(Aws::DynamoDB::Errors::TransactionCanceledException) + + expect(klass_with_composite_key.count).to eq 1 + expect(existing.reload.city).to eq 'Chicago' + end + + it 'imports successfully when hash key matches but range key differs' do + klass_with_composite_key.create!(id: '10', age: 42, city: 'Chicago') + + expect do + described_class.execute do |t| + t.import(klass_with_composite_key, [{ id: '10', age: 43, city: 'New York' }]) + end + end.to change(klass_with_composite_key, :count).by(1) + end + + it 'rolls back the transaction when duplicate composite keys are passed in the same call' do + # DynamoDB Local raises TransactionCanceledException, whereas AWS DynamoDB + # raises ValidationException when a transaction includes multiple operations on the same item. + expect do + described_class.execute do |t| + t.import(klass_with_composite_key, [ + { id: '10', age: 42, city: 'Chicago' }, + { id: '10', age: 42, city: 'New York' } + ]) + end + end.to raise_error(Aws::Errors::ServiceError) + + expect(klass_with_composite_key.count).to eq 0 + end + end + end + + # see https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ReservedWords.html + it 'allows reserved words as partition key and sort key' do + klass = new_class(partition_key: { name: :order, type: :string }) do + range :connection, :string + field :city + end + klass.create_table + + objects = nil + described_class.execute do |t| + objects = t.import(klass, [{ order: 'order-1', connection: 'conn-1', city: 'Chicago' }]) + end + + expect(objects[0].reload.city).to eql 'Chicago' + end end