Geo*_*iev 6 postgresql bash transactions
说我有文件:
file1.sql
file2.sql
file3.sql
我需要在一个事务中执行所有三个文件.我正在寻找一个bash脚本,如:
psql -h hostname -U username dbname -c "
begin;
\i file1.sql
\i file2.sql
\i file3.sql
commit;"
这失败了,出现了错误:Syntax error at or near "\".
我还尝试先连接到数据库,然后执行失败,如下所示:
psql dbname
begin;
\i file1.sql
\i file2.sql
\i file3.sql
commit;
这也失败了,因为'begin'命令仅在连接终止时执行.
是否可以使用PostgreSQL和bash在单个事务中执行多个.sql文件?
编辑:
每个文件的粗略结构类似:
SET CLIENT_ENCODING TO 'WIN1251';
\i file4.sql
\i file5.sql
<etc>
RESET CLIENT_ENCODING;
joo*_*oop 10
使用子shell:
#!/bin/sh
 (echo "BEGIN;"; cat file1.sql; cat file2.sql; echo "COMMIT;") \
 | psql -U the_user the_database
#eof
或使用here-document:
#!/bin/sh
psql -U the_user the_database <<OMG
BEGIN;
\i file1.sql
\i file2.sql
COMMIT;
OMG
#eof
注意:在HERE文档中没有globbing,因此file*sql 不会被扩展.即使在引号内,也会扩展Shell变量.
您还可以使用-1或--single-transaction选项在事务中执行所有脚本:
cat file*.sql | psql -1
我会为启动(开始事务、设置编码等)和完成(提交)创建新文件。
然后运行类似:
cat startup.sql file*.sql finish.sql | psql dbname
| 归档时间: | 
 | 
| 查看次数: | 9782 次 | 
| 最近记录: |