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

Merge pull request #15248 from sgrif/sg-additional-type-map-args

Allow additional arguments to be used during type map lookups
......@@ -178,7 +178,7 @@ def indexes(table_name, name = nil)
def columns(table_name)
# Limit, precision, and scale are all handled by the superclass.
column_definitions(table_name).map do |column_name, type, default, notnull, oid, fmod|
oid = get_oid_type(oid.to_i, fmod.to_i, column_name)
oid = get_oid_type(oid.to_i, fmod.to_i, column_name, type)
PostgreSQLColumn.new(column_name, default, oid, type, notnull == 'f')
end
end
......
......@@ -538,12 +538,12 @@ def translate_exception(exception, message)
private
def get_oid_type(oid, fmod, column_name)
def get_oid_type(oid, fmod, column_name, sql_type = '')
if !type_map.key?(oid)
initialize_type_map(type_map, [oid])
end
type_map.fetch(normalize_oid_type(oid, fmod)) {
type_map.fetch(normalize_oid_type(oid, fmod), sql_type) {
warn "unknown OID #{oid}: failed to recognize type of '#{column_name}'. It will be treated as String."
Type::Value.new.tap do |cast_type|
type_map.register_type(oid, cast_type)
......
......@@ -4,16 +4,16 @@ module Type
class HashLookupTypeMap < TypeMap # :nodoc:
delegate :key?, to: :@mapping
def lookup(type)
@mapping.fetch(type, proc { default_value }).call(type)
def lookup(type, *args)
@mapping.fetch(type, proc { default_value }).call(type, *args)
end
def fetch(type, &block)
@mapping.fetch(type, block).call(type)
def fetch(type, *args, &block)
@mapping.fetch(type, block).call(type, *args)
end
def alias_type(type, alias_type)
register_type(type) { lookup(alias_type) }
register_type(type) { |_, *args| lookup(alias_type, *args) }
end
end
end
......
......@@ -6,13 +6,13 @@ def initialize
@mapping = {}
end
def lookup(lookup_key)
def lookup(lookup_key, *args)
matching_pair = @mapping.reverse_each.detect do |key, _|
key === lookup_key
end
if matching_pair
matching_pair.last.call(lookup_key)
matching_pair.last.call(lookup_key, *args)
else
default_value
end
......@@ -29,9 +29,9 @@ def register_type(key, value = nil, &block)
end
def alias_type(key, target_key)
register_type(key) do |sql_type|
register_type(key) do |sql_type, *args|
metadata = sql_type[/\(.*\)/, 0]
lookup("#{target_key}#{metadata}")
lookup("#{target_key}#{metadata}", *args)
end
end
......
......@@ -88,6 +88,23 @@ def test_register_proc
assert_equal mapping.lookup('varchar'), binary
end
def test_additional_lookup_args
mapping = TypeMap.new
mapping.register_type(/varchar/i) do |type, limit|
if limit > 255
'text'
else
'string'
end
end
mapping.alias_type(/string/i, 'varchar')
assert_equal mapping.lookup('varchar', 200), 'string'
assert_equal mapping.lookup('varchar', 400), 'text'
assert_equal mapping.lookup('string', 400), 'text'
end
def test_requires_value_or_block
mapping = TypeMap.new
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册