Sha256: 6babe119bf7959d9f78c35477485ab79197f78af6e6a84b8220449927b86d68c

Contents?: true

Size: 1.45 KB

Versions: 4

Compression:

Stored size: 1.45 KB

Contents

module TbCore::Mysql2Extensions

  # Create a new table
  #
  def create_table(table_name, options = {})
    if @connection.query_options[:encoding] == 'utf8mb4'
      super(table_name, options.reverse_merge(:options => 'ROW_FORMAT=DYNAMIC ENGINE=InnoDB'))
    else
      super
    end
  end

  # Build a hash of length options for a given table and column name
  #
  # column_name can be either a symbol or an array of symbols
  #
  def length_options_for_utf8mb4_string_index(table_name, column_names)
    length_options = {}
    column_names = [column_names] unless column_names.is_a?(Array)
    column_names.each do |column_name|
      begin
        column = column_for(table_name, column_name)
        if column && column.type == :string
          length_options[column_name] = ActiveRecord::ConnectionAdapters::Mysql2Adapter::MAX_INDEX_LENGTH_FOR_UTF8MB4
        end
      rescue ActiveRecord::ActiveRecordError => e
        logger.info e.message
      end
    end
    return length_options
  end

  # Adds an index to the table
  #
  # See parent method implementation here: 
  # http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_index
  #
  def add_index(table_name, column_name, options = {})
    if options[:length].nil? && @connection.query_options[:encoding] == 'utf8mb4'
      options[:length] = length_options_for_utf8mb4_string_index(table_name, column_name)
    end
    super(table_name, column_name, options)
  end

end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
tb_core-1.3.10 lib/tb_core/mysql2_extensions.rb
tb_core-1.3.9 lib/tb_core/mysql2_extensions.rb
tb_core-1.3.7 lib/tb_core/mysql2_extensions.rb
tb_core-1.3.6 lib/tb_core/mysql2_extensions.rb