I have tables that use UUIDs. I want to be able to insert a new row with or without a UUID as sometimes the client will generate the UUID other times it won\'t.
Each
Overload the gen_random_uuid function:
create or replace function gen_random_uuid()
returns uuid as $$
select 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11'::uuid;
$$ language sql;
create or replace function gen_random_uuid(_id uuid)
returns uuid as $$
select coalesce(_id, gen_random_uuid());
$$ language sql;
Create the table as usual:
create table if not exists person (
id uuid default gen_random_uuid()
);
Call the gen_random_uuid function inside the create_person function:
create or replace function create_person(_id uuid)
returns boolean as $$
insert into person (id) values (gen_random_uuid(_id))
returning true;
$$ language sql;
Then all the insert variations will work:
insert into person (id) values (default);
select create_person(null);
select create_person('b1eebc99-9c0b-4ef8-bb6d-6bb9bd380a22'::uuid);