Nice Postgresql Trick
Thursday, June 29th, 2023This morning I really wanted to be able to set the psql prompt in my sessions because the system we have for creating databases doesn't really create nicely human-readable name, and even so, I'd like to have the name in the prompt match the branch of the code I'm working on... it just works out better.
So I started digging, and the -c parameter is OK, but the psql session terminates after that - so that's not going to work. And piping in the \set commands seemed to be problematic, and then I found this:
$ psql --set=PROMPT1="${br}%R%#%x "
where br is the name of the branch I'm working on. This could then be obtained from git easily, and then put into a function, and it works great!
# # "platter psql (postgres command line tool)" - start a psql session on # the provided branch in the PLATTER_INSTANCE in the .env file in the # current directory (a Node project repo). If no branch is provided, then # the current git branch will be used. # function ppsql() { if [ -f .env ]; then set -o allexport; source .env; set +o allexport local br=$1 if [ ${#br} -eq 0 ]; then br=`cat .git/HEAD | sed -e 's:^.*/::'` fi local url="`npx platter postgres branch url ${br} \ --instance $PLATTER_INSTANCE | tr -d '\n'`?sslmode=require" psql --set=PROMPT1="${br}%R%#%x " --set=PROMPT2="${br}%R%#%x " $url else echo "Not in a Node project directory!" fi }
With this, it's so easy now to be able to keep track of the database (branch) I'm on with Platter, and that makes a really big different to my peace of mind. 🙂