使用Postgresql函数进行change_column迁移

问题描述 投票:0回答:1

orders具有数据类型为cuts_off_attime without time zone列。该表和列已经使用了一段时间,因此该表具有许多保存的记录。我意识到我希望此列改为具有数据类型integer来表示seconds since midnight。我应该如何设置change_column行的格式?

我尝试了一些不同的操作,但似乎无法正确处理。我相信这是我最接近的尝试:

change_column :orders, :cuts_off_at, 'INTEGER USING EXTRACT(epoch from ('2000-01-01 00:00:00'::time - cuts_off_at))'

返回错误:

syntax error, unexpected tINTEGER, expecting end ...USING EXTRACT(epoch from ('2000-01-01 00:00:00'::time - cuts_...

版本:

postgres版本10.12导轨5.2.4.2

ruby-on-rails database postgresql database-migration postgresql-10
1个回答
0
投票

两种迁移方法没有破坏性,可以让您在直接的更新语句中使用postgres魔术。它还可以让您确保一切都按预期进行...

  def change
    rename_column :orders, :cuts_off_at, :cuts_off_at_old
    add_column :orders, :cuts_off_at, :integer
    execute("UPDATE orders SET cuts_off_at = EXTRACT(epoch from ('2000-01-01 00:00:00'::time - cuts_off_at_old))")
  end

然后您可以在以后的迁移中直接删除旧列...

 def change
    remove_column :orders, :cuts_off_at_old
 end

或者如果您需要上下...

  def up
    rename_column :orders, :cuts_off_at, :cuts_off_at_old
    add_column :orders, :cuts_off_at, :integer
    execute("UPDATE orders SET cuts_off_at = EXTRACT(epoch from ('2000-01-01 00:00:00'::time - cuts_off_at_old))")
  end

  def down
    remove_column :orders, :cuts_off_at
    rename_column :orders, :cuts_off_at_old, :cuts_off_at
  end
© www.soinside.com 2019 - 2024. All rights reserved.