SQLALCHEMY无法呈现<class'sqlalchemy.dialects.oracle.base.number'=“”>

时间:2018-11-27 17:46:28

标签: python oracle postgresql sqlalchemy

我想使用sqlalchemy将一个表从一个Oracle数据库复制到Postgre数据库 在oracle和postgre中设置连接和引擎并将表反映到sourceMeta元数据之后,我尝试在destEngine中创建,但是它给我一个错误,提示无法渲染类型...

for t in sourceMeta.sorted_tables:
    newtable = Table(t.name, sourceMeta, autoload=True)
    newtable.metadata.create_all(destEngine)

1 个答案:

答案 0 :(得分:0)

您似乎正在寻找的是sqlalchemys @compiles装饰器。 这是当尝试将表从MS SQL Server数据库复制到PostgreSQL数据库时对我有用的示例。

from sqlalchemy import create_engine, Table, MetaData
from sqlalchemy.schema import CreateTable
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.dialects.mssql import TINYINT, DATETIME, VARCHAR

@compiles(TINYINT, 'postgresql')
def compile_TINYINT_mssql_int(element, compiler, **kw):
    """ Handles mssql TINYINT datatype as INT in postgresql """
    return 'INTEGER'
# add a function for each datatype that causes an error

table_name = '<table_name>'

# create engine, reflect existing columns, and create table object for oldTable
srcEngine = create_engine('mssql+pymssql://<user>:<password>@<host>/<db>')
srcEngine._metadata = MetaData(bind=srcEngine)
srcEngine._metadata.reflect(srcEngine)  # get columns from existing table
srcTable = Table(table_name, srcEngine._metadata)

# create engine and table object for newTable
destEngine = create_engine('postgresql+psycopg2://<user>:<password>@<host><db>')
destEngine._metadata = MetaData(bind=destEngine)
destTable = Table(table_name.lower(), destEngine._metadata)

# copy schema and create newTable from oldTable
for column in srcTable.columns:
    dstCol = column.copy()
    destTable.append_column(dstCol)
    # maybe change column name etc.
print(CreateTable(destTable).compile(destEngine))  # <- check the query that will be used to create the table
destTable.create()

检查文档: https://docs.sqlalchemy.org/en/13/core/compiler.html 也许还有这个例子: https://gist.github.com/methane/2972461