0

I am trying to create function in Postgres which can automate user creation process but it doesn;t accept parameter in DDL statement.

CREATE OR REPLACE FUNCTION AUTOUSER (uname varchar(20))
RETURNS TEXT AS $$
DECLARE 
      nm varchar(20);
BEGIN
    nm=$1;
    CREATE USER nm WITH PASSWORD 'Iash12';
    GRANT ALL ON DATABASE iashdb TO nm;
    GRANT ALL ON  ALL TABLES IN SCHEMA public TO nm;
    RETURN CONCAT(nm,' Created');
END;
$$ 
LANGUAGE plpgsql;

Above function create user as 'nm' instead of passed parameter name however RETURN statement showing correct result. Thanks in advance,

5
  • You need dynamic SQL for this: postgresql.org/docs/current/static/… Commented Apr 26, 2016 at 21:40
  • Dynamic SQL doesn't support DDL statement, it only support, SELECT, UPDATE, INSERT and DELETE. Commented Apr 27, 2016 at 14:07
  • Of course it supports DDL. Where in the manual did you find that statement? Commented Apr 27, 2016 at 14:36
  • EXECUTE 'CREATE USER $1 WITH PASSWORD 'Iash12' '; shows me syntax error: syntax error at or near "' '"; tried with couple of different syntax but no luck so far. Commented Apr 27, 2016 at 14:58
  • You cant use it like this because: "Another restriction on parameter symbols is that they only work in SELECT, INSERT, UPDATE, and DELETE commands. In other statement types (generically called utility statements), you must insert values textually even if they are just data values." Commented Jan 20, 2021 at 10:45

1 Answer 1

4

You need to use dynamic SQL and you need to quote the parameters properly. The easiest way is to use the format() function with the appropriate placeholders:

CREATE OR REPLACE FUNCTION AUTOUSER (uname varchar(20))
RETURNS TEXT AS $$
BEGIN
    execute format('CREATE USER %I WITH PASSWORD %L', uname, 'Iash12');
    execute format('GRANT ALL ON DATABASE iashdb TO %I', uname);
    execute format('GRANT ALL ON  ALL TABLES IN SCHEMA public TO %I', uname);
    RETURN CONCAT(uname,' Created');
END;
$$ 
LANGUAGE plpgsql;

The placeholder %I properly quotes SQL identifiers. The placeholder %L properly deals with string literals.

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

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.