Shell script to execute pgsql commands in files

旧街凉风 提交于 2019-11-29 01:04:15

First off, do not mix psql meta-commands and SQL commands. These are separate sets of commands. There are tricks to combine those (using the psql meta-commands \o and \\ and piping strings to psql in the shell), but stay away from that if you can.

  • Make your files contain only SQL commands.
  • Do not include the CREATE DATABASE statement in the SQL files. Create the db separately, you have multiple files you want to execute in the same template db.

I assume you are operating as system user postgres and you have postgres as Postgres superuser. All databases in the same db cluster on the default port 5432 and the user postgres has password-less access due to an IDENT setting in pg_hba.conf (default settings).

psql postgres -c "CREATE DATABASE mytemplate1 WITH ENCODING 'UTF8'
                  TEMPLATE template0"

I base the new template db on the system template db template0. Read more about that here.
Your question:

How to (...) run a set of pgsql cmds from file

Try:

psql mytemplate1 -f file

Example for batch:

#! /bin/sh

for file in /path/to/files/*; do
    psql mytemplate1 -f "$file"
done

The command option -f makes psql execute SQL commands in a file.

How to create a database based on an existing template at the command line

psql -c 'CREATE DATABASE myDB TEMPLATE mytemplate1'

The command option -c makes psql execute a single SQL command string. Can be multiple commands, terminated by ; - will be executed in one transaction and only the result of the last command returned.
Read about psql command options in the manual.

If you don't provide a database to connect to, psql will use the default maintenance database named postgres. In the second answer it is irrelevant which database we connect to.

you can echo your commands to the psql input:

for dbname in foo foofoo foobar barbar
do
    echo """
CREATE DATABASE $dbname TEMPLATE mytemplate1
""" | psql
done

If you're willing to go the extra mile, you'll probably have more success with sqlalchemy. It'll allow you to build scripts with python instead of bash, which is easier and has better control.

As requested in the comments: https://github.com/srathbun/sqlCmd

Store your sql scripts under a root dir Use dev,tst,prd parametrized dbs Use find to run all your pgsql scripts as shown here Exit on errors

Or just git clone the whole tool from here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!