1

I am trying to create a PL/pgSQL function in PostgreSQL 9.3.6, but there is weird behavior when using the passed argument inside function body. Here is the 'very simple' function:

CREATE OR REPLACE FUNCTION myschema.test (myarg text) RETURNS text AS $$
DECLARE
  entity text;
  buffer text;
BEGIN
    CREATE ROLE myarg;
    RETURN myarg;
END;
$$ LANGUAGE plpgsql;

So, if for instance myarg equals 'test':

  • A role named 'myarg' is created (WRONG)
  • 'test' is returned (CORRECT)

I searched for hours why this could be and no clue... security parameter? Why is myarg not interpreted for creating roles?

Testing with phpPgAdmin through sql files if this has any impact.

1 Answer 1

1

You should use:

EXECUTE FORMAT('CREATE ROLE %I', myarg);

Here you can find an explanation (especially read Craig's answer).


As Erwin stated (thanks), %I is safer than %s. Anyway, myarg should be verified before the function call. Try for example

SELECT myschema.test('something; stupid; here;')
Sign up to request clarification or add additional context in comments.

1 Comment

Be sure to escape myarg as identifier in this context (a role name) or you are open to SQL injection. Use %I with format() unless the identifier is safely escaped already. stackoverflow.com/questions/10705616/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.