Dynamically setting __tablename__ for sharding in SQLAlchemy?

后端 未结 6 1543
我寻月下人不归
我寻月下人不归 2020-12-28 17:11

In order to handle a growing database table, we are sharding on table name. So we could have database tables that are named like this:

table_md5one
table_md5         


        
6条回答
  •  伪装坚强ぢ
    2020-12-28 17:38

    OK, we went with the custom SQLAlchemy declaration rather than the declarative one.

    So we create a dynamic table object like this:

    from sqlalchemy import MetaData, Table, Column
    
    def get_table_object(self, md5hash):
        metadata = MetaData()
        table_name = 'table_' + md5hash
        table_object = Table(table_name, metadata,
            Column('Column1', DATE, nullable=False),
            Column('Column2', DATE, nullable=False)
        )
        clear_mappers()
        mapper(ActualTableObject, table_object)
        return ActualTableObject
    

    Where ActualTableObject is the class mapping to the table.

提交回复
热议问题