Ecto.Query.API.type
type
, go back to Ecto.Query.API module for more information.
Casts the given value to the given type at the database level.
Most of the times, Ecto is able to proper cast interpolated values due to its type checking mechanism. In some situations though, you may want to tell Ecto that a parameter has some particular type:
type(^title, :string)
It is also possible to say the type must match the same of a column:
type(^title, p.title)
Ecto will ensure ^title
is cast to the given type and enforce such
type at the database level. If the value is returned in a select
,
Ecto will also enforce the proper type throughout.
When performing arithmetic operations, type/2
can be used to cast
all the parameters in the operation to the same type:
from p in Post,
select: type(p.visits + ^a_float + ^a_integer, :decimal)
Inside select
, type/2
can also be used to cast fragments:
type(fragment("NOW"), :naive_datetime)
Or to type fields from schemaless queries:
from p in "posts", select: type(p.cost, :decimal)
Or to type aggregation results:
from p in Post, select: type(avg(p.cost), :integer)
from p in Post, select: type(filter(avg(p.cost), p.cost > 0), :integer)