I want to execute several sql scripts sequentially with psql as a single transaction to set up my database schema. What is the best way to do this? In the past I know I had a master script that I ran psql against that included the other files however I don't remember the syntax of this script.
Asked
Active
Viewed 1.5k times
29
xenoterracide
- 2,732
- 4
- 27
- 32
3 Answers
35
Your script could look like this:
BEGIN;
\i file1.sql
\i file2.sql
COMMIT;
Or you could do something like this:
cat file1.sql file2.sql | psql -1 -f -
Peter Eisentraut
- 9,473
- 1
- 29
- 33
-
1[Understanding pipes in the shell](http://superuser.com/q/178796/59284) helped me get the last command. – ma11hew28 Sep 24 '15 at 15:13
-
Your example with BEGIN; COMMIT; does not work, you need semi-columns at the end of each `\i` line: – nichochar Feb 14 '19 at 22:53
1
You could also simply do:
psql -c "BEGIN TRANSACTION;" -f file1.sql -f file2.sql -c "COMMIT;"
caiohamamura
- 111
- 2
0
I did it using find in unix / linux with the path to the file sql past with rep_sql parameter with "read" instruction :
find -P ${rep_sql} -type f -name *.sql -execdir psql -d "mabase" -f {} +
It says: find not following links files whatever the name with ext as «.sql» and execute in the directory of the file psql working with mabase and execute the file found.
a_horse_with_no_name
- 69,148
- 13
- 135
- 173
Deun
- 1