-
-
Notifications
You must be signed in to change notification settings - Fork 180
/
default_primary_key.ex
50 lines (43 loc) · 1.53 KB
/
default_primary_key.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
defmodule Ash.Resource.Transformers.DefaultPrimaryKey do
@moduledoc """
Creates the default primary key if one applies.
Currently, the only resources that get a default primary key are embedded resources.
The reason for this is that resources must have a primary key, and embedded resources
actually make sense without one. But this is simulated with a private uuid primary key.
"""
use Ash.Dsl.Transformer
alias Ash.Dsl.Transformer
alias Ash.Error.Dsl.DslError
@extension Module.concat(["Ash", Resource, Dsl])
def transform(resource, dsl_state) do
if Ash.Resource.Info.embedded?(resource) do
has_pkey? =
resource
|> Ash.Resource.Info.attributes()
|> Enum.any?(& &1.primary_key?)
if has_pkey? do
{:ok, dsl_state}
else
case Transformer.build_entity(@extension, [:attributes], :uuid_primary_key,
name: :autogenerated_id,
private?: true
) do
{:ok, attribute} ->
{:ok, Transformer.add_entity(dsl_state, [:attributes], attribute)}
{:error, error} ->
{:error,
DslError.exception(
module: __MODULE__,
message:
"Could not create default primary key for embedded resource: #{inspect(error)}",
path: [:attributes, :autogenerated_id]
)}
end
end
else
{:ok, dsl_state}
end
end
def after?(Ash.Resource.Transformers.BelongsToSourceField), do: true
def after?(_), do: false
end