Created
November 16, 2016 10:12
-
-
Save ivan-hilckov/080f2e8b064c66b04a9a3267bf57e006 to your computer and use it in GitHub Desktop.
the new psql-load.sh
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
DB_NAME= | |
FILE_PATH= | |
DB_OWNER="postgres" | |
while getopts ":d:u:f:" flag | |
do | |
case "$flag" in | |
'd') DB_NAME=$OPTARG ;; | |
'u') DB_OWNER=$OPTARG ;; | |
'f') FILE_PATH=$OPTARG ;; | |
't') TYPE=$OPTARG ;; | |
esac | |
done | |
CMD_PSQL="psql -U $DB_OWNER $DB_NAME" | |
CMD_RESTORE="pg_restore --host localhost --port 5432 --username postgres --dbname $DB_NAME --role $DB_OWNER --no-password --verbose " | |
SCRITP_FOLDER=`dirname ${BASH_SOURCE[0]}` | |
FILE=$(basename "$FILE_PATH") | |
EXTENSION="${FILE##*.}" | |
echo "Drop database $DB_NAME ..." | |
psql -U postgres -c "DROP DATABASE IF EXISTS $DB_NAME;" | |
echo "Create database $DB_NAME with owner $DB_OWNER ..." | |
psql -U postgres -c "CREATE DATABASE $DB_NAME WITH OWNER = $DB_OWNER;" | |
MSG_UPLOAD="Uploading dump $FILE_PATH type $EXTENSION" | |
unpack_n_restore(){ | |
REAL_NAME="$(dirname $FILE_PATH)/psql-load-data-$(date +%s).backup" | |
echo "Ungzip $FILE_PATH > $REAL_NAME" | |
gunzip -ck $FILE_PATH > $REAL_NAME | |
echo $MSG_UPLOAD | |
$CMD_PSQL < $REAL_NAME | |
rm $REAL_NAME | |
} | |
unpack_n_restore_xz(){ | |
REAL_NAME="$(dirname $FILE_PATH)/psql-load-data-$(date +%s).backup" | |
echo "Ungzip $FILE_PATH > $REAL_NAME" | |
xz -d $FILE_PATH > $REAL_NAME | |
echo $MSG_UPLOAD | |
$CMD_PSQL < $REAL_NAME | |
rm $REAL_NAME | |
} | |
case "$EXTENSION" in | |
'xz') unpack_n_restore_xz ;; | |
'bz2'|'gzip') unpack_n_restore ;; | |
'gz') echo $MSG_UPLOAD; gunzip -c $FILE_PATH | $CMD_PSQL ;; | |
'dump'|'backup') echo $MSG_UPLOAD; $CMD_RESTORE $FILE_PATH ;; | |
*) echo $MSG_UPLOAD; $CMD_PSQL < $FILE_PATH ;; | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment