Postgresql

如何從 bash shell (PostgreSQL) 將環境變數傳遞給 sql 文件

  • March 29, 2021

我需要能夠從.sql使用psql.

psql我正在執行的命令是:

su postgres -c "psql -v ON_ERROR_STOP=1 -v dbname=example -v dbuser=example -e" < ./create-db.sql

我放置example的位置通常設置為$DATABASE_NAMEDATABASE_USER分別在執行psql命令之前在 bash 腳本中設置。

create-db.sql文件是:

\connect postgres
DROP DATABASE IF EXISTS :dbname;
DO $$BEGIN
   CREATE USER :dbuser;
EXCEPTION WHEN duplicate_object THEN
   RAISE NOTICE 'user already exists';
END$$;
ALTER ROLE :"dbuser" SET search_path TO :"dbname",public;
CREATE DATABASE :"dbname"
   OWNER=:dbuser
   ENCODING=UTF8
   LC_COLLATE='en_US.UTF-8'
   LC_CTYPE='en_US.UTF-8'
   TEMPLATE=template0;
\connect :"dbname"
CREATE SCHEMA zulip AUTHORIZATION :"dbuser";

該行中的變數替換DROP DATABASE IF EXISTS :dbname;有效,但是該CREATE USER :dbuser;行失敗後的所有內容都失敗了,我已經嘗試過以下每種方法:

CREATE USER :dbuser; CREATE USER :'dbuser'; CREATE USER :"dbuser";

它總是出錯:

You are now connected to database "postgres" as user "postgres".
DROP DATABASE IF EXISTS example;
NOTICE:  database "example" does not exist, skipping
DROP DATABASE
DO $$BEGIN
   CREATE USER :dbuser;
EXCEPTION WHEN duplicate_object THEN
   RAISE NOTICE 'user already exists';
END$$;
ERROR:  syntax error at or near ":"
LINE 2:     CREATE USER :dbuser;
                       ^

我真的不確定上述內容哪裡出錯了。的輸出psql -Vpsql (PostgreSQL) 12.6 (Ubuntu 12.6-0ubuntu0.20.04.1)

這將允許您這樣做。在您的情況下, ‘$$’ 之間的所有內容都是“美元引用的字元串常量,因此沒有任何內容被解釋。請參閱sql syntax , 4.1.2.4。

\set CREDO 'begin create user ' :dbuser '; exception when duplicate_object then raise notice ''user already exists''; end';
do :'CREDO';

引用自:https://dba.stackexchange.com/questions/288859