Re: Create user or role from inside a function?

From: Roman Neuhauser <neuhauser(at)sigpipe(dot)cz>
To: Dan <ml(at)mutox(dot)org>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Create user or role from inside a function?
Date: 2006-09-01 13:06:32
Message-ID: 20060901130632.GB943@dagan.sigpipe.cz
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

# ml(at)mutox(dot)org / 2006-09-01 20:13:14 +1000:
> Hey,
>
> I am running PostgreSQL 8.1.4 and I want to create a user from inside a
> function. Is this possible in 8.1?
>
> Ive found quite a few references on google using EXECUTE, but this seems
> relevant to earlier versions, not 8.1.
>
> I have a function like this:
>
> CREATE FUNCTION user_create (un varchar, uid bigint, pw varchar) RETURNS
> VARCHAR LANGUAGE plpgsql AS '
> BEGIN
> EXECUTE "CREATE USER " || un || " WITH PASSWORD " || pw;
>
> RETURN un;
> END
> ';

Double quotes can be used only for identifiers (table, column
names, etc), you want to use single quotes for strings. Now, since
you already are in a string (the function body), you need to escape
the single quotes inside. In SQL this is done by doubling the quote
character, IOW, by putting another single quote just before it:

CREATE FUNCTION foo() ...
AS '
BEGIN
EXECUTE ''CREATE USER '' || un || '' WITH PASSWORD '' || pw;
RETURN un;
END
';

That assumes that the un and pw parameters are always passed already
quoted, otherwise you'll get errors like this:

test=# CREATE FUNCTION user_create (un varchar, uid bigint, pw varchar) RETURNS
test-# VARCHAR LANGUAGE plpgsql AS '
test'# BEGIN
test'# EXECUTE ''CREATE USER '' || un || '' WITH PASSWORD '' || pw;
test'# RETURN un;
test'# END
test'# ';
CREATE FUNCTION
test=# select user_create('fubar', 0, 'pass');
ERROR: syntax error at or near "pass" at character 33
QUERY: CREATE USER fubar WITH PASSWORD pass
CONTEXT: PL/pgSQL function "user_create" line 2 at execute statement
LINE 1: CREATE USER fubar WITH PASSWORD pass
^
test=#

--
How many Vietnam vets does it take to screw in a light bulb?
You don't know, man. You don't KNOW.
Cause you weren't THERE. http://bash.org/?255991

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Curtis Scheer 2006-09-01 13:22:44 Insert Rule
Previous Message Christopher Browne 2006-09-01 12:20:41 Re: Postrgesql and Mysql in the same server Linux (Fedora core 5)