How to use variable settings in trigger functions?

前端 未结 3 866
死守一世寂寞
死守一世寂寞 2021-02-19 10:05

I would like to record the id of a user in the session/transaction, using SET, so I could be able to access it later in a trigger function, using current_sett

3条回答
  •  时光说笑
    2021-02-19 10:42

    You can catch the exception when the value doesn't exist - here's the changes I made to get this to work:

    CREATE OR REPLACE FUNCTION add_transition1() RETURNS TRIGGER AS $$
        DECLARE
            user_id integer;
        BEGIN
            BEGIN
                user_id := current_setting('myvars.user_id')::integer;
            EXCEPTION WHEN OTHERS THEN
                user_id := 0;
            END;
    
            INSERT INTO transitions1 (user_id, house_id) VALUES (user_id, NEW.id);
            RETURN NULL;
        END;
    $$ LANGUAGE plpgsql;
    
     CREATE OR REPLACE FUNCTION insert_house() RETURNS void as $$
     DECLARE
        user_id integer;
     BEGIN 
       PERFORM set_config('myvars.user_id', '55', false);
    
       INSERT INTO houses (name) VALUES ('HOUSE PARTY');
     END; $$ LANGUAGE plpgsql;
    

提交回复
热议问题