Skip to content

Commit

Permalink
Dump UUIDs as is
Browse files Browse the repository at this point in the history
  • Loading branch information
josevalim committed Oct 1, 2023
1 parent e25ea9e commit ab815b9
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
13 changes: 12 additions & 1 deletion lib/ecto/adapters/postgres.ex
Original file line number Diff line number Diff line change
Expand Up @@ -151,9 +151,20 @@ defmodule Ecto.Adapters.Postgres do
@impl true
def dumpers({:map, _}, type), do: [&Ecto.Type.embedded_dump(type, &1, :json)]
def dumpers({:in, sub}, {:in, sub}), do: [{:array, sub}]
def dumpers(:binary_id, type), do: [type, Ecto.UUID]
def dumpers(:binary_id, type), do: [type, &dump_uuid/1]
def dumpers(:uuid, Ecto.UUID), do: [&dump_uuid/1]
def dumpers(:uuid, type), do: [&dump_uuid(type, &1)]
def dumpers(_, type), do: [type]

defp dump_uuid(type, uuid) do
with {:ok, value} <- Ecto.Type.dump(type, uuid) do
Ecto.UUID.load(value)
end
end

defp dump_uuid(uuid) when byte_size(uuid) == 36, do: {:ok, uuid}
defp dump_uuid(_other), do: :error

## Query API

@impl Ecto.Adapter.Queryable
Expand Down
19 changes: 17 additions & 2 deletions test/ecto/adapters/postgres_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@ defmodule Ecto.Adapters.PostgresTest do
schema "schema3" do
field :list1, {:array, :string}
field :list2, {:array, :integer}
field :binary_id, :binary_id
field :binary, :binary
field :uuid, Ecto.UUID
end
end

Expand Down Expand Up @@ -939,9 +941,22 @@ defmodule Ecto.Adapters.PostgresTest do
assert all(query) == String.trim(result)
end

test "dumping of binary types" do
query =
Schema3
|> where([s], s.binary == <<0, 1, 2, 3>> and s.uuid == "017f65d1-80bd-152d-f997-afa6dd33a00f")
|> select(true)
|> plan()

assert all(query) ==
"SELECT TRUE FROM \"schema3\" AS s0 " <>
"WHERE ((s0.\"binary\" = '\\x00010203'::bytea) " <>
"AND (s0.\"uuid\" = '017f65d1-80bd-152d-f997-afa6dd33a00f'))"
end

test "order_by and types" do
query = "schema3" |> order_by([e], type(fragment("?", e.binary), ^:decimal)) |> select(true) |> plan()
assert all(query) == "SELECT TRUE FROM \"schema3\" AS s0 ORDER BY s0.\"binary\"::decimal"
query = "schema" |> order_by([e], type(fragment("?", e.field), ^:decimal)) |> select(true) |> plan()
assert all(query) == "SELECT TRUE FROM \"schema\" AS s0 ORDER BY s0.\"field\"::decimal"
end

test "fragments and types" do
Expand Down

0 comments on commit ab815b9

Please sign in to comment.