diff --git a/README.md b/README.md index a6362fd..b7dc733 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,9 @@ docker run --rm \ edoburu/pgbouncer ``` +As an option, you can add pool_mode at the end using a slash.\ +DATABASE_URL="postgres://user:pass@postgres-host/database/**session**" + Kubernetes integration ---------------------- diff --git a/entrypoint.sh b/entrypoint.sh index 7e6ae1a..48c795c 100755 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -20,15 +20,12 @@ fi # # Parameters: # - The url we should parse -# Returns (sets variables): DB_USER, DB_PASSWORD, DB_HOST, DB_PORT, DB_NAME -function parse_url() { - # Thanks to https://stackoverflow.com/a/17287984/146289 +# Returns (sets variables): DB_USER, DB_PASSWORD, DB_HOST, DB_PORT, DB_NAME, POOL_MODE - # Allow to pass values like dj-database-url / django-environ accept +function parse_url() { proto="$(echo $1 | grep :// | sed -e's,^\(.*://\).*,\1,g')" url="$(echo $1 | sed -e s,$proto,,g)" - # extract the user and password (if any) userpass="$(echo $url | grep @ | sed -r 's/^(.*)@([^@]*)$/\1/')" DB_PASSWORD="$(echo $userpass | grep : | cut -d: -f2)" if [ -n "${DB_PASSWORD}" ]; then @@ -37,7 +34,6 @@ function parse_url() { DB_USER="${userpass}" fi - # extract the host -- updated hostport=`echo $url | sed -e s,$userpass@,,g | cut -d/ -f1` port=`echo $hostport | grep : | cut -d: -f2` if [ -n "$port" ]; then @@ -45,9 +41,18 @@ function parse_url() { DB_PORT="${port}" else DB_HOST="${hostport}" + DB_PORT=5432 fi - DB_NAME="$(echo $url | grep / | cut -d/ -f2-)" + # Parse database name and optional pool_mode + path=$(echo $url | cut -d/ -f2-) + DB_NAME=$(echo "$path" | cut -d/ -f1) + POOL_MODE=$(echo "$path" | cut -d/ -f2) + + # If pool_mode is same as db_name or empty, clear it + if [ -z "$POOL_MODE" ] || [ "$POOL_MODE" = "$DB_NAME" ]; then + POOL_MODE="" + fi } # Grabs variables set by `parse_url` and adds them to the userlist if not already set in there. @@ -65,11 +70,13 @@ function generate_userlist_if_needed() { # Grabs variables set by `parse_url` and adds them to the PG config file as a database entry. function generate_config_db_entry() { - printf "\ -${DB_NAME:-*} = host=${DB_HOST:?"Setup pgbouncer config error! You must set DB_HOST env"} \ -port=${DB_PORT:-5432} auth_user=${DB_USER:-postgres} -${CLIENT_ENCODING:+client_encoding = ${CLIENT_ENCODING}\n}\ -" >> "${PG_CONFIG_FILE}" + printf "%s = host=%s port=%s auth_user=%s%s%s\n" \ + "${DB_NAME:-*}" \ + "${DB_HOST:?"Setup pgbouncer config error! You must set DB_HOST env"}" \ + "${DB_PORT:-5432}" \ + "${DB_USER:-postgres}" \ + "${POOL_MODE:+ pool_mode=${POOL_MODE}}" \ + "${CLIENT_ENCODING:+ client_encoding=${CLIENT_ENCODING}}" >> "${PG_CONFIG_FILE}" } # Write the password with MD5 encryption, to avoid printing it during startup. @@ -200,4 +207,4 @@ ${TCP_USER_TIMEOUT:+tcp_user_timeout = ${TCP_USER_TIMEOUT}\n}\ fi echo "Starting $*..." -exec "$@" +exec "$@" \ No newline at end of file