postgresql - 尝试将变量从命令行传递给sql脚本时出错

时间:2015-06-30 04:45:10

标签: sql postgresql psql postgresql-9.3

如何将变量传入此postgresql代码?我知道它适用于前两行和那些变量,但随后它会进入DO语句错误。

我正在使用:p5作为我的参数。

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$

我收到此错误消息:

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

一旦进入DO正文,就会发现此错误。

我在shell脚本中这样称呼它:

"$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

还有其他办法吗?

1 个答案:

答案 0 :(得分:1)

密码应在引号中:

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$