cboebel

cboebel

Ecto (mysql) and UUID

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!

Most Liked

Rainer

Rainer

I updated my test to output the uuid’s:
insert: a0569da7-4201-47a8-bab0-4aca263b735a => ok
insert: cc2d9293-5898-4118-8352-c192090bf6ef => fail, got new id: 3f2d3f3f-583f-4118-3f52-3f3f090b3f00

another run:
insert: 2361f715-48f9-4574-9cb2-379883a8adc4 => got new id: 23613f15-483f-4574-3f3f-373f3f3f3f00

interesting: the new id’s are sharing some parts with the original ones…

/e: now found this: binary id odd bug · Issue #2602 · elixir-ecto/ecto · GitHub
i’ll try that later, hope it fixes the problem :slight_smile:

/e²: Fixed it by adding utf8mb4 to the repo config (config/dev.exs):

# Configure your database
config :testproject, Testproject.Repo,
  username: "xyz",
  password: "xyz",
  database: "xyz",
  hostname: "xyz",
  charset: "utf8mb4",
  collate: "utf8mb4_unicode_ci"
al2o3cr

al2o3cr

This won’t let id through, causing the built-in autogenerate to run instead.

simon

simon

I discovered this in the context of migrations so it might not make any difference here but when your define your primary key add read_after_writes: true.

@primary_key {:id, :binary_id, autogenerate: true, read_after_writes: true}

cboebel

cboebel

MySQL does not like this:

For relational databases, this means the RETURNING option of those statements is used. For this reason, MySQL does not support this option and will raise an error if a schema is inserted/updated with read after writes fields.

isaac-rstor

isaac-rstor

Can you double check that your character encoding and collation is ok? Ecto’s MySQL doesn’t support certain of MySQL encoding types, and I remember having major problems with uuids that drove me up the wall (but were solvable - except when I had to interface with other databases at work) until I switched to postgres.

I can’t be 100% sure but I recall values being trimmed at 3f as being diagnostic of the problem – you’ll have to use utf8- something other other and not Latin, which is the default in MySQL iirc.

Where Next?

Popular in Questions Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
gonzofish
I’m currently trying to understand how to join three tables using Ecto. All the examples I’ve seen use 2, so maybe I’m just missing somet...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New
wernerlaude
In AR this is so simple @articles = current_user.articles How to do in Ecto? def index(conn, _params) do current_user = conn.assig...
New
jc00ke
Expanding on this topic: https://forum.elixirforum.net/t/map-typespec-question/19217 Let’s say I have a map with required and optional k...
New

Other popular topics Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
AstonJ
You’re a programmer, so you don’t need spoon feeding with the conventional drivel about “this is an integer.” No. You need to know what’s...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New

We're in Beta

About us Mission Statement