Skip to content

Instantly share code, notes, and snippets.

@runapp
Created April 6, 2020 17:18
Show Gist options
  • Save runapp/40a19487368ffb9b3647ccf66bb33b6e to your computer and use it in GitHub Desktop.
Save runapp/40a19487368ffb9b3647ccf66bb33b6e to your computer and use it in GitHub Desktop.
A simple postgresql wrapper
#!/bin/sh
if [ $EUID -eq 0 ]; then
echo "Please don't run me with root privilege!"
exit 1
fi
ROOT="$(dirname "$(readlink -f "$0")")"
DATABASE=db
PG_BIN=/usr/lib/postgresql12/bin
PG_DATA="$ROOT/data"
PG_LOG="$PG_DATA/postgresql.log"
PG_INITDB_OPTIONS='--locale="en_US.UTF8"'
PG_OPTIONS="-c listen_addresses= -c unix_socket_directories='$PG_DATA'"
case $1 in
init)
$PG_BIN/pg_ctl init -D "$PG_DATA" -o "$PG_INITDB_OPTIONS"
$PG_BIN/pg_ctl start -D "$PG_DATA" -l "$PG_LOG" -o "$PG_OPTIONS"
echo "Waiting for PGSQL server to start..."
while [ ! -S "$PG_DATA/.s.PGSQL.5432" ]
do
sleep 1
done
$PG_BIN/createdb -h "$PG_DATA" $DATABASE
;;
shell)
$PG_BIN/psql -h "$PG_DATA" $DATABASE
;;
start)
$PG_BIN/pg_ctl start -D "$PG_DATA" -l "$PG_LOG" -o "$PG_OPTIONS"
;;
stop)
$PG_BIN/pg_ctl stop -D "$PG_DATA"
;;
status)
if [ -f "$PG_DATA/postmaster.pid" ] ; then
echo 'Running. PID file writes:'
cat "$PG_DATA/postmaster.pid"
else
echo Stopped.
fi
;;
upgrade)
[ -f "$PG_DATA/postmaster.pid" ] && echo 'Is server running? Stop it first.' && exit 1
$PG_BIN/pg_ctl init -D "${PG_DATA}-new" -o "$PG_INITDB_OPTIONS" || exit $?
mv "${PG_DATA}" "${PG_DATA}-old" && mv "${PG_DATA}-new" "${PG_DATA}" || exit $?
echo 'Please run the following command:'
echo ' ' \"$PG_BIN/pg_upgrade\" -b \"${PG_BIN}-old\" -B \"$PG_BIN\" -d \"${PG_DATA}-old\" -D \"$PG_DATA\"
echo 'This should be helpful for running any post-run scripts by pg_upgrade:'
echo $" \"$PG_BIN/vacuumdb\" --all --analyze-in-stages -h \"$PG_DATA\""
;;
opt)
echo $PG_OPTIONS
;;
*)
echo -e "Unknown command, available are\n init shell start stop status upgrade opt"
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment