ecto icon indicating copy to clipboard operation
ecto copied to clipboard

Primary Key ignores custom Ecto.Type#load after Repo.insert, Repo.all since 2.2.0

Open hasclass opened this issue 8 years ago • 10 comments

When updating from 2.1.6 to 2.2.0 (or higher) we are running into troubles with "deserializing" custom Ecto.Types for primary key. It works fine with normal columns. All our primary keys are UUIDs inside the Postgresql DB .

Our Ecto.Type Custom.PrefixedId transparently adds/removes a prefix to the ids. So clients can work with friendly uuids that indicate their type: e.g. blog_12323-..-23121, post_12323-..-123123

defmodule Blog.Post do
  # adds a "virtual" prefix to a uuid column.  
  alias Custom.PrefixedId

  @primary_key {:id, PrefixedId, autogenerate: true}
  @derive {Phoenix.Param, key: :id}
  @foreign_key_type Ecto.UUID

  schema "posts" do  
    field(:other_id, PrefixedId) # database type is :uuid
  end
end

BEFORE. Correct behaviour with ecto 2.1.6

b = Repo.insert!(%Blog.Post{other_id: UUID.uuid4})
b.id       # => lorem_c0690cf7-3e57-4338-bb0c-9e2279d1d242
b.other_id # => lorem_86399b0f-f9b7-4fd5-93ea-c4665f991cc1

b = Repo.get(Blog.Post, "lorem_c0690cf7-3e57-4338-bb0c-9e2279d1d242")
b.id       # => "lorem_c0690cf7-3e57-4338-bb0c-9e2279d1d242"
b.other_id # => "lorem_86399b0f-f9b7-4fd5-93ea-c4665f991cc1"

[b] = Repo.all(Blog.Post)
b.id       # => "lorem_c0690cf7-3e57-4338-bb0c-9e2279d1d242"
b.other_id # => "lorem_86399b0f-f9b7-4fd5-93ea-c4665f991cc1"

AFTER. with ecto ~> 2.2.0 (all versions)

Blog.Post#id is no longer consistently "deserialized", but other columns with the same Ecto.Type are.

b = Repo.insert!(%Blog.Post{other_id: UUID.uuid4})
b.id       # => c0690cf7-3e57-4338-bb0c-9e2279d1d242
b.other_id # => lorem_86399b0f-f9b7-4fd5-93ea-c4665f991cc1

# But with get it seems to work just fine
b = Repo.get(Blog.Post, "lorem_c0690cf7-3e57-4338-bb0c-9e2279d1d242")
b.id       # => "lorem_c0690cf7-3e57-4338-bb0c-9e2279d1d242" 
b.other_id # => "lorem_86399b0f-f9b7-4fd5-93ea-c4665f991cc1"

# Updating that records other_id keeps the id correct, but does not prefix other_id
b = Repo.get(Blog.Post, "lorem_c0690cf7-3e57-4338-bb0c-9e2279d1d242")
u = Ecto.Changeset.change(b, other_id: UUID.uuid4) |> Repo.update!
u.id       # => "lorem_c0690cf7-3e57-4338-bb0c-9e2279d1d242" 
u.other_id # => "000e235d-e77b-4ef5-91a1-e7bfc3db130e"

[b] = Repo.all(Blog.Post)
b.id       # => "lorem_c0690cf7-3e57-4338-bb0c-9e2279d1d242"
b.other_id # => "lorem_86399b0f-f9b7-4fd5-93ea-c4665f991cc1"

Most probably somehow the Ecto.Type given in @primary_key is not properly registered. Or not consistently applied with primary key columns.

Environment:

PostgreSQL 9.6
Erlang/OTP 20 [erts-9.2.1] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]
Elixir 1.6.4 (compiled with OTP 19)

Updates

  • I made a mistake, Repo.all is actually working fine in the new version. Updated description.
  • Updated with a description when updating

hasclass avatar Jul 11 '18 12:07 hasclass

Perhaps related with https://github.com/elixir-ecto/ecto/issues/2602

hasclass avatar Jul 11 '18 12:07 hasclass

@hasclass can you provide the implementation of the custom type? Also, can you please let us know what UUID.uuid4 returns? Does it have a prefix or not?

josevalim avatar Jul 11 '18 12:07 josevalim

Hi, @josevalim, this is our implementation:

defmodule Custom.PrefixedId do
  @behaviour Ecto.Type

  prefix = "lorem_"
  def type, do: :binary_id

  def cast(unquote(prefix) <> uuid = gid) do
    {:ok, gid}
  end
  def cast(uuid) when byte_size(uuid) == 36 do
    {:ok, unquote(prefix) <> uuid}
  end
  def cast(_), do: :error

  def load(uuid) when is_binary(uuid) do
    {:ok, unquote(prefix) <> uuid}
  end
  def load(_), do: :error

  def dump(unquote(prefix) <> uuid) do
    dump(uuid)
  end
  def dump(uuid) when is_binary(uuid) and byte_size(uuid) == 36 do
    {:ok, uuid}
  end
  def dump(_), do: :error
end

and this is UUID.uuid4/0 example:

iex(1)> Ecto.Type.cast(Custom.PrefixedId, UUID.uuid4)
{:ok, "lorem_f7b1eaeb-340f-40c1-bd86-2c6715076774"}
iex(2)> UUID.uuid4
"8ab8446a-38f9-4a99-a5e4-46cb76373a7e"

0rca avatar Jul 11 '18 12:07 0rca

The responsibilities of the Type functions are converting between representations of the type:

  • cast: external to internal
  • load: database to internal
  • dump: internal to database

Where external means something like JSON or HTML forms, internal means the representation in the struct and database means the representation in the database itself.

Give that, this example is correct:

# Updating that records other_id keeps the id correct, but does not prefix other_id
b = Repo.get(Blog.Post, "lorem_c0690cf7-3e57-4338-bb0c-9e2279d1d242")
u = Ecto.Changeset.change(b, other_id: UUID.uuid4) |> Repo.update!
u.id       # => "lorem_c0690cf7-3e57-4338-bb0c-9e2279d1d242" 
u.other_id # => "000e235d-e77b-4ef5-91a1-e7bfc3db130e"

The change operation of the changeset is expected to receive the internal representation, so no cast or load is performed on it. Given the Type definition you provided, chane should receive the value with the prefix. Ecto.Changeset.change(b, other_id: UUID.uuid4) is not a valid operation for your type.

Similarly, when you create the struct directly, it should use the internal representation, given that %Blog.Post{other_id: UUID.uuid4}) is not valid code. You could verify this by making your type actually enfore the contstraints in the dump function. It should be defined as:

  def dump(unquote(prefix) <> uuid) when byte_size(uuid) == 36 do
    {:ok, uuid}
  end
  def dump(_), do: :error

The dump function should always receive the internal representation of the data.

To sum up, it actually seems to me like the old behaviour in 2.1 was erroneous and now it is correct. There does seem to be some issue with the primary key on insert, but everything else seems correct to me.

michalmuskala avatar Jul 11 '18 12:07 michalmuskala

Thanks for taking the time and the detailed explanation @michalmuskala. By trying to give as much detail as possible I might have confused things a bit.

My original concern was about the insert and the handling of the (resulting) primary key.

b = Repo.insert!(%Blog.Post{})
b.id       # => c0690cf7-3e57-4338-bb0c-9e2279d1d242

# versus loading
b = Repo.get(Blog.Post, "lorem_c0690cf7-3e57-4338-bb0c-9e2279d1d242")
b.id       # => "lorem_86399b0f-f9b7-4fd5-93ea-c4665f991cc1"

In the Repo.insert case I would expect the same result as when I would fetch the record directly from the db using Repo.get and expect that #load (database to internal) is called on the id private key and thus add the prefix.

This behaviour changed after updating from 2.1 to 2.2.

hasclass avatar Jul 11 '18 13:07 hasclass

Yup, this behaviour is definitely a bug.

josevalim avatar Jul 11 '18 15:07 josevalim

@michalmuskala @josevalim I did some digging:

The original commit was https://github.com/elixir-ecto/ecto/commit/543e97abe4473e3b21442136eaf50f024cc28e60

in v.2.1.6 Ecto.Repo.Schema.load_changest/6 is using changeset.types which has the correct custom type for :id.

in v.2.2.0 Ecto.Repo.Schema.load_changest/7 is passed the types in separately as return_types, which contains [{:id, :binary_id}].

return_types is generated here:

    {return_types, return_sources} =
      schema
      |> returning(opts)
      |> add_read_after_writes(schema)
      |> fields_to_sources(dumper)

return_types is now [].

and modified here:

        {changes, extra, return_types, return_sources} =
          autogenerate_id(autogen_id, changeset.changes, return_types, return_sources, adapter)

return_types is now [{:id, :binary_id}].

autogen_id was {:id, :id, :binary_id} but given the rest of the flow it should be {:id, :id, <custom Ecto.Type>}

        autogen_id = schema.__schema__(:autogenerate_id)

that on the other hand seems to be generated by Ecto.Schema:

Ecto.Schema.store_type_autogenerate/5 and Ecto.Schema.autogenerate_id/1. autogenerate_id/1 tries to use the underlying type if it's :id or :binary_id which is here the case. Therefore that enters the branch in store_type_autogenerate/5 that generates the tuple {name, source, <unpacked-id>} which feeds schema.__schema__(:autogenerate_id)

If Ecto.Schema.autogenerate_id/1 needs to be applied already at macro expansion time in store_type_autogenerate then the schema fields can't be used to carry the type information through to Ecto.Repo.Schema.autogenerate_id/5.

I'm a bit stuck now, because I don't see what the new desired design is for carrying the :id field type info through to Ecto.Repo.Schema.load_changest/7.

Thoughts?

unthought avatar Jul 13 '18 04:07 unthought

It seems like we were able to sidestep the issue for our case by using type :uuid instead of :binary_id which then enters the custom autogeneration clause in Ecto.Schema.store_type_autogenerate/5, implementing autogenerate/0 returning a prefixed uuid, and piggy-backing onto Ecto.UUID:

  defmacro defgid(module, opts) do
    prefix = Keyword.fetch!(opts, :prefix) <> "_"

    quote do
      defmodule unquote(module) do
        @behaviour Ecto.Type

        def type, do: :uuid

        def cast(unquote(prefix) <> uuid = gid) do
          {:ok, gid}
        end

        def cast(uuid) when byte_size(uuid) == 36 do
          with {:ok, uuid} <- Ecto.UUID.cast(uuid) do
            {:ok, unquote(prefix) <> uuid}
          end
        end

        def cast(_), do: :error

        def load(uuid) do
          with {:ok, uuid} <- Ecto.UUID.load(uuid) do
            {:ok, unquote(prefix) <> uuid}
          end
        end

        def dump(unquote(prefix) <> uuid) do
          dump(uuid)
        end

        def dump(uuid) when is_binary(uuid) and byte_size(uuid) == 36 do
          Ecto.UUID.dump(uuid)
        end

        def dump(_), do: :error

        @doc false
        def autogenerate, do: unquote(prefix) <> Ecto.UUID.generate()
      end
    end
  end

(Note: it was always a macro..)

This doesn't mean there isn't a bug, but we seem to have escaped it's grasp.

We will report back if we find out more.

unthought avatar Jul 13 '18 18:07 unthought

Hello everyone! The load/1 callback works only for Repo.all. This applies to all fields in the schema, not only to primary key.

Environment

Ubuntu 18.04 PostgreSQL 10.17 Erlang/OTP 22 [erts-10.7.1] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [hipe] Elixir 1.10.3 Ecto 3.4.5

floodico avatar Jun 24 '21 17:06 floodico

Hello everyone! The load/1 callback works only for Repo.all. This applies to all fields in the schema, not only to primary key.

Environment

Ubuntu 18.04 PostgreSQL 10.17 Erlang/OTP 22 [erts-10.7.1] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [hipe] Elixir 1.10.3 Ecto 3.4.5

Ok, i found a solution. See the option :returning here https://hexdocs.pm/ecto/Ecto.Repo.html#c:update/2-options It's necessary to include the field in the list of returned fields, and then the load/1 callback invokes.

floodico avatar Jul 08 '21 11:07 floodico