Skip to content

Commit

Permalink
Adds a configuration flag to enable create_table on save
Browse files Browse the repository at this point in the history
  • Loading branch information
imaximix committed Apr 28, 2023
1 parent 6d757f1 commit ef81000
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 1 deletion.
1 change: 1 addition & 0 deletions lib/dynamoid/config.rb
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ module Config
option :http_idle_timeout, default: nil # - default: 5
option :http_open_timeout, default: nil # - default: 15
option :http_read_timeout, default: nil # - default: 60
option :create_table_on_save, default: true

# The default logger for Dynamoid: either the Rails logger or just stdout.
#
Expand Down
7 changes: 6 additions & 1 deletion lib/dynamoid/persistence.rb
Original file line number Diff line number Diff line change
Expand Up @@ -507,7 +507,12 @@ def persisted?
# @return [true|false] Whether saving successful or not
# @since 0.2.0
def save(options = {})
self.class.create_table(sync: true)
if Dynamoid.config.create_table_on_save
self.class.create_table(sync: true)
else
Dynamoid.logger.warn "Table #{self.class.table_name} is not created as create_table_enabled is disabled"
end

create_or_update = new_record? ? :create : :update

run_callbacks(:save) do
Expand Down
47 changes: 47 additions & 0 deletions spec/dynamoid/persistence_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2293,6 +2293,53 @@ def around_update_callback
end.not_to change { obj.class.count }
end

context 'when disable_create_table_on_save is false' do
before do
Dynamoid.configure do |config|
@original_create_table_on_save = config.create_table_on_save
config.create_table_on_save = false
end
end

after do
Dynamoid.configure do |config|
config.create_table_on_save = @original_create_table_on_save
end
end

it 'raises Aws::DynamoDB::Errors::ResourceNotFoundException error' do
model = klass.new

expect(klass).not_to receive(:create_table)

expect { model.save! }.to raise_error(Aws::DynamoDB::Errors::ResourceNotFoundException)
end
end

context 'when disable_create_table_on_save is false and the table exists' do
before do
Dynamoid.configure do |config|
@original_create_table_on_save = config.create_table_on_save
config.create_table_on_save = false
end
klass.create_table
end

after do
Dynamoid.configure do |config|
config.create_table_on_save = @original_create_table_on_save
end
end

it 'persists the model' do
obj = klass.new(name: 'John')
obj.save

expect(klass.exists?(obj.id)).to eq true
expect(klass.find(obj.id).name).to eq 'John'
end
end

describe 'partition key value' do
it 'generates "id" for new model' do
obj = klass.new
Expand Down

0 comments on commit ef81000

Please sign in to comment.