I am learning PL/pgSQL (coming from a C# background) and defined a procedure to swap two numbers:
CREATE PROCEDURE swap_nums(INOUT arg_left INT, INOUT arg_right INT) LANGUAGE plpgsql AS
$plpgsql$
DECLARE
temp_num INT = arg_left;
BEGIN
arg_left = arg_right;
arg_right = temp_num;
END;
$plpgsql$;
I then call the swap_nums procedure as follows:
DO $plpgsql$
DECLARE
num1 CONSTANT INT NOT NULL = 10;
num2 CONSTANT INT NOT NULL = 20;
BEGIN
RAISE NOTICE 'Before swap: num1=%, num2=%', num1, num2;
CALL swap_nums(num1, num2); -- note CONSTANT variables can be altered via OUT params!
RAISE NOTICE 'After swap: num1=%, num2=%', num1, num2;
END;
$plpgsql$;
The swap_nums function works as expected and I get this output:
NOTICE: Before swap: num1=10, num2=20
NOTICE: After swap: num1=20, num2=10
DO
The docs say:
The CONSTANT option prevents the variable from being assigned to after initialization, so that its value will remain constant for the duration of the block.
...but this is clearly not the case as shown with the num1 and num2 variables above which were declared CONSTANT then passed to a procedure that was able to alter them via OUT parameters.
My question: why does Postgres allow CONSTANT variables to be altered in this way?
In C# for example, the compiler knows if you pass a const to something taking out parameters, you are clearly doing something wrong and the compiler gives an error immediately:
