Inserting a COALESCE(NULL,default)

前端 未结 3 913
逝去的感伤
逝去的感伤 2020-12-11 16:39

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

3条回答
  •  生来不讨喜
    2020-12-11 17:13

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

提交回复
热议问题