2021-01-27 09:07:26 +13:00
|
|
|
defmodule AshPostgres.Test.UniqueIdentityTest do
|
|
|
|
use AshPostgres.RepoCase, async: false
|
2024-03-28 09:52:28 +13:00
|
|
|
alias AshPostgres.Test.Post
|
2021-01-27 09:07:26 +13:00
|
|
|
|
|
|
|
require Ash.Query
|
|
|
|
|
|
|
|
test "unique constraint errors are properly caught" do
|
|
|
|
post =
|
|
|
|
Post
|
2024-03-28 09:52:28 +13:00
|
|
|
|> Ash.Changeset.for_create(:create, %{title: "title"})
|
|
|
|
|> Ash.create!()
|
2021-01-27 09:07:26 +13:00
|
|
|
|
|
|
|
assert_raise Ash.Error.Invalid,
|
|
|
|
~r/Invalid value provided for id: has already been taken/,
|
|
|
|
fn ->
|
|
|
|
Post
|
2024-03-28 09:52:28 +13:00
|
|
|
|> Ash.Changeset.for_create(:create, %{id: post.id})
|
|
|
|
|> Ash.create!()
|
2021-01-27 09:07:26 +13:00
|
|
|
end
|
|
|
|
end
|
2022-07-02 11:12:14 +12:00
|
|
|
|
|
|
|
test "a unique constraint can be used to upsert when the resource has a base filter" do
|
|
|
|
post =
|
|
|
|
Post
|
2024-03-28 09:52:28 +13:00
|
|
|
|> Ash.Changeset.for_create(:create, %{
|
|
|
|
title: "title",
|
|
|
|
uniq_one: "fred",
|
|
|
|
uniq_two: "astair",
|
|
|
|
price: 10
|
|
|
|
})
|
|
|
|
|> Ash.create!()
|
2022-07-02 11:12:14 +12:00
|
|
|
|
|
|
|
new_post =
|
|
|
|
Post
|
2024-03-28 09:52:28 +13:00
|
|
|
|> Ash.Changeset.for_create(:create, %{
|
|
|
|
title: "title2",
|
|
|
|
uniq_one: "fred",
|
|
|
|
uniq_two: "astair"
|
|
|
|
})
|
|
|
|
|> Ash.create!(upsert?: true, upsert_identity: :uniq_one_and_two)
|
2022-07-02 11:12:14 +12:00
|
|
|
|
|
|
|
assert new_post.id == post.id
|
|
|
|
assert new_post.price == 10
|
|
|
|
end
|
2024-06-18 03:38:28 +12:00
|
|
|
|
|
|
|
test "a unique constraint can be used to upsert when backed by a calculation" do
|
|
|
|
post =
|
|
|
|
Post
|
|
|
|
|> Ash.Changeset.for_create(:create, %{
|
|
|
|
title: "title",
|
|
|
|
uniq_if_contains_foo: "abcfoodef",
|
|
|
|
price: 10
|
|
|
|
})
|
|
|
|
|> Ash.create!()
|
|
|
|
|
|
|
|
new_post =
|
|
|
|
Post
|
|
|
|
|> Ash.Changeset.for_create(:create, %{
|
|
|
|
title: "title2",
|
|
|
|
uniq_if_contains_foo: "abcfoodef"
|
|
|
|
})
|
|
|
|
|> Ash.create!(upsert?: true, upsert_identity: :uniq_if_contains_foo)
|
|
|
|
|
|
|
|
assert new_post.id == post.id
|
|
|
|
assert new_post.price == 10
|
|
|
|
end
|
2021-01-27 09:07:26 +13:00
|
|
|
end
|