在SQLAlchemy中检查表格兼容性。

4

我声明了一些代表远程数据库的表格。

我想要检查我的表格定义是否与我连接到的远程数据库相匹配。

我有以下函数:

def verify_db_tables(conn, metadata):
    """checks that the tables declared in metadata are actually in the db"""
    for table in metadata.tables.values():
        check = sqlalchemy.MetaData()
        check.reflect(conn, table.schema, True, (table.name,))
        check = check.tables[table.key]
        for column in table.c:
            if column.name not in check.c:
                raise Exception("table %s does not contain column %s" %
                        (table.key, column.name))
            check_column = check.c[column.name]
            if check_column.type != column.type:
                raise Exception("column %s.%s is %s but expected %s" %
                        (table.key, column.name, check_column.type, column.type))

我并不关心表格中是否有额外的列,也不关心是否有额外的表格。

然而,当我运行这段代码时,我会得到以下错误:

Exception: column dx.mail_data.message_id is INTEGER but expected INTEGER

如何检查反映表中的列与我的定义相同类型?

1个回答

1
SQLite使用类层次结构,因此这将很好地工作。
    if not instance(check_column.type, column.type.__class__):

糟糕!感觉很明显却没注意到。 - Will

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接