Hello,
I’m having a vexing issue using Ecto.UUIDs as my primary key in a table. When I create a record, I generate the UUID for the id, and pass that along with the other fields to insert. A record is created, and the UUID is shown. When I query the record, I get a different UUID back.
Here’s an example of what I’m seeing. Code for the schema and repo follow the example.
I believe I’m doing something dumb but, at least for me, the dumber it is the harder it is to find.
iex(5)> Repo.insert(%ReplicationType{id: Ecto.UUID.generate(), name: "test3"})
18:32:49.063 [debug] QUERY OK db=0.8ms queue=7.6ms
INSERT INTO `replication_types` (`id`,`name`,`inserted_at`,`updated_at`) VALUES (?,?,?,?) [<<71, 34, 96, 242, 205, 97, 72, 47, 171, 47, 132, 161, 18, 187, 187, 138>>, "test3", ~N[2019-04-19 22:32:49], ~N[2019-04-19 22:32:49]]
{:ok,
%Pserver.Pserver.ReplicationType{
__meta__: #Ecto.Schema.Metadata<:loaded, "replication_types">,
id: "472260f2-cd61-482f-ab2f-84a112bbbb8a",
inserted_at: ~N[2019-04-19 22:32:49],
name: "test3",
replication_tables: #Ecto.Association.NotLoaded<association :replication_tables is not loaded>,
sites: #Ecto.Association.NotLoaded<association :sites is not loaded>,
updated_at: ~N[2019-04-19 22:32:49]
}}
iex(6)> Repo.get_by(ReplicationType, name: "test3")
18:33:11.506 [debug] QUERY OK source="replication_types" db=8.9ms
SELECT r0.`id`, r0.`name`, r0.`inserted_at`, r0.`updated_at` FROM `replication_types` AS r0 WHERE (r0.`name` = ?) ["test3"]
%Pserver.Pserver.ReplicationType{
__meta__: #Ecto.Schema.Metadata<:loaded, "replication_types">,
id: "4722603f-3f61-482f-3f2f-3f3f123f3f3f",
inserted_at: ~N[2019-04-19 22:32:49],
name: "test3",
replication_tables: #Ecto.Association.NotLoaded<association :replication_tables is not loaded>,
sites: #Ecto.Association.NotLoaded<association :sites is not loaded>,
updated_at: ~N[2019-04-19 22:32:49]
}
the code for ReplicationType:
defmodule Pserver.Pserver.ReplicationType do
use Ecto.Schema
import Ecto.Changeset
alias Pserver.Pserver.{ReplicationTable, Site}
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "replication_types" do
# field :id, :binary_id
field :name, :string
has_many :sites, Site
has_many :replication_tables, ReplicationTable
timestamps()
end
@doc false
def changeset(replication_type, attrs) do
replication_type
|> cast(attrs, [:name])
|> validate_required([:name])
|> unique_constraint(:name)
end
end
And the Repo…
defmodule Pserver.Repo do
use Ecto.Repo,
otp_app: :pserver,
adapter: Ecto.Adapters.MySQL
end
Thank you!