2

I have the following function in PostgreSQL:

create function test_createuser(username varchar, userpassword varchar) returns void as $$
begin
  CREATE USER username WITH PASSWORD userpassword;
end;
$$ language plpgsql;

However this gives the following error:

syntax error at or near "userpassword"

The function compiles if I place instead a literal string as the password, such as 'mypassword'.

Is there a way to call create user and pass the password from a variable?

2 Answers 2

8

You'll have to use dynamic SQL:

EXECUTE format('CREATE USER %I PASSWORD %L', username, userpassword);
Sign up to request clarification or add additional context in comments.

2 Comments

this line is subject to SQL injections and I should address that, is that correct?
This line is not vulnerable to SQL injection. It's good that you think about these things though! %I and %L will escape everything properly.
3

I still got the same parse error using the EXECUTE method (ERROR: syntax error at or near "2" - Note: the password starts with a "2"). Instead I added string quotation marks when I read the password from the environment variable.

\set psqluser `echo "$PSQL_USER"`
\set psqlpassword `echo "'$PSQL_PASSWORD'"`    -- Add the quotations '' for the password already here
CREATE USER :psqluser WITH ENCRYPTED PASSWORD :psqlpassword;

I don't know if it is good practice, but it works.

Comments

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.