Localize.Ecto.Type.Duration (Localize SQL v2.0.0)

Copy Markdown View Source

An Ecto.Type storing an Elixir Duration.t/0 in a PostgreSQL interval column.

Elixir's Duration is an amount of time in calendar units, which is exactly what the PostgreSQL interval type stores. Storing a duration as an interval rather than a number of seconds keeps its calendar meaning — "one month" is a month, not thirty days — and lets the database add it to a date or sum a column of them.

For the localized Localize.Duration.t/0 struct, see Localize.Duration.Ecto.Type.

Schema

# in a migration
add :retention, :interval

# in a schema
field :retention, Localize.Ecto.Type.Duration

Normalization

PostgreSQL interval keeps three components — months, days and time — so units within a component are interchangeable: ninety minutes loads back as one hour and thirty minutes, and a week loads back as seven days (interval has no separate week). The month and day components are kept distinct, because PostgreSQL applies them separately when an interval is added to a date. A duration already in this normal form round-trips unchanged.

Summary

Functions

Callback implementation for Ecto.Type.embed_as/1.

Returns whether two durations store the same interval.

Functions

embed_as(_)

Callback implementation for Ecto.Type.embed_as/1.

equal?(term1, term2)

@spec equal?(term(), term()) :: boolean()

Returns whether two durations store the same interval.

An interval keeps months, days and time, so ninety minutes is stored and loaded as one hour and thirty minutes. The two are not ==, but they are the same interval, so a changeset that casts one over the other records no change.

Arguments

  • left is a duration or nil.

  • right is a duration or nil.

Returns

  • true when both dump to the same interval, or are ==, or

  • false otherwise.

Examples

iex> Localize.Ecto.Type.Duration.equal?(Duration.new!(minute: 90), Duration.new!(hour: 1, minute: 30))
true

iex> Localize.Ecto.Type.Duration.equal?(Duration.new!(minute: 90), Duration.new!(minute: 91))
false