Ecto - 无法删除自定义命名的唯一索引

Ecto - unable to drop custom-named unique index

我无法成功 运行 Ecto 迁移以删除唯一索引,该索引在最初创建时已提供 :name 属性(因此默认索引名称不是用过的)。但是,我现在无法删除该索引,因为 Ecto 似乎正在尝试查找名称不正确的索引(尽管我已经提供了它)。

唯一索引最初是通过这样的迁移创建的:

def change do
  create(
    unique_index("foo", [:bar_id],
      where: "rejected IS NULL AND accepted IS NULL)",
      name: :bar_pending_index
    )
  )
end

当我检查 psql shell 中的 table 时,我看到该索引列为:

"bar_pending_index" UNIQUE, btree (bar_id) WHERE rejected IS NULL AND accepted IS NULL

为了删除索引,我编写了以下迁移:

def up do
  drop index("foo", [:bar_pending_index])
end

def down do
  create(
    unique_index("foo", [:bar_id],
      where: "rejected IS NULL AND accepted IS NULL)",
      name: :bar_pending_index
    )
  )
end

但是,当我尝试 运行 此迁移时,出现错误

14:01:56.573 [info]  == Running 20210610173741 MyApp.Repo.Migrations.DropIndex.up/0 forward

14:01:56.576 [info]  drop index foo_bar_pending_index_index
** (Postgrex.Error) ERROR 42704 (undefined_object) index "foo_bar_pending_index" does not exist

在我看来,它似乎在尝试应用 Ecto 通常认为的“默认”命名约定,也就是说它希望在索引名称前加上 table 名称并附加带有单词“index”的索引名称。通过 Ecto 迁移删除自定义命名索引的合适方法是什么?谢谢!

当您执行 drop index("foo", [:bar_pending_index]) 时,您正在调用相同的 index/3 function used to create an index, similar to unique_index/3

查看这两个函数的文档,您会注意到第二个参数始终是要用于索引的列(drop 上的示例:drop index("posts", [:name]) 有点模棱两可因为列名 :name).

所以,您应该做的实际上与您创建索引的方式非常相似,例如:

drop index("foo", [:bar_id], name: :bar_pending_index)