also check out these guys, doing something similar:

http://trac.pocoo.org/wiki/DatabaseApi


On Apr 5, 2006, at 12:21 PM, Gabriel Jacobo wrote:

I have been checking on the issue of ActiveMapper, regarding its use when classes with multiple inter-relations are involved. It quickly became evident that if you intend to use ActiveMapper for a case where the complexity of the classes goes a little beyond the test case, the code fails, except you take extreme care with the ordering of the classes, and even so there are times where you can ´t do this, because there are constraints that come from the table declarations that collide with the constraints for the ordering of the classes regarding their relationships.

Anyway...I think I´ve managed to modify ActiveMapper to lessen this problem, maybe even solve it completely (at least to the extent of my testing it works just fine). This modification is barely more than a dirty hack, but it "just works". What I did was decouple the table creation phase from the relations processing, which now must be started "by hand", calling the function "connect_classes". Upon calling this function, the system will check everyclass asociated with ActiveMapperMeta, and will order them in the correct order for everything to work fine.

So, without further ado I will copy the code of the modified ActiveMapper...if someone can test it (I´ve tried 6 interconnected classes and there seemed to be no problems) it should prove a good addittion to the SVN repository. The usage method is the exact same as always, but you need to call activemapper.connect_classes prior using the classes. You should be able to shuffle the ordering of the declaration of the classes without repercusions...

Best Regards,

Gabriel.

activemapper.py

---

from sqlalchemy import objectstore, create_engine, assign_mapper, relation, mapper
from sqlalchemy             import and_, or_
from sqlalchemy             import Table, Column, ForeignKey
from sqlalchemy.ext.proxy   import ProxyEngine

import inspect
import sys

#
# the "proxy" to the database engine... this can be swapped out at runtime
#
engine = ProxyEngine()



#
# declarative column declaration - this is so that we can infer the colname
#
class column(object):
   def __init__(self, coltype, colname=None, foreign_key=None,
                primary_key=False, *args, **kwargs):
       if isinstance( foreign_key, basestring ):
           foreign_key= ForeignKey( foreign_key )
       self.coltype     = coltype
       self.colname     = colname
       self.foreign_key = foreign_key
       self.primary_key = primary_key
#         self.unique      = kwargs.pop( 'unique', None )
#         self.index       = kwargs.pop( 'indexed', None )
       self.kwargs      = kwargs
       self.args        = args

#
# declarative relationship declaration
#
class relationship(object):
def __init__(self, classname, colname=None, backref=None, private=False,
                lazy=True, uselist=True, secondary=None):
       self.classname = classname
       self.colname   = colname
       self.backref   = backref
       self.private   = private
       self.lazy      = lazy
       self.uselist   = uselist
       self.secondary = secondary

class one_to_many(relationship):
def __init__(self, classname, colname=None, backref=None, private=False, lazy=True): relationship.__init__(self, classname, colname, backref, private, lazy, uselist=True)


class one_to_one(relationship):
def __init__(self, classname, colname=None, backref=None, private=False, lazy=True): relationship.__init__(self, classname, colname, backref, private, lazy, uselist=False)

class many_to_many(relationship):
   def __init__(self, classname, secondary, backref=None, lazy=True):
relationship.__init__(self, classname, None, backref, False, lazy,
                             uselist=True, secondary=secondary)


#
# SQLAlchemy metaclass and superclass that can be used to do SQLAlchemy
# mapping in a declarative way, along with a function to process the
# relationships between dependent objects as they come in, without blowing
# up if the classes aren't specified in a proper order
#

__deferred_classes__  = []
def process_relationships(klass, was_deferred=False):
   defer = False
   for propname, reldesc in klass.relations.items():
       if not reldesc.classname in ActiveMapperMeta.classes:
           if not was_deferred: __deferred_classes__.append(klass)
           defer = True
     if not defer:
       relations = {}
       for propname, reldesc in klass.relations.items():
           relclass = ActiveMapperMeta.classes[reldesc.classname]
           relations[propname] = relation(relclass.mapper,
                                          secondary=reldesc.secondary,
                                          backref=reldesc.backref,
                                          private=reldesc.private,
                                          lazy=reldesc.lazy,
                                          uselist=reldesc.uselist)
       if len(relations)>0:
           assign_mapper(klass, klass.table, properties=relations)
                 if was_deferred: __deferred_classes__.remove(klass)
     if not was_deferred:
       for deferred_class in __deferred_classes__:
           process_relationships(deferred_class, was_deferred=True)



class ActiveMapperMeta(type):
   classes = {}
     def __init__(cls, clsname, bases, dict):
       table_name = clsname.lower()
       columns    = []
       relations  = {}
_engine = getattr( sys.modules[cls.__module__], "__engine__", engine )
             if 'mapping' in dict:
           members = inspect.getmembers(dict.get('mapping'))
           for name, value in members:
               if name == '__table__':
                   table_name = value
                   continue
                             if '__engine__' == name:
                   _engine= value
                   continue
                                 if name.startswith('__'): continue
                             if isinstance(value, column):
                   if value.foreign_key:
                       col = Column(value.colname or name,
                                    value.coltype,
                                    value.foreign_key,
                                    primary_key=value.primary_key,
                                    *value.args, **value.kwargs)
                   else:
                       col = Column(value.colname or name,
                                    value.coltype,
                                    primary_key=value.primary_key,
                                    *value.args, **value.kwargs)
                   columns.append(col)
#                     if value.indexed:
#                         # create a Index object for the column
# index= Index( "%s_idx" % (value.colname or name),
#                                       col, unique= value.unique )
                   continue
                             if isinstance(value, relationship):
                   relations[name] = value
           assert _engine is not None, "No engine specified"
           cls.table = Table(table_name, _engine, *columns)
           assign_mapper(cls, cls.table)
           cls.relations = relations
           ActiveMapperMeta.classes[clsname] = cls
           #process_relationships(cls)
super(ActiveMapperMeta, cls).__init__(clsname, bases, dict)


class ActiveMapper(object):
   __metaclass__ = ActiveMapperMeta
     def set(self, **kwargs):
       for key, value in kwargs.items():
           setattr(self, key, value)


#
# a utility function to create all tables for all ActiveMapper classes
#

def create_tables():
   for klass in ActiveMapperMeta.classes.values():
       klass.table.create()



def connect_classes():
#Order classes according to their relationships for processing the relationships in the appropriate order.
   mylist = []
   for cls in ActiveMapperMeta.classes:
   relations = ActiveMapperMeta.classes[cls].relations
   behind = 0
   r  = range(len(mylist))

#Test every relation of this class against the ones already in the mylist
   for relname in relations:
       for x in r:
           if mylist[x] == relations[relname].classname:
               behind = x+1
#Test every relation of the classes in the mylist against this class
   for x in r:
       relations = ActiveMapperMeta.classes[mylist[x]].relations
       for relname in relations:
           if mylist[x] == relations[relname].classname:
                   if behind <= x:
                       behind = x+1
   mylist.insert(behind, cls)
     #Process relationships according to the given order
   for cls in mylist:
       process_relationships(ActiveMapperMeta.classes[cls])


-------------------------------------------------------
This SF.Net email is sponsored by xPML, a groundbreaking scripting language that extends applications into web and mobile media. Attend the live webcast and join the prime developer group breaking into this new coding territory! http://sel.as-us.falkag.net/sel? cmd=lnk&kid=110944&bid=241720&dat=121642
_______________________________________________
Sqlalchemy-users mailing list
Sqlalchemy-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/sqlalchemy-users



-------------------------------------------------------
This SF.Net email is sponsored by xPML, a groundbreaking scripting language
that extends applications into web and mobile media. Attend the live webcast
and join the prime developer group breaking into this new coding territory!
http://sel.as-us.falkag.net/sel?cmd=lnk&kid0944&bid$1720&dat1642
_______________________________________________
Sqlalchemy-users mailing list
Sqlalchemy-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/sqlalchemy-users

Reply via email to