read

Upfront: extending existing Modules and Classes in Ruby is awesome.

for one of my recent projects I had to read the "comment" from an a MySQL table field. After a short look in ActiveRecords ConnectionAdapters for MySQL I realized the existing method uses

SHOW FIELDS FROM table
instead of the necessary
SHOW FULL FIELDS FROM table
which includes the required "comment" column.

First I added an attribute (accessor) to the MysqlColumn Class to store the comment.

module ActiveRecord
  module ConnectionAdapters
    class MysqlColumn
      attr_accessor :comment
    end 
  end
end

Next, the existing method, that loads and assings attributes like "fieldname", "size", "type" needed an upgrade. (Change SQL Statement & Assignment of "comment")

module ActiveRecord
  module ConnectionAdapters
    class MysqlAdapter

      def columns(table_name, name = nil)
        sql = "SHOW FULL FIELDS FROM #{quote_table_name(table_name)}"
        columns = []
        result = execute(sql, name)
        result.each { |field| 
          c = MysqlColumn.new(field[0], field[4], field[1], field[2] == "YES") 
          c.comment = field[8] 
          columns << c
        }
        result.free
        columns
      end 
 
    end
  end
end     

Notes:

  • For Rails Projects, I think, you need to place this in a .rb file in config/initializers
  • In my environment (sinatra) I had to add following requirement:
    require 'active_record/connection_adapters/mysql_adapter'
Back to Overview