This commit is contained in:
Barnabas Jovanovics 2024-07-22 16:26:39 +02:00
parent 01edc539fc
commit 2e7ab8bcaa
2 changed files with 36 additions and 0 deletions

View file

@ -1,4 +1,5 @@
defmodule AshPostgres.AtomicsTest do
alias AshPostgres.Test.Comment
alias AshPostgres.Test.Author
use AshPostgres.RepoCase, async: false
alias AshPostgres.Test.Post
@ -291,4 +292,24 @@ defmodule AshPostgres.AtomicsTest do
|> Ash.bulk_update!(:set_title_from_author, %{}, return_records?: true)
|> Map.get(:records)
end
test "can use list aggregate in validation" do
post =
Post
|> Ash.Changeset.for_create(:create, %{title: "foo", price: 1})
|> Ash.create!()
Comment
|> Ash.Changeset.for_create(:create, %{post_id: post.id, title: "foo"})
|> Ash.create!()
|> dbg()
Logger.configure(level: :debug)
assert_raise Ash.Error.Invalid, ~r/Can only delete if Post has no comments/, fn ->
post
|> Ash.Changeset.for_destroy(:destroy_if_no_comments, %{})
|> Ash.destroy()
end
end
end

View file

@ -13,6 +13,17 @@ defmodule PassIfOriginalDataPresent do
end
end
defmodule HasNoComments do
alias Ash.Error.Invalid
use Ash.Resource.Validation
def atomic(_changeset, _opts, _context) do
# This uses the list aggregate because we want to specifically test this aggregate
{:atomic, [], expr(list(comments, field: :id) > 0),
expr(error(^Invalid, %{message: "Can only delete if Post has no comments"}))}
end
end
defmodule AshPostgres.Test.Post do
@moduledoc false
use Ash.Resource,
@ -92,6 +103,10 @@ defmodule AshPostgres.Test.Post do
change(filter(expr(title == "fred")))
end
destroy :destroy_if_no_comments do
validate(HasNoComments)
end
update :update_only_freds do
change(filter(expr(title == "fred")))
end