From cc84272b73074b1523ee83d5f21f88e9fca41a2c Mon Sep 17 00:00:00 2001 From: Oliver Severin Mulelid-Tynes Date: Thu, 19 Jun 2025 18:20:35 +0200 Subject: [PATCH] Fix foreign key constraint on specially named references --- lib/data_layer.ex | 9 ++++++++- test/references_test.exs | 23 +++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/lib/data_layer.ex b/lib/data_layer.ex index ddfdc060..22efd25e 100644 --- a/lib/data_layer.ex +++ b/lib/data_layer.ex @@ -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} -> diff --git a/test/references_test.exs b/test/references_test.exs index afb89acd..626a2d97 100644 --- a/test/references_test.exs +++ b/test/references_test.exs @@ -105,4 +105,27 @@ defmodule AshPostgres.ReferencesTest do end end end + + test "named reference results in properly applied foreign_key_constraint/3 on the underlying changeset" do + # 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