我们正在尝试设置一个 SaaS 服务,支持共享数据库和架构中的多租户。我们计划在所有表上都有一个tenant_id 列。我想做的是,开发人员不必编写任何额外的代码,我的查询就可以按此租户 ID 自动过滤所有涉及的表。在 SQL Alchemy 中是否有一种透明的方法来实现这一点?
我发现如何覆盖默认查询对象:
self.session = sessionmaker(bind=engine, query_cls=TenantLimitingQuery)
但在 TenantLimitingQuery 内部如何将其应用于所有涉及的表?
class TenantLimitingQuery(Query):
def get(self, ident):
#apply filter here
我的表具有相同的列来标识名为tenant_id的租户,因此在该获取函数中我需要按tenant_id=current_tenant_id进行过滤
这在使用食谱维基,转载于此:
from sqlalchemy.orm.query import Query
class LimitingQuery(Query):
def get(self, ident):
# override get() so that the flag is always checked in the
# DB as opposed to pulling from the identity map. - this is optional.
return Query.get(self.populate_existing(), ident)
def __iter__(self):
return Query.__iter__(self.private())
def from_self(self, *ent):
# override from_self() to automatically apply
# the criterion too. this works with count() and
# others.
return Query.from_self(self.private(), *ent)
def private(self):
mzero = self._mapper_zero()
if mzero is not None:
crit = mzero.class_.public == True
return self.enable_assertions(False).filter(crit)
else:
return self
这个想法是在迭代查询对象时按需应用过滤器。
如果您希望过滤器也应用于关系,则需要使用这个食谱反而。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)