Sequel 迁移 - 仅在 table 还没有时添加列

Sequel migration - only add column if table does not have it yet

我正在尝试创建一个 Sequel 迁移,它遍历 table 的列表,如果 table 还没有该列,则尝试添加该列.

例如:

Sequel.migration do
  change do
    table_list = [:table1, :table2, :table3]

    table_list.each do |t|
      if t does not have :specific_column yet
        alter_table(t) do
          add_column :sepcific_column, type: String
        end
      end
    end
  end
end

是否可以判断该列是否已存在于 table 中,以便我可以相应地做一些事情?

是的,这是可能的。该方法 Dataset#columns returns 列的列表。此结果可用于检查 include?

完整示例:

Sequel.migration do
  change do
    table_list = [:table1, :table2, :table3]

    table_list.each do |t|
      if ! self[t].columns.include?(:specific_column)
        alter_table(t) do
          add_column :specific_column, type: String
        end
      end
    end
  end
end

Sequel.migration do
  change do
    table_list = [:table1, :table2, :table3]

    table_list.each do |t|
        alter_table(t) do
          add_column :specific_column, type: String
        end unless self[t].columns.include?(:specific_column)
      end
    end
  end
end