From 1c70d7e70afd36cc006bcea2bb2ad229613a5d8d Mon Sep 17 00:00:00 2001 From: kosenka Date: Mon, 7 Apr 2025 13:56:40 +0300 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20pg=5Frestore.sh?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pg_restore.sh | 74 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 pg_restore.sh diff --git a/pg_restore.sh b/pg_restore.sh new file mode 100644 index 0000000..b0b5ae4 --- /dev/null +++ b/pg_restore.sh @@ -0,0 +1,74 @@ +#!/bin/sh + +PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin + +HOST=localhost +PORT=5432 +PGPASSWORD=$PG_PASS +USER=postgres +TPL=template1 + +pathB=./backup +DBUSER=$DB_USER +DBPASS=$DB_PASS +DATABASE=$DB_NAME + +psql_connect() { + export PGPASSWORD + psql -h $HOST -U $USER -p $PORT -c "SELECT VERSION()" > /dev/null 2> pg_restore.tmp + if [ '0' -ne "$?" ]; then + echo "Can't connect to PostgreSQL $HOST\n$(cat pg_restore.tmp)" + echo "Error: Connection to $HOST failed" + exit + fi + rm pg_restore.tmp +} + +psql_query() { + sql_tmp=$(mktemp) + echo "$1" > $sql_tmp + export PGPASSWORD + psql -h $HOST -U $USER -f "$sql_tmp" + #2> /dev/null + rm -f $sql_tmp +} + +add_pgsql_database() { + psql_connect + + #query="CREATE ROLE $DBUSER WITH LOGIN PASSWORD '$DBPASS'" + #psql_query "$query" > /dev/null + + query="CREATE DATABASE $DATABASE OWNER $DBUSER" + if [ "$TPL" = 'template0' ]; then + query="$query ENCODING '$charset' TEMPLATE $TPL" + else + query="$query TEMPLATE $TPL" + fi + psql_query "$query" > /dev/null + + query="GRANT ALL PRIVILEGES ON DATABASE $DATABASE TO $DBUSER" + psql_query "$query" > /dev/null + + query="GRANT CONNECT ON DATABASE template1 to $DBUSER" + psql_query "$query" > /dev/null + + query="SELECT rolpassword FROM pg_authid WHERE rolname='$DBUSER'" + md5=$(psql_query "$query" | grep md5 | cut -f 2 -d \ ) +} + +psql_connect + +query="REVOKE ALL PRIVILEGES ON DATABASE $DATABASE FROM $DBUSER" +psql_query "$query" + +query="DROP DATABASE $DATABASE" +psql_query "$query" + +add_pgsql_database + +PGPASSWORD=$PG_PASS +export PGPASSWORD +pg_restore -j 2 -h $HOST -U $DBUSER -d $DATABASE $pathB/$1 + +unset PGPASSWORD