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

Copy Markdown View Source

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

A Localize.Duration is an amount of time in calendar units — a year, three months, two days — and interval is the PostgreSQL type for exactly that. Storing one as an interval rather than a number of seconds keeps the calendar meaning that "one month" carries (a month is not always thirty days), and lets the database add an interval to a date or sum a column of them.

Schema

# in a migration
add :billing_period, :interval

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

Normalization

PostgreSQL interval keeps three components — months, days and time — so the units within each component are interchangeable: a duration of ninety minutes is stored as, and loaded back as, one hour and thirty minutes, and thirteen months as one year and one month. Durations that are already in their normal form round-trip unchanged. The day and month components are kept distinct — a month is never folded into days — because PostgreSQL applies them separately when an interval is added to a date.

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.Duration.Ecto.Type.equal?(%Localize.Duration{minute: 90}, %Localize.Duration{hour: 1, minute: 30})
true

iex> Localize.Duration.Ecto.Type.equal?(%Localize.Duration{minute: 90}, %Localize.Duration{minute: 91})
false