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
This post is originally published here.
Top comments (2)
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...Thanks a million, it help me a lot!