Skip to content

Commit

Permalink
Run delete operation in a transaction (#1055)
Browse files Browse the repository at this point in the history
* Run delete operations in a transaction

* Add `after_commit` callback to delete operations
  • Loading branch information
akadusei authored Aug 12, 2024
1 parent bec9058 commit a604962
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 6 deletions.
7 changes: 7 additions & 0 deletions spec/avram/operations/delete_operation_callbacks_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,19 @@ private class DeleteOperationWithCallbacks < User::DeleteOperation
mark_callback("after_delete_in_a_block with #{deleted_user.name}")
end

after_commit :run_after_commit

private def update_number
mark_callback("before_delete_update_number")
end

private def notify_complete(deleted_user)
mark_callback("after_delete_notify_complete is #{deleted_user.name}")
end

private def run_after_commit(deleted_user)
mark_callback("after_commit_#{deleted_user.name.underscore}")
end
end

describe "Avram::DeleteOperation callbacks" do
Expand All @@ -41,6 +47,7 @@ describe "Avram::DeleteOperation callbacks" do
operation.callbacks_that_ran.should contain "before_delete_in_a_block"
operation.callbacks_that_ran.should contain "after_delete_notify_complete is Jerry"
operation.callbacks_that_ran.should contain "after_delete_in_a_block with Jerry"
operation.callbacks_that_ran.should contain "after_commit_jerry"
end
end
end
28 changes: 22 additions & 6 deletions src/avram/delete_operation.cr
Original file line number Diff line number Diff line change
Expand Up @@ -35,18 +35,32 @@ abstract class Avram::DeleteOperation(T)
T.name.underscore
end

delegate :database, :table_name, :primary_key_name, to: T

def delete : Bool
before_delete

if valid?
result = delete_or_soft_delete(@record)
@record = result
after_delete(@record)
publish_delete_success_event
mark_as_deleted
transaction_committed = database.transaction do
@record = delete_or_soft_delete(record)
after_delete(record)
true
end

if transaction_committed
mark_as_deleted
after_commit(record)
publish_delete_success_event
true
else
mark_as_failed
publish_delete_failed_event
false
end
else
publish_delete_failed_event
mark_as_failed
publish_delete_failed_event
false
end
end

Expand Down Expand Up @@ -88,6 +102,8 @@ abstract class Avram::DeleteOperation(T)

def after_delete(_record : T); end

def after_commit(_record : T); end

# :nodoc:
def publish_delete_failed_event
Avram::Events::DeleteFailedEvent.publish(
Expand Down

0 comments on commit a604962

Please sign in to comment.