Skip to content

Commit b49897f

Browse files
Create Duration guide (#4580)
1 parent a0ca993 commit b49897f

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Duration Types with Postgrex
2+
3+
As of Ecto 3.12.0, Ecto supports a `:duration` type which maps to Elixir's `Duration` struct (available as of Elixir 1.17).
4+
5+
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`.
6+
7+
1. Define your migration
8+
9+
```elixir
10+
create table("movies") do
11+
add :running_time, :interval
12+
end
13+
```
14+
15+
2. Define your schema
16+
17+
```elixir
18+
defmodule Movie do
19+
use Ecto.Schema
20+
21+
schema "movies" do
22+
field :running_time, :duration
23+
end
24+
end
25+
```
26+
27+
3. Define your custom Postgrex type module and specify intervals should decode to `Duration`
28+
29+
```elixir
30+
# Inside lib/my_app/postgrex_types.ex
31+
32+
Postgrex.Types.define(MyApp.PostgrexTypes, [], interval_decode_type: Duration)
33+
```
34+
35+
4. Make Ecto aware of the Postgrex type module in your configuration
36+
37+
```elixir
38+
config :my_app, MyApp.Repo, types: MyApp.PostgresTypes
39+
```

mix.exs

+1
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,7 @@ defmodule Ecto.MixProject do
148148
"guides/howtos/Composable transactions with Multi.md",
149149
"guides/howtos/Constraints and Upserts.md",
150150
"guides/howtos/Data mapping and validation.md",
151+
"guides/howtos/Duration Types with Postgrex.md",
151152
"guides/howtos/Dynamic queries.md",
152153
"guides/howtos/Multi tenancy with query prefixes.md",
153154
"guides/howtos/Multi tenancy with foreign keys.md",

0 commit comments

Comments
 (0)