Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Duration guide #4580

Merged
merged 5 commits into from
Feb 21, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions guides/howtos/Duration Types with Postgrex.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Duration Types with Postgrex

As of Ecto 3.12.0, Ecto supports a `:duration` type which maps to Elixir's `Duration` struct (available as of Elixir 1.17).

One natural use case for this is when using Postgres's `interval` type. Historically, Postgrex loads intervals from the database into a custom `Postgrex.Interval` struct. With the introduction of `Duration`, there is now the option to choose between the two. Please follow the steps below to enable mapping to `Duration`.

1. Define your migration

```elixir
create table("movies") do
add :running_time, :interval
end
```

2. Define your schema

```elixir
defmodule Movie do
use Ecto.Schema

schema "movies" do
field :running_time, :duration
end
end
```

3. Define your custom Postgrex type module and specify intervals should decode to `Duration`

```elixir
# Inside lib/my_app/postgrex_types.ex

Postgrex.Types.define(MyApp.PostgrexTypes, [], interval_decode_type: Duration)
```

4. Make Ecto aware of the Postgrex type module in your configuration

```elixir
config :my_app, MyApp.Repo, types: MyApp.PostgresTypes
```
1 change: 1 addition & 0 deletions mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ defmodule Ecto.MixProject do
"guides/howtos/Composable transactions with Multi.md",
"guides/howtos/Constraints and Upserts.md",
"guides/howtos/Data mapping and validation.md",
"guides/howtos/Duration Types with Postgrex.md",
"guides/howtos/Dynamic queries.md",
"guides/howtos/Multi tenancy with query prefixes.md",
"guides/howtos/Multi tenancy with foreign keys.md",
Expand Down
Loading