运行 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/