0

I am currently trying to add a user to the database when a new comercial register is inserted to the comercial table.

CREATE OR REPLACE FUNCTION anade_usuario() RETURNS TRIGGER AS $$
DECLARE
nom TEXT;
BEGIN
    /* SELECT NEW.dni INTO nom;  */
    nom := NEW.dni;
    CREATE USER nom WITH PASSWORD 'pass';
    GRANT ALL PRIVILEGES ON DATABASE "fira" TO nom;
    RETURN NEW;
END;
$$ LANGUAGE 'plpgsql';


\echo Creating trigger number 3.
\echo --------------------------
CREATE TRIGGER trigger3 AFTER INSERT ON comercial
FOR EACH ROW EXECUTE PROCEDURE anade_usuario();

But the script seems to add the user 'nom' instead of the user with the id NEW.dni and so at the second insert I receive an error. What should I change?

2
  • Whenever you say "I receive an error", you should cut & paste the entire error so that we know what the error says. There are many different errors that are possible, and seeing the error message will help us with your problem. Commented May 27, 2015 at 20:39
  • You are right Andy, I will take it into account, thank you! Commented May 27, 2015 at 21:01

1 Answer 1

1

You need to execute it as a dynamic command: http://www.postgresql.org/docs/9.1/static/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN

Something along the lines of this:

EXECUTE 'CREATE USER "' || nom || '" WITH ... '
INTO user
USING checked_user, checked_date;
Sign up to request clarification or add additional context in comments.

5 Comments

I have change it to EXECUTE 'CREATE USER ' || nom || ' WITH PASSWORD ' || 'pass'; but now I get a syntax error psql:comercial/insert_intos.sql:4: ERROR: syntax error at or near "00123456" LINE 1: CREATE USER 00123456B WITH PASSWORD pass
If your username starts with a number you'll need to add quotes to it, I'll modify the example
You seem to get closer and closer to the truth :). Changed it to EXECUTE 'CREATE USER ''' || nom || ''' WITH PASSWORD ' || 'pass'; and the error is now psql:comercial/insert_intos.sql:4: ERROR: syntax error at or near "'00123456B'" LINE 1: CREATE USER '00123456B' WITH PASSWORD pass
Oops... wrong quotes :X Should be " instead of ''
Thank you very much Wolph. It worked with double quotes, the final form: EXECUTE 'CREATE USER ' || '"' || nom || '"' ||' WITH PASSWORD ' ||''''|| 'pass'||'''';

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.