Skip to content

Instantly share code, notes, and snippets.

@stevecj
Last active August 29, 2015 14:03
Show Gist options
  • Save stevecj/f09b8e368ee8aa9bebec to your computer and use it in GitHub Desktop.
Save stevecj/f09b8e368ee8aa9bebec to your computer and use it in GitHub Desktop.
Require a :limit option for MySQL text columns created in Rails 3 app so don't unintentionally make 64K column that silently truncates.
# == config/initializers/require_limit_for_mysql_text.rb ==
# Fail when an attempt is made to specify a MySQL text
# columnn in a migration without providing a :limit value.
# This helps to prevent accidentally defining a 64K column
# (default) when a 16MB or 4GB coumn is desired.
# Note that MySQL silently truncates the data when it is
# too long for the column, so problems are only apparent
# later when attempting to retrieve the data (if then).
# Fail if class not already defined or auto-requirable.
ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter
module ActiveRecord
module ConnectionAdapters
AbstractMysqlAdapter.class_eval do
def type_to_sql_with_text_limit_required(type, limit = nil, precision = nil, scale = nil)
if "#{type}" == 'text' && limit.nil?
raise "Don't define a text column without specifying a limit."
end
type_to_sql_without_text_limit_required(type, limit, precision, scale)
end
alias_method_chain :type_to_sql, :text_limit_required
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment