每天都省时间的 PostgreSQL 元命令
大多数人刚开始接触 PostgreSQL 时,最先学会的是 SQL:
SELECT*FROMemployees;但很快,psql 里会展开另一个世界——一类看起来不像 SQL、也不以分号结尾的命令。
这就是PostgreSQL 元命令(Meta Commands),它们悄无声息地支撑着几乎所有资深 DBA 的日常工作流。
元命令不负责查询数据,它们关注的是高效地导航、检视和控制 PostgreSQL 会话与数据库。
元命令究竟是什么?
元命令是由 psql 解释的特殊指令,而不是由 PostgreSQL 本身解释的。
这意味着:
- 它们不是 SQL
- 它们在客户端即时执行
- 它们是 psql 终端工具专有的
- 它们不像 SQL 语句那样以分号结尾
- 元命令的主战场是与数据库的交互,而不是与数据库中数据的交互
速查表(快速参考)
以下是使用频率最高的元命令。除此之外还有很多,但下面这些是最常用的。
连接与会话管理
这些命令帮助你发现数据库、建立连接,以及确认当前会话状态。
| 命令 | 说明 |
|---|---|
\c | 连接到另一个数据库 |
\l | 列出集群中所有可用的数据库 |
\l+ | 列出集群中所有可用的数据库,并显示更多细节,如数据库大小等 |
\conninfo | 显示当前数据库连接的信息 |
下面是连接与会话管理相关命令的示例(原文截图已改写为文本):
postgres=# \c salesdb You are now connected to database "salesdb" as user "postgres". salesdb=# \l List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges -----------+----------+----------+-------------+-------------+----------------------- postgres | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | salesdb | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | 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 | =c/postgres + | | | | | postgres=CTc/postgres (4 rows) salesdb=# \l+ List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges | Size | Tablespace | Description -----------+----------+----------+-------------+-------------+-------------------+---------+------------+------------- postgres | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | | 8553 kB | pg_default | salesdb | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | | 12 MB | pg_default | template0 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres +| 8553 kB | pg_default | unmodifiable | | | | | postgres=CTc/... | | | template1 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres +| 8713 kB | pg_default | default template | | | | | postgres=CTc/... | | | (4 rows) salesdb=# \conninfo You are connected to database "salesdb" as user "postgres" on host "localhost" (address "127.0.0.1") at port "5432".检视数据库对象
\d系列命令是 psql 最强大的功能之一。这些命令可用于发现数据库对象、查看它们的定义,以及查看额外的元数据。
| 命令 | 说明 |
|---|---|
\d | 描述数据库对象,或列出当前 search_path 中可见的对象 |
\d object_name | 描述指定的表、视图、序列或其他数据库对象 |
\d+ object_name | 显示某个对象的扩展信息 |
\dt | 列出表。支持 schema 名和通配符模式 |
\di | 列出索引。支持通配符模式 |
\dn | 列出当前数据库中的 schema |
\du | 列出数据库角色 |
\db | 列出表空间 |
\dx | 列出已安装的扩展 |
\df | 列出函数和存储过程 |
\sf function_name | 显示指定函数/存储过程的源代码 |
使用对象名与通配符
大多数对象检视类命令都接受对象名、带 schema 限定的名称,以及通配符模式。
例如:
\dt列出当前 search_path 中的所有表。
\dtpublic.*列出publicschema 中的所有表。
其他若干元命令也支持同样的模式匹配,包括\di、\df以及\d系列。
下面是\d系列命令的示例(原文截图已改写为文本):
salesdb=# \d List of relations Schema | Name | Type | Owner --------+-----------------------------+----------+---------- public | customers | table | postgres public | customers_customer_id_seq | sequence | postgres public | order_items | table | postgres public | orders | table | postgres public | products | table | postgres public | v_monthly_sales | view | postgres (6 rows) salesdb=# \dt public.* List of relations Schema | Name | Type | Owner --------+--------------+-------+---------- public | customers | table | postgres public | order_items | table | postgres public | orders | table | postgres public | products | table | postgres (4 rows) salesdb=# \d orders Table "public.orders" Column | Type | Collation | Nullable | Default -------------+-----------------------------+-----------+----------+----------------------------------- order_id | bigint | | not null | nextval('orders_order_id_seq'::regclass) customer_id | integer | | not null | order_date | timestamp without time zone | | not null | now() status | character varying(20) | | not null | 'pending'::character varying total_amount| numeric(12,2) | | | 0 Indexes: "orders_pkey" PRIMARY KEY, btree (order_id) "idx_orders_customer_id" btree (customer_id) "idx_orders_order_date" btree (order_date) Foreign-key constraints: "orders_customer_id_fkey" FOREIGN KEY (customer_id) REFERENCES customers(customer_id) Referenced by: TABLE "order_items" CONSTRAINT "order_items_order_id_fkey" FOREIGN KEY (order_id) REFERENCES orders(order_id) salesdb=# \d+ orders Table "public.orders" Column | Type | Storage | Compression | Stats target | Description -------------+-----------------------------+----------+-------------+--------------+------------- order_id | bigint | plain | | | ... Indexes: "orders_pkey" PRIMARY KEY, btree (order_id) Access method: heap salesdb=# \di List of relations Schema | Name | Type | Owner | Table --------+------------------------+-------+----------+------------- public | idx_orders_customer_id | index | postgres | orders public | idx_orders_order_date | index | postgres | orders public | orders_pkey | index | postgres | orders (3 rows) salesdb=# \dn List of schemas Name | Owner --------+------------------- audit | postgres public | pg_database_owner (2 rows) salesdb=# \du List of roles Role name | Attributes | Member of -----------+------------------------------------------------------------+----------- app_rw | | {} postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {} salesdb=# \db List of tablespaces Name | Owner | Location ------------+----------+---------- pg_default | postgres | pg_global | postgres | (2 rows) salesdb=# \dx List of installed extensions Name | Version | Schema | Description -----------+---------+------------+------------------------------------------------------------------- pg_stat_statements | 1.10 | public | track planning and execution statistics of all SQL statements plpgsql | 1.0 | pg_catalog | PL/pgSQL procedural language (2 rows)格式化查询结果
有若干元命令可以改善查询输出的可读性,在处理宽结果集时尤其有用。
| 命令 | 说明 |
|---|---|
\x [on|off|auto] | 切换扩展(纵向)显示模式 |
\o filename | 将查询输出重定向到文件或管道 |
\o | 将查询输出恢复为输出到终端 |
监控查询执行
这些命令有助于衡量查询性能,并可反复执行查询以便持续监控。
| 命令 | 说明 |
|---|---|
\timing [on|off] | 切换查询执行耗时显示 |
\watch seconds | 按指定间隔重复执行当前查询 |
执行与自动化任务
这些命令可以简化重复性工作,并打通 psql、SQL 脚本与操作系统之间的协作。
| 命令 | 说明 |
|---|---|
\i filename | 执行文件中的命令 |
\gexec | 将查询返回的每个字段作为一条 SQL 语句执行 |
\! command | 不退出 psql 提示符即可执行 shell 命令 |
获取帮助
内置的帮助命令让你无需离开终端,就能快速查阅 psql 元命令文档和 PostgreSQL SQL 语法。
| 命令 | 说明 |
|---|---|
\? | 显示所有可用的 psql 元命令 |
\h | 列出可查看语法帮助的 SQL 命令 |
\h command | 显示某条具体 SQL 命令的语法帮助 |
什么是 .psqlrc?
.psqlrc是位于用户主目录下的启动文件,psql 在会话开始时读取它。它里面可以存放元命令和 SQL,在第一个提示符出现之前自动执行。它的主要价值在于保持默认配置的一致性——耗时统计、输出格式、自定义提示符等——不必每次重复设置,从而加快日常工作,并减少跨数据库连接时的失误。
一个最简的.psqlrc可能长这样:
\timingon\x auto这些设置在每一个新的 psql 会话中都会自动加载。效果如下(原文截图已改写为文本):
$ psql -d salesdb Timing is on. Expanded display is used automatically. psql (17.2) Type "help" for help. salesdb=# SELECT count(*) FROM orders; count ------- 24531 (1 row) Time: 12.483 ms可以看到,无需手动输入\timing on,耗时统计就已经开启;当结果集较宽时,输出也会自动切换为纵向(expanded)模式。
结论
PostgreSQL 的强大来自 SQL——但对 DBA 来说,psql 元命令让日常管理变得轻松得多、也高效得多。
多数开发者只用到少数几个命令,比如\dt或\d。但经验丰富的 DBA 依赖的是一整套更丰富的工具箱,以便:
- 更快地排查生产问题
- 高效地在大系统中导航
- 减少对重复 SQL 的依赖
- 将重复性任务自动化
- 快速调试复杂问题
理解 SQL 与 PostgreSQL 元命令之间关系的一个简单方式,是把它们比作开车。
SQL 就像开车本身——它是抵达目的地的根本手段。它用来检索、插入、更新和删除数据,让应用和用户能够与数据库中存储的信息进行交互。
而元命令则像是汽车的仪表盘。仪表盘本身不会驱动车辆前进,但它提供了速度、油量、发动机健康状况、导航状态以及各类告警等关键信息。没有仪表盘当然也能开车,但那意味着你在对车辆状况和性能了解极其有限的情况下行驶。
同理,SQL 负责操纵和检索数据,而 PostgreSQL 元命令则让你看清数据库环境本身。它们帮助管理员检视数据库对象、穿行于各类 schema、监控会话、查看角色与权限、复查对象定义,并高效完成大量管理任务。
本质上,SQL 让你与数据交互,而元命令让你与PostgreSQL 环境交互。二者共同构成一套互补的工具组合,让数据库专业人员工作更高效、排障更迅速、管理 PostgreSQL 更有底气。