如何 运行 更新 Ecto 的迁移?
How to run updating in migration for Ecto?
我想向一个 table 添加一列,我希望它是一个 NOT NULL 列。但是我已经有了一些现有数据,所以我决定添加列,将所有行更新为某个值并将列修改为 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] 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 是正确的方法,但您需要在第一个 alter
块之后添加对 Ecto.Migration.flush/0
的调用,以确保所有更改都立即在数据库上执行,而不是被排队等待稍后执行,这是默认设置。
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
我想向一个 table 添加一列,我希望它是一个 NOT NULL 列。但是我已经有了一些现有数据,所以我决定添加列,将所有行更新为某个值并将列修改为 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] 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 是正确的方法,但您需要在第一个 alter
块之后添加对 Ecto.Migration.flush/0
的调用,以确保所有更改都立即在数据库上执行,而不是被排队等待稍后执行,这是默认设置。
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