【问题标题】:Function for generating queries to restore constraints after drop based on table with constraint information基于具有约束信息的表生成查询以在删除后恢复约束的功能
【发布时间】:2017-08-02 14:40:21
【问题描述】:

我必须删除我的 Postgres 数据库中的所有约束来更新 PK 和 FK 使用的数据类型。在此之前,我想确保我可以在更新后重建这些约束。首先,我执行下面的代码来获取一个包含三列 table_fromconnamepg_get_constraintdef 的表,其中包含所有约束信息。

select conrelid::regclass AS table_from, conname, pg_get_constraintdef(c.oid)
from   pg_constraint c
join   pg_namespace n ON n.oid = c.connamespace
where  contype in ('f', 'p','c','u') order by contype

table_from 包含表名,例如fooconname 约束的名称,例如fk_foo_2_barpg_get_constraintdef 包含约束定义,例如
FOREIGN KEY (foo_id) REFERENCES bar(bar_id) DEFERRABLE INITIALLY DEFERRED

如何生成用于创建约束的所有查询?我不想手动做,因为有 1000 多个约束处于活动状态。

【问题讨论】:

  • 我肯定遗漏了一些东西,但是您不能使用此查询通过简单的字符串连接来获取您想要的查询吗?你有表的名字,约束的名字和它的定义,还有什么遗漏的吗?
  • 澄清一下,我正在考虑类似于select 'alter table ' || conrelid::regclass || ' add constraint ' || conname || etc. etc. 的内容,或者不管语法是什么,让其余的查询保持原样。
  • 好吧,还没注意到我已经完成了一半的工作,我试试看……

标签: postgresql constraints


【解决方案1】:

大部分工作实际上已经完成......

select 'alter table ' || conrelid::regclass || ' add constraint ' || conname || ' ' || pg_get_constraintdef(c.oid)
from   pg_constraint c
join   pg_namespace n ON n.oid = c.connamespace
where  contype in ('f', 'p','c','u') order by contype

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-22
    • 1970-01-01
    相关资源
    最近更新 更多