Skip to content

Instantly share code, notes, and snippets.

@seanlinsley seanlinsley/psqlprompt.sh
Last active Jun 10, 2016

Embed
What would you like to do?
# 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

This comment has been minimized.

Copy link
Owner Author

seanlinsley commented Jan 12, 2016

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

This comment has been minimized.

Copy link
Owner 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
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.