Writing a conditional psql script
psql
supports the conditional \if
, \elif
, \else
, and \endif
meta-commands. In this recipe, we will demonstrate some of them.
Getting ready
We want to improve the vartest.sql
script so that it runs VACUUM
if there are dead rows in that table.
How to do it…
We can add conditional commands to vartest.sql
, resulting in the following script:
\set needs_vacuum false
SELECT schemaname
, relname
, n_dead_tup
, n_live_tup
, n_dead_tup > 0 AS needs_vacuum
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 1
\gset
\if :needs_vacuum
\qecho Running VACUUM on table :"relname" in schema :"schemaname"
\qecho Rows before: :n_dead_tup dead, :n_live_tup live
VACUUM ANALYZE :schemaname.:relname;
\qecho Waiting 1 second...
SELECT pg_sleep(1);
SELECT n_dead_tup AS n_dead_tup_now
, n_live_tup AS n_live_tup_now
FROM pg_stat_user_tables
WHERE schemaname = :'schemaname' AND relname = :'relname&apos...