BigW Consortium Gitlab

mysql_set_length_for_binary_indexes.rb 711 Bytes
Newer Older
1 2 3 4
# This patches ActiveRecord so indexes for binary columns created using the
# MySQL adapter apply a length of 20. Otherwise MySQL can't create an index on
# binary columns.

5 6 7 8
module MysqlSetLengthForBinaryIndex
  def add_index(table_name, column_names, options = {})
    Array(column_names).each do |column_name|
      column = ActiveRecord::Base.connection.columns(table_name).find { |c| c.name == column_name }
9

10 11
      if column&.type == :binary
        options[:length] = 20
12 13
      end
    end
14 15

    super(table_name, column_names, options)
16 17
  end
end
18 19 20 21

if defined?(ActiveRecord::ConnectionAdapters::Mysql2Adapter)
  ActiveRecord::ConnectionAdapters::Mysql2Adapter.send(:prepend, MysqlSetLengthForBinaryIndex)
end