Last active
May 24, 2026 02:10
-
-
Save hasandiwan/4d26952f1b8c5c8f42ff4f1b6e90a073 to your computer and use it in GitHub Desktop.
Connecting to Postgres with a JDBC URL
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/sh | |
| # Input variable | |
| jdbc_url="$1" | |
| # 1. Handle the "jdbc:" prefix | |
| case "$jdbc_url" in | |
| jdbc:*) url_to_parse=$(echo "$jdbc_url" | cut -c 6-) ;; | |
| *) url_to_parse="$jdbc_url" ;; | |
| esac | |
| # 2. Extract components using sed/awk | |
| # Format: scheme://hostname:port/path?query | |
| scheme=$(echo "$url_to_parse" | sed -n 's/^\([^:]*\).*/\1/p') | |
| # Remove scheme and :// | |
| rest=$(echo "$url_to_parse" | sed 's/^[^:]*:\/\///') | |
| # Extract hostname and port | |
| host_port=$(echo "$rest" | cut -d'/' -f1) | |
| hostname=$(echo "$host_port" | cut -d':' -f1) | |
| port=$(echo "$host_port" | grep ":" | cut -d':' -f2) | |
| # Extract path and query | |
| path_query=$(echo "$rest" | cut -d'/' -f2-) | |
| path=$(echo "$path_query" | cut -d'?' -f1) | |
| query=$(echo "$path_query" | cut -d'?' -f2) | |
| # 3. Parse Query Params into JSON objects | |
| # This simulates: [{k: ', '.join(q)} for k, q in parse_qs(parsed.query).items()] | |
| params_json="" | |
| if [ -n "$query" ] && [ "$query" != "$path_query" ]; then | |
| # Split by & | |
| IFS='&' | |
| for pair in $query; do | |
| key=$(echo "$pair" | cut -d'=' -f1) | |
| val=$(echo "$pair" | cut -d'=' -f2) | |
| item="{\"${key}\": \"${val}\"}" | |
| if [ -z "$params_json" ]; then | |
| params_json="$item" | |
| else | |
| params_json="$params_json, $item" | |
| fi | |
| done | |
| unset IFS | |
| fi | |
| # Get everything after the '?' | |
| query="${jdbc_url#*?}" | |
| # Strip everything up to 'user=' | |
| user="${query#*user=}" | |
| # Strip everything from the first '&' to the end | |
| user="${user%%&*}" | |
| password_tmp="${query#*password=}" | |
| password="${password_tmp%%&*}" | |
| env PGPASSWORD="${password}" psql --dbname="${path}" --host="${hostname}" --port="${port:-5432}" --username="${user}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment