Skip to content

raise error if the constraint is created on a field that doesn't exist #579

New issue

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

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

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
6 changes: 6 additions & 0 deletions lib/migration_generator/migration_generator.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
31 changes: 31 additions & 0 deletions test/migration_generator_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down