Custom UUID generator

Hi, I was reading the docs for primary key on postgresql and I saw that there was a way to add a custom stored procedure that returns a UUID. There is a test case as well that uses a custom uuid generator but I wasn’t sure how to to implement this myself.

Like in the test case where do I place ‘my_uuid_generator()’ and how to implement it in my rails application?


If you look my_uuid_generator() is added to postgres at

You can add a stored procedure in a similar fashion in a migration.

That’s what I thought but I wasn’t sure where to place the uuid_function that the migration refers to. So that go in a helper file or part of the migration?

uuid_function is defined -

  • it just switches on if postgres supports gen_random_uuid() otherwise it uses uuid_generate_v4()
    gen_random_uuid() is part of the pgcrypto module - uuid_generate_v4() is part of the uuid-ossp module -

My question, if this is my migration:


def change

connection.execute <<-SQL
CREATE OR REPLACE FUNCTION john_uuid_generator() RETURNS uuid
AS $$ SELECT * FROM #{uuid_function} $$


Where do I define john_uuid_generator()?


That statement you pasted defines it, it’s stored as a function in postgres. See for docs on how this works in postgres.