提交 53008447 编写于 作者: R Rafael Mendonça França

Merge pull request #15200 from sgrif/sg-type-map-mysql

Use the generic type map object for mysql field lookups
......@@ -297,23 +297,17 @@ def cast_value(value)
end
end
TYPES = {}
class << self
TYPES = ConnectionAdapters::Type::HashLookupTypeMap.new # :nodoc:
# Register an MySQL +type_id+ with a typecasting object in
# +type+.
def self.register_type(type_id, type)
TYPES[type_id] = type
end
def self.alias_type(new, old)
TYPES[new] = TYPES[old]
end
delegate :register_type, :alias_type, to: :TYPES
def self.find_type(field)
def find_type(field)
if field.type == Mysql::Field::TYPE_TINY && field.length > 1
TYPES[Mysql::Field::TYPE_LONG]
TYPES.lookup(Mysql::Field::TYPE_LONG)
else
TYPES.fetch(field.type) { Type::Value.new }
TYPES.lookup(field.type)
end
end
end
......@@ -322,18 +316,10 @@ def self.find_type(field)
alias_type Mysql::Field::TYPE_LONGLONG, Mysql::Field::TYPE_LONG
alias_type Mysql::Field::TYPE_NEWDECIMAL, Mysql::Field::TYPE_LONG
register_type Mysql::Field::TYPE_VAR_STRING, Type::Value.new
register_type Mysql::Field::TYPE_BLOB, Type::Value.new
register_type Mysql::Field::TYPE_DATE, Type::Date.new
register_type Mysql::Field::TYPE_DATETIME, Fields::DateTime.new
register_type Mysql::Field::TYPE_TIME, Fields::Time.new
register_type Mysql::Field::TYPE_FLOAT, Type::Float.new
Mysql::Field.constants.grep(/TYPE/).map { |class_name|
Mysql::Field.const_get class_name
}.reject { |const| TYPES.key? const }.each do |const|
register_type const, Type::Value.new
end
end
def initialize_type_map(m) # :nodoc:
......
......@@ -11,7 +11,9 @@
require 'active_record/connection_adapters/type/string'
require 'active_record/connection_adapters/type/text'
require 'active_record/connection_adapters/type/time'
require 'active_record/connection_adapters/type/type_map'
require 'active_record/connection_adapters/type/hash_lookup_type_map'
module ActiveRecord
module ConnectionAdapters
......
module ActiveRecord
module ConnectionAdapters
module Type
class HashLookupTypeMap < TypeMap # :nodoc:
def lookup(type)
@mapping.fetch(type, proc { default_value }).call(type)
end
def alias_type(type, alias_type)
register_type(type) { lookup(alias_type) }
end
end
end
end
end
......@@ -95,6 +95,19 @@ def test_requires_value_or_block
mapping.register_type(/only key/i)
end
end
def test_lookup_non_strings
mapping = HashLookupTypeMap.new
mapping.register_type(1, 'string')
mapping.register_type(2, 'int')
mapping.alias_type(3, 1)
assert_equal mapping.lookup(1), 'string'
assert_equal mapping.lookup(2), 'int'
assert_equal mapping.lookup(3), 'string'
assert_kind_of Type::Value, mapping.lookup(4)
end
end
end
end
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册