diff --git a/sql/bin/db-init b/sql/bin/db-init --- a/sql/bin/db-init +++ b/sql/bin/db-init @@ -18,25 +18,33 @@ DB_LOCALE="C.UTF-8" DB_TEMPLATE="template0" +cd "$( dirname $0 )/.." + if ! [ -f "$SQL_INIT" ] ; then echo "Cannot find $SQL_INIT. Abort." - echo "Note: db-init should usually be run from swh-storage/sql as bin/db-init." exit 2 fi -if [ -z "$1" -o -z "$2" -o -z "$3" ] ; then - echo "Usage: bin/db-init DB_PORT DB_NAME DB_USER" - echo "Example: bin/db-init 5432 softwareheritage-dev swhdev" +if [ -z "$1" ] ; then + echo "Usage: bin/db-init DB_NAME [DB_USER [DB_PORT]]" + echo "Example: bin/db-init softwareheritage-dev" echo "Note: DB_NAME should not exist and will be created; DB_USER can exist." exit 2 fi -db_port="$1" -db_name="$2" -db_user="$3" -conn_flags="--port ${db_port}" +db_name="$1" +db_user="${2:-$USER}" + +conn_flags="" +if [ -n "$3" ]; then + conn_flags="--port $3" +fi -echo "I: creating Postgres user ${db_user} ..." -createuser $conn_flags --pwprompt "$db_user" || true +user_exists=$( psql postgres -tAc "SELECT 1 FROM pg_roles + WHERE rolname='$db_user'" ) +if [ "$user_exists" != "1" ]; then + echo "I: creating Postgres user ${db_user} ..." + createuser $conn_flags --pwprompt "$db_user" || true +fi echo "I: creating Postgres database ${db_name} ..." createdb $conn_flags \