Skip to content

Commit

Permalink
Remove max year from timestamptz (#689)
Browse files Browse the repository at this point in the history
  • Loading branch information
greg-rychlewski authored Jul 6, 2024
1 parent ea802cc commit 0dfa7ef
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 14 deletions.
16 changes: 2 additions & 14 deletions lib/postgrex/extensions/timestamptz.ex
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,9 @@ defmodule Postgrex.Extensions.TimestampTZ do
use Postgrex.BinaryExtension, send: "timestamptz_send"

@gs_epoch NaiveDateTime.to_gregorian_seconds(~N[2000-01-01 00:00:00.0]) |> elem(0)

@gs_unix_epoch NaiveDateTime.to_gregorian_seconds(~N[1970-01-01 00:00:00.0]) |> elem(0)
@us_epoch (@gs_epoch - @gs_unix_epoch) * 1_000_000

@gs_max elem(NaiveDateTime.to_gregorian_seconds(~N[9999-01-01 00:00:00.0]), 0) - @gs_unix_epoch
@us_max @gs_max * 1_000_000

@gs_min elem(NaiveDateTime.to_gregorian_seconds(~N[-4713-01-01 00:00:00.0]), 0) - @gs_unix_epoch
@us_min @gs_min * 1_000_000

@plus_infinity 9_223_372_036_854_775_807
@minus_infinity -9_223_372_036_854_775_808

Expand All @@ -40,13 +33,8 @@ defmodule Postgrex.Extensions.TimestampTZ do
## Helpers

def encode_elixir(%DateTime{utc_offset: 0, std_offset: 0} = datetime) do
case DateTime.to_unix(datetime, :microsecond) do
microsecs when microsecs in @us_min..@us_max ->
<<8::int32(), microsecs - @us_epoch::int64()>>

_ ->
raise ArgumentError, "#{inspect(datetime)} is not in the year range -4713..9999"
end
microsecs = DateTime.to_unix(datetime, :microsecond)
<<8::int32(), microsecs - @us_epoch::int64()>>
end

def encode_elixir(%DateTime{} = datetime) do
Expand Down
7 changes: 7 additions & 0 deletions test/calendar_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,13 @@ defmodule CalendarTest do
] = query("SELECT timestamp with time zone '1981-01-01BC 00:00:00.123456'", [])
end

test "decode timestamptz out of bounds", context do
%Postgrex.Error{postgres: %{message: message}} =
query("SELECT timestamp with time zone '4714-01-01BC 00:00:00.123456'", [])

assert message =~ "timestamp out of range"
end

@tag :capture_log
test "decode infinity", context do
assert_raise ArgumentError, fn -> query("SELECT 'infinity'::timestamp", []) end
Expand Down

0 comments on commit 0dfa7ef

Please sign in to comment.