SET LOCAL to a previously stored value

442 views Asked by At

I want to temporarily change the lock_timeout in my PL/pgSQL function, and I thought it would be as simple as this:

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'

But this gives me this result:

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

How can I store and reset that lock_timeout setting correctly?

1

There are 1 answers

0
Laurenz Albe On BEST ANSWER

Utility statements like SET cannot be used with parameters.

You`ll have to either use dynamic SQL like

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

or use

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