# psql 元命令

> 使用 psql 命令探索对象、格式化结果、运行脚本并自定义会话。

---

LLMS 索引： [llms.txt](/llms.txt)

---

`psql` 的元命令（也称*反斜线命令*）是客户端快捷操作，可以让交互式数据库探索变得快速而愉快。它们由客户端解释，而不是由服务器解释——在交互式环境中和通过 `psql -f` 读取的文件中都能工作。一旦用熟了这些命令，日常工作中的大多数场景都不再需要打开 GUI 工具。

## 本章要点 {#learn}

- 基本的探索命令（`\l`、`\dt`、`\d`、`\df`、`\dn`）
- 帮助快捷命令（`\?`、`\h`）
- 输出和格式化命令（`\x`、`\timing`、`\pset`）
- 运行脚本和保存输出（`\i`、`\o`、`\copy`）
- 使用 `~/.psqlrc` 自定义会话

## 示例 {#example}

```text {num="56.1" caption="psql 元命令"}
psql command reference (backslash commands also work in psql -f scripts):

Exploration
  \l                    list databases
  \c dbname             connect to a database
  \dn                   list schemas
  \dt                   list tables in the current search_path
  \dt schema.*          list tables in a specific schema
  \dt *.*               list every table everywhere
  \d table              describe a table (columns, types, indexes, constraints)
  \d+ table             describe a table verbosely (storage, comments)
  \di                   list indexes
  \dv                   list views
  \dm                   list materialized views
  \df pattern           list functions whose name matches
  \du                   list roles (users/groups)
  \dx                   list installed extensions

Help
  \?                    list all meta-commands
  \h                    list SQL commands
  \h SELECT             help on the SELECT statement

Session/output
  \x                    toggle expanded display (column-per-line)
  \timing               toggle showing query timing
  \pset pager off       disable the less-style pager
  \pset format aligned  default table format; alternatives include csv, html, unaligned
  \a                    toggle "unaligned" mode (use format csv for CSV escaping)
  \o file               redirect query output to a file (\o without arg disables)

Files and scripts
  \i file.sql           run a SQL script from inside psql
  \ir file.sql          run relative to the current script
  \copy table FROM 'file.csv' WITH (FORMAT csv, HEADER true)  client-side import
  \copy (SELECT ...) TO 'file.csv' WITH (FORMAT csv, HEADER true)  client-side export

Editing
  \e                    open the last query in $EDITOR (or write a new one)
  \ef function_name     open a function definition in $EDITOR
  \ev view_name         open a view definition in $EDITOR
  \q                    quit
```

`psql -f script.sql` 会同时处理 SQL 和反斜线命令。下面链接的 SQL 文件展示了查询系统目录的替代方案；当调用方是数据库驱动而不是 psql 时，这些方案很有用。不要把本命令参考中的说明性标签粘贴到脚本中。

最有用的命令是 `\d table`（以及它的详细版本 `\d+ table`）。它会显示列、类型、默认值、索引、约束、外键和触发器——你需要了解一张表结构的所有信息。

最有用的*显示切换命令*是 `\x`（扩展显示）。对于有 30 列的行，默认的表格输出无法阅读；扩展显示会将 `column | value` 按每行一项打印。使用 `\x auto`，只有当行对终端来说太宽时才切换显示方式。

`\copy` 是 `COPY` 在客户端一侧的对应命令。它在*客户端*机器上读写文件；`COPY` 则在*服务器*上读写文件。要将 CSV 装载到远程 PostgreSQL 中，应使用 `\copy`。

## 运行示例 {#run}

运行本课的 SQL 部分：

```text
$ psql -f source/psql-meta-commands.sql postgres
 ...
 current_database | current_user | current_schema
------------------+--------------+----------------
 postgres         | your_user    | public
(1 row)
 ...
```

## 常见陷阱 {#pitfalls}

- 通过数据库驱动直接发送 `\dt` 会失败，因为它是 psql 语法。它可以在交互式环境中工作，也可以在由 `psql -f` 执行的文件中运行。
- 不带参数的 `\d` 会列出当前 `search_path` 中的*所有内容*——输出很长。可以使用 `\dt`、`\di`、`\dv` 等命令进行筛选。
- `\copy` 和 `COPY`：`\copy` 在客户端运行（因此相对路径是客户端路径，CSV 文件来自你的机器）；`COPY` 在服务器上运行。根据文件所在位置选择正确的命令。
- 你的 `psqlrc` 会在每次会话开始时运行。其中一条语句损坏，就可能让 psql 无法使用，直到你修复该文件。

> [!TIP] 提示
> `~/.psqlrc` 用来保存你的自定义设置。常见条目包括：
>
> ```text
> \set PROMPT1 '%n@%/%x%R%# '
> \set HISTSIZE 5000
> \timing on
> \pset null '∅'
> \set COMP_KEYWORD_CASE upper
> ```

> [!NOTE] 动手练习
> 在交互式 `psql postgres` 会话中，运行 `\dt`、`\d fruits`、`\df *agg*`，然后运行 `\h SELECT`。切换 `\x`，再运行 `SELECT * FROM pg_indexes LIMIT 1;`，查看扩展显示。运行一个查询并将输出通过管道写入文件：`\o out.txt`、`SELECT * FROM fruits;`、`\o`（停止重定向）。

## 下载 {#downloads}

SQL 文件：[psql-meta-commands.sql](/examples/source/psql-meta-commands.sql) · [全部示例文件](/examples/examples.zip) · [准备工作](/#prerequisites)
