Skip to content

Commit d828a6a

Browse files
committed
Set a default timezone on mix ecto.create for PG
1 parent b1f477c commit d828a6a

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

integration_test/pg/storage_test.exs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,22 @@ defmodule Ecto.Integration.StorageTest do
7878
drop_database()
7979
end
8080

81+
test "storage up sets timezone to UTC by default" do
82+
assert Postgres.storage_up(params()) == :ok
83+
{output, _} = run_psql("SHOW timezone;", [params()[:database]])
84+
assert output =~ "Etc/UTC"
85+
after
86+
drop_database()
87+
end
88+
89+
test "storage up with custom timestamp timezone" do
90+
assert Postgres.storage_up([timestamp: "America/New_York"] ++ params()) == :ok
91+
{output, _} = run_psql("SHOW timezone;", [params()[:database]])
92+
assert output =~ "America/New_York"
93+
after
94+
drop_database()
95+
end
96+
8197
test "storage down (twice in a row)" do
8298
create_database()
8399
assert Postgres.storage_down(params()) == :ok

lib/ecto/adapters/postgres.ex

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,7 @@ defmodule Ecto.Adapters.Postgres do
228228

229229
case run_query(create_command, opts) do
230230
{:ok, _} ->
231-
:ok
231+
storage_up_timestamp(database, opts)
232232

233233
{:error, %{postgres: %{code: :duplicate_database}}} ->
234234
{:error, :already_up}
@@ -239,6 +239,21 @@ defmodule Ecto.Adapters.Postgres do
239239
end
240240
end
241241

242+
defp storage_up_timestamp(database, opts) do
243+
timestamp = Keyword.get(opts, :timestamp, "Etc/UTC")
244+
245+
if timestamp do
246+
alter_command = ~s(ALTER DATABASE "#{database}" SET timezone TO '#{timestamp}')
247+
248+
case run_query(alter_command, opts) do
249+
{:ok, _} -> :ok
250+
{:error, error} -> {:error, Exception.message(error)}
251+
end
252+
else
253+
:ok
254+
end
255+
end
256+
242257
defp concat_if(content, nil, _), do: content
243258
defp concat_if(content, false, _), do: content
244259
defp concat_if(content, value, fun), do: content <> " " <> fun.(value)

0 commit comments

Comments
 (0)