pg_get_viewdef() 是一个系统函数,用于生成重新创建指定视图或物化视图所需的 SQL。
pg_get_viewdef() 在 PostgreSQL 6.4 中被添加。
用法
pg_get_viewdef ( view oid [, pretty boolean ] ) → text
pg_get_viewdef ( view oid, wrap_column integer ) → text
pg_get_viewdef ( view text [, pretty boolean ] ) → text
请注意,返回的 text 值是从元数据中重建的,并非原始 CREATE VIEW 或 CREATE MATERIALIZED VIEW 命令的逐字文本。
第三个变体已弃用。
变更历史
- PostgreSQL 9.3
- 输出始终缩进 (commit 62e66640)
- PostgreSQL 7.4
- 添加了
pretty选项 (commit 52347b66)
- 添加了
- PostgreSQL 6.4
- 添加于(提交 15cb32d9)
示例
使用以下视图定义对 pg_get_viewdef() 的基本用法示例
postgres=# CREATE TABLE foo ( id INT NOT NULL, val TEXT, ts TIMESTAMP WITH TIME ZONE ); CREATE TABLE postgres=# CREATE VIEW bar AS SELECT * FROM foo WHERE ts >= '2022-01-01'; CREATE VIEW
基本形式返回视图定义的详细渲染,类似于 pg_dump 发出的内容。
postgres=# SELECT pg_get_viewdef('bar'::regclass);
pg_get_viewdef
-------------------------------------------------------------------------
SELECT foo.id, +
foo.val, +
foo.ts +
FROM foo +
WHERE (foo.ts >= '2022-01-01 00:00:00+09'::timestamp with time zone);
(1 row)
可选的 pretty 标志会生成一个不那么详细的版本,主要避免嵌套括号。
postgres=# SELECT pg_get_viewdef('bar', true);
pg_get_viewdef
-----------------------------------------------------------------------
SELECT foo.id, +
foo.val, +
foo.ts +
FROM foo +
WHERE foo.ts >= '2022-01-01 00:00:00+09'::timestamp with time zone;
(1 row)
第二个版本的 pg_get_viewdef() 允许提供一个整数值,该值尝试将行合并到提供的数值为止。
postgres=# SELECT pg_get_viewdef('bar'::regclass, 30);
pg_get_viewdef
-----------------------------------------------------------------------
SELECT foo.id, foo.val, +
foo.ts +
FROM foo +
WHERE foo.ts >= '2022-01-01 00:00:00+09'::timestamp with time zone;
(1 row)
postgres=# SELECT pg_get_viewdef('bar'::regclass, 50);
pg_get_viewdef
-----------------------------------------------------------------------
SELECT foo.id, foo.val, foo.ts +
FROM foo +
WHERE foo.ts >= '2022-01-01 00:00:00+09'::timestamp with time zone;
(1 row)
参考资料
- PostgreSQL 文档: 系统目录信息函数
另请参阅
pg_get_constraintdef(), pg_get_functiondef(), pg_get_indexdef(), pg_get_ruledef(), pg_get_statisticsobjdef(), pg_get_triggerdef()
