Skip to content

Instantly share code, notes, and snippets.

@seanlinsley
Last active June 10, 2016 18:40
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save seanlinsley/c3c9d0c704c21c5c67e0 to your computer and use it in GitHub Desktop.
# This asks the user if they want a read-only or read-write PSQL session. PSQL
# provides `\prompt`, but that doesn't provide a way to conditionally prompt
# based on whether it was being run interactively, or from bash-completion.
#
# Save this file to ~/.psqlprompt and add the below to ~/.psqlrc:
#
# \set read_only `bash ~/.psqlprompt`
# set default_transaction_read_only = :read_only;
#
function psql_prompt() {
local pid=$PID
local name="$(ps -o comm= $(ps -o pid= $pid))"
# This is a somewhat fragile way of detecting whether we're inside of
# bash-completion. The initial version of this script used the `state` attribute
# (`stat` on Linux) from `ps` for the parent process to check for `+` indicating
# whether it had control of the terminal. But it appears that OSX and Linux have
# opposite interpretations of that attribute. 💀
if [[ ! $name =~ 'awk' ]]; then
while true; do
read -p 'should this session be read-only? ' answer
case $answer in
[Yy]*) echo true; break;;
[Nn]*) echo false; break;;
esac
done
else
echo false;
fi;
}
psql_prompt
\set read_only `bash ~/.psqlprompt`
set default_transaction_read_only = :read_only;
@seanlinsley
Copy link
Author

Note that the names of the two files are wrong. They're only named like they are because Gists don't provide a way to set the language other than their file extension.

  • psqlprompt.sh -> .psqlprompt
  • psqlrc.sql -> .psqlrc

@seanlinsley
Copy link
Author

seanlinsley commented Jun 10, 2016

Note: pg_restore is fixed in Postgres 9.5.3 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment