【发布时间】:2021-05-07 14:58:47
【问题描述】:
我一直在玩 SqlAlchemy 示例代码 examples.versioned_history.history_meta : https://docs.sqlalchemy.org/en/14/_modules/examples/versioned_history/history_meta.html。
当我使用它从现有表创建历史表时,它们都是使用不正确的表排序规则创建的。现有的表都是在声明式中创建的,如下所示:
from history_meta import Versioned
class Thingo(Base,Versioned):
__tablename__ = 'thingos'
__table_args__ = {'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8'}
这会导致表排序规则属性为utf_general_ci(好!)。当我使用示例history_meta 代码生成thingos_history 实例时,这些表是使用latin1_swedish_ci 的表排序属性创建的(糟糕!)。
确保动态生成的thingos_history 表获得与源表相同的表排序规则属性的最佳方法是什么?
(如果这在每列/每表的基础上不容易实现,则可以使用 UTF8 编码创建所有 _history tables)
============================
按照 cmets 中的建议(感谢 @rfkortekaas),我尝试将字符集 (?charset=utf8) 作为参数添加到 create_engine() 的 URL 查询字符串,并提供与 connect_args 相同的参数 (create_engine(uri, connect_args={'use_unicode':True,'charset':'utf8'}) ),但是当以history_meta 的方式动态创建表时,这是无效的,似乎被忽略了,有利于 MYSQL 自己的默认排序规则。
如上所示,生成thingos_history 的源thingos 表使用声明式表定义,该表定义在__table_args__ 中指定'mysql_charset': 'utf8',但这不适用于动态创建的thingos_history 表. thingos_history 没有声明性表类定义供我提供 __table_args__ 给,它是从 thingos 映射器创建的:
table = Table(
local_mapper.local_table.name + "_history",
local_mapper.local_table.metadata,
*cols,
schema=local_mapper.local_table.schema
)
我正在努力解决的问题是 SQLAlchemy 提供什么语法来设置以这种方式生成的表的表排序规则,如果没有为此提供任何选项,我必须有哪些选项来动态生成 thingos_history 表来自thingos,确实使用源表的表排序规则或强制表排序规则为utf_general_ci。
【问题讨论】:
标签: sqlalchemy