我使用具有多个模式的数据库(并且模式的数量是动态的,在启动时不知道)。每个模式都存储相同的表定义。
在文档中,我看到我可以为相应的模式名称设置模式选项。但是当表存在于不同的模式中时,它如何工作?是否可以在运行时切换模式名称?
更新29-11-2013 我找到了这个http://www.sqlalchemy.org/trac/wiki/UsageRecipes/EntityName,并编写了以下例程来打开正确的架构
engine = create_engine('db_host', echo=True)
dbSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
dbSession.configure(bind=engine)
metadata = MetaData(engine)
aTable = Table('aTable', metadata,
Column('foo', String, primary_key=True),
Column('bar', String))
def map_class_to_some_table(cls, table, entity_name, **kw):
newcls = type(entity_name, (cls, ), {})
mapper(newcls, table, **kw)
return newcls
class ObjectDefinition(object):
def __init__(self):
pass
class ObjectRepository():
objectMapper = {}
@classmethod
def _getObjectMapper(cls, aSchema):
if cls.objectMapper == None:
cls.objectMapper = {}
mapper = cls.objectMapper .get(aSchema)
if mapper == None:
logging.debug('Need to create a new mapper for schema %s'%aSchema)
objectSchemaTable = aTable.tometadata(metadata, schema=aSchema)
mapper = map_class_to_some_table(ObjectDefinition, objectSchemaTable , "object_%s"%aSchema)
cls.objectMapper [aSchema] = mapper
return mapper
@staticmethod
def loadAllObject(schema):
return dbSession.query(UserRepository._getUserMapper(schema)).all()