How to execute multiple SQL files from a local directory in PostgreSQL/PgAdmin4 in on transaction in Windows? - sql

I have a folder in a directory in my PC which contains multiple SQL files. Each of the file is a Postgres function. I want to execute every SQL file situated in the folder at a time in PostgreSQL server using PgAdmin or in other way. How can I accomplish this?

I apologize if I'm oversimplifying your question, but if the main issue is how to execute all SQL files without having to call them one by one, you just need to put them in a loop, e.g. in bash calling psql
#!/bin/bash
for f in *.sql
do
psql -h dbhost -d db -U dbuser -f $f
done
Or cat them and pipe the result to psql stdin:
$ cat /path/to/files/*.sql | psql -h dbhost -d db -U dbuser
And if you need them to run in a single transaction, consider merging the SQL files, e.g. using cat - this assumes all statements in your sql file are properly terminated:
$ cat /path/to/files/*.sql > merged.sql

Related

How to run all postgres sql scripts from same folder using shell script

How do i write a shell script that runs postgres sql scripts stored in one folder sequentially.Example
1)dump.sql,
2)store.sql,
3)merge.sql,
4)import.sql
are to run sequentially in the same order and all the scripts are in the same folder. How do i write a shell script that performs the tasks sequentially.
Inside psql you can use "\i " to load a script. But also "\ir ".
So in your case create a load-all.sql file in the same directory as your other files..
contents load-all.sql:
\ir dump.sql
\ir store.sql
\ir merge.sql
\ir import.sql
inside psql:
psql# \i /path/to/file/load-all.sql
You can create a simple script e.g run.sh and the define variables corresponding to your environment. Here is a simple script that is running 2 sql files which are present on Desktop
PG_HOME=/usr/pgsql-12
PGUSER=postgres
DATABASE=postgres
PORT=5432
FILES_HOME=/home/edb/Desktop
$PG_HOME/bin/psql -U $PGUSER -d $DATABASE -p $PORT -f $FILES_HOME/dump.sql
$PG_HOME/bin/psql -U $PGUSER -d $DATABASE -p $PORT -f $FILES_HOME/store.sql
There are database schema migration tools available to help manage this process.
Examples include:
Flyway
Liquibase
I use Flyway. It does exactly what you want, connects to the database and runs a bunch of SQL scripts found in a folder. The order of execution is determined by the file names named using a certain convention.
On the first run, Flyway adds its own table to your database to store the history of what SQL scripts have been run. On subsequent runs, Flyway knows what SQL scripts have already been applied (and should be skipped) and which scripts are fresh (and should be applied).
Try this:
param([string]$directory = "")
$files = Get-ChildItem $directory
for ($i=0; $i -lt $files.Count; $i++) {
$scriptName = $files[$i].Name
psql -U <username> -d <database> -h <host> -p <port> -f $directory\$scriptName
}
directory is an argument you should pass to the script.
So executing it with:
./sqlScript.ps1 C:\Users\<username>\Desktop\<pathToDict>
If you are troubling with executing psql on windows environment you can get help with
this:
How to start psql.exe

Create and import pgsql database after pg_dump

I am new to postgres. I have exported a large, complex database with the following command in the terminal
pg_dump -U USERNAME DBNAME > dbexport.pgsql
Now that I have transferred this .pgsql file to a different computer, what is the right command to automatically create and restore the exact same database as was exported? Any suggestions would be appreciated
The way you dumped the database, the information about the database itself is not included in the dump (which is a plain SQL file).
You can either use the -C option to include CREATE DATABASE in the dump (the dump has to be restored with psql), or you use the custom format:
pg_dump -F c -U postgres DBNAME -f dbexport.pgsql
That can be restored with pg_restore like this:
pg_restore -C -d postgres -U postgres dbexport.pgsql

How to execute postgres' sql queries from batch file?

I need to execute SQL from batch file.
I am executing following to connect to Postgres and select data from table
C:/pgsql/bin/psql -h %DB_HOST% -p 5432 -U %DB_USER% -d %DB_NAME%
select * from test;
I am able to connect to database, however I'm getting the error
'select' is not recognized as an internal or external command,
operable program or batch file.
Has anyone faced such issue?
This is one of the query i am trying, something similar works in shell script, (please ignore syntax error in the query if there are any)
copy testdata (col1,col2,col3) from '%filepath%/%csv_file%' with csv;
You could pipe it into psql
(
echo select * from test;
) | C:/pgsql/bin/psql -h %DB_HOST% -p 5432 -U %DB_USER% -d %DB_NAME%
When closing parenthesis are part of the SQL query they have to be escaped with three carets.
(
echo insert into testconfig(testid,scenarioid,testname ^^^) values( 1,1,'asdf'^^^);
) | psql -h %DB_HOST% -p 5432 -U %DB_USER% -d %DB_NAME%
Use the -f parameter to pass the batch file name
C:/pgsql/bin/psql -h %DB_HOST% -p 5432 -U %DB_USER% -d %DB_NAME% -f 'sql_batch_file.sql'
http://www.postgresql.org/docs/current/static/app-psql.html
-f filename
--file=filename
Use the file filename as the source of commands instead of reading commands interactively. After the file is processed, psql terminates. This is in many ways equivalent to the meta-command \i.
If filename is - (hyphen), then standard input is read until an EOF indication or \q meta-command. Note however that Readline is not used in this case (much as if -n had been specified).
if running on Linux, this is what worked for me (need to update values below with your user, db name etc)
psql "host=YOUR_HOST port=YOUR_PORT dbname=YOUR_DB_NAME user=YOUR_USER_NAME password=YOUR_PASSWORD" -f "fully_qualified_path_to_your_script.sql"
You cannot put the query on separate line, batch interpreter will assume it's another command instead of a query for psql. I believe you will need to quote it as well.
I agree with Spidey:
1] if you are passing the file with the sql use -f or --file parameter
When you want to execute several commands the best way to do that is to add parameter -f, and after that just type path to your file without any " or ' marks (relative paths works also):
psql -h %host% -p 5432 -U %user% -d %dbname% -f ..\..\folder\Data.txt
It also works in .NET Core. I need it to add basic data to my database after migrations.
Kindly refer to the documentation
1] if you are passing the file with the sql use -f or --file parameter
2] if you are passing individual command use -c or --command parameter
If you are trying the shell script
psql postgresql://$username:$password#$host/$database < /app/sql_script/script.sql

In isql, is there a way for me to run several SQL statements from a file?

I have a file that contains several SQL queries.
Can I somehow run them via isql (I'm doing the calls from Bash script, so no access to Perl DBI or JDBC)
I tried piping them into isql command via echo /my/file | isql -my-other-parameters but that didn't work.
Yes.
If you're running ISQL in interactive mode, you can load an entire contents of the file using :r my-filename command from > prompt.
From Bash script, it's also possible to do - but you need to carefully make sure that
The SQL file you are piping in has a go statement at the end. That is a VERY common cause of issues like the one you mentioned.
That statement has a newline after it.
From a script, you can do it 2 ways: Pass on STDIN via a pipe/redirect; OR, pass in the file name via isql's -i parameter
In my case it was isq -n for a piped query to work.
isql -U $DB_USR -P $DB_PWD -S $DB_PATH -D $DB_NAME -w 500 < $FILE

How do you execute SQL from within a bash script?

I have some SQL scripts that I'm trying to automate. In the past I have used SQL*Plus, and called the sqlplus binary manually, from a bash script.
However, I'm trying to figure out if there's a way to connect to the DB, and call the script from inside of the bash script... so that I can insert date and make the queries run relative to a certain number of days in the past.
I'm slightly confused. You should be able to call sqlplus from within the bash script. This may be what you were doing with your first statement
Try Executing the following within your bash script:
#!/bin/bash
echo Start Executing SQL commands
sqlplus <user>/<password> #file-with-sql-1.sql
sqlplus <user>/<password> #file-with-sql-2.sql
If you want to be able to pass data into your scripts you can do it via SQLPlus by passing arguments into the script:
Contents of file-with-sql-1.sql
select * from users where username='&1';
Then change the bash script to call sqlplus passing in the value
#!/bin/bash
MY_USER=bob
sqlplus <user>/<password> #file-with-sql-1.sql $MY_USER
You can also use a "here document" to do the same thing:
VARIABLE=SOMEVALUE
sqlplus connectioninfo << HERE
start file1.sql
start file2.sql $VARIABLE
quit
HERE
Here is a simple way of running MySQL queries in the bash shell
mysql -u [database_username] -p [database_password] -D [database_name] -e "SELECT * FROM [table_name]"
Maybe you can pipe SQL query to sqlplus. It works for mysql:
echo "SELECT * FROM table" | mysql --user=username database
I've used the jdbcsql project on Sourceforge.
On *nix systems, this will create a csv stream of results to standard out:
java -Djava.security.egd=file///dev/urandom -jar jdbcsql.jar -d oracledb_SID -h $host -p 1521 -U some_username -m oracle -P "$PW" -f excel -s "," "$1"
Note that adding the -Djava.security.egd=file///dev/urandom increases performance greatly
Windows commands are similar: see http://jdbcsql.sourceforge.net/
If you do not want to install sqlplus on your server/machine then the following command-line tool can be your friend. It is a simple Java application, only Java 8 that you need in order to you can execute this tool.
The tool can be used to run any SQL from the Linux bash or Windows command line.
Example:
java -jar sql-runner-0.2.0-with-dependencies.jar \
-j jdbc:oracle:thin:#//oracle-db:1521/ORCLPDB1.localdomain \
-U "SYS as SYSDBA" \
-P Oradoc_db1 \
"select 1 from dual"
Documentation is here.
You can download the binary file from here.
As Bash doesn't have built in sql database connectivity... you will need to use some sort of third party tool.