DEV Community

Iván González Sáiz
Iván González Sáiz

Posted on

Generate UUID fields in Phoenix with Postgresql

If for some reason you need to create a UUID field for your schema (a non-primary key field), and you don't want to manage the creation of the value to store on the new database record, you can specify in the migration to use as default value the uuid_generate_v4() Postgresql method, so it will be auto-generated on the insert:

defmodule App.Repo.Migrations.AddUuidFieldToUser do
  use Ecto.Migration

  def change do
    create table(:users) do
      add(:some_new_field, :uuid, default: fragment("uuid_generate_v4()"))
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

Depending on the configuration of your database, maybe you will see this error running the migration:

** (Postgrex.Error) ERROR 42883 (undefined_function): function uuid_generate_v4() does not exist
Enter fullscreen mode Exit fullscreen mode

This is because your database hasn't the uuid-ossp module activated. You can activate by login to your database and execute this query:

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
Enter fullscreen mode Exit fullscreen mode

Or if you don't have access to the database, you can create a migration in order to execute the query like:

defmodule App.Repo.Migrations.AddUuidGenerateV4ExtensionToDatabase do
  use Ecto.Migration

  def change do
    execute("CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";")
  end
end
Enter fullscreen mode Exit fullscreen mode

You can see more in-depth information about uuid-ossp module here. So when the migrations are executed properly, add to your schema the new field, and there you have it! Your new shiny auto-generated UUID field.

defmodule App.User do
  use Ecto.Schema

  import Ecto.Changeset

  schema "users" do
    ...

    field(:some_new_field, :binary_id)

    timestamps()
  end

  ...
end
Enter fullscreen mode Exit fullscreen mode

This post is originally published here.

Top comments (2)

Collapse
 
rhymes profile image
rhymes • Edited

Cool!

Consider using gen_random_uuid() instead of uuid_generate_v4 if you only need UUIDv4 ids (we shouldn't use the other pseudo random generators anyway, but that's another story :D).

I admit I'm not 100% sure of the difference (the latter is in pgcrypto) but gen_random_uuid() seems to be faster: jasonaowen.net/blog/2017/Apr/13/be...

Collapse
 
lcezermf profile image
Luiz Cezer

Thanks a million, it help me a lot!