Skip to content

Commit

Permalink
fix: handle list of atomic conditions (#1194) (#1195)
Browse files Browse the repository at this point in the history
  • Loading branch information
danielatdpg authored May 22, 2024
1 parent 3e7f691 commit 05379e1
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
14 changes: 14 additions & 0 deletions lib/ash/changeset/changeset.ex
Original file line number Diff line number Diff line change
Expand Up @@ -885,6 +885,20 @@ defmodule Ash.Changeset do
{:error, _} ->
{:cont, {:atomic, false}}

[{:atomic, _, expr, _as_error} | rest] ->
exprs = [expr | Enum.map(rest, &elem(&1, 2))]

new_expr =
Enum.reduce(exprs, condition, fn expr, condition ->
if condition == true do
expr
else
expr(^condition and ^expr)
end
end)

{:cont, {:atomic, new_expr}}

{:atomic, _, expr, _as_error} ->
new_expr =
if condition == true do
Expand Down
51 changes: 51 additions & 0 deletions test/changeset/changeset_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,43 @@ defmodule Ash.Test.Changeset.ChangesetTest do
end
end

defmodule ResourceWithMultipleConstraintChanges do
@moduledoc false
use Ash.Resource, domain: Domain, data_layer: Ash.DataLayer.Ets

ets do
private?(true)
end

actions do
default_accept :*
defaults [:read, :destroy, create: :*, update: :*]
end

attributes do
uuid_primary_key :id

attribute :publication_status, :atom do
public? true
allow_nil? false
default :draft
end

attribute :published_at, :utc_datetime_usec, public?: true
end

changes do
change set_attribute(:publication_status, :published) do
where [
attribute_equals(:published_at, nil),
compare(:published_at,
less_than_or_equal_to: &DateTime.utc_now/0
)
]
end
end
end

describe "new" do
test "it wraps a new resource in a `create` changeset" do
assert %Ash.Changeset{
Expand Down Expand Up @@ -1202,4 +1239,18 @@ defmodule Ash.Test.Changeset.ChangesetTest do
refute Ash.Changeset.present?(changeset, :author_id)
end
end

test "some test" do
resource =
ResourceWithMultipleConstraintChanges
|> Ash.Changeset.for_create(:create, %{})
|> Ash.create!()

updated_resource =
resource
|> Ash.Changeset.for_update(:update, %{published_at: ~U[2024-01-01T09:22:22Z]})
|> Ash.update!()

assert :published == updated_resource.publication_status
end
end

0 comments on commit 05379e1

Please sign in to comment.