简体   繁体   English

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

[英]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? 如何将变量传递到此Postgresql代码中? I know it works for the first 2 lines and those variables, but then it errors going into the DO statement.. 我知道它适用于前两行和那些变量,但是随后在DO语句中出错。

I'm using :p5 as my parameter. 我使用: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$

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. 一旦进入DO主体,便会出现此错误。

I'm calling it this in a shell script like so: 我在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

Is there another way to do this? 还有另一种方法吗?

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$

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM