Skip to content

Commit adf7a04

Browse files
authored
fix: Fix foreign key constraint on specially named references (#572)
1 parent abaa6e7 commit adf7a04

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

lib/data_layer.ex

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2682,8 +2682,15 @@ defmodule AshPostgres.DataLayer do
26822682
resource
26832683
|> Ash.Resource.Info.relationships()
26842684
|> Enum.reduce(changeset, fn relationship, changeset ->
2685+
# Check if there's a custom reference name defined in the DSL
26852686
name =
2686-
"#{AshPostgres.DataLayer.Info.table(resource)}_#{relationship.source_attribute}_fkey"
2687+
case AshPostgres.DataLayer.Info.reference(resource, relationship.name) do
2688+
%{name: custom_name} when not is_nil(custom_name) ->
2689+
custom_name
2690+
2691+
_ ->
2692+
"#{AshPostgres.DataLayer.Info.table(resource)}_#{relationship.source_attribute}_fkey"
2693+
end
26872694

26882695
case repo.default_constraint_match_type(:foreign, name) do
26892696
{:regex, regex} ->

test/references_test.exs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,4 +105,27 @@ defmodule AshPostgres.ReferencesTest do
105105
end
106106
end
107107
end
108+
109+
test "named reference results in properly applied foreign_key_constraint/3 on the underlying changeset" do
110+
# Create a comment with an invalid post_id
111+
assert {:error, %Ash.Error.Invalid{errors: errors}} =
112+
AshPostgres.Test.Comment
113+
|> Ash.Changeset.for_create(:create, %{
114+
title: "Test Comment",
115+
# This post doesn't exist
116+
post_id: Ash.UUID.generate()
117+
})
118+
|> Ash.create()
119+
120+
assert [
121+
%Ash.Error.Changes.InvalidAttribute{
122+
field: :post_id,
123+
message: "does not exist",
124+
private_vars: private_vars
125+
}
126+
] = errors
127+
128+
assert Keyword.get(private_vars, :constraint) == "special_name_fkey"
129+
assert Keyword.get(private_vars, :constraint_type) == :foreign_key
130+
end
108131
end

0 commit comments

Comments
 (0)