Skip to content

Fix generated foreign key constraint on specially named references #572

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Merged
merged 1 commit into from
Jun 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion lib/data_layer.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2682,8 +2682,15 @@ defmodule AshPostgres.DataLayer do
resource
|> Ash.Resource.Info.relationships()
|> Enum.reduce(changeset, fn relationship, changeset ->
# Check if there's a custom reference name defined in the DSL
name =
"#{AshPostgres.DataLayer.Info.table(resource)}_#{relationship.source_attribute}_fkey"
case AshPostgres.DataLayer.Info.reference(resource, relationship.name) do
%{name: custom_name} when not is_nil(custom_name) ->
custom_name

_ ->
"#{AshPostgres.DataLayer.Info.table(resource)}_#{relationship.source_attribute}_fkey"
end

case repo.default_constraint_match_type(:foreign, name) do
{:regex, regex} ->
Expand Down
23 changes: 23 additions & 0 deletions test/references_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -105,4 +105,27 @@
end
end
end

test "named reference results in properly applied foreign_key_constraint/3 on the underlying changeset" do

Check failure on line 109 in test/references_test.exs

View workflow job for this annotation

GitHub Actions / ash-ci (15) / mix test

test named reference results in properly applied foreign_key_constraint/3 on the underlying changeset (AshPostgres.ReferencesTest)

Check failure on line 109 in test/references_test.exs

View workflow job for this annotation

GitHub Actions / ash-ci (16) / mix test

test named reference results in properly applied foreign_key_constraint/3 on the underlying changeset (AshPostgres.ReferencesTest)
# Create a comment with an invalid post_id
assert {:error, %Ash.Error.Invalid{errors: errors}} =
AshPostgres.Test.Comment
|> Ash.Changeset.for_create(:create, %{
title: "Test Comment",
# This post doesn't exist
post_id: Ash.UUID.generate()
})
|> Ash.create()

assert [
%Ash.Error.Changes.InvalidAttribute{
field: :post_id,
message: "does not exist",
private_vars: private_vars
}
] = errors

assert Keyword.get(private_vars, :constraint) == "special_name_fkey"
assert Keyword.get(private_vars, :constraint_type) == :foreign_key
end
end
Loading