Another cast vs dump question for a custom Ecto type

Ecto.Types handle 3 different data representations. Outside data (most often from form inputs, or json fields in the db), runtime data (how your data is put into your structs by ecto and used at runtime) and the database representations as db column.

cast goes from outside data -> runtime data
dump goes from anything (outside data or runtime data) -> database column data
load goes from database column data -> runtime data

For json (map) fields there’s also
json encoding from anything -> database json value
cast from database json value -> runtime value

The reason why cast/json encoding need to deal with “anything” is because there’s nobody stopping you from inserting data via Repo.insert_all or manipulating a struct manually and there’s no casting involved. So any validation of correct data needs to be done in both cast and dump, where one converts to runtime data and the other to database column data.

7 Likes