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 https://github.com/rails/rails/blob/650ea5e5cf50d8a7242499463cf1762922d330a8/activerecord/test/cases/adapters/postgresql/uuid_test.rb#L193 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?

Thanks.

If you look my_uuid_generator() is added to postgres at https://github.com/rails/rails/blob/650ea5e5cf50d8a7242499463cf1762922d330a8/activerecord/test/cases/adapters/postgresql/uuid_test.rb#L186

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:

migration.rb

def change

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

end

Where do I define john_uuid_generator()?

Thanks!

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