简体   繁体   English

bash 脚本中的 Postgres 脚本

[英]Postgres script in a bash script

I created a script in pgadmin4.我在 pgadmin4 中创建了一个脚本。 The script consists of querying a table.该脚本包括查询表。

In this table I have an element which contains value1 |在这个表中,我有一个包含 value1 | 的元素。 value2 |值2 | valueX (the number of elements may vary from row to row). valueX(元素的数量可能因行而异)。

In pgadmin4 I used this script:在 pgadmin4 中,我使用了这个脚本:

#!/bin/bash

psql "postgresql://id:password@127.0.0.1/table" << EOF
do $$
DECLARE
        _id int;
        _name text;
        _value text;
begin
FOR _id, _name IN select id, unnest(string_to_array(themes, '|')) from data LOOP
if EXISTS (select id_theme from theme where uri_theme = concat('<',_name,'>')) then
 insert into data_themes(data_id, theme_id) values (_id, (select id_theme from theme where uri_theme = concat('<',_name,'>')) );
RAISE NOTICE 'test % / %', _id, _name;
end if;
end loop;
end;
$$;
EOF

the script works as I want it to, in pgadmin4.该脚本在 pgadmin4 中按我的意愿工作。

However, when I want to run this script in a bash script it gives me an error但是,当我想在 bash 脚本中运行这个脚本时,它给了我一个错误

WARNING: there is no transaction in progress COMMIT警告:没有正在进行的事务提交

It stops in the middle of the loop (around 25,000 lines) and shows me the error.它停在循环的中间(大约 25,000 行)并向我显示错误。

I put this:我把这个:

\echo :AUTOCOMMIT
\set AUTOCOMMIT off
\echo :AUTOCOMMIT

I don't understand why the script works on pgadmin and doesn't work in a bash script.我不明白为什么该脚本适用于 pgadmin 而不适用于 bash 脚本。 Thanks for your help谢谢你的帮助

I don't understand why the script works on pgadmin and doesn't work in a bash script.我不明白为什么该脚本适用于 pgadmin 而不适用于 bash 脚本。

Because you effectively run a different script.因为您有效地运行了不同的脚本。 $$ is a variable in bash . $$bash一个变量。 Inside a here-document ( << EOF ... EOF ) variables are expanded.在 here-document ( << EOF ... EOF ) 中,变量被扩展。 Therefore, you run something like因此,您运行类似

do 1234
....
1234;

To fix this, quote the here document:要解决此问题,请引用此处的文档:

psql "postgresql://id:password@127.0.0.1/table" << 'EOF'
do $$
...
$$;
EOF

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

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