Skip to content

Commit

Permalink
fix: primary keys are implicitly uniquely constrained.
Browse files Browse the repository at this point in the history
Closes #332.
  • Loading branch information
jimsynz committed Jun 15, 2023
1 parent 7b46e13 commit 424085b
Showing 1 changed file with 31 additions and 18 deletions.
49 changes: 31 additions & 18 deletions lib/ash_authentication/validations/attribute.ex
Original file line number Diff line number Diff line change
Expand Up @@ -60,28 +60,41 @@ defmodule AshAuthentication.Validations.Attribute do
"""
@spec validate_attribute_unique_constraint(map, [atom], module) :: :ok | {:error, Exception.t()}
def validate_attribute_unique_constraint(dsl_state, fields, resource) do
message =
case fields do
[field] ->
"The `#{inspect(field)}` attribute on the resource `#{inspect(resource)}` should be uniquely constrained"

[_ | _] = fields ->
fields =
fields
|> Enum.map(&"`#{&1}`")
|> to_sentence(final: "and")
fields = MapSet.new(fields)

"The #{fields} attributes on the resource `#{inspect(resource)}` should be uniquely constrained"
end
identities =
dsl_state
|> Info.identities()
|> Enum.map(&MapSet.new(&1.keys))

fields = MapSet.new(fields)
primary_key =
dsl_state
|> Info.primary_key()
|> MapSet.new()

dsl_state
|> Info.identities()
|> Enum.find(&MapSet.equal?(MapSet.new(&1.keys), fields))
identities
|> Enum.concat(primary_key)
|> Enum.find(&MapSet.equal?(&1, fields))
|> case do
nil -> {:error, DslError.exception(path: [:identities, :identity], message: message)}
_ -> :ok
nil ->
message =
case Enum.to_list(fields) do
[field] ->
"The `#{inspect(field)}` attribute on the resource `#{inspect(resource)}` should be uniquely constrained"

[_ | _] = fields ->
fields =
fields
|> Enum.map(&"`#{&1}`")
|> to_sentence(final: "and")

"The #{fields} attributes on the resource `#{inspect(resource)}` should be uniquely constrained"
end

{:error, DslError.exception(path: [:identities, :identity], message: message)}

_ ->
:ok
end
end
end

0 comments on commit 424085b

Please sign in to comment.