Files
docker-zulip/custom_zulip_files/scripts/setup/postgres-init-db
2017-03-21 01:17:51 +01:00

75 lines
2.3 KiB
Bash
Executable File

#!/bin/bash
set -e
set -x
# A bit of a helper variable, default is voyager
DEPLOYMENT_TYPE="${DEPLOYMENT_TYPE:-voyager}"
# What user should we use for connecting to the database
POSTGRES_USER="${POSTGRES_USER:-postgres}"
# Shut down all services to ensure a quiescent state.
if [ -e "/var/run/supervisor.sock" ]; then
supervisorctl stop all
fi
# Don't "terminate" psql sessions when run in docker!
if [ "$DEPLOYMENT_TYPE" != "dockervoyager" ]; then
# Drop any open connections to any old database. Hackishly call using
# source because postgres user can't read /root/zulip/scripts/setup.
source "$(dirname "$0")/terminate-psql-sessions" postgres zulip zulip_base
fi
# Create the "connect" command here
POSTGRES_COMMAND="psql"
if [ ! -z "$DB_HOST" ]; then
POSTGRES_COMMAND="$POSTGRES_COMMAND -h $DB_HOST"
fi
if [ ! -z "$DB_HOST_PORT" ]; then
POSTGRES_COMMAND="$POSTGRES_COMMAND -p $DB_HOST_PORT"
fi
if [ ! -z "$DB_USER" ]; then
POSTGRES_COMMAND="$POSTGRES_COMMAND -U $DB_USER"
fi
if [ ! -z "$DB_PASS" ]; then
export PGPASSWORD="$DB_PASS"
fi
(
# Make sure the current working directory is readable by postgres
cd /
su "$POSTGRES_USER" -c "$POSTGRES_COMMAND" <<EOF
CREATE USER zulip;
ALTER ROLE zulip SET search_path TO zulip,public;
EOF
# Never drop the database when run from docker!
# In Docker we have to run this script everytime we start the container, so don't drop.
if [ "$DEPLOYMENT_TYPE" != "dockervoyager" ]; then
su "$POSTGRES_USER" -c "$POSTGRES_COMMAND" <<EOF
DROP DATABASE IF EXISTS zulip;
EOF
fi
# Ignore errors here, if there is a connection problem the first command would have already failed
# There could be other problems, why the database couldn't get created,
# but it's better to just ignore an eventual error here, because the next
# command/query fails when the database doesn't exists
su "$POSTGRES_USER" -c "$POSTGRES_COMMAND" <<EOF || :
CREATE DATABASE zulip OWNER=zulip;
EOF
su "$POSTGRES_USER" -c "$POSTGRES_COMMAND zulip" <<EOF
CREATE SCHEMA zulip AUTHORIZATION zulip;
CREATE EXTENSION tsearch_extras SCHEMA zulip;
EOF
)
unset PGPASSWORD
# Don't clear memcached from within the docker container
if [ "$DEPLOYMENT_TYPE" != "dockervoyager" ]; then
# Clear memcached to avoid contamination from previous database state
sh "$(dirname "$0")/flush-memcached"
fi
echo "Database created"