显示 psql 内部用于显示数据库元信息的 SQL 命令

场景:你想了解更多关于系统目录的信息,或者想了解psql如何与后端交互。psql 使用各种 SQL 语句为不同的\d斜杠函数生成输出,但输出通常是隐藏的。

解决方案

  • 使用以下命令启动psql-E命令行选项
  • (在psql运行期间) 设置ECHO_HIDDEN为非零整数值

两者都会导致psql显示它生成的 SQL。 请注意,如果将ECHO_HIDDEN设置为noexec,则会显示 SQL 但不会执行它(这将有效地禁用信息性斜杠命令)。

elephant~$ psql -U postgres -E
psql (9.2.3)
Type "help" for help.

postgres=# \l
********* QUERY **********
SELECT d.datname as "Name",
       pg_catalog.pg_get_userbyid(d.datdba) as "Owner",
       pg_catalog.pg_encoding_to_char(d.encoding) as "Encoding",
       d.datcollate as "Collate",
       d.datctype as "Ctype",
       pg_catalog.array_to_string(d.datacl, E'\n') AS "Access privileges"
FROM pg_catalog.pg_database d
ORDER BY 1;
**************************

                                     List of databases
      Name       |   Owner   | Encoding |   Collate   |    Ctype    |   Access privileges   
-----------------+-----------+----------+-------------+-------------+-----------------------
 template0       | postgres  | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
                 |           |          |             |             | postgres=CTc/postgres
 template1       | postgres  | UTF8     | en_US.UTF-8 | en_US.UTF-8 | postgres=CTc/postgres+
                 |           |          |             |             | =c/postgres
 testdb          | testuser  | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
(3 rows)

postgres=# \set ECHO_HIDDEN noexec
postgres=# \l
********* QUERY **********
SELECT d.datname as "Name",
       pg_catalog.pg_get_userbyid(d.datdba) as "Owner",
       pg_catalog.pg_encoding_to_char(d.encoding) as "Encoding",
       d.datcollate as "Collate",
       d.datctype as "Ctype",
       pg_catalog.array_to_string(d.datacl, E'\n') AS "Access privileges"
FROM pg_catalog.pg_database d
ORDER BY 1;
**************************