Check for value with current_setting()

与世无争的帅哥 提交于 2019-12-05 12:57:21

问题


I'm trying to work with current_setting().

I came up with this:

CREATE OR REPLACE FUNCTION process_audit() RETURNS TRIGGER AS $audit$
    DECLARE
        user_id integer;
    BEGIN
        BEGIN
            user_id := current_setting('hws.current_user_id');
        EXCEPTION WHEN OTHERS THEN
            user_id := NULL;
        END;
        ...
        RETURN NULL;
   END;
$audit$ LANGUAGE plpgsql;

The setting is set via:

SELECT set_config('hws.current_user_id', '5', true); -- true = local setting -> only visible in current transaction

The problem is, that current_setting() throws an exception if the value is not valid. I don't want to use EXCEPTION because I read that exception blocks are expensive.

Is there a way to check if the setting has a value without using exceptions?

Btw: I also tried to read from pg_settings but that doesn't seem to work with local settings.


回答1:


9.6 and newer:

PostgreSQL (9.6+) supports current_setting('setting_name', 't') to fetch a setting and return NULL if it's unset. you can combine this with coalesce to supply a default.

9.5 and older:

Per the question, you can do it with a plpgsql function that uses a BEGIN ... EXCEPTION handler, if you don't mind the performance hit and clumsiness. But there's no built-in support.




回答2:


Shouldn't you also make a cast? As follows,

user_id := current_setting('hws.current_user_id')::integer;


来源:https://stackoverflow.com/questions/17956601/check-for-value-with-current-setting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!