postgresql - 无法删除索引,因为唯一约束需要它 (postgres)

标签 postgresql

运行 Postgres 9.6。

我正在尝试编写数据库迁移代码以删除冗余的唯一约束和索引。问题是在某些安装中存在这些索引和约束,而在其他安装中则不存在。

推荐的丢弃方式是:

alter table <table_name> drop constraint <unique_name>

但是当约束不存在时失败,并且没有“if exists”子句。 “drop index”命令有一个“if exists”子句,但最初也失败了:

db=> drop index if exists <unique_name>;
ERROR:  cannot drop index <unique_name> because constraint <unique_name> on table <table_name> requires it

等等,“drop index”有一个“cascade”选项来删除依赖对象,所以我们可以使用它!

嗯,不。我得到了同样的回应:

db=> drop index if exists <unique_name> cascade;
ERROR:  cannot drop index <unique_name> because constraint <unique_name> on table <table_name> requires it

注意:我看过很多看似相关的答案,其中“级联”为人们解决了问题,但这些都提到了外键约束,而不是唯一约束。

注意:这与尝试并发删除索引时不支持级联无关;当你添加“并发”关键字时,你会得到一个非常明确的

ERROR:  DROP INDEX CONCURRENTLY does not support CASCADE

这是一个已知错误吗?还是我遗漏了什么?

最佳答案

您可以使用 DO 语句并捕获错误:

DO
$$BEGIN
   ALTER TABLE <table_name> DROP CONSTRAINT <unique_name>;
EXCEPTION
   WHEN undefined_object
      THEN NULL;  -- ignore the error
END$$;

关于postgresql - 无法删除索引,因为唯一约束需要它 (postgres),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57754479/

相关文章:

ruby-on-rails - ActiveRecord AVG 计算

django - 使用 postgresql-8.4 和 django 进行全文搜索

postgresql - 阻止 PostgreSQL 在多行中拆分值)?

java - OSGI 容器中的数据源

postgresql - 如何在 Postgres 表上存储 Go 的当前时间(小时-分钟-秒)?

java - Junit 不会断言 true

postgresql - 错误: missing FROM-clause entry for table "cte" while executing query in CTE

postgresql - 无法使用 docker build 连接到 postgres 数据库

sql - PostgreSQL 和 PHP。从查询中获取会增加 char 字符串的空间

python - 如何通过 SQLAlchemy 中的自定义函数进行排序