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

后端 未结 4 1385
闹比i
闹比i 2021-01-02 08:50

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

相关标签:
4条回答
  • 2021-01-02 09:21

    FYI, for Windows command line:

    FOR /F "usebackq" %A IN (`dir *.sql /b/a-d`) DO psql -f %A
    
    0 讨论(0)
  • 2021-01-02 09:22

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

    cat file*.sql | psql -1
    
    0 讨论(0)
  • 2021-01-02 09:26

    I'd create new files for the startup (start transaction, set encoding etc) and finish (commit).

    Then run something like:

    cat startup.sql file*.sql finish.sql | psql dbname
    
    0 讨论(0)
  • 2021-01-02 09:36

    Either use a sub-shell:

    #!/bin/sh
     (echo "BEGIN;"; cat file1.sql; cat file2.sql; echo "COMMIT;") \
     | psql -U the_user the_database
    
    #eof
    

    or use a here-document:

    #!/bin/sh
    psql -U the_user the_database <<OMG
    BEGIN;
    
    \i file1.sql
    
    \i file2.sql
    
    COMMIT;
    OMG
    
    #eof
    

    NOTE: in HERE-documents there will be no globbing, so file*sql will not be expanded. Shell-variables will be expanded, even within quotes.

    0 讨论(0)
提交回复
热议问题