mysql_set_length_for_binary_indexes.rb 1.05 KB
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 9 10 11 12 13 14 15 16 17
module MysqlSetLengthForBinaryIndexAndIgnorePostgresOptionsForSchema
  # This method is used in Rails 5 schema loading as t.index
  def index(column_names, options = {})
    # Ignore indexes that use opclasses,
    # also see config/initializers/mysql_ignore_postgresql_options.rb
    if options[:opclasses]
      warn "WARNING: index on columns #{column_names} uses unsupported option, skipping."
      return
    end

    options[:length] ||= {}
    Array(column_names).each do |column_name|
      column = columns.find { |c| c.name == column_name }
18

19 20
      if column&.type == :binary
        options[:length][column_name] = 20
21 22
      end
    end
23 24

    super(column_names, options)
25
  end
26
end
27

28 29
if defined?(ActiveRecord::ConnectionAdapters::MySQL::TableDefinition)
  ActiveRecord::ConnectionAdapters::MySQL::TableDefinition.send(:prepend, MysqlSetLengthForBinaryIndexAndIgnorePostgresOptionsForSchema)
30
end