What is the difference between Ecto.Type's cast and dump?

Hello there!

Trying to sketch a custom type to store a string as a tsvector in a database. Right now I’m stuck trying to understand the difference between cast and dump functions. Documentation is not terribly helpful here:

cast(type, value)
Casts a value to the given type

dump(type, value, dumper \ &dump/2)
Dumps a value to the given type

Would appreciate any help. Thanks in advance.

1 Like

cast and load transform data.
dump is a guard guard clause.

eg: atom_to_string and reverse…

defmodule Whatever.Atom do
  @behaviour Ecto.Type
  def type, do: :binary
  def cast(atom) when is_atom(atom), do: {:ok, to_string(atom)}
  def cast(string) when is_binary(string), do: {:ok, string}
  def cast(_), do: :error
  def load(string) when is_binary(string), do: {:ok, String.to_atom(string)}
  def load(_), do: :error
  def dump(string) when is_binary(string), do: {:ok, string}
  def dump(_), do: :error
1 Like

cast/2 is the function used when you call Ecto.Changeset.cast/3 while dump/2 is used to get your data ready to be written to the database.

This means that cast is used to (potentially) convert your data into an internal normalized representation which will be part of your changesets. It also used for verifying that something is actually valid input data for your type.

The Ecto.Date module has some nice examples of it in its source code. As you can see there, cast/2 is used to normalize input from several different formats …

… while dump/2 simply prepares the data to be written to the database: