Full TIL Post

Generate UUID fields in Phoenix with Postgresql

29 Jun 2018 · Elixir
Uuid phoenix 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

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

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";

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

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
About
About The Author

Iván González - Software Developer

Hi, my name is Iván (aka dreamingechoes). I'm a passionate software developer from the north of Spain, interested in all kind of technologies.

Leave a comment!