将本地设置为先前存储的值

SET LOCAL to a previously stored value

我想临时更改 PL/pgSQL 函数中的 lock_timeout,我认为它会像这样简单:

CREATE OR REPLACE FUNCTION public.myfunction()
RETURNS void AS
$body$
DECLARE
    l_tmp_lock_timeout TEXT;
BEGIN
    -- We want this to bail out when no lock is gained
    SHOW lock_timeout INTO l_tmp_lock_timeout;
    SET LOCAL lock_timeout TO '10s';
    RAISE NOTICE 'Local lock timeout set to 10s, was %', l_tmp_lock_timeout;

    -- ... do stuff ...

    -- and reset the lock timeout
    SET LOCAL lock_timeout TO l_tmp_lock_timeout;
    RAISE NOTICE 'Local lock timeout set to %', l_tmp_lock_timeout;

    RETURN;    
END;
$body$
LANGUAGE 'plpgsql'

但这给了我这个结果:

NOTICE:  Local lock timeout set to 10s, was 0
ERROR:  invalid value for parameter "lock_timeout": "l_tmp_lock_timeout"
CONTEXT:  SQL statement "SET LOCAL lock_timeout TO l_tmp_lock_timeout"
PL/pgSQL function myfunction() line 48 at SQL statement

如何正确存储和重置 lock_timeout 设置?

SET 等实用程序语句不能与参数一起使用。

您必须使用动态 SQL 之类的

EXECUTE format('SET lock_timeout = %L', l_tmp_lock_timeout);

或使用

SELECT set_config('lock_timeout', l_tmp_lock_timeout, FALSE);