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

Respect precision for intervals #699

Merged
Merged
Show file tree
Hide file tree
Changes from 3 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
12 changes: 11 additions & 1 deletion lib/postgrex/extensions/interval.ex
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ defmodule Postgrex.Extensions.Interval do
def init(opts), do: Keyword.get(opts, :interval_decode_type, Postgrex.Interval)

if Code.ensure_loaded?(Duration) do
import Bitwise, warn: false
@default_precision 6
@precision_mask 0xFFFF

def encode(_) do
quote location: :keep do
%Postgrex.Interval{months: months, days: days, secs: seconds, microsecs: microseconds} ->
Expand Down Expand Up @@ -58,6 +62,12 @@ defmodule Postgrex.Extensions.Interval do
hours = div(minutes, 60)
minutes = rem(minutes, 60)

precision =
case var!(mod) do
unspecified when unspecified in [-1, nil] -> unquote(@default_precision)
modifier -> modifier &&& unquote(@precision_mask)
end

Duration.new!(
year: years,
month: months,
Expand All @@ -66,7 +76,7 @@ defmodule Postgrex.Extensions.Interval do
hour: hours,
minute: minutes,
second: seconds,
microsecond: {microseconds, 6}
microsecond: {microseconds, precision}
)
end
end
Expand Down
11 changes: 11 additions & 0 deletions test/query_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,17 @@ defmodule QueryTest do
assert [[[%Duration{second: 10, microsecond: {240_000, 6}}]]] =
P.query!(pid, "SELECT ARRAY[interval '10240000 microseconds']", []).rows
end

test "decode interval with Elixir Duration and precision" do
opts = [database: "postgrex_test", backoff_type: :stop, types: Postgrex.ElixirDurationTypes]
{:ok, pid} = P.start_link(opts)

assert [[%Duration{second: 10, microsecond: {240_000, 2}}]] =
P.query!(pid, "SELECT interval(2) '10240000 microseconds'", []).rows

assert [[[%Duration{second: 10, microsecond: {0, 0}}]]] =
P.query!(pid, "SELECT ARRAY[interval(0) '10240000 microseconds']", []).rows
end
end

test "decode point", context do
Expand Down
Loading