-
-
Notifications
You must be signed in to change notification settings - Fork 181
/
changeset.ex
5342 lines (4562 loc) · 171 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
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
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 `Ash.create/2`
and `Ash.update/2`.
# Changeset lifecycle
## Action Lifecycle
The following example illustrates the hook lifecycle of a changeset.
```elixir
defmodule AshChangesetLifeCycleExample do
def change(changeset, _, _) do
changeset
# execute code both before and after the transaction
|> Ash.Changeset.around_transaction(fn changeset, callback ->
callback.(changeset)
end)
# execute code before the transaction is started. Use for things like external calls
|> Ash.Changeset.before_transaction(fn changeset -> changeset end)
# execute code in the transaction, before and after the data layer is called
|> Ash.Changeset.around_action(fn changeset, callback ->
callback.(changeset)
end)
# execute code in the transaction, before the data layer is called
|> Ash.Changeset.before_action(fn changeset -> changeset end)
# execute code in the transaction, after the data layer is called, only if the action is successful
|> Ash.Changeset.after_action(fn changeset, result -> {:ok, result} end)
# execute code after the transaction, both in success and error cases
|> Ash.Changeset.after_transaction(fn changeset, success_or_error_result -> success_or_error_result end
end
end
```
"""
defstruct [
:__validated_for_action__,
:action_type,
:action,
:domain,
:data,
:handle_errors,
:resource,
:tenant,
:to_tenant,
:timeout,
invalid_keys: MapSet.new(),
filter: nil,
added_filter: nil,
action_failed?: false,
atomics: [],
atomic_validations: [],
after_action: [],
after_transaction: [],
arguments: %{},
around_action: [],
around_transaction: [],
attributes: %{},
before_action: [],
before_transaction: [],
context: %{},
context_changes: %{},
defaults: [],
errors: [],
params: %{},
attribute_changes: %{},
atomic_changes: [],
casted_attributes: %{},
casted_arguments: %{},
phase: :pending,
relationships: %{},
select: nil,
load: [],
valid?: true
]
defimpl Inspect do
import Inspect.Algebra
@spec inspect(Ash.Changeset.t(), Inspect.Opts.t()) ::
{:doc_cons, :doc_line | :doc_nil | binary | tuple,
:doc_line | :doc_nil | binary | tuple}
| {:doc_group,
:doc_line
| :doc_nil
| binary
| {:doc_collapse, pos_integer}
| {:doc_force, any}
| {:doc_break | :doc_color | :doc_cons | :doc_fits | :doc_group | :doc_string, any,
any}
| {:doc_nest, any, :cursor | :reset | non_neg_integer, :always | :break},
:inherit | :self}
def inspect(changeset, opts) do
context = Map.delete(changeset.context, :private)
context =
if context == %{} do
empty()
else
concat("context: ", to_doc(context, opts))
end
tenant =
if changeset.tenant do
concat(
"tenant: ",
to_doc(changeset.to_tenant, opts)
)
else
empty()
end
domain =
if changeset.domain do
concat("domain: ", to_doc(changeset.domain, opts))
else
empty()
end
select =
if changeset.select do
concat("select: ", to_doc(changeset.select, opts))
else
empty()
end
load =
if changeset.load && changeset.load != [] do
concat("load: ", to_doc(changeset.load, opts))
else
empty()
end
atomics =
if Enum.empty?(changeset.atomics) do
empty()
else
concat("atomics: ", to_doc(changeset.atomics, opts))
end
container_doc(
"#Ash.Changeset<",
[
domain,
concat("action_type: ", inspect(changeset.action_type)),
concat("action: ", inspect(changeset.action && changeset.action.name)),
tenant,
concat("attributes: ", to_doc(changeset.attributes, opts)),
atomics,
concat("relationships: ", to_doc(changeset.relationships, opts)),
arguments(changeset, opts),
concat("errors: ", to_doc(changeset.errors, opts)),
concat("data: ", to_doc(changeset.data, opts)),
context,
concat("valid?: ", to_doc(changeset.valid?, opts)),
select,
load
],
">",
opts,
fn str, _ -> str end
)
end
defp arguments(changeset, opts) do
if changeset.action do
if Enum.empty?(changeset.action.arguments) do
empty()
else
arg_string =
changeset.action.arguments
|> Enum.filter(fn argument ->
match?({:ok, _}, Ash.Changeset.fetch_argument(changeset, argument.name))
end)
|> Map.new(fn argument ->
if argument.sensitive? do
{argument.name, "**redacted**"}
else
{argument.name, Ash.Changeset.get_argument(changeset, argument.name)}
end
end)
|> to_doc(opts)
concat(["arguments: ", arg_string])
end
else
empty()
end
end
end
@type after_action_fun ::
(t, Ash.Resource.record() ->
{:ok, Ash.Resource.record()}
| {:ok, Ash.Resource.record(), [Ash.Notifier.Notification.t()]}
| {:error, any})
@type after_transaction_fun ::
(t, {:ok, Ash.Resource.record()} | {:error, any} ->
{:ok, Ash.Resource.record()} | {:error, any})
@type before_action_fun :: (t -> t | {t, %{notifications: [Ash.Notifier.Notification.t()]}})
@type before_transaction_fun :: (t -> t)
@type around_result ::
{:ok, Ash.Resource.record(), t(), %{notifications: list(Ash.Notifier.Notification.t())}}
| {:error, Ash.Error.t()}
@type around_callback :: (t() -> around_result)
@type around_action_fun :: (t, around_callback -> around_result)
@type around_transaction_fun :: (t -> {:ok, Ash.Resource.record()} | {:error, any})
@phases [
:atomic,
:pending,
:validate,
:before_action,
:after_action,
:before_transaction,
:after_transaction,
:around_action,
:around_transaction
]
@type phase :: unquote(Enum.reduce(@phases, &{:|, [], [&1, &2]}))
@type t :: %__MODULE__{
__validated_for_action__: atom | nil,
action: Ash.Resource.Actions.action() | nil,
action_failed?: boolean,
action_type: Ash.Resource.Actions.action_type() | nil,
after_action: [after_action_fun | {after_action_fun, map}],
after_transaction: [after_transaction_fun | {after_transaction_fun, map}],
atomics: Keyword.t(),
domain: module | nil,
arguments: %{optional(atom) => any},
around_action: [around_action_fun | {around_action_fun, map}],
around_transaction: [around_transaction_fun | {around_transaction_fun, map}],
attributes: %{optional(atom) => any},
before_action: [before_action_fun | {around_action_fun, map}],
before_transaction: [before_transaction_fun | {before_transaction_fun, map}],
context: map,
filter: Ash.Filter.t() | nil,
added_filter: Ash.Filter.t() | nil,
data: Ash.Resource.record() | nil,
defaults: [atom],
errors: [Ash.Error.t()],
handle_errors:
nil | (t, error :: any -> :ignore | t | (error :: any) | {error :: any, t}),
invalid_keys: MapSet.t(),
params: %{optional(atom | binary) => any},
phase: phase(),
relationships: %{
optional(atom) =>
%{optional(atom | binary) => any} | [%{optional(atom | binary) => any}]
},
resource: module,
select: [atom] | nil,
load: keyword(keyword),
tenant: term(),
timeout: pos_integer() | nil,
valid?: boolean
}
@type error_info ::
String.t()
| [
{:field, atom()}
| {:fields, [atom()]}
| {:message, String.t()}
| {:value, any()}
]
| %{:__struct__ => atom(), required(atom()) => any()}
alias Ash.Error.{
Changes.InvalidArgument,
Changes.InvalidAttribute,
Changes.InvalidChanges,
Changes.InvalidRelationship,
Changes.NoSuchAttribute,
Changes.NoSuchRelationship,
Changes.Required,
Invalid.NoSuchInput,
Invalid.NoSuchResource
}
require Ash.Tracer
import Ash.Expr
require Logger
defmodule OriginalDataNotAvailable do
@moduledoc "A value placed in changeset.data to indicate that the original data is not available"
defstruct reason: :atomic_query_update
@type t :: %__MODULE__{reason: :atomic_query_update}
end
defmacrop maybe_already_validated_error!(changeset, alternative \\ nil) do
{function, arity} = __CALLER__.function
if alternative do
quote do
changeset = unquote(changeset)
if changeset.__validated_for_action__ && !changeset.context[:private][:in_before_action?] do
IO.warn("""
Changeset has already been validated for action #{inspect(changeset.__validated_for_action__)}.
For safety, we prevent any changes after that point because they will bypass validations or other action logic.. To proceed anyway,
you can use `#{unquote(alternative)}/#{unquote(arity)}`. However, you should prefer a pattern like the below, which makes
any custom changes *before* calling the action.
Resource
|> Ash.Changeset.new()
|> Ash.Changeset.#{unquote(function)}(...)
|> Ash.Changeset.for_create(...)
""")
end
end
else
quote do
changeset = unquote(changeset)
if changeset.__validated_for_action__ && !changeset.context[:private][:in_before_action?] do
IO.warn("""
Changeset has already been validated for action #{inspect(changeset.__validated_for_action__)}.
For safety, we prevent any changes using `#{unquote(function)}/#{unquote(arity)}` after that point because they will bypass validations or other action logic.
Instead, you should change or set this value before calling the action, like so:
Resource
|> Ash.Changeset.new()
|> Ash.Changeset.#{unquote(function)}(...)
|> Ash.Changeset.for_create(...)
""")
end
end
end
end
@doc """
Returns a new changeset over a resource.
*Warning*: You almost always want to use `for_action` or `for_create`, etc. over this function if possible.
You can use this to start a changeset and make changes prior to calling `for_action`. This is not typically
necessary, but can be useful as an escape hatch. For example:
```elixir
Resource
|> Ash.Changeset.new()
|> Ash.Changeset.change_attribute(:name, "foobar")
|> Ash.Changeset.for_action(...)
```
"""
@spec new(Ash.Resource.t() | Ash.Resource.record()) :: t
def new(record_or_resource) do
{resource, record, action_type} =
case record_or_resource do
%resource{} = record -> {resource, record, :update}
resource -> {resource, struct(resource), :create}
end
tenant =
record
|> Map.get(:__metadata__, %{})
|> Map.get(:tenant, nil)
context = Ash.Resource.Info.default_context(resource) || %{}
if Ash.Resource.Info.resource?(resource) do
%__MODULE__{resource: resource, data: record, action_type: action_type}
|> set_context(context)
|> set_tenant(tenant)
else
%__MODULE__{
resource: resource,
action_type: action_type,
data: struct(resource)
}
|> add_error(NoSuchResource.exception(resource: resource))
|> set_tenant(tenant)
|> set_context(context)
end
end
@doc """
Ensure that only the specified attributes are present in the results.
The first call to `select/2` will replace the default behavior of selecting
all attributes. Subsequent calls to `select/2` will combine the provided
fields unless the `replace?` option is provided with a value of `true`.
If a field has been deselected, selecting it again will override that (because a single list of fields is tracked for selection)
Primary key attributes always selected and cannot be deselected.
When attempting to load a relationship (or manage it with `Ash.Changeset.manage_relationship/3`),
if the source field is not selected on the query/provided data an error will be produced. If loading
a relationship with a query, an error is produced if the query does not select the destination field
of the relationship.
Datalayers currently are not notified of the `select` for a changeset(unlike queries), and creates/updates select all fields when they are performed.
A select provided on a changeset sets the unselected fields to `nil` before returning the result.
Use `ensure_selected/2` if you wish to make sure a field has been selected, without deselecting any other fields.
"""
def select(changeset, fields, opts \\ []) do
if opts[:replace?] do
%{changeset | select: Enum.uniq(List.wrap(fields))}
else
%{changeset | select: Enum.uniq(List.wrap(fields) ++ (changeset.select || []))}
end
end
@doc """
Calls the provided load statement on the result of the action at the very end of the action.
"""
@spec load(t(), term()) :: t()
def load(changeset, load) do
query =
changeset.resource
|> Ash.Query.new()
|> Map.put(:errors, [])
|> Ash.Query.load(changeset.load)
|> Ash.Query.load(load)
changeset = %{
changeset
| load: Enum.concat(changeset.load || [], List.wrap(load))
}
Enum.reduce(query.errors, changeset, &add_error(&2, &1))
end
@doc """
Ensures that the given attributes are selected.
The first call to `select/2` will *limit* the fields to only the provided fields.
Use `ensure_selected/2` to say "select this field (or these fields) without deselecting anything else".
See `select/2` for more.
"""
def ensure_selected(changeset, fields) do
if changeset.select do
Ash.Changeset.select(changeset, List.wrap(fields))
else
to_select =
changeset.resource
|> Ash.Resource.Info.attributes()
|> Enum.map(& &1.name)
Ash.Changeset.select(changeset, to_select)
end
end
@doc """
Ensure the the specified attributes are `nil` in the changeset results.
"""
def deselect(changeset, fields) do
select =
if changeset.select do
changeset.select
else
changeset.resource
|> Ash.Resource.Info.attributes()
|> Enum.map(& &1.name)
end
select = select -- List.wrap(fields)
select(changeset, select, replace?: true)
end
def selecting?(changeset, field) do
case changeset.select do
nil ->
not is_nil(Ash.Resource.Info.attribute(changeset.resource, field))
select ->
if field in select do
true
else
attribute = Ash.Resource.Info.attribute(changeset.resource, field)
attribute && attribute.primary_key?
end
end || loading?(changeset, field)
end
@doc """
Returns true if the field/relationship or path to field/relationship is being loaded.
It accepts an atom or a list of atoms, which is treated for as a "path", i.e:
Resource |> Ash.Changeset.load(friends: [enemies: [:score]]) |> Ash.Changeset.loading?([:friends, :enemies, :score])
iex> true
Resource |> Ash.Changeset.load(friends: [enemies: [:score]]) |> Ash.Changeset.loading?([:friends, :score])
iex> false
Resource |> Ash.Changeset.load(friends: [enemies: [:score]]) |> Ash.Changeset.loading?(:friends)
iex> true
"""
def loading?(changeset, path) do
changeset.resource
|> Ash.Query.new()
|> Ash.Query.load(changeset.load)
|> Ash.Query.loading?(path)
end
@doc """
Returns a list of attributes, aggregates, relationships, and calculations that are being loaded
Provide a list of field types to narrow down the returned results.
"""
def accessing(changeset, types \\ [:attributes, :relationships, :calculations, :attributes]) do
changeset.resource
|> Ash.Query.new()
|> Ash.Query.load(changeset.load)
|> Map.put(:select, changeset.select)
|> Ash.Query.accessing(types)
end
@spec fully_atomic_changeset(
resource :: Ash.Resource.t(),
action :: atom() | Ash.Resource.Actions.action(),
params :: map(),
opts :: Keyword.t()
) :: Ash.Changeset.t() | {:not_atomic, String.t()}
def fully_atomic_changeset(resource, action, params, opts \\ []) do
action =
case action do
action when is_atom(action) -> Ash.Resource.Info.action(resource, action)
action -> action
end
if action.manual do
{:not_atomic,
"manual action `#{inspect(resource)}.#{action.name}` cannot be performed atomically"}
else
changeset =
resource
|> Ash.Changeset.new()
|> then(fn changeset ->
if data = opts[:data] do
Map.put(changeset, :data, data)
else
Map.put(changeset, :data, %OriginalDataNotAvailable{})
end
end)
|> Map.put(:context, opts[:context] || %{})
|> Map.put(:params, params)
|> Map.put(:action, action)
|> Map.put(:action_type, action.type)
|> Map.put(:atomics, opts[:atomics] || [])
|> Ash.Changeset.set_tenant(opts[:tenant])
{changeset, _opts} =
Ash.Actions.Helpers.set_context_and_get_opts(
opts[:domain] || Ash.Resource.Info.domain(resource),
changeset,
opts
)
changeset = set_phase(changeset, :atomic)
with :ok <- verify_notifiers_support_atomic(resource, action),
%Ash.Changeset{} = changeset <-
atomic_params(changeset, action, params, opts),
%Ash.Changeset{} = changeset <- atomic_changes(changeset, action),
%Ash.Changeset{} = changeset <- atomic_defaults(changeset),
%Ash.Changeset{} = changeset <- atomic_update(changeset, opts[:atomic_update] || []),
%Ash.Changeset{} = changeset <-
hydrate_atomic_refs(changeset, opts[:actor], Keyword.take(opts, [:eager?])) do
if Enum.empty?(changeset.after_action || []) do
changeset
else
{:error, "Cannot perform a changeset with after action hooks atomically"}
end
else
{:not_atomic, reason} ->
{:not_atomic, reason}
end
end
|> case do
{:not_atomic, reason} ->
{:not_atomic, reason}
{:error, error} ->
{:error, error}
changeset ->
clear_phase(changeset)
end
end
defp atomic_defaults(changeset) do
with %__MODULE__{} <- atomic_static_update_defaults(changeset) do
atomic_lazy_update_defaults(changeset)
end
end
defp atomic_static_update_defaults(changeset) do
changeset.resource
|> Ash.Resource.Info.static_default_attributes(:update)
|> Enum.reject(fn attribute ->
Ash.Changeset.changing_attribute?(changeset, attribute.name)
end)
|> Enum.reduce_while(changeset, fn attribute, changeset ->
case Ash.Type.cast_atomic(
attribute.type,
attribute.update_default,
attribute.constraints
) do
{:atomic, atomic} ->
{:cont, atomic_update(changeset, attribute.name, {:atomic, atomic})}
{:error, error} ->
{:cont,
add_invalid_errors(attribute.update_default, :attribute, changeset, attribute, error)}
{:not_atomic, reason} ->
{:halt, {:not_atomic, reason}}
end
end)
end
defp atomic_lazy_update_defaults(changeset) do
changeset.resource
|> Ash.Resource.Info.lazy_matching_default_attributes(:update)
|> Enum.concat(
Ash.Resource.Info.lazy_non_matching_default_attributes(changeset.resource, :update)
)
|> Enum.reject(fn attribute ->
Ash.Changeset.changing_attribute?(changeset, attribute.name)
end)
|> Enum.reduce_while(changeset, fn attribute, changeset ->
cond do
attribute.update_default == (&DateTime.utc_now/0) ->
{:cont, atomic_update(changeset, attribute.name, Ash.Expr.expr(now()))}
attribute.update_default == (&Ash.UUID.generate/0) ->
{:cont, atomic_update(changeset, attribute.name, Ash.Expr.expr(^Ash.UUID.generate()))}
true ->
{:halt,
{:not_atomic,
"update_default for `#{inspect(attribute.name)}` cannot be done atomically: #{inspect(attribute.update_default)}"}}
end
end)
end
defp verify_notifiers_support_atomic(resource, action) do
resource
|> Ash.Resource.Info.notifiers()
|> Enum.filter(fn notifier ->
notifier.requires_original_data?(resource, action)
end)
|> case do
[] ->
:ok
notifiers ->
{:not_atomic,
"notifiers #{inspect(notifiers)} require original data for #{inspect(resource)}.#{action.name}"}
end
end
defp atomic_changes(changeset, action) do
changes =
action.changes
|> Enum.concat(Ash.Resource.Info.changes(changeset.resource, changeset.action_type))
|> Enum.concat(Ash.Resource.Info.validations(changeset.resource, changeset.action_type))
context = %{
actor: changeset.context[:private][:actor],
tenant: changeset.tenant,
authorize?: changeset.context[:private][:authorize?] || false,
tracer: changeset.context[:private][:tracer]
}
changeset = set_phase(changeset, :atomic)
Enum.reduce_while(changes, changeset, fn
%{change: _} = change, changeset ->
case run_atomic_change(changeset, change, context) do
{:not_atomic, reason} ->
{:halt, {:not_atomic, reason}}
changeset ->
{:cont, changeset}
end
%{validation: _} = validation, changeset ->
case run_atomic_validation(changeset, validation, context) do
{:not_atomic, reason} ->
{:halt, {:not_atomic, reason}}
changeset ->
{:cont, changeset}
end
end)
|> case do
{:not_atomic, reason} -> {:not_atomic, reason}
%__MODULE__{} = changeset -> clear_phase(changeset)
end
end
defp run_atomic_validation(
changeset,
%{validation: {module, validation_opts}, where: where, message: message},
context
) do
case List.wrap(
module.atomic(
changeset,
validation_opts,
struct(Ash.Resource.Validation.Context, Map.put(context, :message, message))
)
) do
[{:atomic, _, _, _} | _] = atomics ->
Enum.reduce_while(atomics, changeset, fn
{:atomic, _fields, condition_expr, error_expr}, changeset ->
condition_expr = rewrite_atomics(changeset, condition_expr)
Ash.Expr.walk_template(condition_expr, fn
{:_atomic_ref, field} ->
atomic_ref(changeset, field)
other ->
other
end)
case atomic_condition(where, changeset, context) do
{:atomic, condition} ->
case condition do
true ->
{:cont, validate_atomically(changeset, condition_expr, error_expr)}
false ->
{:cont, changeset}
condition ->
condition_expr =
expr(^condition and ^condition_expr)
{:cont, validate_atomically(changeset, condition_expr, error_expr)}
end
{:not_atomic, reason} ->
{:halt, {:not_atomic, reason}}
end
end)
|> case do
{:not_atomic, reason} -> {:not_atomic, reason}
changeset -> changeset
end
[:ok] ->
changeset
[{:error, error}] ->
if message do
error = override_validation_message(error, message)
Ash.Changeset.add_error(changeset, error)
else
Ash.Changeset.add_error(changeset, error)
end
[{:not_atomic, error}] ->
{:not_atomic, error}
end
end
defp rewrite_atomics(changeset, expr) do
Ash.Expr.walk_template(expr, fn
{:_atomic_ref, ref} ->
atomic_ref(changeset, ref)
other ->
other
end)
end
defp run_atomic_change(
changeset,
%{change: {module, change_opts}, where: where},
context
) do
change_opts =
Ash.Expr.fill_template(
change_opts,
changeset.context.private[:actor],
changeset.arguments,
changeset.context
)
with {:atomic, changeset, atomic_changes} <-
atomic_with_changeset(
module.atomic(changeset, change_opts, struct(Ash.Resource.Change.Context, context)),
changeset
),
{:atomic, condition} <- atomic_condition(where, changeset, context) do
case condition do
true ->
atomic_update(changeset, atomic_changes)
false ->
changeset
condition ->
atomic_changes =
Map.new(atomic_changes, fn {key, value} ->
new_value =
expr(
if ^condition do
^value
else
^ref(key)
end
)
{key, new_value}
end)
atomic_update(changeset, atomic_changes)
end
else
{:ok, changeset} ->
changeset
{:not_atomic, reason} ->
{:not_atomic, reason}
:ok ->
changeset
end
end
defp atomic_with_changeset({:atomic, atomics}, changeset), do: {:atomic, changeset, atomics}
defp atomic_with_changeset(other, _), do: other
defp validate_atomically(changeset, condition_expr, error_expr) do
%{
changeset
| atomic_validations: [{condition_expr, error_expr} | changeset.atomic_validations]
}
end
@doc """
Gets a reference to a field, or the current atomic update expression of that field.
"""
def atomic_ref(changeset, field) do
case Keyword.fetch(changeset.atomics, field) do
{:ok, atomic} ->
attribute = Ash.Resource.Info.attribute(changeset.resource, field)
Ash.Expr.expr(type(^atomic, ^attribute.type, ^attribute.constraints))
:error ->
case Map.fetch(changeset.attributes, field) do
{:ok, new_value} ->
attribute = Ash.Resource.Info.attribute(changeset.resource, field)
Ash.Expr.expr(type(^new_value, ^attribute.type, ^attribute.constraints))
:error ->
expr(^ref(field))
end
end
end
@doc false
def atomic_condition(where, changeset, context) do
Enum.reduce_while(where, {:atomic, true}, fn {module, validation_opts},
{:atomic, condition} ->
case module.atomic(
changeset,
validation_opts,
struct(Ash.Resource.Validation.Context, context)
) do
{:atomic, _, expr, _as_error} ->
new_expr =
if condition == true do
expr
else
expr(^condition and ^expr)
end
{:cont, {:atomic, new_expr}}
{:not_atomic, reason} ->
{:halt, {:not_atomic, reason}}
end
end)
end
defp atomic_params(changeset, action, params, opts) do
if opts[:assume_casted?] do
Enum.reduce_while(params, changeset, fn {key, value}, changeset ->
cond do
has_argument?(action, key) ->
{:cont, %{changeset | arguments: Map.put(changeset.arguments, key, value)}}
attribute = Ash.Resource.Info.attribute(changeset.resource, key) ->
case Ash.Type.cast_atomic(attribute.type, value, attribute.constraints) do
{:atomic, atomic} ->
atomic = set_error_field(atomic, attribute.name)
{:cont, atomic_update(changeset, attribute.name, {:atomic, atomic})}
{:error, error} ->
{:cont, add_invalid_errors(value, :attribute, changeset, attribute, error)}
{:not_atomic, reason} ->
{:halt, {:not_atomic, reason}}
end
match?("_" <> _, key) ->
{:cont, changeset}
key in List.wrap(opts[:skip_unknown_inputs]) ->
{:cont, changeset}
true ->
{:cont,
add_error(
changeset,
NoSuchInput.exception(
resource: changeset.resource,
action: action.name,
input: key,
inputs: Ash.Resource.Info.action_inputs(changeset.resource, action.name)
)
)}
end
end)
else
Enum.reduce_while(params, changeset, fn {key, value}, changeset ->
cond do
has_argument?(action, key) ->
{:cont, set_argument(changeset, key, value)}
attribute = Ash.Resource.Info.attribute(changeset.resource, key) ->
cond do
attribute.name in action.accept ->
case Ash.Type.cast_atomic(attribute.type, value, attribute.constraints) do
{:atomic, atomic} ->
{:cont, atomic_update(changeset, attribute.name, {:atomic, atomic})}
{:error, error} ->
{:cont, add_invalid_errors(value, :attribute, changeset, attribute, error)}
{:not_atomic, reason} ->
{:halt, {:not_atomic, reason}}
end
key in List.wrap(opts[:skip_unknown_inputs]) ->
{:cont, changeset}
match?("_" <> _, key) ->
{:cont, changeset}
true ->
{:cont,
add_error(
changeset,
NoSuchInput.exception(
resource: changeset.resource,
action: action.name,
input: key,
inputs: Ash.Resource.Info.action_inputs(changeset.resource, action.name)
)
)}
end
match?("_" <> _, key) ->
{:cont, changeset}
key in List.wrap(opts[:skip_unknown_inputs]) ->
{:cont, changeset}
true ->
{:cont,
add_error(
changeset,
NoSuchInput.exception(
resource: changeset.resource,
action: action.name,
input: key,
inputs: Ash.Resource.Info.action_inputs(changeset.resource, action.name)
)
)}
end
end)
end