Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute several .sql files in a single transaction using PostgreSQL and bash

Say I have the files:

file1.sql
file2.sql
file3.sql

I need all three files to be executed in a single transaction. I'm looking for a bash script like:

psql -h hostname -U username dbname -c "
begin;
\i file1.sql
\i file2.sql
\i file3.sql
commit;"

This fails with an error: Syntax error at or near "\".

I also tried connecting to the DB first and then executing the fails, like that:

psql dbname
begin;
\i file1.sql
\i file2.sql
\i file3.sql
commit;

This also fails, because the 'begin' command executes only when the connection is terminated.

Is it possible to execute several .sql files in a single transaction using PostgreSQL and bash?

Edit:

The rough structure of each of the files is similar:

SET CLIENT_ENCODING TO 'WIN1251';
\i file4.sql
\i file5.sql
<etc>
RESET CLIENT_ENCODING;
like image 780
George Georgiev Avatar asked Jul 21 '15 10:07

George Georgiev


1 Answers

You can also use the -1 or --single-transaction option to execute all your scripts in a transaction:

cat file*.sql | psql -1
like image 151
TianyuZhu Avatar answered Oct 06 '22 00:10

TianyuZhu