-
-
Notifications
You must be signed in to change notification settings - Fork 194
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
transactions multi-table MVP #688
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,118 @@ | ||
# Transactions in Dynamoid | ||
|
||
Synchronous write operations are supported in Dynamoid using transactions. | ||
If any action in the transaction fails they all fail. | ||
The following actions are supported: | ||
|
||
* Create - add a new item if it does not already exist | ||
* Upsert - add a new item or update an existing item, no callbacks | ||
* Update - modifies one or more attributes from an existig item | ||
* Delete - remove an item without callbacks, validations nor existence check | ||
* Destroy - remove an item, fails if item does not exist | ||
|
||
## Examples | ||
|
||
|
||
|
||
### Save models | ||
Models can be saved in a transaction. | ||
New records are created otherwise the model is updated. | ||
Save, create, update, validate and destroy callbacks are called around the transaction as appropriate. | ||
Validation failures will throw Dynamoid::Errors::DocumentNotValid. | ||
|
||
```ruby | ||
user = User.find(1) | ||
article = Article.new(body: 'New article text', user_id: user.id) | ||
Dynamoid::TransactionWrite.execute do |txn| | ||
txn.save!(article) | ||
user.last_article_id = article.id | ||
txn.save!(user) | ||
end | ||
``` | ||
|
||
### Create items | ||
Items can be created inside of a transaction. | ||
The hash key and range key, if applicable, are used to determine uniqueness. | ||
Creating will fail with Aws::DynamoDB::Errors::TransactionCanceledException if an item already exists unless skip_existence_check is true. | ||
This example creates a user with a unique id and unique email address by creating 2 items. | ||
An additional item is upserted in the same transaction. | ||
Upserts will update updated_at but will not create created_at. | ||
|
||
```ruby | ||
user_id = SecureRandom.uuid | ||
email = '[email protected]' | ||
Dynamoid::TransactionWrite.execute do |txn| | ||
txn.create!(User, id: user_id) | ||
txn.create!(UserEmail, id: "UserEmail##{email}", user_id: user_id) | ||
txn.create!(Address, { id: 'A#2', street: '456' }, { skip_existence_check: true }) | ||
txn.upsert!(Address, id: 'A#1', street: '123') | ||
end | ||
``` | ||
|
||
### Destroy or delete items | ||
Models can be used or the model class and key can be specified. | ||
When the key is a single column it is specified as a single value or a hash | ||
with the name of the hash key. | ||
When using a composite key the key must be a hash with the hash key and range key. | ||
destroy() uses callbacks and validations and fails if the item does not exist. | ||
Use delete() to skip callbacks, validations and the existence check. | ||
|
||
```ruby | ||
article = Article.find(1) | ||
tag = article.tag | ||
Dynamoid::TransactionWrite.execute do |txn| | ||
txn.destroy!(article) | ||
txn.destroy!(Article, 2) # performs find() automatically and then runs destroy callbacks | ||
txn.destroy!(tag) | ||
txn.delete(Tag, 2) # delete record with hash key '2' if it exists | ||
txn.delete(Tag, id: 2) # equivalent of the above if the hash key column is 'id' | ||
txn.delete(Tag, id: 'key#abcd', my_sort_key: 'range#1') # when range key is required | ||
end | ||
``` | ||
|
||
### Skipping callbacks and validations | ||
Validations and callbacks can be skipped per action. | ||
Validation failures will throw Dynamoid::Errors::DocumentNotValid when using the bang! methods. | ||
Note that validation callbacks are run when validation happens even if skipping callbacks here. | ||
Skipping callbacks and validation guarantees no callbacks. | ||
|
||
```ruby | ||
user = User.find(1) | ||
user.red = true | ||
Dynamoid::TransactionWrite.execute do |txn| | ||
txn.save!(user, skip_callbacks: true) | ||
txn.create!(User, { name: 'bob' }, { skip_callbacks: true }) | ||
end | ||
Dynamoid::TransactionWrite.execute do |txn| | ||
txn.save!(user, skip_validation: true) | ||
txn.create!(User, { name: 'bob' }, { skip_validation: true }) | ||
end | ||
``` | ||
|
||
### Validation failures that don't raise | ||
All of the transaction methods can be called without the bang! which results in | ||
false instead of a raised exception when validation fails. | ||
Ignoring validation failures can lead to confusion or bugs so always check return status when not using a bang! | ||
|
||
```ruby | ||
user = User.find(1) | ||
user.red = true | ||
Dynamoid::TransactionWrite.execute do |txn| | ||
if txn.save(user) # won't raise validation exception | ||
txn.update(UserCount, id: 'UserCount#Red', count: 5) | ||
else | ||
puts 'ALERT: user not valid, skipping' | ||
end | ||
end | ||
``` | ||
|
||
### Incrementally building a transaction | ||
Transactions can also be built without a block. | ||
|
||
```ruby | ||
transaction = Dynamoid::TransactionWrite.new | ||
transaction.create!(User, id: user_id) | ||
transaction.create!(UserEmail, id: "UserEmail##{email}", user_id: user_id) | ||
transaction.upsert!(Address, id: 'A#1', street: '123') | ||
transaction.commit | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
# frozen_string_literal: true | ||
|
||
# Prepare all the actions of the transaction for sending to the AWS SDK. | ||
module Dynamoid | ||
module AdapterPlugin | ||
class AwsSdkV3 | ||
class Transact | ||
attr_reader :client | ||
|
||
def initialize(client) | ||
@client = client | ||
end | ||
|
||
# Perform all of the item actions in a single transaction. | ||
# | ||
# @param [Array] items of type Dynamoid::Transaction::Action or | ||
# any other object whose to_h is a transact_item hash | ||
# | ||
def transact_write_items(items) | ||
transact_items = items.map(&:to_h) | ||
params = { | ||
transact_items: transact_items, | ||
return_consumed_capacity: 'TOTAL', | ||
return_item_collection_metrics: 'SIZE' | ||
} | ||
client.transact_write_items(params) # returns this | ||
end | ||
end | ||
end | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,101 @@ | ||
# frozen_string_literal: true | ||
|
||
require 'dynamoid/transaction_write/action' | ||
require 'dynamoid/transaction_write/create' | ||
require 'dynamoid/transaction_write/delete' | ||
require 'dynamoid/transaction_write/destroy' | ||
require 'dynamoid/transaction_write/update_upsert' | ||
require 'dynamoid/transaction_write/update' | ||
require 'dynamoid/transaction_write/upsert' | ||
|
||
module Dynamoid | ||
class TransactionWrite | ||
attr_accessor :action_inputs, :models | ||
|
||
def initialize(_options = {}) | ||
@action_inputs = [] | ||
@models = [] | ||
end | ||
|
||
def self.execute(options = {}) | ||
transaction = new(options) | ||
yield(transaction) | ||
transaction.commit | ||
end | ||
|
||
def commit | ||
return unless @action_inputs.present? # nothing to commit | ||
|
||
Dynamoid.adapter.transact_write_items(@action_inputs) | ||
models.each { |model| model.new_record = false } | ||
end | ||
|
||
def save!(model, options = {}) | ||
save(model, options.reverse_merge(raise_validation_error: true)) | ||
end | ||
|
||
def save(model, options = {}) | ||
model.new_record? ? create(model, {}, options) : update(model, {}, options) | ||
end | ||
|
||
def create!(model_or_model_class, attributes = {}, options = {}) | ||
create(model_or_model_class, attributes, options.reverse_merge(raise_validation_error: true)) | ||
end | ||
|
||
def create(model_or_model_class, attributes = {}, options = {}) | ||
add_action_and_validate Dynamoid::TransactionWrite::Create.new(model_or_model_class, attributes, options) | ||
end | ||
|
||
# upsert! does not exist because upserting instances that can raise validation errors is not officially supported | ||
|
||
def upsert(model_or_model_class, attributes = {}, options = {}) | ||
add_action_and_validate Dynamoid::TransactionWrite::Upsert.new(model_or_model_class, attributes, options) | ||
end | ||
|
||
def update!(model_or_model_class, attributes = {}, options = {}) | ||
update(model_or_model_class, attributes, options.reverse_merge(raise_validation_error: true)) | ||
end | ||
|
||
def update(model_or_model_class, attributes = {}, options = {}) | ||
add_action_and_validate Dynamoid::TransactionWrite::Update.new(model_or_model_class, attributes, options) | ||
end | ||
|
||
def delete(model_or_model_class, key_or_attributes = {}, options = {}) | ||
add_action_and_validate Dynamoid::TransactionWrite::Delete.new(model_or_model_class, key_or_attributes, options) | ||
end | ||
|
||
def destroy!(model_or_model_class, key_or_attributes = {}, options = {}) | ||
destroy(model_or_model_class, key_or_attributes, options.reverse_merge(raise_validation_error: true)) | ||
end | ||
|
||
def destroy(model_or_model_class, key_or_attributes = {}, options = {}) | ||
add_action_and_validate Dynamoid::TransactionWrite::Destroy.new(model_or_model_class, key_or_attributes, options) | ||
end | ||
|
||
private | ||
|
||
# validates unless validations are skipped | ||
# runs callbacks unless callbacks are skipped | ||
# raise validation error or returns false if not valid | ||
# otherwise adds hash of action to list in preparation for committing | ||
def add_action_and_validate(action) | ||
if !action.skip_validation? && !action.valid? | ||
raise Dynamoid::Errors::DocumentNotValid, action.model if action.raise_validation_error? | ||
|
||
return false | ||
end | ||
|
||
if action.skip_callbacks? | ||
@action_inputs << action.to_h | ||
else | ||
action.run_callbacks do | ||
@action_inputs << action.to_h | ||
end | ||
end | ||
action.changes_applied # action has been processed and added to queue so mark as applied | ||
models << action.model if action.model | ||
|
||
action.model || true # return model if it exists | ||
end | ||
end | ||
end |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
minor: Not the perfect name for a class.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Any suggestions? This class wraps TransactWriteItems and someday maybe TransactGetItems as named by AWS.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
TBH I would move
transact_write_items
into the main plugin class. It's small and simple enough (what was a reason to move some methods into separate classes)