Skip to content

Commit

Permalink
Add returning option to update_all (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
rschef authored Aug 17, 2020
1 parent 8f70ba4 commit 3f4f6f3
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
3 changes: 2 additions & 1 deletion lib/paper_trail.ex
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ defmodule PaperTrail do
prefix: prefix,
model_key: multi_name,
version_key: multi_name,
return_operation: multi_name
return_operation: multi_name,
returning: boolean()
]

@type result :: {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()}
Expand Down
3 changes: 2 additions & 1 deletion lib/paper_trail/multi.ex
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ defmodule PaperTrail.Multi do
model_key = get_model_key(options)
version_key = get_version_key(options)
entries = make_version_structs(%{event: "update"}, queryable, changes, options)
returning = !!options[:returning] && RepoClient.return_operation(options) == version_key

case RepoClient.strict_mode(options) do
true ->
Expand All @@ -156,7 +157,7 @@ defmodule PaperTrail.Multi do
_ ->
multi
|> Ecto.Multi.update_all(model_key, queryable, updates)
|> Ecto.Multi.insert_all(version_key, Version, entries)
|> Ecto.Multi.insert_all(version_key, Version, entries, returning: returning)
end
end

Expand Down
17 changes: 17 additions & 0 deletions test/paper_trail/base_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -640,6 +640,23 @@ defmodule PaperTrailTest do
] = PaperTrail.VersionQueries.get_versions(User, user3.id)
end

test "update_all with returning option returns inserted version" do
create_user()
%{id: user2_id} = create_user()
%{id: user3_id} = create_user()
ids = [user2_id, user3_id]
new_username = "isaac"

{2, [%PaperTrail.Version{item_id: ^user2_id}, %PaperTrail.Version{item_id: ^user3_id}]} =
User
|> where([p], p.id in ^ids)
|> CustomPaperTrail.update_all(
[set: [username: new_username]],
returning: true,
return_operation: :version
)
end

defp create_user do
User.changeset(%User{}, %{token: "fake-token", username: "izelnakri"}) |> @repo.insert!
end
Expand Down

0 comments on commit 3f4f6f3

Please sign in to comment.