Inserting a COALESCE(NULL,default)

前端 未结 3 916
逝去的感伤
逝去的感伤 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 16:57

    There's no way to re-use the defined default on the column. The default is only there to define what happens if an INSERT doesn't specify a value. By this definition a null value is still "specified" and therefore default can't be used.

    Your comment that someone might not use the function indicates that a trigger is better for your requirements than a simple function.

    https://www.postgresql.org/docs/current/static/plpgsql-trigger.html

    CREATE OR REPLACE FUNCTION default_id() RETURNS TRIGGER AS $default_id$
        BEGIN       
            IF (NEW.id IS NULL) THEN
                NEW.id := gen_random_uuid();
            END IF;
            RETURN NEW;
        END;
    $default_id$ LANGUAGE plpgsql;
    
    CREATE TRIGGER default_id_trigger
    BEFORE INSERT OR UPDATE ON person
        FOR EACH ROW EXECUTE PROCEDURE default_id();
    

    If you do want to do this with a function then the simplest way is just to assign the value before inserting:

    CREATE OR REPLACE FUNCTION create_person(
        id UUID
    ) RETURNS BOOLEAN LANGUAGE plpgsql SECURITY DEFINER AS $$
    BEGIN
        IF id IS NULL THEN
            id := gen_random_uuid();
        END IF;
        -- OR
        -- id := coalesce(id, gen_random_uuid());
        INSERT INTO person( id )
        VALUES (id);
        RETURN FOUND;
    END;
    $$;
    

提交回复
热议问题