/
changeset.ex
877 lines (734 loc) · 27.2 KB
/
changeset.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
defmodule Ash.Changeset do
@moduledoc """
Changesets are used to create and update data in Ash.
Create a changeset with `new/1` or `new/2`, and alter the attributes
and relationships using the functions provided in this module. Nothing in this module
actually incurs changes in a data layer. To commit a changeset, see `c:Ash.Api.create/2`
and `c:Ash.Api.update/2`.
## Primary Keys
For relationship manipulation using `append_to_relationship/3`, `remove_from_relationship/3`
and `replace_relationship/3` there are three types that can be used for primary keys:
1.) An instance of the resource in question.
2.) If the primary key is just a single field, i.e `:id`, then a single value, i.e `1`
3.) A map of keys to values representing the primary key, i.e `%{id: 1}` or `%{id: 1, org_id: 2}`
## Join Attributes
For many to many relationships, the attributes on a join relationship may be set while relating items
by passing a tuple of the primary key and the changes to be applied. This is done via upserts, so
update validations on the join resource are *not* applied, but create validations are.
For example:
```elixir
Ash.Changeset.replace_relationship(changeset, :linked_tickets, [
{1, %{link_type: "blocking"}},
{a_ticket, %{link_type: "caused_by"}},
{%{id: 2}, %{link_type: "related_to"}}
])
```
"""
defstruct [
:data,
:action_type,
:resource,
:api,
:tenant,
arguments: %{},
context: %{},
after_action: [],
before_action: [],
errors: [],
valid?: true,
attributes: %{},
relationships: %{},
change_dependencies: [],
requests: []
]
defimpl Inspect do
import Inspect.Algebra
def inspect(changeset, opts) do
container_doc(
"#Ash.Changeset<",
[
concat("action_type: ", inspect(changeset.action_type)),
concat("attributes: ", to_doc(changeset.attributes, opts)),
concat("relationships: ", to_doc(changeset.relationships, opts)),
concat("errors: ", to_doc(changeset.errors, opts)),
concat("data: ", to_doc(changeset.data, opts)),
concat("valid?: ", to_doc(changeset.valid?, opts))
],
">",
opts,
fn str, _ -> str end
)
end
end
@type t :: %__MODULE__{}
alias Ash.Error.{
Changes.InvalidArgument,
Changes.InvalidAttribute,
Changes.InvalidRelationship,
Changes.NoSuchAttribute,
Changes.NoSuchRelationship,
Changes.Required,
Invalid.NoSuchResource
}
@doc "Return a changeset over a resource or a record"
@spec new(Ash.resource() | Ash.record(), initial_attributes :: map) :: t
def new(resource, initial_attributes \\ %{})
def new(%resource{} = record, initial_attributes) do
tenant =
record
|> Map.get(:__metadata__, %{})
|> Map.get(:tenant, nil)
if Ash.Resource.resource?(resource) do
%__MODULE__{resource: resource, data: record, action_type: :update}
|> change_attributes(initial_attributes)
|> set_tenant(tenant)
else
%__MODULE__{resource: resource, action_type: :create, data: struct(resource)}
|> add_error(NoSuchResource.exception(resource: resource))
|> set_tenant(tenant)
end
end
def new(resource, initial_attributes) do
if Ash.Resource.resource?(resource) do
%__MODULE__{resource: resource, action_type: :create, data: struct(resource)}
|> change_attributes(initial_attributes)
else
%__MODULE__{resource: resource, action_type: :create, data: struct(resource)}
|> add_error(NoSuchResource.exception(resource: resource))
end
end
@doc """
Wraps a function in the before/after action hooks of a changeset.
The function takes a changeset and if it returns
`{:ok, result}`, the result will be passed through the after
action hooks.
"""
@spec with_hooks(
t(),
(t() ->
{:ok, Ash.record(), %{notifications: list(Ash.notification())}} | {:error, term})
) ::
{:ok, term} | {:error, term}
def with_hooks(changeset, func) do
changeset =
Enum.reduce_while(changeset.before_action, changeset, fn before_action, changeset ->
case before_action.(changeset) do
%{valid?: true} = changeset -> {:cont, changeset}
changeset -> {:halt, changeset}
end
end)
if changeset.valid? do
case func.(changeset) do
{:ok, result} ->
Enum.reduce_while(
changeset.after_action,
{:ok, result, %{notifications: []}},
fn after_action, {:ok, result, %{notifications: notifications} = acc} ->
case after_action.(changeset, result) do
{:ok, new_result, new_notifications} ->
{:cont,
{:ok, new_result, %{acc | notifications: notifications ++ new_notifications}}}
{:ok, new_result} ->
{:cont, {:ok, new_result, acc}}
{:error, error} ->
{:halt, {:error, error}}
end
end
)
{:error, error} ->
{:error, error}
end
else
{:error, changeset.errors}
end
end
@doc "Gets the changing value or the original value of an attribute"
@spec get_attribute(t, atom) :: term
def get_attribute(changeset, attribute) do
case fetch_change(changeset, attribute) do
{:ok, value} ->
value
:error ->
get_data(changeset, attribute)
end
end
@doc "Gets the new value for an attribute, or `:error` if it is not being changed"
@spec fetch_change(t, atom) :: {:ok, any} | :error
def fetch_change(changeset, attribute) do
Map.fetch(changeset.attributes, attribute)
end
@doc "Gets the original value for an attribute"
@spec get_data(t, atom) :: {:ok, any} | :error
def get_data(changeset, attribute) do
Map.get(changeset.data, attribute)
end
@spec put_context(t(), atom, term) :: t()
def put_context(changeset, key, value) do
%{changeset | context: Map.put(changeset.context, key, value)}
end
@spec set_tenant(t(), String.t()) :: t()
def set_tenant(changeset, tenant) do
%{changeset | tenant: tenant}
end
@spec set_context(t(), map) :: t()
def set_context(changeset, map) do
%{changeset | context: Map.merge(changeset.context, map)}
end
@doc false
def cast_arguments(changeset, action) do
Enum.reduce(action.arguments, %{changeset | arguments: %{}}, fn argument, new_changeset ->
value = Map.get(changeset.arguments, argument.name)
if is_nil(value) && !argument.allow_nil? do
Ash.Changeset.add_error(
changeset,
Required.exception(field: argument.name, type: :argument)
)
else
with {:ok, casted} <- Ash.Type.cast_input(argument.type, value),
:ok <- Ash.Type.apply_constraints(argument.type, casted, argument.constraints) do
%{new_changeset | arguments: Map.put(new_changeset.arguments, argument.name, value)}
else
_ ->
Ash.Changeset.add_error(
changeset,
InvalidArgument.exception(field: argument.name)
)
end
end
end)
end
@doc """
Appends a record or a list of records to a relationship. Stacks with previous removals/additions.
Accepts a primary key or a list of primary keys. See the section on "Primary Keys" in the
module documentation for more.
For many to many relationships, accepts changes for any `join_attributes` configured on
the resource. See the section on "Join Attributes" in the module documentation for more.
Cannot be used with `belongs_to` or `has_one` relationships.
See `replace_relationship/3` for manipulating `belongs_to` and `has_one` relationships.
"""
@spec append_to_relationship(t, atom, Ash.primary_key() | [Ash.primary_key()]) :: t()
def append_to_relationship(changeset, relationship, record_or_records) do
case Ash.Resource.relationship(changeset.resource, relationship) do
nil ->
error =
NoSuchRelationship.exception(
resource: changeset.resource,
name: relationship
)
add_error(changeset, error)
%{cardinality: :one, type: type} = relationship ->
error =
InvalidRelationship.exception(
relationship: relationship.name,
message: "Cannot append to a #{type} relationship"
)
add_error(changeset, error)
%{writable?: false} = relationship ->
error =
InvalidRelationship.exception(
relationship: relationship.name,
message: "Relationship is not editable"
)
add_error(changeset, error)
%{type: :many_to_many} = relationship ->
case primary_keys_with_changes(relationship, List.wrap(record_or_records)) do
{:ok, primary_keys} ->
relationships =
changeset.relationships
|> Map.put_new(relationship.name, %{})
|> add_to_relationship_key_and_reconcile(relationship, :add, primary_keys)
%{changeset | relationships: relationships}
{:error, error} ->
add_error(changeset, error)
end
relationship ->
case primary_key(relationship, List.wrap(record_or_records)) do
{:ok, primary_keys} ->
relationships =
changeset.relationships
|> Map.put_new(relationship.name, %{})
|> add_to_relationship_key_and_reconcile(relationship, :add, primary_keys)
%{changeset | relationships: relationships}
{:error, error} ->
add_error(changeset, error)
end
end
end
@doc """
Removes a record or a list of records to a relationship. Stacks with previous removals/additions.
Accepts a primary key or a list of primary keys. See the section on "Primary Keys" in the
module documentation for more.
Cannot be used with `belongs_to` or `has_one` relationships.
See `replace_relationship/3` for manipulating those relationships.
"""
@spec remove_from_relationship(t, atom, Ash.primary_key() | [Ash.primary_key()]) :: t()
def remove_from_relationship(changeset, relationship, record_or_records) do
case Ash.Resource.relationship(changeset.resource, relationship) do
nil ->
error =
NoSuchRelationship.exception(
resource: changeset.resource,
name: relationship
)
add_error(changeset, error)
%{cardinality: :one, type: type} = relationship ->
error =
InvalidRelationship.exception(
relationship: relationship.name,
message: "Cannot remove from a #{type} relationship"
)
add_error(changeset, error)
%{writable?: false} = relationship ->
error =
InvalidRelationship.exception(
relationship: relationship.name,
message: "Relationship is not editable"
)
add_error(changeset, error)
relationship ->
case primary_key(relationship, List.wrap(record_or_records)) do
{:ok, primary_keys} ->
relationships =
changeset.relationships
|> Map.put_new(relationship.name, %{})
|> add_to_relationship_key_and_reconcile(relationship, :remove, primary_keys)
%{changeset | relationships: relationships}
{:error, error} ->
add_error(changeset, error)
nil
end
end
end
defp add_to_relationship_key_and_reconcile(relationships, relationship, key, to_add) do
Map.update!(relationships, relationship.name, fn relationship_changes ->
relationship_changes
|> Map.put_new(key, [])
|> Map.update!(key, &Kernel.++(to_add, &1))
|> reconcile_relationship_changes()
end)
end
@doc """
Replaces the value of a relationship. Any previous additions/removals are cleared.
Accepts a primary key or a list of primary keys. See the section on "Primary Keys" in the
module documentation for more.
For many to many relationships, accepts changes for any `join_attributes` configured on
the resource. See the section on "Join Attributes" in the module documentation for more.
For a `has_many` or `many_to_many` relationship, this means removing any currently related
records that are not present in the replacement list, and creating any that do not exist
in the data layer.
For a `belongs_to` or `has_one`, replace with a `nil` value to unset a relationship.
"""
@spec replace_relationship(
t(),
atom(),
Ash.primary_key() | [Ash.primary_key()] | nil
) :: t()
def replace_relationship(changeset, relationship, record_or_records) do
case Ash.Resource.relationship(changeset.resource, relationship) do
nil ->
error =
NoSuchRelationship.exception(
resource: changeset.resource,
name: relationship
)
add_error(changeset, error)
%{writable?: false} = relationship ->
error =
InvalidRelationship.exception(
relationship: relationship.name,
message: "Relationship is not editable"
)
add_error(changeset, error)
%{cardinality: :one, type: type}
when is_list(record_or_records) and length(record_or_records) > 1 ->
error =
InvalidRelationship.exception(
relationship: relationship.name,
message: "Cannot replace a #{type} relationship with multiple records"
)
add_error(changeset, error)
%{type: :many_to_many} = relationship ->
case primary_keys_with_changes(relationship, List.wrap(record_or_records)) do
{:ok, primary_key} ->
relationships =
Map.put(changeset.relationships, relationship.name, %{replace: primary_key})
%{changeset | relationships: relationships}
{:error, error} ->
add_error(changeset, error)
end
relationship ->
records =
if relationship.cardinality == :one do
if is_list(record_or_records) do
List.first(record_or_records)
else
record_or_records
end
else
List.wrap(record_or_records)
end
case primary_key(relationship, records) do
{:ok, primary_key} ->
relationships =
Map.put(changeset.relationships, relationship.name, %{replace: primary_key})
changeset
|> check_entities_for_direct_write(relationship.name, List.wrap(records))
|> Map.put(:relationships, relationships)
{:error, error} ->
add_error(changeset, error)
end
end
end
defp check_entities_for_direct_write(changeset, relationship_name, records) do
if Enum.all?(records, &is_resource?/1) do
relation_entities =
Map.merge(Map.get(changeset.context, :destination_entities, %{}), %{
relationship_name => Enum.group_by(records, & &1.__struct__)
})
put_context(changeset, :destination_entities, relation_entities)
else
changeset
end
end
defp is_resource?(record) do
Ash.Resource.resource?(record.__struct__)
rescue
_error ->
false
end
@doc "Returns true if an attribute exists in the changes"
@spec changing_attribute?(t(), atom) :: boolean
def changing_attribute?(changeset, attribute) do
Map.has_key?(changeset.attributes, attribute)
end
@doc "Returns true if a relationship exists in the changes"
@spec changing_relationship?(t(), atom) :: boolean
def changing_relationship?(changeset, relationship) do
Map.has_key?(changeset.relationships, relationship)
end
@doc "Change an attribute only if is not currently being changed"
@spec change_new_attribute(t(), atom, term) :: t()
def change_new_attribute(changeset, attribute, value) do
if changing_attribute?(changeset, attribute) do
changeset
else
change_attribute(changeset, attribute, value)
end
end
@doc """
Change an attribute if is not currently being changed, by calling the provided function
Use this if you want to only perform some expensive calculation for an attribute value
only if there isn't already a change for that attribute
"""
@spec change_new_attribute_lazy(t(), atom, (() -> any)) :: t()
def change_new_attribute_lazy(changeset, attribute, func) do
if changing_attribute?(changeset, attribute) do
changeset
else
change_attribute(changeset, attribute, func.())
end
end
@doc """
Add an argument to the changeset, which will be provided to the action
"""
def set_argument(changeset, argument, value) do
%{changeset | arguments: Map.put(changeset.arguments, argument, value)}
end
@doc """
Remove an argument from the changeset
"""
def delete_argument(changeset, argument_or_arguments) do
argument_or_arguments
|> List.wrap()
|> Enum.reduce(changeset, fn argument, changeset ->
%{changeset | arguments: Map.delete(changeset.arguments, argument)}
end)
end
@doc """
Merge a map of arguments to the arguments list
"""
def set_arguments(changeset, map) do
%{changeset | arguments: Map.merge(changeset.arguments, map)}
end
@doc """
Force change an attribute if is not currently being changed, by calling the provided function
See `change_new_attribute_lazy/3` for more.
"""
@spec force_change_new_attribute_lazy(t(), atom, (() -> any)) :: t()
def force_change_new_attribute_lazy(changeset, attribute, func) do
if changing_attribute?(changeset, attribute) do
changeset
else
force_change_attribute(changeset, attribute, func.())
end
end
@doc "Calls `change_attribute/3` for each key/value pair provided"
@spec change_attributes(t(), map | Keyword.t()) :: t()
def change_attributes(changeset, changes) do
Enum.reduce(changes, changeset, fn {key, value}, changeset ->
change_attribute(changeset, key, value)
end)
end
@doc "Adds a change to the changeset, unless the value matches the existing value"
def change_attribute(changeset, attribute, value) do
case Ash.Resource.attribute(changeset.resource, attribute) do
nil ->
error =
NoSuchAttribute.exception(
resource: changeset.resource,
name: attribute
)
add_error(changeset, error)
%{writable?: false} = attribute ->
add_attribute_invalid_error(changeset, attribute, "Attribute is not writable")
attribute ->
with {:ok, casted} <- Ash.Type.cast_input(attribute.type, value),
:ok <- validate_allow_nil(attribute, casted),
:ok <- Ash.Type.apply_constraints(attribute.type, casted, attribute.constraints) do
data_value = Map.get(changeset.data, attribute.name)
cond do
is_nil(data_value) and is_nil(casted) ->
changeset
Ash.Type.equal?(attribute.type, casted, data_value) ->
changeset
true ->
%{changeset | attributes: Map.put(changeset.attributes, attribute.name, casted)}
end
else
:error ->
add_attribute_invalid_error(changeset, attribute)
{:error, error_or_errors} ->
error_or_errors
|> List.wrap()
|> Enum.reduce(changeset, &add_attribute_invalid_error(&2, attribute, &1))
end
end
end
@doc "Calls `force_change_attribute/3` for each key/value pair provided"
@spec force_change_attributes(t(), map) :: t()
def force_change_attributes(changeset, changes) do
Enum.reduce(changes, changeset, fn {key, value}, changeset ->
force_change_attribute(changeset, key, value)
end)
end
@doc "Changes an attribute even if it isn't writable"
@spec force_change_attribute(t(), atom, any) :: t()
def force_change_attribute(changeset, attribute, value) do
case Ash.Resource.attribute(changeset.resource, attribute) do
nil ->
error =
NoSuchAttribute.exception(
resource: changeset.resource,
name: attribute
)
add_error(changeset, error)
attribute ->
with {:ok, casted} <- Ash.Type.cast_input(attribute.type, value),
:ok <- Ash.Type.apply_constraints(attribute.type, casted, attribute.constraints) do
data_value = Map.get(changeset.data, attribute.name)
cond do
is_nil(data_value) and is_nil(casted) ->
changeset
Ash.Type.equal?(attribute.type, casted, data_value) ->
changeset
true ->
%{changeset | attributes: Map.put(changeset.attributes, attribute.name, casted)}
end
else
:error ->
add_attribute_invalid_error(changeset, attribute)
{:error, error_or_errors} ->
error_or_errors
|> List.wrap()
|> Enum.reduce(changeset, &add_attribute_invalid_error(&2, attribute, &1))
end
end
end
@doc "Adds a before_action hook to the changeset."
@spec before_action(t(), (t() -> t())) :: t()
def before_action(changeset, func) do
%{changeset | before_action: [func | changeset.before_action]}
end
@doc "Adds an after_action hook to the changeset."
@spec after_action(
t(),
(t(), Ash.record() ->
{:ok, Ash.record()} | {:ok, Ash.record(), list(Ash.notification())} | {:error, term})
) :: t()
def after_action(changeset, func) do
%{changeset | after_action: [func | changeset.after_action]}
end
@doc "Returns the original data with attribute changes merged."
@spec apply_attributes(t()) :: Ash.record()
def apply_attributes(changeset) do
Enum.reduce(changeset.attributes, changeset.data, fn {attribute, value}, data ->
Map.put(data, attribute, value)
end)
end
@doc "Adds an error to the changesets errors list, and marks the change as `valid?: false`"
@spec add_error(t(), Ash.error()) :: t()
def add_error(changeset, error) do
%{changeset | errors: [error | changeset.errors], valid?: false}
end
defp reconcile_relationship_changes(%{replace: _, add: add} = changes) do
changes
|> Map.delete(:add)
|> Map.update!(:replace, fn replace ->
replace ++ add
end)
|> reconcile_relationship_changes()
end
defp reconcile_relationship_changes(%{replace: _, remove: remove} = changes) do
changes
|> Map.delete(:remove)
|> Map.update!(:replace, fn replace ->
Enum.reject(replace, &(&1 in remove))
end)
|> reconcile_relationship_changes()
end
defp reconcile_relationship_changes(changes) do
changes
|> update_if_present(:replace, &uniq_if_list/1)
|> update_if_present(:remove, &uniq_if_list/1)
|> update_if_present(:add, &uniq_if_list/1)
end
defp uniq_if_list(list) when is_list(list), do: Enum.uniq(list)
defp uniq_if_list(other), do: other
defp update_if_present(map, key, func) do
if Map.has_key?(map, key) do
Map.update!(map, key, func)
else
map
end
end
defp through_changeset(relationship, changes) do
new(relationship.through, changes)
end
defp primary_keys_with_changes(_, []), do: {:ok, []}
defp primary_keys_with_changes(relationship, records) do
Enum.reduce_while(records, {:ok, []}, fn
{record, changes}, {:ok, acc} ->
with {:ok, primary_key} <- primary_key(relationship, record),
%{valid?: true} = changeset <- through_changeset(relationship, changes) do
{:cont, {:ok, [{primary_key, changeset} | acc]}}
else
%{valid?: false, errors: errors} -> {:halt, {:error, errors}}
{:error, error} -> {:halt, {:error, error}}
end
record, {:ok, acc} ->
case primary_key(relationship, record) do
{:ok, primary_keys} when is_list(primary_keys) ->
{:cont, {:ok, primary_keys ++ acc}}
{:ok, primary_key} ->
{:cont, {:ok, [primary_key | acc]}}
{:error, error} ->
{:halt, {:error, error}}
end
end)
end
defp primary_key(_, nil), do: {:ok, nil}
defp primary_key(relationship, records) when is_list(records) do
case Ash.Resource.primary_key(relationship.destination) do
[_field] ->
multiple_primary_keys(relationship, records)
_ ->
pluck_pk_fields(relationship, records)
end
end
defp primary_key(relationship, record) do
do_primary_key(relationship, record)
end
defp pluck_pk_fields(relationship, records) do
Enum.reduce_while(
records,
{:ok, []},
fn
record, {:ok, acc} ->
case do_primary_key(relationship, record) do
{:ok, pk} -> {:cont, {:ok, [pk | acc]}}
{:error, error} -> {:halt, {:error, error}}
end
end
)
end
defp do_primary_key(relationship, record) when is_map(record) do
primary_key = Ash.Resource.primary_key(relationship.destination)
is_pkey_map? =
Enum.all?(
primary_key,
fn key ->
Map.has_key?(record, key) || Map.has_key?(record, to_string(key))
end
)
if is_pkey_map? do
pkey =
Enum.reduce(primary_key, %{}, fn key, acc ->
case Map.fetch(record, key) do
{:ok, value} -> Map.put(acc, key, value)
:error -> Map.put(acc, key, Map.get(record, to_string(key)))
end
end)
{:ok, pkey}
else
error =
InvalidRelationship.exception(
relationship: relationship.name,
message: "Invalid identifier #{inspect(record)}"
)
{:error, error}
end
end
defp do_primary_key(relationship, record) do
single_primary_key(relationship, record)
end
defp multiple_primary_keys(relationship, values) do
Enum.reduce_while(values, {:ok, []}, fn record, {:ok, primary_keys} ->
case do_primary_key(relationship, record) do
{:ok, pkey} -> {:cont, {:ok, [pkey | primary_keys]}}
{:error, error} -> {:halt, {:error, error}}
end
end)
end
defp single_primary_key(relationship, value) do
with [field] <- Ash.Resource.primary_key(relationship.destination),
attribute <- Ash.Resource.attribute(relationship.destination, field),
{:ok, casted} <- Ash.Type.cast_input(attribute.type, value) do
{:ok, %{field => casted}}
else
_ ->
error =
InvalidRelationship.exception(
relationship: relationship.name,
message: "Invalid identifier #{inspect(value)}"
)
{:error, error}
end
end
@doc false
def changes_depend_on(changeset, dependency) do
%{changeset | change_dependencies: [dependency | changeset.change_dependencies]}
end
@doc false
def add_requests(changeset, requests) when is_list(requests) do
Enum.reduce(requests, changeset, &add_requests(&2, &1))
end
def add_requests(changeset, request) do
%{changeset | requests: [request | changeset.requests]}
end
defp validate_allow_nil(%{allow_nil?: false} = attribute, nil) do
{:error,
InvalidAttribute.exception(
field: attribute.name,
message: "must be present"
)}
end
defp validate_allow_nil(_, _), do: :ok
defp add_attribute_invalid_error(changeset, attribute, message \\ nil) do
error =
InvalidAttribute.exception(
field: attribute.name,
message: message
)
add_error(changeset, error)
end
end