Search code examples
rubymigrationsequel

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


I am trying to create a Sequel migration that goes through a list of tables, and try to add a specific column if the table does not of that column yet.

For example:

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

Is is possible to tell if the column already exist in a table, so I can do stuff accordingly?


Solution

  • Yes, it is possible. The method Dataset#columns returns a list of columns. This result can be used to be checked with include?

    Full example:

    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
    

    or

    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