-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
changeset.ex
2374 lines (1908 loc) · 88 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 Ecto.Changeset do
@moduledoc ~S"""
Changesets allow filtering, casting, validation and
definition of constraints when manipulating structs.
There is an example of working with changesets in the introductory
documentation in the `Ecto` module. The functions `cast/4` and
`change/2` are the usual entry points for creating changesets.
The first one is used to cast and validate external parameters,
such as parameters sent through a form, API, command line, etc.
The second one is used to change data directly from your application.
The remaining functions in this module, such as validations,
constraints, association handling, are about manipulating
changesets. Let's discuss some of this extra functionality.
## External vs internal data
Changesets allow working with both kinds of data:
* internal to the application - for example programatically generated,
or coming from other subsystems. This use case is primarily covered
by the `change/2` and `put_change/3` functions.
* external to the application - for example data provided by the user in
a form that needs to be type-converted and properly validated. This use case
is primarily covered by the `cast/4` function.
## Validations and constraints
Ecto changesets provide both validations and constraints which
are ultimately turned into errors in case something goes wrong.
The difference between them is that most validations can be
executed without a need to interact with the database and, therefore,
are always executed before attempting to insert or update the entry
in the database. Some validations may happen against the database but
they are inherently unsafe. Those validations start with a `unsafe_`
prefix, such as `unsafe_validate_unique/3`.
On the other hand, constraints rely on the database and are always safe.
As a consequence, validations are always checked before constraints.
Constraints won't even be checked in case validations failed.
Let's see an example:
defmodule User do
use Ecto.Schema
import Ecto.Changeset
schema "users" do
field :name
field :email
field :age, :integer
end
def changeset(user, params \\ %{}) do
user
|> cast(params, [:name, :email, :age])
|> validate_required([:name, :email])
|> validate_format(:email, ~r/@/)
|> validate_inclusion(:age, 18..100)
|> unique_constraint(:email)
end
end
In the `changeset/2` function above, we define three validations.
They check that `name` and `email` fields are present in the
changeset, the e-mail is of the specified format, and the age is
between 18 and 100 - as well as a unique constraint in the email
field.
Let's suppose the e-mail is given but the age is invalid. The
changeset would have the following errors:
changeset = User.changeset(%User{}, %{age: 0, email: "mary@example.com"})
{:error, changeset} = Repo.insert(changeset)
changeset.errors #=> [age: {"is invalid", []}, name: {"can't be blank", []}]
In this case, we haven't checked the unique constraint in the
e-mail field because the data did not validate. Let's fix the
age and assume, however, that the e-mail already exists in the
database:
changeset = User.changeset(%User{}, %{age: 42, email: "mary@example.com"})
{:error, changeset} = Repo.insert(changeset)
changeset.errors #=> [email: {"has already been taken", []}]
Validations and constraints define an explicit boundary when the check
happens. By moving constraints to the database, we also provide a safe,
correct and data-race free means of checking the user input.
## Empty values
Many times, the data given on cast needs to be further pruned, specially
regarding empty values. For example, if you are gathering data to be
cast from the command line or through an HTML form or any other text-based
format, it is likely those means cannot express nil values. For
those reasons, changesets include the concept of empty values, which are
values that will be automatically converted to the field's default value
on `cast/4`. Those values are stored in the changeset `empty_values` field
and default to `[""]`.
## Associations, embeds and on replace
Using changesets you can work with associations as well as with embedded
structs. Changesets provide a convenient way to working with associations
as whole values - for example considering the entire list of has_many
associations and not focusing just on a single one. Two main functions
that provide this functionality are `cast_assoc/3` for working with external
data, and `put_assoc/3` for working with internal data - the difference
between those two functions is analogical to the difference between
`cast/4` and `change/2`.
Sometimes related data may be replaced by incoming data and by
default Ecto won't allow such. Such behaviour can be changed when defining
the relation by setting `:on_replace` option in your association/embed
definition according to the values below:
* `:raise` (default) - do not allow removing association or embedded
data via parent changesets
* `:mark_as_invalid` - if attempting to remove the association or
embedded data via parent changeset - an error will be added to the parent
changeset, and it will be marked as invalid
* `:nilify` - sets owner reference column to `nil` (available only for
associations)
* `:update` - updates the association, available only for has_one and belongs_to.
This option will update all the fields given to the changeset including the id
for the association
* `:delete` - removes the association or related data from the database.
This option has to be used carefully
The `:delete` option in particular must be used carefully as it would allow
users to delete any associated data. If you need deletion, it is often preferred
to add a separate boolean virtual field to the changeset function that will allow
you to manually mark it for deletion, as in the example below:
defmodule Comment do
use Ecto.Schema
import Ecto.Changeset
schema "comments" do
field :body, :string
field :delete, :boolean, virtual: true
end
def changeset(comment, params) do
cast(comment, params, [:body, :delete])
|> maybe_mark_for_deletion
end
defp maybe_mark_for_deletion(changeset) do
if get_change(changeset, :delete) do
%{changeset | action: :delete}
else
changeset
end
end
end
## Schemaless changesets
In the changeset examples so far, we have always used changesets to
validate and cast data contained in a struct, such as the `%User{}`
struct defined by the `User` module.
However, changesets can also be used with data in a plain map, by
passing a tuple containing both the data and the supported types:
data = %{}
types = %{first_name: :string, last_name: :string, email: :string}
changeset =
{data, types}
|> Ecto.Changeset.cast(params["sign_up"], Map.keys(types))
|> validate_required(...)
|> validate_length(...)
Such functionality makes Ecto extremely useful to cast, validate and prune
data even if it is not meant to be persisted to the database.
### Changeset actions
Changesets have an action field which is usually set by `Ecto.Repo`
whenever one of the operations such as `insert` or `update` is called:
changeset = User.changeset(%User{}, %{age: 42, email: "mary@example.com"})
{:error, changeset} = Repo.insert(changeset)
changeset.action
#=> :insert
This means that when working with changesets that are not meant to be
persisted to the database, such as schemaless changesets, you may need
to explicitly set the action to one specific value. Frameworks such as
Phoenix uses the action value to define how a HTML forms should act.
Instead of setting the action manually, you may use `apply_action/2` that
emulates operations such as `Repo.insert`. `apply_action/2` will return
`{:ok, changes}` if the changeset is valid or `{:error, changeset}`, with
the given `action` set in the changeset in case of errors.
## The Ecto.Changeset struct
The fields are:
* `valid?` - Stores if the changeset is valid
* `data` - The changeset source data, for example, a struct
* `params` - The parameters as given on changeset creation
* `changes` - The `changes` from parameters that were approved in casting
* `errors` - All errors from validations
* `validations` - All validations performed in the changeset
* `constraints` - All constraints defined in the changeset
* `required` - All required fields as a list of atoms
* `filters` - Filters (as a map `%{field => value}`) to narrow the scope of update/delete queries
* `action` - The action to be performed with the changeset
* `types` - Cache of the data's field types
* `empty_values` - A list of values to be considered empty
* `repo` - The repository applying the changeset (only set after a Repo function is called)
* `repo_opts` - A keyword list of options given to the underlying repository operation
"""
require Ecto.Query
alias __MODULE__
alias Ecto.Changeset.Relation
@empty_values [""]
# If a new field is added here, def merge must be adapted
defstruct valid?: false, data: nil, params: nil, changes: %{},
errors: [], validations: [], required: [], prepare: [],
constraints: [], filters: %{}, action: nil, types: nil,
empty_values: @empty_values, repo: nil, repo_opts: []
@type t :: %Changeset{valid?: boolean(),
repo: atom | nil,
repo_opts: Keyword.t,
data: Ecto.Schema.t | map | nil,
params: %{String.t => term} | nil,
changes: %{atom => term},
required: [atom],
prepare: [(t -> t)],
errors: [{atom, error}],
constraints: [constraint],
validations: Keyword.t,
filters: %{atom => term},
action: action,
types: nil | %{atom => Ecto.Type.t}}
@type error :: {String.t, Keyword.t}
@type action :: nil | :insert | :update | :delete | :replace | :ignore
@type constraint :: %{type: :unique, constraint: String.t, match: :exact | :suffix,
field: atom, message: error}
@type data :: map()
@type types :: map()
@number_validators %{
less_than: {&</2, "must be less than %{number}"},
greater_than: {&>/2, "must be greater than %{number}"},
less_than_or_equal_to: {&<=/2, "must be less than or equal to %{number}"},
greater_than_or_equal_to: {&>=/2, "must be greater than or equal to %{number}"},
equal_to: {&==/2, "must be equal to %{number}"},
}
@relations [:embed, :assoc]
@match_types [:exact, :suffix, :prefix]
@actions [:insert, :update, :delete, :replace]
@doc """
Wraps the given data in a changeset or adds changes to a changeset.
Changed attributes will only be added if the change does not have the
same value as the field in the data.
This function is useful for:
* wrapping a struct inside a changeset
* directly changing a struct without performing castings nor validations
* directly bulk-adding changes to a changeset
The function is meant for working with data internal to the application.
Because of that neither validation nor casting is performed. This means
`change/2` expects the keys in the `changes` map or keyword to be atoms.
When a changeset is passed as the first argument, the changes passed as the
second argument are merged over the changes already in the changeset if they
differ from the values in the struct. If `changes` is an empty map, this
function is a no-op.
When a `{data, types}` is passed as the first argument, a changeset is
created with the given data and types and marked as valid.
See `cast/4` if you'd prefer to cast and validate external parameters.
## Examples
iex> changeset = change(%Post{})
%Ecto.Changeset{...}
iex> changeset.valid?
true
iex> changeset.changes
%{}
iex> changeset = change(%Post{author: "bar"}, title: "title")
iex> changeset.changes
%{title: "title"}
iex> changeset = change(%Post{title: "title"}, title: "title")
iex> changeset.changes
%{}
iex> changeset = change(changeset, %{title: "new title", body: "body"})
iex> changeset.changes.title
"new title"
iex> changeset.changes.body
"body"
"""
@spec change(Ecto.Schema.t | t | {data, types}, %{atom => term} | Keyword.t) :: t | no_return
def change(data, changes \\ %{})
def change({data, types}, changes) when is_map(data) do
change(%Changeset{data: data, types: Enum.into(types, %{}), valid?: true}, changes)
end
def change(%Changeset{types: nil}, _changes) do
raise ArgumentError, "changeset does not have types information"
end
def change(%Changeset{changes: changes, types: types} = changeset, new_changes)
when is_map(new_changes) or is_list(new_changes) do
{changes, errors, valid?} =
get_changed(changeset.data, types, changes, new_changes,
changeset.errors, changeset.valid?)
%{changeset | changes: changes, errors: errors, valid?: valid?}
end
def change(%{__struct__: struct} = data, changes) when is_map(changes) or is_list(changes) do
types = struct.__changeset__
{changes, errors, valid?} = get_changed(data, types, %{}, changes, [], true)
%Changeset{valid?: valid?, data: data, changes: changes,
errors: errors, types: types}
end
defp get_changed(data, types, old_changes, new_changes, errors, valid?) do
Enum.reduce(new_changes, {old_changes, errors, valid?}, fn
{key, value}, {changes, errors, valid?} ->
put_change(data, changes, errors, valid?, key, value, Map.get(types, key))
end)
end
@doc """
Applies the given `params` as changes for the given `data` according to
the given set of keys. Returns a changeset.
The given `data` may be either a changeset, a schema struct or a `{data, types}`
tuple. The second argument is a map of `params` that are cast according
to the type information from `data`. `params` is a map with string keys
or a map with atom keys containing potentially unsafe data.
During casting, all `permitted` parameters will have their key name converted
to an atom and stored as a change in the `:changes` field of the changeset.
All parameters that are not explicitly permitted are ignored.
If casting of all fields is successful, the changeset is returned as valid.
## Options
* `:empty_values` - a list of values to be considered as empty when casting.
Defaults to the changeset value, which defaults to `[""]`
## Examples
iex> changeset = cast(post, params, [:title])
iex> if changeset.valid? do
...> Repo.update!(changeset)
...> end
Passing a changeset as the first argument:
iex> changeset = cast(post, %{title: "Hello"}, [:title])
iex> new_changeset = cast(changeset, %{title: "Foo", body: "Bar"}, [:body])
iex> new_changeset.params
%{"title" => "Foo", "body" => "Bar"}
Or creating a changeset from a simple map with types:
iex> data = %{title: "hello"}
iex> types = %{title: :string}
iex> changeset = cast({data, types}, %{title: "world"}, [:title])
iex> apply_changes(changeset)
%{title: "world"}
## Composing casts
`cast/4` also accepts a changeset as its first argument. In such cases, all
the effects caused by the call to `cast/4` (additional errors and changes)
are simply added to the ones already present in the argument changeset.
Parameters are merged (**not deep-merged**) and the ones passed to `cast/4`
take precedence over the ones already in the changeset.
"""
@spec cast(Ecto.Schema.t | t | {data, types},
%{binary => term} | %{atom => term} | :invalid,
[String.t | atom],
Keyword.t) :: t | no_return
def cast(data, params, permitted, opts \\ [])
def cast(_data, %{__struct__: _} = params, _permitted, _opts) do
raise Ecto.CastError, type: :map, value: params,
message: "expected params to be a :map, got: `#{inspect params}`"
end
def cast({data, types}, params, permitted, opts) when is_map(data) do
cast(data, types, %{}, params, permitted, opts)
end
def cast(%Changeset{types: nil}, _params, _permitted, _opts) do
raise ArgumentError, "changeset does not have types information"
end
def cast(%Changeset{changes: changes, data: data, types: types, empty_values: empty_values} = changeset,
params, permitted, opts) do
opts = Keyword.put_new(opts, :empty_values, empty_values)
new_changeset = cast(data, types, changes, params, permitted, opts)
cast_merge(changeset, new_changeset)
end
def cast(%{__struct__: module} = data, params, permitted, opts) do
cast(data, module.__changeset__, %{}, params, permitted, opts)
end
defp cast(%{} = data, %{} = types, %{} = changes, :invalid, permitted, opts) when is_list(permitted) do
{empty_values, _opts} = Keyword.pop(opts, :empty_values, @empty_values)
_ = Enum.each(permitted, &cast_key/1)
%Changeset{params: nil, data: data, valid?: false, errors: [],
changes: changes, types: types, empty_values: empty_values}
end
defp cast(%{} = data, %{} = types, %{} = changes, %{} = params, permitted, opts) when is_list(permitted) do
{empty_values, _opts} = Keyword.pop(opts, :empty_values, @empty_values)
params = convert_params(params)
defaults = case data do
%{__struct__: struct} -> struct.__struct__()
%{} -> %{}
end
{changes, errors, valid?} =
Enum.reduce(permitted, {changes, [], true},
&process_param(&1, params, types, data, empty_values, defaults, &2))
%Changeset{params: params, data: data, valid?: valid?,
errors: Enum.reverse(errors), changes: changes,
types: types, empty_values: empty_values}
end
defp cast(%{}, %{}, %{}, params, permitted, _opts) when is_list(permitted) do
raise Ecto.CastError, type: :map, value: params,
message: "expected params to be a :map, got: `#{inspect params}`"
end
defp process_param(key, params, types, data, empty_values, defaults, {changes, errors, valid?}) do
{key, param_key} = cast_key(key)
type = type!(types, key)
current =
case changes do
%{^key => value} -> value
_ -> Map.get(data, key)
end
case cast_field(key, param_key, type, params, current, empty_values, defaults, valid?) do
{:ok, value, valid?} ->
{Map.put(changes, key, value), errors, valid?}
:missing ->
{changes, errors, valid?}
:invalid ->
{changes, [{key, {"is invalid", [type: type, validation: :cast]}} | errors], false}
end
end
defp type!(types, key) do
case types do
%{^key => {tag, _}} when tag in @relations ->
raise "casting #{tag}s with cast/4 is not supported, use cast_#{tag}/3 instead"
%{^key => type} ->
type
_ ->
raise ArgumentError, "unknown field `#{key}`. Only fields, " <>
"embeds and associations (except :through ones) are supported in changesets"
end
end
defp cast_key(key) when is_binary(key) do
try do
{String.to_existing_atom(key), key}
rescue
ArgumentError ->
raise ArgumentError, "could not convert the parameter `#{key}` into an atom, `#{key}` is not a schema field"
end
end
defp cast_key(key) when is_atom(key),
do: {key, Atom.to_string(key)}
defp cast_field(key, param_key, type, params, current, empty_values, defaults, valid?) do
case params do
%{^param_key => value} ->
value = if value in empty_values, do: Map.get(defaults, key), else: value
case Ecto.Type.cast(type, value) do
{:ok, ^current} ->
:missing
{:ok, value} ->
{:ok, value, valid?}
:error ->
:invalid
end
_ ->
:missing
end
end
defp convert_params(params) do
params
|> Enum.reduce(nil, fn
{key, _value}, nil when is_binary(key) ->
nil
{key, _value}, _ when is_binary(key) ->
raise Ecto.CastError, type: :map, value: params,
message: "expected params to be a map with atoms or string keys, " <>
"got a map with mixed keys: #{inspect params}"
{key, value}, nil when is_atom(key) ->
[{Atom.to_string(key), value}]
{key, value}, acc when is_atom(key) ->
[{Atom.to_string(key), value} | acc]
end)
|> case do
nil -> params
list -> :maps.from_list(list)
end
end
## Casting related
@doc """
Casts the given association with the changeset parameters.
This function should be used when working with the entire association at
once (and not a single element of a many-style association) and using data
external to the application.
When updating the data, this function requires the association to have been
preloaded in the changeset struct. Missing data will
invoke the `:on_replace` behaviour defined on the association.
Preloading is not necessary for newly built structs.
The parameters for the given association will be retrieved
from `changeset.params`. Those parameters are expected to be
a map with attributes, similar to the ones passed to `cast/4`.
Once parameters are retrieved, `cast_assoc/3` will match those
parameters with the associations already in the changeset record.
For example, imagine a user has many addresses relationship where
post data is sent as follows
%{"name" => "john doe", "addresses" => [
%{"street" => "somewhere", "country" => "brazil", "id" => 1},
%{"street" => "elsewhere", "country" => "poland"},
]}
and then
user
|> Repo.preload(:addresses)
|> Ecto.Changeset.cast(params, [])
|> Ecto.Changeset.cast_assoc(:addresses)
Once `cast_assoc/3` is called, Ecto will compare those parameters
with the addresses already associated with the user and act as follows:
* If the parameter does not contain an ID, the parameter data
will be passed to `changeset/2` with a new struct and become
an insert operation
* If the parameter contains an ID and there is no associated child
with such ID, the parameter data will be passed to `changeset/2`
with a new struct and become an insert operation
* If the parameter contains an ID and there is an associated child
with such ID, the parameter data will be passed to `changeset/2`
with the existing struct and become an update operation
* If there is an associated child with an ID and its ID is not given
as parameter, the `:on_replace` callback for that association will
be invoked (see the "On replace" section on the module documentation)
Every time the `changeset/2` function is invoked, it must return a changeset.
Note developers are allowed to explicitly set the `:action` field of a
changeset to instruct Ecto how to act in certain situations. Let's suppose
that, if one of the associations has only empty fields, you want to ignore
the entry altogether instead of showing an error. The changeset function could
be written like this:
def changeset(struct, params) do
struct
|> cast(struct, params, [:title, :body])
|> validate_requited([:title, :body])
|> case do
%{valid?: false, changes: changes} = changeset when changes == %{} ->
# If the changeset is invalid and has no changes, it is
# because all required fields are missing, so we ignore it.
%{changeset | action: :ignore}
changeset ->
changeset
end
end
## Alternatives to cast_assoc/3
`cast_assoc/3` is useful when the associated data is managed alongside
the parent struct, all at once.
To work with a single element of an association, other functions are
more appropriate. For example to insert a single associated struct for a
`has_many` association it's much easier to construct the associated struct
with `Ecto.build_assoc/3` and persist it directly with `c:Ecto.Repo.insert/2`.
Furthermore, if each side of the association is managed separately,
it is preferable to use `put_assoc/3` and directly instruct Ecto how
the association should look like.
For example, imagine you are receiving a set of tags you want to
associate to an user. Those tags are meant to exist upfront. Using
`cast_assoc/3` won't work as desired because the tags are not managed
alongside the user. In such cases, `put_assoc/3` will work as desired.
With the given parameters:
%{"name" => "john doe", "tags" => ["learner"]}
and then:
tags = Repo.all(from t in Tag, where: t.name in ^params["tags"])
user
|> Repo.preload(:tags)
|> Ecto.Changeset.cast(params) # No need to allow :tags as we put them directly
|> Ecto.Changeset.put_assoc(:tags, tags) # Explicitly set the tags
Note the changeset must have been previously `cast` using `cast/4`
before this function is invoked.
## Options
* `:with` - the function to build the changeset from params.
Defaults to the changeset/2 function in the association module
* `:required` - if the association is a required field
* `:required_message` - the message on failure, defaults to "can't be blank"
* `:invalid_message` - the message on failure, defaults to "is invalid"
"""
def cast_assoc(changeset, name, opts \\ []) when is_atom(name) do
cast_relation(:assoc, changeset, name, opts)
end
@doc """
Casts the given embed with the changeset parameters.
The parameters for the given embed will be retrieved
from `changeset.params`. Those parameters are expected to be
a map with attributes, similar to the ones passed to `cast/4`.
Once parameters are retrieved, `cast_embed/3` will match those
parameters with the embeds already in the changeset record.
See `cast_assoc/3` for an example of working with casts and
associations which would also apply for embeds.
The changeset must have been previously `cast` using
`cast/4` before this function is invoked.
## Options
* `:with` - the function to build the changeset from params.
Defaults to the changeset/2 function in the embed module
* `:required` - if the embed is a required field
* `:required_message` - the message on failure, defaults to "can't be blank"
* `:invalid_message` - the message on failure, defaults to "is invalid"
"""
def cast_embed(changeset, name, opts \\ []) when is_atom(name) do
cast_relation(:embed, changeset, name, opts)
end
defp cast_relation(type, %Changeset{data: data, types: types}, _name, _opts)
when data == nil or types == nil do
raise ArgumentError, "cast_#{type}/3 expects the changeset to be cast. " <>
"Please call cast/4 before calling cast_#{type}/3"
end
defp cast_relation(type, %Changeset{} = changeset, key, opts) do
{key, param_key} = cast_key(key)
%{data: data, types: types, params: params, changes: changes} = changeset
%{related: related} = relation = relation!(:cast, type, key, Map.get(types, key))
params = params || %{}
{changeset, required?} =
if opts[:required] do
{update_in(changeset.required, &[key|&1]), true}
else
{changeset, false}
end
on_cast = Keyword.get_lazy(opts, :with, fn -> on_cast_default(type, related) end)
original = Map.get(data, key)
changeset =
case Map.fetch(params, param_key) do
{:ok, value} ->
current = Relation.load!(data, original)
case Relation.cast(relation, value, current, on_cast) do
{:ok, change, relation_valid?} when change != original ->
missing_relation(%{changeset | changes: Map.put(changes, key, change),
valid?: changeset.valid? and relation_valid?}, key, current, required?, relation, opts)
:error ->
%{changeset | errors: [{key, {message(opts, :invalid_message, "is invalid"), [type: expected_relation_type(relation)]}} | changeset.errors], valid?: false}
_ -> # ignore or ok with change == original
missing_relation(changeset, key, current, required?, relation, opts)
end
:error ->
missing_relation(changeset, key, original, required?, relation, opts)
end
update_in changeset.types[key], fn {type, relation} ->
{type, %{relation | on_cast: on_cast}}
end
end
defp on_cast_default(type, module) do
fn struct, params ->
try do
module.changeset(struct, params)
rescue
e in UndefinedFunctionError ->
case System.stacktrace do
[{^module, :changeset, args_or_arity, _}] when args_or_arity == 2
when length(args_or_arity) == 2 ->
raise ArgumentError, """
the module #{inspect module} does not define a changeset/2 function,
which is used by cast_#{type}/3. You need to either:
1. implement the #{type}.changeset/2 function
2. pass the :with option to cast_#{type}/3 with an anonymous function that expects 2 args
When using an inline embed, the :with option must be given
"""
stacktrace ->
reraise e, stacktrace
end
end
end
end
defp expected_relation_type(%{cardinality: :one}), do: :map
defp expected_relation_type(%{cardinality: :many}), do: {:array, :map}
defp missing_relation(%{changes: changes, errors: errors} = changeset,
name, current, required?, relation, opts) do
current_changes = Map.get(changes, name, current)
if required? and Relation.empty?(relation, current_changes) do
errors = [{name, {message(opts, :required_message, "can't be blank"), [validation: :required]}} | errors]
%{changeset | errors: errors, valid?: false}
else
changeset
end
end
defp relation!(_op, type, _name, {type, relation}),
do: relation
defp relation!(op, type, name, nil),
do: raise(ArgumentError, "cannot #{op} #{type} `#{name}`, assoc `#{name}` not found. Make sure it is spelled correctly and properly pluralized (or singularized)")
defp relation!(op, type, name, {other, _}) when other in @relations,
do: raise(ArgumentError, "expected `#{name}` to be an #{type} in `#{op}_#{type}`, got: `#{other}`")
defp relation!(op, type, name, schema_type),
do: raise(ArgumentError, "expected `#{name}` to be an #{type} in `#{op}_#{type}`, got: `#{inspect schema_type}`")
## Working with changesets
@doc """
Merges two changesets.
This function merges two changesets provided they have been applied to the
same data (their `:data` field is equal); if the data differs, an
`ArgumentError` exception is raised. If one of the changesets has a `:repo`
field which is not `nil`, then the value of that field is used as the `:repo`
field of the resulting changeset; if both changesets have a non-`nil` and
different `:repo` field, an `ArgumentError` exception is raised.
The other fields are merged with the following criteria:
* `params` - params are merged (not deep-merged) giving precedence to the
params of `changeset2` in case of a conflict. If both changesets have their
`:params` fields set to `nil`, the resulting changeset will have its params
set to `nil` too.
* `changes` - changes are merged giving precedence to the `changeset2`
changes.
* `errors` and `validations` - they are simply concatenated.
* `required` - required fields are merged; all the fields that appear
in the required list of both changesets are moved to the required
list of the resulting changeset.
## Examples
iex> changeset1 = cast(%Post{}, %{title: "Title"}, [:title])
iex> changeset2 = cast(%Post{}, %{title: "New title", body: "Body"}, [:title, :body])
iex> changeset = merge(changeset1, changeset2)
iex> changeset.changes
%{body: "Body", title: "New title"}
iex> changeset1 = cast(%Post{body: "Body"}, %{title: "Title"}, [:title])
iex> changeset2 = cast(%Post{}, %{title: "New title"}, [:title])
iex> merge(changeset1, changeset2)
** (ArgumentError) different :data when merging changesets
"""
@spec merge(t, t) :: t | no_return
def merge(changeset1, changeset2)
def merge(%Changeset{data: data} = cs1, %Changeset{data: data} = cs2) do
new_repo = merge_identical(cs1.repo, cs2.repo, "repos")
new_repo_opts = Keyword.merge(cs1.repo_opts, cs2.repo_opts)
new_action = merge_identical(cs1.action, cs2.action, "actions")
new_filters = Map.merge(cs1.filters, cs2.filters)
new_validations = cs1.validations ++ cs2.validations
new_constraints = cs1.constraints ++ cs2.constraints
new_empty_vals = Enum.uniq(cs1.empty_values ++ cs2.empty_values)
cast_merge %{cs1 | repo: new_repo, repo_opts: new_repo_opts, filters: new_filters,
action: new_action, validations: new_validations,
constraints: new_constraints, empty_values: new_empty_vals}, cs2
end
def merge(%Changeset{}, %Changeset{}) do
raise ArgumentError, message: "different :data when merging changesets"
end
defp cast_merge(cs1, cs2) do
new_params = (cs1.params || cs2.params) && Map.merge(cs1.params || %{}, cs2.params || %{})
new_changes = Map.merge(cs1.changes, cs2.changes)
new_errors = Enum.uniq(cs1.errors ++ cs2.errors)
new_required = Enum.uniq(cs1.required ++ cs2.required)
new_types = cs1.types || cs2.types
new_valid? = cs1.valid? and cs2.valid?
%{cs1 | params: new_params, valid?: new_valid?, errors: new_errors, types: new_types,
changes: new_changes, required: new_required}
end
defp merge_identical(object, nil, _thing), do: object
defp merge_identical(nil, object, _thing), do: object
defp merge_identical(object, object, _thing), do: object
defp merge_identical(lhs, rhs, thing) do
raise ArgumentError, "different #{thing} (`#{inspect lhs}` and " <>
"`#{inspect rhs}`) when merging changesets"
end
@doc """
Fetches the given field from changes or from the data.
While `fetch_change/2` only looks at the current `changes`
to retrieve a value, this function looks at the changes and
then falls back on the data, finally returning `:error` if
no value is available.
For relations, these functions will return the changeset
original data with changes applied. To retrieve raw changesets,
please use `fetch_change/2`.
## Examples
iex> post = %Post{title: "Foo", body: "Bar baz bong"}
iex> changeset = change(post, %{title: "New title"})
iex> fetch_field(changeset, :title)
{:changes, "New title"}
iex> fetch_field(changeset, :body)
{:data, "Bar baz bong"}
iex> fetch_field(changeset, :not_a_field)
:error
"""
@spec fetch_field(t, atom) :: {:changes, term} | {:data, term} | :error
def fetch_field(%Changeset{changes: changes, data: data, types: types}, key) do
case Map.fetch(changes, key) do
{:ok, value} ->
{:changes, change_as_field(types, key, value)}
:error ->
case Map.fetch(data, key) do
{:ok, value} -> {:data, data_as_field(data, types, key, value)}
:error -> :error
end
end
end
@doc """
Gets a field from changes or from the data.
While `get_change/3` only looks at the current `changes`
to retrieve a value, this function looks at the changes and
then falls back on the data, finally returning `default` if
no value is available.
For relations, these functions will return the changeset data
with changes applied. To retrieve raw changesets, please use `get_change/3`.
iex> post = %Post{title: "A title", body: "My body is a cage"}
iex> changeset = change(post, %{title: "A new title"})
iex> get_field(changeset, :title)
"A new title"
iex> get_field(changeset, :not_a_field, "Told you, not a field!")
"Told you, not a field!"
"""
@spec get_field(t, atom, term) :: term
def get_field(%Changeset{changes: changes, data: data, types: types}, key, default \\ nil) do
case Map.fetch(changes, key) do
{:ok, value} ->
change_as_field(types, key, value)
:error ->
case Map.fetch(data, key) do
{:ok, value} -> data_as_field(data, types, key, value)
:error -> default
end
end
end
defp change_as_field(types, key, value) do
case Map.get(types, key) do
{tag, relation} when tag in @relations ->
Relation.apply_changes(relation, value)
_other ->
value
end
end
defp data_as_field(data, types, key, value) do
case Map.get(types, key) do
{tag, _relation} when tag in @relations ->
Relation.load!(data, value)
_other ->
value
end
end
@doc """
Fetches a change from the given changeset.
This function only looks at the `:changes` field of the given `changeset` and
returns `{:ok, value}` if the change is present or `:error` if it's not.
## Examples
iex> changeset = change(%Post{body: "foo"}, %{title: "bar"})
iex> fetch_change(changeset, :title)
{:ok, "bar"}
iex> fetch_change(changeset, :body)
:error
"""
@spec fetch_change(t, atom) :: {:ok, term} | :error
def fetch_change(%Changeset{changes: changes} = _changeset, key) when is_atom(key) do
Map.fetch(changes, key)
end
@doc """
Gets a change or returns a default value.
## Examples
iex> changeset = change(%Post{body: "foo"}, %{title: "bar"})
iex> get_change(changeset, :title)
"bar"
iex> get_change(changeset, :body)
nil
"""
@spec get_change(t, atom, term) :: term
def get_change(%Changeset{changes: changes} = _changeset, key, default \\ nil) when is_atom(key) do
Map.get(changes, key, default)
end
@doc """
Updates a change.
The given `function` is invoked with the change value only if there
is a change for the given `key`. Note that the value of the change
can still be `nil` (unless the field was marked as required on `validate_required/3`).
## Examples
iex> changeset = change(%Post{}, %{impressions: 1})
iex> changeset = update_change(changeset, :impressions, &(&1 + 1))
iex> changeset.changes.impressions
2
"""
@spec update_change(t, atom, (term -> term)) :: t