On May 19, 2011, at 5:04 AM, Faheem Mitha wrote:

> 
> from sqlalchemy import *
> from sqlalchemy.orm import *
> 
> def make_pheno_table(meta, schema, name='pheno'):
>    pheno_table = Table(
>        name, meta,
>        Column('patientid', String(60), primary_key=True),
>        schema=schema,
>        )
>    return pheno_table
> 
> class Pheno(object):
>    def __init__(self, patientid):
>        self.patientid = patientid
> 
> def make_tables(schema):
>    from sqlalchemy import MetaData
>    meta = MetaData()
>    pheno_table = make_pheno_table(meta, schema)
>    mapper(Pheno, pheno_table)
>    table_dict = {'metadata': meta, 'pheno_table':pheno_table}
>    return table_dict
> 
> table_dict = make_tables('foo')
> table_dict = make_tables('bar')

I'm sure I mentioned earlier, one of the reasons you're finding this difficult 
is because of this type of pattern, where you're calling mapper() and Table at 
a different scope than where you make your classes i.e. within a callable 
versus module level.   At the very least a function like make_tables() would 
ensure that its internal implementation is called only once, such as:

_table_dict = None
def make_tables():
    global _table_dict
    if _table_dict is not None:
        return _table_dict
   _table_dict = {.... }

otherwise, you're creating new MetaData objects each time, rebuilding a whole 
new set of Tables in it each time, i.e. its a total mess.     Engine, Session 
registry, MetaData, your set of classes and their mappers, these should all be 
global objects, created once per application.   If you want to use functions to 
initiate their existence that is fine but you should be maintaining singleton 
behavior in any case.   

> 
> from sqlalchemy.orm.exc import UnmappedClassError
> 
> try:
>    class_mapper(Pheno)
> except UnmappedClassError:
>    mapper(Pheno, pheno_table)
> 
> *********************************************************************
> 
> If a mapper is not defined for Pheno, it throws an
> UnmappedClassError. This at least doesn't return an error in my test
> script, but I haven't checked if it actually works.

It will work, but a more reasonable design wouldn't need such a pattern.


-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to