sqlalchemy dynamic schema on entity at runtime

前端 未结 4 557
一生所求
一生所求 2020-12-09 00:00

I\'m using SQL Alchemy and have some schema\'s that are account specific. The name of the schema is derived using the account ID, so I don\'t have the name of the schema un

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-09 00:25

    edit: Although you can do what I did here, using the schema translation map as shown in the the answer below is the proper way to do it.

    They are set statically. Foreign keys needs the same treatment, and I have an additional issue, in that I have multiple schemas that contain multiple tables so I did this:

    from sqlalchemy.ext.declarative import declarative_base
    
    staging_dbase = declarative_base()
    model_dbase = declarative_base()
    
    
    def adjust_schemas(staging, model):
        for vv in staging_dbase.metadata.tables.values():
            vv.schema = staging
        for vv in model_dbase.metadata.tables.values():
            vv.schema = model
    
    
    def all_tables():
        return staging_dbase.metadata.tables.union(model_dbase.metadata.tables)
    

    Then in my startup code:

    adjust_schemas(staging=staging_name, model=model_name)
    

    You can mod this for a single declarative base.

提交回复
热议问题