pg_get_indexdef() 是一个系统函数,用于生成重建指定索引所需的 SQL。
pg_get_indexdef() 在 PostgreSQL 6.4 中添加。
用法
pg_get_indexdef (indexoid[,columninteger,prettyboolean] ) →text
请注意,返回的文本是从元数据重建的,并非原始 CREATE INDEX 命令的 verbatim 文本。
变更历史
- PostgreSQL 9.3
- 输出始终缩进 (commit 62e66640)
- PostgreSQL 7.4
- 添加了
pretty选项 (commit 52347b66)
- 添加了
- PostgreSQL 6.4
- 添加(提交 f93b6974)
示例
假设有以下表定义
postgres=# CREATE TABLE foo (id INT PRIMARY KEY);
CREATE TABLE
postgres=# \d foo
Table "public.foo"
Column | Type | Collation | Nullable | Default
--------+---------+-----------+----------+---------
id | integer | | not null |
Indexes:
"foo_pkey" PRIMARY KEY, btree (id)
pg_get_indexdef() 可以为隐式创建的 foo_pkey 索引生成 CREATE INDEX 命令,如下所示:
postgres=# SELECT pg_get_indexdef('foo_pkey'::regclass);
pg_get_indexdef
-------------------------------------------------------------
CREATE UNIQUE INDEX foo_pkey ON public.foo USING btree (id)
(1 row)
如果 pretty 参数设置为 TRUE,则可以创建更简洁的定义(这需要将 column 参数设置为 0)
postgres=# SELECT pg_get_indexdef('foo_pkey'::regclass, 0, true);
pg_get_indexdef
------------------------------------------------------
CREATE UNIQUE INDEX foo_pkey ON foo USING btree (id)
(1 row)
如果指定了 column 参数,则仅返回该位置匹配的列名
postgres=# SELECT pg_get_indexdef('bar_cols'::regclass) ;
pg_get_indexdef
--------------------------------------------------------------
CREATE INDEX bar_cols ON public.bar USING btree (col1, col2)
(1 row)
postgres=# SELECT pg_get_indexdef('bar_cols'::regclass, 1, false),
pg_get_indexdef('bar_cols'::regclass, 2, true);
pg_get_indexdef | pg_get_indexdef
-----------------+-----------------
col1 | col2
(1 row)
在这种情况下,pretty 参数没有效果。
如果提供了无效的 column 参数,则返回空字符串
postgres=# SELECT pg_get_indexdef('bar_cols'::regclass, -1, true);
pg_get_indexdef
-----------------
(1 row)
参考资料
- PostgreSQL 文档: 系统目录信息函数
另请参阅
pg_get_constraintdef(), pg_get_functiondef(), pg_get_ruledef(), pg_get_statisticsobjdef(), pg_get_triggerdef(), pg_get_viewdef()
