diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt index 7433adaa4b738..55b35368215c4 100644 --- a/doc/source/whatsnew/v0.16.0.txt +++ b/doc/source/whatsnew/v0.16.0.txt @@ -60,7 +60,8 @@ Bug Fixes - Fixed bug in ``to_sql`` when mapping a Timestamp object column (datetime column with timezone info) to the according sqlalchemy type (:issue:`9085`). - +- Fixed bug in ``to_sql`` ``dtype`` argument not accepting an instantiated + SQLAlchemy type (:issue:`9083`). diff --git a/pandas/io/sql.py b/pandas/io/sql.py index 50c620c044403..b4318bdc2a3bf 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -1159,9 +1159,9 @@ def to_sql(self, frame, name, if_exists='fail', index=True, """ if dtype is not None: - import sqlalchemy.sql.type_api as type_api + from sqlalchemy.types import to_instance, TypeEngine for col, my_type in dtype.items(): - if not issubclass(my_type, type_api.TypeEngine): + if not isinstance(to_instance(my_type), TypeEngine): raise ValueError('The type of %s is not a SQLAlchemy ' 'type ' % col) diff --git a/pandas/io/tests/test_sql.py b/pandas/io/tests/test_sql.py index 2ca30f3aea0ea..b185d530e056c 100644 --- a/pandas/io/tests/test_sql.py +++ b/pandas/io/tests/test_sql.py @@ -1229,6 +1229,14 @@ def test_dtype(self): self.assertRaises(ValueError, df.to_sql, 'error', self.conn, dtype={'B': str}) + # GH9083 + df.to_sql('dtype_test3', self.conn, dtype={'B': sqlalchemy.String(10)}) + meta.reflect() + sqltype = meta.tables['dtype_test3'].columns['B'].type + print(sqltype) + self.assertTrue(isinstance(sqltype, sqlalchemy.String)) + self.assertEqual(sqltype.length, 10) + def test_notnull_dtype(self): cols = {'Bool': Series([True,None]), 'Date': Series([datetime(2012, 5, 1), None]),