A tale of making a company-wide psqlrc to use with pgbouncer. (2021)

https://www.depesz.com/2021/06/23/a-tale-of-making-company-wide-standard-psqlrc/

At a company we have literally thousands of Pg servers. The layout is also kinda non-obvious. Each database is named the same, but contains different data. And in front of it all, we have pgbouncers.

After some talk, it was suggested that perhaps we could make psql prompt show which database it is connected to. And perhaps some more information, like backend pid. I thought it will be simple…

For starters – we have a function defined, named dba.smi which returns a bit of trivia about the server we run it on. It's based on text files that exist on the filesystem and contain information like:

  • project name
  • environment (production, beta, test)
  • cluster (in our case cluster is simply a number (usually). Each cluster means at least 3 separate databases: primary, secondary, and report. For historical reasons source data is using old vocabulary: master, slave, and backup.

All of these can be fetched with calls to dba.smi(), and every user in system can call this function. Great. Trivial task. Wrote psqlrc like this:

SELECT
    dba.smi('aws_tag_project') AS project,
    dba.smi('aws_tag_environment') AS env,
    dba.smi('aws_tag_cluster') AS cluster,
    dba.smi('aws_tag_pgrole') AS pgrole \gset smi_
\SET PROMPT1 '%`date +%H:%M:%S` %:smi_project: %:smi_env:, cluster %:smi_cluster:, %:smi_pgrole: db: %n@%/, pid:%p\n%x%R%# '

After loading it, I got beautiful prompt:

15:39:31 magic production, cluster 1, backup db: depesz-rw@appdb, pid:22025
=>

Tested it on database server connected to app database, all works well. Success.

Well, no. when I connected to another database, like postgres, I got:

psql:/home/depesz/.psqlrc:5: ERROR:  schema "dba" does NOT exist
LINE 2:     dba.smi('aws_tag_project') AS project,
            ^
15:41:22  , cluster ,  db: depesz-rw@postgres, pid:23229
=>

Well, that ain't nice. I tried to hide it with adding \set QUIET in the beginning, and \unset QUIET at the end, but it didn't help.

Luckily, psql has conditionals. So I can first check if the function is there. While working on it I also discovered that smi returns old names of pgroles, so I have to map it to new ones. Trivial. New version:

\SET QUIET
SELECT EXISTS(
    SELECT 1
    FROM pg_proc p
        JOIN pg_namespace n ON p.pronamespace = n.oid
    WHERE p.proname = 'smi' AND n.nspname = 'dba'
) \gset smi_
\IF :smi_exists
    SELECT
        dba.smi('aws_tag_project') AS project,
        dba.smi('aws_tag_environment') AS env,
        dba.smi('aws_tag_cluster') AS cluster,
        CASE dba.smi('aws_tag_pgrole')
            WHEN 'master' THEN 'primary'
            WHEN 'slave' THEN 'secondary'
            WHEN 'backup' THEN 'report'
            ELSE dba.smi('aws_tag_pgrole')
        END AS pgrole \gset smi_
    \SET PROMPT1 '%`date +%H:%M:%S` %:smi_project: %:smi_env:, cluster %:smi_cluster:, %:smi_pgrole: db: %n@%/, pid:%p\n%x%R%# '
\ELSE
    \SET PROMPT1 '%`date +%H:%M:%S` db: %n@%/, pid:%p\n%x%R%# '
\endif
\unset QUIET

Amazing. Now, when I try to connect to database that doesn't have dba.smi(), I just get plain prompt:

16:04:14 db: depesz-rw@postgres, pid:5144
=>

All is well, and am ready to push to production. Just sanity check, I'll connect, like any user would, through a pgbouncer, that's just formality. Right? Not quite:

16:05:40 magic production, cluster 1, report db: depesz-rw@appdb, pid:830285059
=>

Well, it looks OK, but the pid is definitely incorrect. Apparently whatever psql displays as pid (%p) is not really pid when connecting through pgBouncer.

Luckily, that is simple to work around. I will just get the pid using select query:

SELECT pg_backend_pid() \gset

and then, instead of %p, will use %:pg_backend_pid:.

Simple, and works.

But then it hit me: what will happen if I will connect to the special, magical, pgbouncer database? Users don't do it, but I might. In case you don't know – when you connect through pgbouncer, there is special “database" named pgbouncer where you can connect, and display some info from pgbouncer itself. Basically admin interface for pgbouncer.

Surely it will work, right? Well, no:

psql:/home/depesz/.psqlrc:3: ERROR:  invalid command 'SELECT pg_backend_pid() ', USE SHOW HELP;
psql:/home/depesz/.psqlrc:10: ERROR:  invalid command 'select EXISTS(
    SELECT 1
    from pg_proc p
        join pg_namespace n on p.pronamespace = n.oid
    where p.proname = 'smi' and n.nspname = 'dba'
) ', USE SHOW HELP;
psql:/home/depesz/.psqlrc:12: error: unrecognized VALUE ":smi_exists" FOR "\if expression": BOOLEAN expected

Apparently this magical pgbouncer database doesn't handle selects. At all:

=# SELECT 1;
ERROR:  invalid command 'select 1;', USE SHOW HELP;

Well, OK. But that's simple. I will just check if database name is pgbouncer, and if yes – use simpler prompt. And when it's not – use normal code.

psql even helpfully has DBNAME variable, so it should be easy. Right?

=# \IF :DBNAME = pgbouncer
unrecognized VALUE "pgbouncer = pgbouncer" FOR "\if expression": BOOLEAN expected

Apparently psql's \if expression can only parse single value, and it has to be one of: true, false, 1, 0, on, off, yes, no.

So, how to get one of these, let's say 1/0, if the dbname is pgbouncer? I can't use select. I can't use logic in \if…. cue despair.

Luckily, in docs I found this bit:

The expression argument of an \if or \elif command is subject to variable interpolation and backquote expansion

backquote. So I can call shell! Solution became obvious:

\IF `test :DBNAME = pgbouncer && echo 1 || echo 0`

this requires that we have test program installed, but it's by default everywhere, so I don't care. Much.

So, all things said, finally the psqlrc is:

-- Hide confirmation messages
\SET QUIET
-- Check if we're connecting to database pgbouncer. It is very limited, and can't run SELECT's
\IF `test :DBNAME = pgbouncer && echo 1 || echo 0`
    -- This is pgbouncer. User plain prompt
    \SET PROMPT1 '%`date +%H:%M:%S` db: %n@%/\n%x%R%# '
\ELSE
    -- This isn't pgbouncer. So we should have SELECTs available
    -- If we're connecting through pgbouncer, then prompt's %p is not real, so get real PID
    SELECT pg_backend_pid() \gset
    -- Check if there is dba.smi() function
    SELECT EXISTS(SELECT 1 FROM pg_proc p JOIN pg_namespace n ON p.pronamespace = n.oid WHERE p.proname = 'smi' AND n.nspname = 'dba') \gset smi_
    \IF :smi_exists
        -- If dba.smi() exists, get data from it, and put it in prompt.
        SELECT
            dba.smi('aws_tag_project') AS project,
            dba.smi('aws_tag_environment') AS env,
            dba.smi('aws_tag_cluster') AS cluster,
            CASE dba.smi('aws_tag_pgrole')
                WHEN 'master' THEN 'primary'
                WHEN 'slave' THEN 'secondary'
                WHEN 'backup' THEN 'report'
                ELSE dba.smi('aws_tag_pgrole')
            END AS pgrole \gset smi_
        \SET PROMPT1 '%`date +%H:%M:%S` %:smi_project: %:smi_env:, cluster %:smi_cluster:, %:smi_pgrole: db: %n@%/, pid:%:pg_backend_pid:\n%x%R%# '
    \ELSE
        -- If dba.smi() is not available, pick simpler prompt
        \SET PROMPT1 '%`date +%H:%M:%S` db: %n@%/, pid:%:pg_backend_pid:\n%x%R%# '
    \endif
\endif
-- Common settings, regardless of dba.smi() existence
\SET PROMPT2 '%R%# '
\pset NULL '[null]'
-- Use sensible pager
\pset pager always
\setenv PAGER 'less -iMFXSx4R'
-- It's 21st century, let's use unicode for borders
\pset linestyle unicode
-- Stop hiding confirmation messages
\unset QUIET
-- vim: set ft=sql:

and it does what I wanted it to do. Installed it as /etc/postgresql-common/psqlrc everywhere, and it works.

When I showed it to colleague, he said: I had no idea psqlrc files could be so complex. And this kinda prompted me to write this blogpost. They (psqlrcs) can. They can do a lot of things, and if writing them doesn't seem simple – it's because we rarely do. But, I think, it's worth it.

{
"by": "fanf2",
"descendants": 0,
"id": 40247574,
"score": 2,
"time": 1714743723,
"title": "A tale of making a company-wide psqlrc to use with pgbouncer. (2021)",
"type": "story",
"url": "https://www.depesz.com/2021/06/23/a-tale-of-making-company-wide-standard-psqlrc/"
}
{
"author": "depesz",
"date": "2024-11-21T15:39:31.000Z",
"description": null,
"image": "https://secure.gravatar.com/avatar/392959cbb0f397e63876fd33e80ea372?s=42&d=identicon&r=x",
"logo": null,
"publisher": "=$ |",
"title": "A tale of making company-wide standard psqlrc – select * from depesz;",
"url": "https://www.depesz.com/2021/06/23/a-tale-of-making-company-wide-standard-psqlrc/"
}
{
"url": "https://www.depesz.com/2021/06/23/a-tale-of-making-company-wide-standard-psqlrc/",
"title": "A tale of making company-wide standard psqlrc – select * from depesz;",
"description": "At a company we have literally thousands of Pg servers. The layout is also kinda non-obvious. Each database is named the same, but contains different data. And in front of it all, we have pgbouncers. After...",
"links": [
"https://www.depesz.com/?p=3972",
"https://www.depesz.com/2021/06/23/a-tale-of-making-company-wide-standard-psqlrc/"
],
"image": "",
"content": "<article>\n\t<div>\n\t\t<p>At a company we have literally thousands of Pg servers. The layout is also kinda non-obvious. Each database is named the same, but contains different data. And in front of it all, we have pgbouncers.</p>\n<p>After some talk, it was suggested that perhaps we could make psql prompt show which database it is connected to. And perhaps some more information, like backend pid. I thought it will be simple…</p>\n<p>For starters – we have a function defined, named <em>dba.smi</em> which returns a bit of trivia about the server we run it on. It's based on text files that exist on the filesystem and contain information like:</p>\n<ul>\n<li>project name</li>\n<li>environment (production, beta, test)</li>\n<li>cluster (in our case cluster is simply a number (usually). Each cluster means at least 3 separate databases: primary, secondary, and report. For historical reasons source data is using old vocabulary: master, slave, and backup.</li>\n</ul>\n<p>All of these can be fetched with calls to dba.smi(), and every user in system can call this function. Great. Trivial task. Wrote psqlrc like this:</p>\n<div><pre><span>SELECT</span>\n dba<span>.</span>smi<span>(</span><span>'aws_tag_project'</span><span>)</span> <span>AS</span> project<span>,</span>\n dba<span>.</span>smi<span>(</span><span>'aws_tag_environment'</span><span>)</span> <span>AS</span> env<span>,</span>\n dba<span>.</span>smi<span>(</span><span>'aws_tag_cluster'</span><span>)</span> <span>AS</span> cluster<span>,</span>\n dba<span>.</span>smi<span>(</span><span>'aws_tag_pgrole'</span><span>)</span> <span>AS</span> pgrole \\gset smi_\n\\<span>SET</span> PROMPT1 <span>'%`date +%H:%M:%S` %:smi_project: %:smi_env:, cluster %:smi_cluster:, %:smi_pgrole: db: %n@%/, pid:%p<span>\\n</span>%x%R%# '</span></pre></div>\n<p>After loading it, I got beautiful prompt:</p>\n<div><pre>15:39:31 magic production, cluster 1, backup db: depesz-rw@appdb, pid:22025\n=&gt;</pre></div>\n<p>Tested it on database server connected to app database, all works well. Success.</p>\n<p>Well, no. when I connected to another database, like <em>postgres</em>, I got:</p>\n<div><pre>psql:<span>/</span>home<span>/</span>depesz<span>/.</span>psqlrc:<span>5</span>: ERROR: schema <span>\"dba\"</span> does <span>NOT</span> exist\nLINE <span>2</span>: dba<span>.</span>smi<span>(</span><span>'aws_tag_project'</span><span>)</span> <span>AS</span> project<span>,</span>\n ^\n<span>15</span>:<span>41</span>:<span>22</span> <span>,</span> cluster <span>,</span> db: depesz<span>-</span>rw@postgres<span>,</span> pid:<span>23229</span>\n<span>=&gt;</span></pre></div>\n<p>Well, that ain't nice. I tried to hide it with adding <em>\\set QUIET</em> in the beginning, and <em>\\unset QUIET</em> at the end, but it didn't help.</p>\n<p>Luckily, psql has conditionals. So I can first check if the function is there. While working on it I also discovered that smi returns old names of pgroles, so I have to map it to new ones. Trivial. New version:</p>\n<div><pre>\\<span>SET</span> QUIET\n<span>SELECT</span> <span>EXISTS</span><span>(</span>\n <span>SELECT</span> <span>1</span>\n <span>FROM</span> pg_proc p\n <span>JOIN</span> pg_namespace n <span>ON</span> p<span>.</span>pronamespace <span>=</span> n<span>.</span>oid\n <span>WHERE</span> p<span>.</span>proname <span>=</span> <span>'smi'</span> <span>AND</span> n<span>.</span>nspname <span>=</span> <span>'dba'</span>\n<span>)</span> \\gset smi_\n\\<span>IF</span> :smi_exists\n <span>SELECT</span>\n dba<span>.</span>smi<span>(</span><span>'aws_tag_project'</span><span>)</span> <span>AS</span> project<span>,</span>\n dba<span>.</span>smi<span>(</span><span>'aws_tag_environment'</span><span>)</span> <span>AS</span> env<span>,</span>\n dba<span>.</span>smi<span>(</span><span>'aws_tag_cluster'</span><span>)</span> <span>AS</span> cluster<span>,</span>\n <span>CASE</span> dba<span>.</span>smi<span>(</span><span>'aws_tag_pgrole'</span><span>)</span>\n <span>WHEN</span> <span>'master'</span> <span>THEN</span> <span>'primary'</span>\n <span>WHEN</span> <span>'slave'</span> <span>THEN</span> <span>'secondary'</span>\n <span>WHEN</span> <span>'backup'</span> <span>THEN</span> <span>'report'</span>\n <span>ELSE</span> dba<span>.</span>smi<span>(</span><span>'aws_tag_pgrole'</span><span>)</span>\n <span>END</span> <span>AS</span> pgrole \\gset smi_\n \\<span>SET</span> PROMPT1 <span>'%`date +%H:%M:%S` %:smi_project: %:smi_env:, cluster %:smi_cluster:, %:smi_pgrole: db: %n@%/, pid:%p<span>\\n</span>%x%R%# '</span>\n\\<span>ELSE</span>\n \\<span>SET</span> PROMPT1 <span>'%`date +%H:%M:%S` db: %n@%/, pid:%p<span>\\n</span>%x%R%# '</span>\n\\endif\n\\unset QUIET</pre></div>\n<p>Amazing. Now, when I try to connect to database that doesn't have dba.smi(), I just get plain prompt:</p>\n<div><pre>16:04:14 db: depesz-rw@postgres, pid:5144\n=&gt;</pre></div>\n<p>All is well, and am ready to push to production. Just sanity check, I'll connect, like any user would, through a pgbouncer, that's just formality. Right? Not quite:</p>\n<div><pre>16:05:40 magic production, cluster 1, report db: depesz-rw@appdb, pid:830285059\n=&gt;</pre></div>\n<p>Well, it looks OK, but the pid is definitely incorrect. Apparently whatever psql displays as pid (%p) is not really pid when connecting through pgBouncer.</p>\n<p>Luckily, that is simple to work around. I will just get the pid using select query:</p>\n<div><pre><span>SELECT</span> pg_backend_pid<span>(</span><span>)</span> \\gset</pre></div>\n<p>and then, instead of %p, will use %:pg_backend_pid:.</p>\n<p>Simple, and works.</p>\n<p>But then it hit me: what will happen if I will connect to the special, magical, <em>pgbouncer</em> database? Users don't do it, but I might. In case you don't know – when you connect through pgbouncer, there is special “database\" named <em>pgbouncer</em> where you can connect, and display some info from pgbouncer itself. Basically admin interface for pgbouncer.</p>\n<p>Surely it will work, right? Well, no:</p>\n<div><pre>psql:<span>/</span>home<span>/</span>depesz<span>/.</span>psqlrc:<span>3</span>: ERROR: invalid command <span>'SELECT pg_backend_pid() '</span><span>,</span> <span>USE</span> <span>SHOW</span> HELP;\npsql:<span>/</span>home<span>/</span>depesz<span>/.</span>psqlrc:<span>10</span>: ERROR: invalid command <span>'select EXISTS(\n SELECT 1\n from pg_proc p\n join pg_namespace n on p.pronamespace = n.oid\n where p.proname = '</span>smi<span>' and n.nspname = '</span>dba<span>'\n) '</span><span>,</span> <span>USE</span> <span>SHOW</span> HELP;\npsql:<span>/</span>home<span>/</span>depesz<span>/.</span>psqlrc:<span>12</span>: error: unrecognized <span>VALUE</span> <span>\":smi_exists\"</span> <span>FOR</span> <span>\"<span>\\i</span>f expression\"</span>: <span>BOOLEAN</span> expected</pre></div>\n<p>Apparently this magical pgbouncer database doesn't handle selects. At all:</p>\n<div><pre><span>=</span># <span>SELECT</span> <span>1</span>;\nERROR: invalid command <span>'select 1;'</span><span>,</span> <span>USE</span> <span>SHOW</span> HELP;</pre></div>\n<p>Well, OK. But that's simple. I will just check if database name is pgbouncer, and if yes – use simpler prompt. And when it's not – use normal code.</p>\n<p>psql even helpfully has DBNAME variable, so it should be easy. Right?</p>\n<div><pre><span>=</span># \\<span>IF</span> :DBNAME <span>=</span> pgbouncer\nunrecognized <span>VALUE</span> <span>\"pgbouncer = pgbouncer\"</span> <span>FOR</span> <span>\"<span>\\i</span>f expression\"</span>: <span>BOOLEAN</span> expected</pre></div>\n<p>Apparently psql's \\if expression can only parse single value, and it has to be one of: true, false, 1, 0, on, off, yes, no.</p>\n<p>So, how to get one of these, let's say 1/0, if the dbname is pgbouncer? I can't use select. I can't use logic in \\if…. cue despair.</p>\n<p>Luckily, in <a target=\"_blank\" href=\"https://www.postgresql.org/docs/12/app-psql.html#PSQL-METACOMMAND-IF\">docs</a> I found this bit:</p>\n<blockquote><p>The expression argument of an \\if or \\elif command is subject to variable interpolation and backquote expansion</p></blockquote>\n<p><em>backquote</em>. So I can call shell! Solution became obvious:</p>\n<div><pre>\\<span>IF</span> <span>`test :DBNAME = pgbouncer &amp;&amp; echo 1 || echo 0`</span></pre></div>\n<p>this requires that we have test program installed, but it's by default everywhere, so I don't care. Much.</p>\n<p>So, all things said, finally the psqlrc is:</p>\n<div><pre><span>-- Hide confirmation messages</span>\n\\<span>SET</span> QUIET\n<span>-- Check if we're connecting to database pgbouncer. It is very limited, and can't run SELECT's</span>\n\\<span>IF</span> <span>`test :DBNAME = pgbouncer &amp;&amp; echo 1 || echo 0`</span>\n <span>-- This is pgbouncer. User plain prompt</span>\n \\<span>SET</span> PROMPT1 <span>'%`date +%H:%M:%S` db: %n@%/<span>\\n</span>%x%R%# '</span>\n\\<span>ELSE</span>\n <span>-- This isn't pgbouncer. So we should have SELECTs available</span>\n <span>-- If we're connecting through pgbouncer, then prompt's %p is not real, so get real PID</span>\n <span>SELECT</span> pg_backend_pid<span>(</span><span>)</span> \\gset\n <span>-- Check if there is dba.smi() function</span>\n <span>SELECT</span> <span>EXISTS</span><span>(</span><span>SELECT</span> <span>1</span> <span>FROM</span> pg_proc p <span>JOIN</span> pg_namespace n <span>ON</span> p<span>.</span>pronamespace <span>=</span> n<span>.</span>oid <span>WHERE</span> p<span>.</span>proname <span>=</span> <span>'smi'</span> <span>AND</span> n<span>.</span>nspname <span>=</span> <span>'dba'</span><span>)</span> \\gset smi_\n \\<span>IF</span> :smi_exists\n <span>-- If dba.smi() exists, get data from it, and put it in prompt.</span>\n <span>SELECT</span>\n dba<span>.</span>smi<span>(</span><span>'aws_tag_project'</span><span>)</span> <span>AS</span> project<span>,</span>\n dba<span>.</span>smi<span>(</span><span>'aws_tag_environment'</span><span>)</span> <span>AS</span> env<span>,</span>\n dba<span>.</span>smi<span>(</span><span>'aws_tag_cluster'</span><span>)</span> <span>AS</span> cluster<span>,</span>\n <span>CASE</span> dba<span>.</span>smi<span>(</span><span>'aws_tag_pgrole'</span><span>)</span>\n <span>WHEN</span> <span>'master'</span> <span>THEN</span> <span>'primary'</span>\n <span>WHEN</span> <span>'slave'</span> <span>THEN</span> <span>'secondary'</span>\n <span>WHEN</span> <span>'backup'</span> <span>THEN</span> <span>'report'</span>\n <span>ELSE</span> dba<span>.</span>smi<span>(</span><span>'aws_tag_pgrole'</span><span>)</span>\n <span>END</span> <span>AS</span> pgrole \\gset smi_\n \\<span>SET</span> PROMPT1 <span>'%`date +%H:%M:%S` %:smi_project: %:smi_env:, cluster %:smi_cluster:, %:smi_pgrole: db: %n@%/, pid:%:pg_backend_pid:<span>\\n</span>%x%R%# '</span>\n \\<span>ELSE</span>\n <span>-- If dba.smi() is not available, pick simpler prompt</span>\n \\<span>SET</span> PROMPT1 <span>'%`date +%H:%M:%S` db: %n@%/, pid:%:pg_backend_pid:<span>\\n</span>%x%R%# '</span>\n \\endif\n\\endif\n<span>-- Common settings, regardless of dba.smi() existence</span>\n\\<span>SET</span> PROMPT2 <span>'%R%# '</span>\n\\pset <span>NULL</span> <span>'[null]'</span>\n<span>-- Use sensible pager</span>\n\\pset pager always\n\\setenv PAGER <span>'less -iMFXSx4R'</span>\n<span>-- It's 21st century, let's use unicode for borders</span>\n\\pset linestyle unicode\n<span>-- Stop hiding confirmation messages</span>\n\\unset QUIET\n<span>-- vim: set ft=sql:</span></pre></div>\n<p>and it does what I wanted it to do. Installed it as /etc/postgresql-common/psqlrc everywhere, and it works.</p>\n<p>When I showed it to colleague, he said: <em>I had no idea psqlrc files could be so complex</em>. And this kinda prompted me to write this blogpost. They (psqlrcs) can. They can do a lot of things, and if writing them doesn't seem simple – it's because we rarely do. But, I think, it's worth it.</p>\n\t</div>\n</article>",
"author": "",
"favicon": "",
"source": "depesz.com",
"published": "",
"ttr": 231,
"type": ""
}