1

Does anyone know why this works this way? When I tried in other stored procedures and text is normally replaced with the value that is specified as stored procedure parameter.

CREATE OR REPLACE FUNCTION setUserId(userId text)
returns void AS $$
    BEGIN 
    SET session "myapp.userId" = userId;
    END
$$ LANGUAGE plpgsql;
app=# select * from setUserId('myuserId');
 setuserid
-----------

(1 row)

app=# select current_setting('myapp.userId');
 current_setting
-----------------
 userid
(1 row)

app=#

1 Answer 1

3

According to the manual,

SET session "myapp.userId" = userId

is equivalent to

SET session "myapp.userId" = 'userId'

so the input parameter name userId is considered as the new value for the run-time parameter instead of the input parameter value 'myuserId'.

If you want the run-time parameter to consider the value 'myuserId' of the input parameter userId, you need a dynamic statement :

CREATE OR REPLACE FUNCTION setUserId(userIdtext)
returns void AS $$
    BEGIN
    EXECUTE '
    SET session "myapp.userId" = ' || quote_nullable(userId) ;
    END
$$ LANGUAGE plpgsql;

demo in dbfiddle

Sign up to request clarification or add additional context in comments.

1 Comment

Alternatively use set_config('myapp.userId', userid)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.