实体在运行时的sqlalchemy动态模式 [英] sqlalchemy dynamic schema on entity at runtime

查看:135
本文介绍了实体在运行时的sqlalchemy动态模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用SQL Alchemy,并且具有一些特定于帐户的架构。模式名称是使用帐户ID派生的,因此在进入应用程序服务或存储库层之前,我没有模式名称。我想知道是否可以对在运行时动态设置了架构的实体运行查询吗?



我知道我需要设置 __ table_args __ ['schema'] ,并尝试使用内置的type()来做到这一点,但我总是收到以下错误:

 无法为映射表

I汇编任何主键列准备放弃,只写简单的sql,但我真的很讨厌这样做。知道如何做到这一点吗?我正在使用SA 0.99,并且确实映射了PK。



谢谢

解决方案

edit:尽管您可以做我在这里所做的事情,但是使用下面的答案中所示的模式转换映射是正确的方法。



它们是静态设置的。外键需要同样的处理,还有一个额外的问题,就是我有包含多个表的多个模式,所以我这样做:

  from sqlalchemy.ext.declarative import declarative_base 

staging_dbase = declarative_base()
model_dbase = declarative_base()


def adjust_schemas(staging, model):
for vv在staging_dbase.metadata.tables.values()中:
vv.schema =在$ v $ schema = vb在model_dbase.metadata.tables.values()中:
vv.schema =模型


def all_tables():
return staging_dbase.metadata.tables.union(model_dbase.metadata.tables)

然后在我的启动代码中:

  Adjust_schemas(staging = staging_name,model = model_name)

您可以为单个声明性基数进行修改。 / p>

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 until I hit my application service or repository layer. I'm wondering if it's possible to run a query against an entity that has it's schema dynamically set at runtime?

I know I need to set the __table_args__['schema'] and have tried doing that using the type() built-in, but I always get the following error:

could not assemble any primary key columns for mapped table

I'm ready to give up and just write straight sql, but I really hate to do that. Any idea how this can be done? I'm using SA 0.99 and I do have a PK mapped.

Thanks

解决方案

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.

这篇关于实体在运行时的sqlalchemy动态模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆