Last active
June 11, 2020 02:16
-
-
Save jamiecook/b2ca2c2519fb0bda16099da20d7ee27c to your computer and use it in GitHub Desktop.
Bash completion for connecting psql to lots of databases. Combine with a ~/.pgpass file for easy db connections.
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/bash | |
DB_SEARCH_DIRS="$HOME/Projects $HOME/src /opt $HOME/src/vlc $HOME/Projects/vlc $HOME/p $HOME/src/bdk" | |
# See https://stackoverflow.com/questions/1494178/how-to-define-hash-tables-in-bash | |
setup_database_list() { | |
declare -Ag databases | |
databases["short_name"]="psql -U user -h hostname -p 5432 db_name" | |
databases["short_name_number_2"]="psql -U different_user -h different_hostname -p 5432 different_db_name" | |
} | |
get_db_list() { | |
setup_database_list | |
echo ${!databases[@]} | |
} | |
db() { | |
local PATTERN=$1 | |
local COMMAND=$2 | |
setup_database_list | |
CONNECT_STR=${databases[$PATTERN]} | |
if [[ -z "${CONNECT_STR}" ]]; then | |
echo "Can't find database ${PATTERN}"; | |
# exit -1 | |
else | |
if [[ "$COMMAND" == "connect" ]]; then | |
# Actually execute the connection string to get a psql shell | |
$CONNECT_STR | |
elif [[ "${COMMAND}" == "-f" ]]; then | |
# Run the given file against the given connection | |
local filename=$3 | |
if [[ -f ${filename} ]]; then | |
$CONNECT_STR -f "$filename" | |
else | |
echo "No such file ${filename}" | |
exit -1 | |
fi | |
elif [[ "${COMMAND}" == "-c" ]]; then | |
$CONNECT_STR -c "$3" | |
else | |
echo ${COMMAND} | |
echo ${CONNECT_STR} | |
fi | |
fi | |
} | |
_check_db_dirs() { | |
cache_complete /bin/bash .cache_dbdir "get_db_list" | |
} | |
complete -F _check_db_dirs -o default db |
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
$ db short_name connect | |
psql (12.2, server 9.5.15) | |
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off) | |
Type "help" for help. | |
db_name=> \q | |
$ # Use tab completion on database names | |
$ db sho<tab> | |
short_name short_name_number_2 | |
$ db short | |
$ # Execute given SQL against the given database (similar to psql -c) | |
$ db short_name -c "select * from spatial_ref_sys limit 0;" | |
srid | auth_name | auth_srid | srtext | proj4text | |
------+-----------+-----------+--------+----------- | |
(0 rows) | |
$ # Execute SQL from given filename against the given database (similar to psql -f) | |
$ db short_name -f filename.sql | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment