Revealing the Queries Behind psql’s Backslash Commands
PostgreSQL‘s psql interactive terminal tool provides several useful “backslash list commands” such as \d
(lists “relations” such as tables, views, indexes, and sequences), \dt
(lists tables), \di
(lists indexes), \ds
(lists sequences), \dv
(lists views), \df
(lists functions), \du
(lists roles), and \?
(displays help/usage details on backslash commands). These commands are concise and much simpler to use than writing the queries against PostgreSQL system catalogs (pg_class, pg_roles, pg_namespace, pg_trigger, pg_index, etc.) and information_schema that would provide the same types of details.
Although the psql
backslash commands are easier to use than their associated queries, there are situations when it is important to know the full query behind a particular command. These situations include needing to perform a slightly different/adapted query from that associated with the pre-built command and needing to perform similar queries in scripts or code that are being used as PostgreSQL clients instead of psql
. These situations make it important to be able to determine what queries psql
is performing and the psql
option -E
(or --echo-hidden
) allow that.
The PostgreSQL psql documentation states that the psql
options -E
and --echo-hidden
“echo the actual queries generated by \d
and other backslash commands.” The documentation adds commentary on why this is useful, “You can use this to study psql’s internal operations.” When psql
is started with the -E
or --echo-hidden
options, it will display the query associated with a backslash command before executing that command. The next screen snapshot illustrates this for the \du
command used to show roles.
From use of psql -E
and execution of the command \du
, we’re able to see that the query underling \du
is this:
1 2 3 4 5 6 7 8 9 10 11 12 | SELECT r.rolname, r.rolsuper, r.rolinherit, r.rolcreaterole, r.rolcreatedb, r.rolcanlogin, r.rolconnlimit, r.rolvaliduntil, ARRAY( SELECT b.rolname FROM pg_catalog.pg_auth_members m JOIN pg_catalog.pg_roles b ON (m.roleid = b.oid) WHERE m.member = r.oid) as memberof , r.rolreplication , r.rolbypassrls FROM pg_catalog.pg_roles r WHERE r.rolname !~ '^pg_' ORDER BY 1; |
Although the query is not nearly as nice to use as \du
, we are now able to adapt this query for a related but different use case and are able to run this query from a PostgreSQL client other than psql
.
Published on System Code Geeks with permission by Dustin Marx, partner at our SCG program. See the original article here: Revealing the Queries Behind psql’s Backslash Commands Opinions expressed by System Code Geeks contributors are their own. |