PostgreSQL 实用技巧合集

December 24, 2025

PostgreSQL 实用技巧合集

本文汇总了 PostgreSQL 日常使用中的一些实用技巧。


导出整个数据库的表结构 (DDL) 并包含注释

如果你想导出整个数据库的所有表结构 (DDL),并且包含注释 (COMMENT),可以通过以下几种常用方法实现。

方法 1:使用 pg_dump(推荐)

PostgreSQL 自带的 pg_dump 工具可以直接导出表结构(不包含数据)并包含注释。

pg_dump -U 用户名 -d 数据库名 -s -f schema.sql

参数说明:

参数说明
-U 用户名连接数据库的用户名
-d 数据库名数据库名称
-s只导出 schema(DDL),不导出数据
-f schema.sql输出文件路径

这样导出的 schema.sql 文件中会包含:

  • 所有表的 CREATE TABLE 语句
  • 所有索引、约束、序列、视图等 DDL
  • 所有注释(COMMENT ON TABLE、COMMENT ON COLUMN 等)

例子:

pg_dump -U postgres -d mydb -s -f /tmp/mydb_schema.sql

方法 2:导出指定 schema

如果你只想导出某个 schema 下的表结构:

pg_dump -U 用户名 -d 数据库名 -n schema_name -s -f schema_name.sql

例如:

pg_dump -U postgres -d mydb -n public -s -f public_schema.sql

方法 3:使用 pg_get_tabledef()(PostgreSQL 16+)

PostgreSQL 16 开始提供原生函数直接返回完整的 CREATE TABLE:

SELECT pg_get_tabledef('public.my_table'::regclass);

⚠️ Warning: 该函数仅在 PostgreSQL 16+ 版本中可用,早期版本没有此函数。

方法 4:使用 pgAdmin / DBeaver GUI 导出

在图形化工具中(如 pgAdmin、DBeaver):

  1. 右键数据库或 schema → Generate SQL → DDL Script
  2. 选择是否包括:
    • Tables
    • Views
    • Comments
    • Indexes
    • Sequences
  3. 导出即可生成完整的带注释 DDL。

方法 5:查询系统表导出注释

导出所有表的注释:

SELECT
  'COMMENT ON TABLE ' || c.relname || ' IS ''' || d.description || ''';'
FROM pg_class c
JOIN pg_description d ON c.oid = d.objoid
WHERE c.relkind = 'r'
  AND d.objsubid = 0;

导出所有列的注释:

SELECT
  'COMMENT ON COLUMN ' || c.relname || '.' || a.attname || ' IS ''' || d.description || ''';'
FROM pg_description d
JOIN pg_class c ON c.oid = d.objoid
JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = d.objsubid
WHERE c.relkind = 'r'
  AND d.objsubid > 0;

最佳实践总结

目的推荐方法
导出整个数据库 DDL + 注释pg_dump -s ✅
导出指定 schemapg_dump -n schema_name -s ✅
单表结构 (PostgreSQL 16+)pg_get_tabledef()
图形化导出pgAdmin / DBeaver
脚本生成注释查询 pg_description

pg_dump 执行环境详解

pg_dump 是 PostgreSQL 客户端工具,可以在以下地方运行:

操作系统命令行

系统执行位置
Linux / macOS终端 (Terminal)
WindowsPowerShell 或 cmd

pg_dump 安装路径

系统默认安装路径
Linux (apt/yum)/usr/bin/pg_dump 或 /usr/pgsql-<version>/bin/pg_dump
macOS (Homebrew)/usr/local/bin/pg_dump 或 /opt/homebrew/bin/pg_dump
WindowsC:\Program Files\PostgreSQL\<version>\bin\pg_dump.exe

确认路径:

# Linux/macOS
which pg_dump

# Windows
where pg_dump

确认版本:

pg_dump --version

连接参数

pg_dump 通过网络连接 PostgreSQL,常用参数:

参数说明
-h数据库服务器地址
-p端口(默认 5432)
-U用户名
-d数据库名

完整例子:

pg_dump -h localhost -p 5432 -U postgres -d mydb -s -f schema.sql

Docker 容器中的数据库

如果数据库运行在 Docker 容器中:

方式一:进入容器执行

docker exec -it postgres_container bash
pg_dump -U postgres -d mydb -s > /tmp/schema.sql

方式二:从宿主机通过网络访问

pg_dump -h 127.0.0.1 -p 5432 -U postgres -d mydb -s -f schema.sql

执行环境总结

场景执行位置示例命令
本地数据库本机命令行pg_dump -U postgres -d mydb -s -f schema.sql
远程数据库本机命令行 + -h 参数pg_dump -h remote_ip -U user -d db -s -f schema.sql
Docker 内数据库容器内执行docker exec -it pg bash -c "pg_dump -U postgres -d db -s > /tmp/schema.sql"
WindowsPowerShell / CMDpg_dump -U postgres -d mydb -s -f "C:\path\schema.sql"

从 Amazon RDS 导出 DDL

RDS 不能登录数据库主机,但 pg_dump 是客户端工具——只要你的机器能连到 RDS 的 5432 端口,就可以直接导出。

方案 A:本机直连 RDS

前提:RDS "Publicly accessible = Yes",安全组放行你当前公网 IP 的 TCP 5432。

pg_dump \
  -h your-rds-endpoint.rds.amazonaws.com \
  -p 5432 \
  -U dbuser \
  -d dbname \
  -s \
  --no-owner --no-privileges \
  --sslmode=require \
  --sslrootcert=/path/to/rds-combined-ca-bundle.pem \
  -f schema.sql

💡 Tip: --sslmode=require + AWS RDS CA 证书更稳。证书文件到 AWS 官方下载,保存为 rds-combined-ca-bundle.pem。

方案 B:RDS 不对公网开放(走跳板或端口转发)

B1. SSH 跳板(你有一台在同 VPC 的 EC2)

# 本地开隧道:把本地 5432 → RDS:5432,通过 bastion 主机
ssh -i your-key.pem -L 5432:your-rds-endpoint.rds.amazonaws.com:5432 ec2-user@bastion-ec2-public-ip

开着这个终端不关,另起一个终端跑:

pg_dump -h 127.0.0.1 -p 5432 -U dbuser -d dbname -s \
  --sslmode=require --sslrootcert=/path/to/rds-combined-ca-bundle.pem \
  -f schema.sql

B2. AWS SSM Session Manager 端口转发(无公网也可)

前提:一台装了 SSM Agent 的 EC2 在同 VPC,且能访问 RDS 5432,且你本地已配置 awscli。

aws ssm start-session \
  --target i-xxxxxxxxxxxxxxxxx \
  --document-name AWS-StartPortForwardingSession \
  --parameters "localPortNumber=5432,portNumber=5432,host=your-rds-endpoint.rds.amazonaws.com"

开好后,用 -h 127.0.0.1 -p 5432 跑 pg_dump。

方案 C:在 VPC 内跑 pg_dump

在同 VPC/子网里起一台小 EC2(或用已有运维机),安装 PostgreSQL 客户端,然后直接:

pg_dump -h your-rds-endpoint.rds.amazonaws.com -p 5432 -U dbuser -d dbname -s \
  --sslmode=require --sslrootcert=/path/to/rds-combined-ca-bundle.pem \
  -f /tmp/schema.sql

再把文件 scp 回本地即可。

可选:用 IAM 数据库认证(免存密码)

RDS PostgreSQL 支持 IAM 令牌作为"临时密码"(约 15 分钟有效)。需要为数据库用户启用 IAM 认证。

TOKEN=$(aws rds generate-db-auth-token \
  --hostname your-rds-endpoint.rds.amazonaws.com \
  --port 5432 \
  --region your-region \
  --username dbuser)

PGPASSWORD="$TOKEN" pg_dump \
  -h your-rds-endpoint.rds.amazonaws.com \
  -p 5432 \
  -U dbuser \
  -d dbname \
  -s \
  --sslmode=require --sslrootcert=/path/to/rds-combined-ca-bundle.pem \
  -f schema.sql

RDS 常见问题自检清单

检查项说明
安全组RDS 的 SG 必须允许来源(你的公网 IP / 跳板机 ENI)访问 5432
NACL子网的 NACL 不要拦截 5432
参数组若 rds.force_ssl=1,务必加 --sslmode=require 和 CA 证书
账号权限导出 DDL 需要能读取系统 catalog(一般普通用户即可)
版本匹配建议 pg_dump 版本 ≤ RDS 引擎主版本(相差过大偶有兼容问题)

使用连接字符串 (Connection String)

pg_dump 支持用 PostgreSQL 连接字符串 来代替 -h -p -U -d 这些参数。

URI 格式(最常见)

pg_dump 'postgresql://用户名:密码@主机:端口/数据库名?参数=值' -s -f schema.sql

示例:

pg_dump 'postgresql://dbuser:MyP@[email protected]:5432/mydb?sslmode=require' -s -f schema.sql

keyword=value 格式

也可以用空格分隔的键值对:

pg_dump 'host=your-rds-endpoint.rds.amazonaws.com port=5432 dbname=mydb user=dbuser password=MyPassword sslmode=require' -s -f schema.sql

带上 RDS SSL 证书

如果你的 RDS 强制 SSL,可以加上:

pg_dump 'postgresql://dbuser:[email protected]:5432/mydb?sslmode=verify-full&sslrootcert=/path/to/rds-combined-ca-bundle.pem' -s -f schema.sql

密码特殊字符处理

URL 中密码如果含有特殊字符(如 @, #, ?, &, $),需要 URL 编码:

字符URL 编码
@%40
#%23
?%3F
&%26
$%24
%%25

例如:MyP@ss$word! → MyP%40ss%24word!

⚠️ Warning: 连接字符串务必使用单引号包裹!双引号在 shell 中会解析 $ 等特殊字符,导致密码被错误解析。

# 正确:使用单引号
pg_dump 'postgresql://user:Pa$$word@host:5432/db' -s -f schema.sql

# 错误:双引号会导致 $$ 被 shell 解析
pg_dump "postgresql://user:Pa$$word@host:5432/db" -s -f schema.sql

避免密码暴露

把密码放到环境变量里,而不是直接写在 URI 中:

export PGPASSWORD='MyP@ssword!'
pg_dump 'postgresql://[email protected]:5432/mydb?sslmode=require' -s -f schema.sql

或一次性写法:

PGPASSWORD='MyP@ssword!' pg_dump 'postgresql://[email protected]:5432/mydb?sslmode=require' -s -f schema.sql

连接字符串总结

方式示例
URI 连接串'postgresql://user:pass@host:5432/db?sslmode=require'
keyword=value'host=host port=5432 user=user password=pass dbname=db sslmode=require'
加 SSL 证书?sslmode=verify-full&sslrootcert=/path/to/rds-combined-ca-bundle.pem
环境变量存密码PGPASSWORD=... pg_dump 'postgresql://user@host/db'

References

  1. PostgreSQL Documentation - pg_dump. (n.d.). Retrieved December 24, 2025, from https://www.postgresql.org/docs/current/app-pgdump.html
  2. PostgreSQL Documentation - System Catalogs. (n.d.). Retrieved December 24, 2025, from https://www.postgresql.org/docs/current/catalogs.html
  3. AWS Documentation - Using SSL with a PostgreSQL DB instance. (n.d.). Retrieved December 24, 2025, from https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/PostgreSQL.Concepts.General.SSL.html
  4. AWS Documentation - IAM database authentication for MariaDB, MySQL, and PostgreSQL. (n.d.). Retrieved December 24, 2025, from https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.html

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-12-24). PostgreSQL 实用技巧合集. https://caiborui.com/blog/2025-12-24-zh-postgresql-tips

@misc{borui2025-092f635f,
  author = {borui},
  title = {{PostgreSQL 实用技巧合集}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-12-24-zh-postgresql-tips}
}