Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir Postgrex using uuid

Tags:

elixir

I am using Postgrex library for my database, and I have the following problem: one of the columns in the database is of type uuid. I am using the UUID module in elixir but whenever I try to persist something to the database I get the following error: Postgrex expected a binary of 16 bytes, got "3c5fda26-ea3b-4c77-8f19-06e106a61eda". I have tried to store it as a plain string but it was not possible as you can see. How should I convert the uuid before persisting it to the database?

like image 477
Tano Avatar asked Nov 07 '18 15:11

Tano


3 Answers

I have just found that the UUID module has already a function called UUID.string_to_binary! , and its better to use this one instead of Ectos', as I am not using Ecto at all

like image 163
Tano Avatar answered Nov 17 '22 19:11

Tano


UUID is a string, but not a "human readable string". What you see as 3c5fda26-ea3b-4c77-8f19-06e106a61eda is not UUID, it is only one of the possible human readable representations. What you need is to pass direct, internal, UUID representation which in fact is binary of 16 bytes. To parse string form it hexadecimal representation to binary representation you can use Ecto.UUID.dump/1.

like image 34
Hauleth Avatar answered Nov 17 '22 19:11

Hauleth


Set the type of the field as binary_id in the schema.

For Example:

@primary_key {:id, :binary_id, autogenerate: true}
@derive {Phoenix.Param, key: :id}
schema “companies” do
 field :name, :string
 field :mission_statement, :string

 has_many :managers, EctoUuid.Manager
 timestamps
end
like image 3
Tessy Thomas Avatar answered Nov 17 '22 20:11

Tessy Thomas