【问题标题】:SQLAlchemy: A table reflected from an existing table gets different table collationSQLAlchemy:从现有表反映的表获得不同的表排序规则
【发布时间】: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


    【解决方案1】:

    docs 中所见,创建表的函数接受关键字参数mysql_charset

    如果您查看line 127 上的examples.versioned_history.history_meta 文件,则会创建历史表实例。您可以将其更改为包含 `mysql_charset='utf8'。

    table = Table(local_mapper.local_table.name + "_history",
                  local_mapper.local_table.metadata,
                  *cols,
                  schema=local_mapper.local_table.schema,
                  mysql_charset='utf8'
                  )
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-26
      • 1970-01-01
      • 2014-10-16
      • 1970-01-01
      • 2018-04-04
      • 2017-04-24
      • 2012-08-27
      相关资源
      最近更新 更多