Dynamically setting __tablename__ for sharding in SQLAlchemy?

后端 未结 6 1513
我寻月下人不归
我寻月下人不归 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:41

    Instead of using imperative creating Table object, you can use usual declarative_base and make a closure to set a table name as the following:

    def make_class(Base, table_name):
        class User(Base):
            __tablename__ = table_name
            id = Column(Integer, primary_key=True)
            name= Column(String)
    
        return User
    
    Base = declarative_base()
    engine = make_engine()
    custom_named_usertable = make_class(Base, 'custom_name')
    Base.metadata.create_all(engine)
    
    session = make_session(engine)
    new_user = custom_named_usertable(name='Adam')
    session.add(new_user)
    session.commit()
    session.close()
    engine.dispose()
    

提交回复
热议问题