On 7th of July, Andres Freund committed patch:

Add psql PROMPT variable showing the pid of the connected to backend.
The substitution for the pid is %p.
Author: Julien Rouhaud
Discussion: <a href="http://git.postgresql.org/gitweb/?p=postgresql.git;a=object;h=116262CF971C844FB6E793F8809B51C6E99D48">116262CF971C844FB6E793F8809B51C6E99D48</a>@BPXM02GP.gisp.nec.co.jp

It was over a month ago, but in the mean time I was on vacation, and I wanted to test it with some specific case.

Anyway – the description seems to be obvious. Just in case it isn't, let me show you how it works. Normally when you start psql, you'll get prompt looking like:


where “depesz" is the name of database you're connected to.

You can of course modify it, using many variables, described in the manual

I, for example, configured my psql, so that my default prompt shows:

(depesz@[local]:5960) 20:39:33 [depesz] 

Which shows my username in database, where the database is (localhost, over unix socket, port 5960), current time, and name of the database that I'm connected to.

Now, since 9.6, we will have one more addition – ability to add pid of backend.

Let's see:

$ \set PROMPT1 '%n@%/ : %p $ '
depesz@depesz : 26853 $

Nice. What good is it? Well, I can immediately see it, even in history, so I can easily grep for it in logs. Or use the value in queries, like:

depesz@depesz : 26853 $ select count(*) from pg_stat_activity where pid <> 26853;
(1 row)

So far, so good. But, I want to test it in harsh conditions. What will happen if the pid of backend would change? This could happen if we're using pgbouncer in transaction/statement pooling modes.

So, I connected to pgbouncer, and ran:

depesz=# select pg_backend_pid();
(1 row)
depesz=# \set PROMPT1 '%n@%/ : %p $ '
depesz@depesz : 1658680808 $

Whoa. Clearly the value is not what we expected. Even in session pooling, the received pid is meaningless.

I take it that it's because pgbouncer takes over the field in returned data, and inserts there something that can be used to track this connection in pgbouncer itself, but I have no idea what.

In any case – pgbouncer is external tool, and there are no warranties that psql will work with it to 100% of its capabilities.

I for one, like it, and will most likely use in many places, thank guys.

  1. One comment

  2. # Torsten Förtsch
    Aug 23, 2015

    You don’t need to wait for PG 9.6 to display the backend pid in your prompt. The following should work at least since 9.3.

    In ~/.psqlrc:

    — note the absence of the ; at the end of the next line
    select pg_backend_pid() as bpid
    \gset my_

    \set PROMPT1 ‘%n@%/ : %:my_bpid: $ ‘

    It probably won’t work with pgbouncer either.

Leave a comment