gpt4 book ai didi

elixir - 如何在Ecto迁移中运行更新?

转载 作者:行者123 更新时间:2023-12-04 05:06:24 24 4
gpt4 key购买 nike

我在一个项目中使用PhoenixEcto

我想向一个表中添加一列,并且我希望它是一个非空列。但是我已经有一些存在的数据,因此我决定添加该列,将所有行更新为某个值,并将该列修改为NOT NULL。

我尝试了以下两个代码:

  # solution 1
def up do
alter table(:channels) do
add :type, :integer
Exchat.Repo.update_all("channels", set: [type: 1])
modify :type, :integer, null: false
end
end

# solution 2
def up do
alter table(:channels) do
add :type, :integer
end
Exchat.Repo.update_all("channels", set: [type: 1])
alter table(:channels) do
modify :type, :integer, null: false
end
end

他们两个都没有工作,我得到了如下错误:
23::40::07.514 [info]  == Running Exchat.Repo.Migrations.AddTypeToChannels.up/0 forward

23::40::07.541 [debug] UPDATE "channels" AS c0 SET "type" = $1 [1] ERROR query=12.0ms
** (Postgrex.Error) ERROR (undefined_column): column "type" of relation "channels" does not exist
(ecto) lib/ecto/adapters/sql.ex:383: Ecto.Adapters.SQL.execute_and_cache/7

我不确定它是否与Ecto版本有关,但是我的Ecto版本是2.0.0-rc.0。

有什么办法可以做到这一点?还是我的示例代码有问题?

最佳答案

解决方案2是正确的方法,但是您需要在第一个Ecto.Migration.flush/0块之后添加对 alter 的调用,以确保所有更改都立即在数据库上执行,而不是排队等待稍后执行,这是默认设置。

def up do
alter table(:channels) do
add :type, :integer
end
flush()
Exchat.Repo.update_all("channels", set: [type: 1])
alter table(:channels) do
modify :type, :integer, null: false
end
end

关于elixir - 如何在Ecto迁移中运行更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36723407/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com