Skip to content

Commit

Permalink
Preserve time precision on decode
Browse files Browse the repository at this point in the history
Fixes #675.
  • Loading branch information
thenrio committed May 15, 2024
1 parent ef6bd2f commit 2d20f4e
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
9 changes: 7 additions & 2 deletions lib/postgrex/extensions/time.ex
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,15 @@ defmodule Postgrex.Extensions.Time do

def microsecond_to_elixir(microsec) do
sec = div(microsec, 1_000_000)
microsec = rem(microsec, 1_000_000)

microsec_precision =
case rem(microsec, 1_000_000) do
0 -> {0, 0}
m -> {m, 6}
end

sec
|> :calendar.seconds_to_time()
|> Time.from_erl!({microsec, 6})
|> Time.from_erl!(microsec_precision)
end
end
13 changes: 7 additions & 6 deletions test/calendar_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@ defmodule CalendarTest do
end

test "decode time", context do
assert [[~T[00:00:00.000000]]] = query("SELECT time '00:00:00'", [])
assert [[~T[01:02:03.000000]]] = query("SELECT time '01:02:03'", [])
assert [[~T[23:59:59.000000]]] = query("SELECT time '23:59:59'", [])
assert [[~T[04:05:06.000000]]] = query("SELECT time '04:05:06 PST'", [])
assert [[~T[04:05:06.000000]]] = query("SELECT time '04:05:06-8'", [])
assert [[~T[04:05:06.000000]]] = query("SELECT time '04:05:06-8'", [])
assert [[~T[00:00:00]]] = query("SELECT time '00:00:00'", [])
assert [[~T[01:02:03]]] = query("SELECT time '01:02:03'", [])
assert [[~T[23:59:59]]] = query("SELECT time '23:59:59'", [])
assert [[~T[04:05:06]]] = query("SELECT time '04:05:06 PST'", [])
assert [[~T[04:05:06]]] = query("SELECT time '04:05:06-8'", [])
assert [[~T[04:05:06]]] = query("SELECT time '04:05:06-8'", [])

assert [[~T[00:00:00.123000]]] = query("SELECT time '00:00:00.123'", [])
assert [[~T[00:00:00.123456]]] = query("SELECT time '00:00:00.123456'", [])
Expand Down Expand Up @@ -253,6 +253,7 @@ defmodule CalendarTest do
end

test "encode time", context do
assert [[~T[01:02:03]]] = query("SELECT $1::time", [~T[01:02:03]])
assert [["00:00:00"]] = query("SELECT $1::time::text", [~T[00:00:00.0000]])
assert [["01:02:03"]] = query("SELECT $1::time::text", [~T[01:02:03]])
assert [["23:59:59"]] = query("SELECT $1::time::text", [~T[23:59:59]])
Expand Down

0 comments on commit 2d20f4e

Please sign in to comment.