Don’t generate any DROP TABLE directives with autogenerate

When running autogenerate against a database that has existing tables outside of the application’s autogenerated metadata, it may be desirable to prevent autogenerate from considering any of those existing tables to be dropped. This will prevent autogenerate from detecting tables removed from the local metadata as well however this is only a small caveat.

当对具有应用程序自动生成的元数据之外的现有表的数据库运行自动生成时,可能需要阻止自动生成考虑删除任何现有的表。 这也将阻止自动生成检测从本地元数据中删除的表,但这只是一个小警告。

The most direct way to achieve this using the EnvironmentContext.configure.include_object hook. There is no need to hardcode a fixed “whitelist” of table names; the hook gives enough information in the given arguments to determine if a particular table name is not part of the local MetaData being autogenerated, by checking first that the type of object is "table", then that reflected is True, indicating this table name is from the local database connection, not the MetaData, and finally that compare_to is None, indicating autogenerate is not comparing this Table to any Table in the local MetaData collection:

使用 EnvironmentContext.configure.include_object 钩子实现此目的的最直接方法。 无需硬编码固定的表名“白名单”; 钩子在给定的参数中提供了足够的信息来确定特定的表名是否不是自动生成的本地元数据的一部分,首先检查对象的类型是“表”,然后反映的是真,表明这个表名是来自本地数据库连接,而不是 MetaData,最后 compare_toNone ,表示 autogenerate 不会将此 Table 与本地 MetaData 集合中的任何 Table 进行比较:

# in env.py

def include_object(object, name, type_, reflected, compare_to):
    if type_ == "table" and reflected and compare_to is None:
        return False
    else:
        return True


context.configure(
    # ...
    include_object = include_object
)