From b0978c50ed8509761fa71ece054bc9aae64177d7 Mon Sep 17 00:00:00 2001 From: Andrew Hannigan Date: Wed, 18 Nov 2020 09:55:01 -0600 Subject: [PATCH] Implement TypeEngine.as_generic() and tests Fixes: #5659 --- lib/sqlalchemy/sql/type_api.py | 7 ++++++- test/sql/test_types.py | 20 ++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/lib/sqlalchemy/sql/type_api.py b/lib/sqlalchemy/sql/type_api.py index bca6e9020e..e4d66c54f7 100644 --- a/lib/sqlalchemy/sql/type_api.py +++ b/lib/sqlalchemy/sql/type_api.py @@ -470,7 +470,7 @@ class TypeEngine(Traversible): "sqlalchemy.sql.sqltypes", "sqlalchemy.sql.type_api", ) - and t._is_generic_type() + and hasattr(t, '_is_generic_type') and t._is_generic_type() ): if t in (TypeEngine, UserDefinedType): return NULLTYPE.__class__ @@ -478,6 +478,11 @@ class TypeEngine(Traversible): else: return self.__class__ + def as_generic(self): + """Return an instance of the generic type corresponding to this type""" + + return util.constructor_copy(self, self._generic_type_affinity()) + def dialect_impl(self, dialect): """Return a dialect-specific implementation for this :class:`.TypeEngine`. diff --git a/test/sql/test_types.py b/test/sql/test_types.py index fd1783e098..570383dfed 100644 --- a/test/sql/test_types.py +++ b/test/sql/test_types.py @@ -383,6 +383,26 @@ class TypeAffinityTest(fixtures.TestBase): assert t1.dialect_impl(d)._type_affinity is postgresql.UUID +class AsGenericTest(fixtures.TestBase): + @testing.combinations( + (String(), String()), + (VARCHAR(length=100), String(length=100)), + (NVARCHAR(length=100), Unicode(length=100)), + (DATE(), Date()), + ) + def test_as_generic(self, t1, t2): + assert repr(t1.as_generic()) == repr(t2) + + @testing.combinations(*[(t,) for t in _all_types(omit_special_types=True)]) + def test_as_generic_all_types(self, type_): + if issubclass(type_, ARRAY): + t1 = type_(String) + else: + t1 = type_() + + t1.as_generic() + + class PickleTypesTest(fixtures.TestBase): @testing.combinations( ("Boo", Boolean()), -- 2.47.3