0

I'm trying to create a function that dynamically changes the password for a client but I get an error "ERROR: syntax error at or near "=" ALTER USER postgres WITH PASSWORD = '$1';"

How do I fix this? Thank you for your time

CREATE OR REPLACE FUNCTION public."Change_password"(
    password character varying)
    RETURNS void
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
AS $BODY$
BEGIN
   ALTER USER postgres WITH PASSWORD= '$1';

END
$BODY$;

ALTER FUNCTION public."Change_password"(character varying)
    OWNER TO postgres;
    
    SELECT public."Change_password"(
    '10'
)
1
  • PASSWORD= THE equal SIGN is WRONG!!!! BEWARE Commented Mar 27, 2023 at 14:57

2 Answers 2

1

Apart from the trivial syntax error of the superfluous =, you cannot use a parameter in an ALTER statement. You will have to use dynamic SQL:

EXECUTE format(
           'ALTER ROLE postgres PASSWORD %L',
           $1
        );

Let me add that changing a superuser's password from an application like that does not look like a sane security concept. You are not running your application with a database superuser, are you?

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

1 Comment

I'm running a localhost server for a client and I wanted the client to easily change the password if need be.
0

A plain syntax error, according to ALTER USER documentation: there is no = after PASSWORD it should be: ALTER USER postgres WITH PASSWORD '$1';

EDIT: After looking into problem deeper, it seems that whole statement must be run dynamically. Check the answers to similar question: How to change user password in postgreSQL

5 Comments

This is not correct for my version. It's setting the password to $1
Well so the error does not appear anymore and code works. If you want it to be changed dynamically just replace ‘$1’ with ‘password’ parameter
That doesn't work either, it sets the password to string "password" without quotes. Changing the input parameter to something else like pass doesn't work either.
ALTER USER postgres WITH PASSWORD password; - is that what you have tried ?
It throws syntax error.

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.