Search code examples
sqlpostgresqlpsqlpostgresql-9.3

postgresql - error trying to pass a variable from command line to a sql script


How do I pass in a variable into this postgresql code? I know it works for the first 2 lines and those variables, but then it errors going into the DO statement..

I'm using :p5 as my parameter.

CREATE ROLE :v3 LOGIN ENCRYPTED PASSWORD :p3 NOSUPERUSER INHERIT NOCREATEDB NOCREATEROLE NOREPLICATION;
ALTER ROLE :v3 SET search_path = foo_bar_dev_:v4;
DO
$body$
BEGIN
   IF NOT EXISTS (
      SELECT *
      FROM   pg_catalog.pg_user
      WHERE  usename = 'foo_readonly') THEN

      CREATE ROLE foo_readonly LOGIN PASSWORD :p5 ;
   END IF;
END
$body$

I'm getting this error message:

psql:Test.sql:18: ERROR:  syntax error at or near ":"
LINE 9:       CREATE ROLE foo_readonly LOGIN PASSWORD :p5 ;
                                                      ^

Once it gets into the DO body is when I get this error.

I'm calling it this in a shell script like so:

"$PSQL" -h $HOST_NM             \
        -p $PORT                \
        -U foo                  \
        -v v3=$USER             \
        -v p3="'$USER_PWD'"     \
        -v p4="'$1'"            \
        -v p5="'$READONLY_PWD'" \
        -a                      \
        -f Test.sql postgres | tee >> $LOG

Is there another way to do this?


Solution

  • password should be in quotes:

    CREATE ROLE :v3 LOGIN ENCRYPTED PASSWORD :p3 NOSUPERUSER INHERIT NOCREATEDB NOCREATEROLE NOREPLICATION;
    ALTER ROLE :v3 SET search_path = foo_bar_dev_:v4;
    DO
    $body$
    BEGIN
       IF NOT EXISTS (
          SELECT *
          FROM   pg_catalog.pg_user
          WHERE  usename = 'foo_readonly') THEN
    
          CREATE ROLE foo_readonly LOGIN PASSWORD ':p5' ;
       END IF;
    END
    $body$