From 57ec307420e1e1c826d07ea8f923504058ec4657 Mon Sep 17 00:00:00 2001 From: marco Dell'Olio Date: Sun, 29 Jun 2025 20:47:10 -0400 Subject: [PATCH] raise error if the constraint is created on a field that doesn't exist --- .../migration_generator.ex | 6 ++++ test/migration_generator_test.exs | 31 +++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/lib/migration_generator/migration_generator.ex b/lib/migration_generator/migration_generator.ex index a5984a67..8a7df6e8 100644 --- a/lib/migration_generator/migration_generator.ex +++ b/lib/migration_generator/migration_generator.ex @@ -3125,6 +3125,12 @@ defmodule AshPostgres.MigrationGenerator do resource |> Ash.Resource.Info.attribute(attribute) + if is_nil(attr) do + raise """ + Cannot create the check constraint '#{constraint.name}', the attribute '#{attribute}' does not exist in the resource '#{resource}' or is nil. + """ + end + attr.source || attr.name end) diff --git a/test/migration_generator_test.exs b/test/migration_generator_test.exs index e284e847..a315e13f 100644 --- a/test/migration_generator_test.exs +++ b/test/migration_generator_test.exs @@ -2425,6 +2425,37 @@ defmodule AshPostgres.MigrationGeneratorTest do assert File.read!(file) =~ ~S[drop_if_exists constraint(:posts, :price_must_be_positive)] end + + test "raise an error if the attribute does not exist or is nil" do + defposts do + attributes do + uuid_primary_key(:id) + attribute(:price, :integer, public?: true) + end + + postgres do + check_constraints do + check_constraint(:whatever, "price_must_be_positive", check: ~S["price" > 0]) + end + end + end + + defdomain([Post]) + + error = + assert_raise RuntimeError, fn -> + AshPostgres.MigrationGenerator.generate(Domain, + snapshot_path: "test_snapshots_path", + migration_path: "test_migration_path", + quiet: true, + format: false, + auto_name: true + ) + end + + assert error.message =~ + "Cannot create the check constraint 'price_must_be_positive', the attribute 'whatever' does not exist in the resource 'Elixir.Post' or is nil." + end end describe "polymorphic resources" do