示例#1
0
 def add_fixture_set(self, fset):
     from sqlobject.classregistry import findClass
     so_class = fset.obj_id()
     kls = findClass(so_class)
     # this maybe isn't very flexible ...
     self.template.add_import("from %s import %s" % (
                         kls.__module__, so_class))  
示例#2
0
    def __get_user_in_database(self, user_name, user_record):
        """Make sure the user exists in the application DB

        If needed, autocreate it. This is useful to automatically populate the
        application DB with users from the LDAP, the first time they try to
        log in.

        Return the user instance from the DB if found or autocreated, or None
        if not.
        """
        user_class = classregistry.findClass(self.userclass_name)

        try:
            user = user_class.by_user_name(user_name)

        except SQLObjectNotFound:
            if self.autocreate:
                log.info("Creating user in app DB: %s" % user_name)
                # Set an empty password, it doesn't matter anyway as it is
                # checked from LDAP, not from the application DB
                user = user_class(user_name=user_name, password='',
                                  display_name=user_record[1]['cn'][0])

            else:
                log.error("No such user in app DB: %s", user_name)
                return None

        return user
示例#3
0
 def add_fixture_set(self, fset):
     from sqlobject.classregistry import findClass
     so_class = fset.obj_id()
     kls = findClass(so_class)
     # this maybe isn't very flexible ...
     self.template.add_import("from %s import %s" % (
                         kls.__module__, so_class))
示例#4
0
    def fetchChildren(self):
        """Prefetch childrens' data

        Fetch childrens' data for every subclass in one big .select()
        to avoid .get() fetching it one by one.
        """
        self._childrenResults = {}
        if self._childNameIdx is None:
            return
        childIdsNames = {}
        childNameIdx = self._childNameIdx
        for result in self._results:
            childName = result[childNameIdx+1]
            if childName:
                ids = childIdsNames.get(childName)
                if ids is None:
                    ids = childIdsNames[childName] = []
                ids.append(result[0])
        dbconn = self.dbconn
        rawconn = self.rawconn
        cursor = rawconn.cursor()
        registry = self.select.sourceClass.sqlmeta.registry
        for childName, ids in childIdsNames.items():
            klass = findClass(childName, registry)
            select = klass.select(sqlbuilder.IN(sqlbuilder.SQLConstant("id"), ids))
            query = dbconn.queryForSelect(select)
            if dbconn.debug:
                dbconn.printDebug(rawconn, query, 'Select children of the class %s' % childName)
            self.dbconn._executeRetry(rawconn, cursor, query)
            for result in cursor.fetchall():
                self._childrenResults[result[0]] = result[1:]
示例#5
0
	def __init__(self,model,name=None,excCols=None):
		self.model=model
		self.tableName=self.model.sqlmeta.table
		self.name=name or self.tableName
		self.joins={}
		for k,v in self.model.sqlmeta.columns.items():
			if type(v)==col.SOForeignKey:
				model=findClass(v.foreignKey,self.model.sqlmeta.registry)
				self.joins[model.sqlmeta.table]={'column':k,'model':model}
				self.joins[model.sqlmeta.table]['joinOn']=self.createExpr('{0}.{1}'.format(model.sqlmeta.table,'id'))==self.createExpr(k)
		if excCols:
			self.excCols=excCols
示例#6
0
 def findReverseDependencies(cls):
     """
     Return a list of classes that cls depends on. Note that
     "depends on" here mean "has a foreign key pointing to".
     """
     depended = []
     for _col in cls.sqlmeta.columnList:
         if _col.foreignKey:
             other = findClass(_col.foreignKey,
                               _col.soClass.sqlmeta.registry)
             if (other is not cls) and (other not in depended):
                 depended.append(other)
     return depended
示例#7
0
 def findReverseDependencies(cls):
     """
     Return a list of classes that cls depends on. Note that
     "depends on" here mean "has a foreign key pointing to".
     """
     depended = []
     for _col in cls.sqlmeta.columnList:
         if _col.foreignKey:
             other = findClass(_col.foreignKey,
                               _col.soClass.sqlmeta.registry)
             if (other is not cls) and (other not in depended):
                 depended.append(other)
     return depended
示例#8
0
    def fetchChildren(self):
        """Prefetch childrens' data

        Fetch childrens' data for every subclass in one big .select()
        to avoid .get() fetching it one by one.
        """
        self._childrenResults = {}
        if self._childNameIdx is None:
            return
        childIdsNames = {}
        childNameIdx = self._childNameIdx
        for result in self._results:
            childName = result[childNameIdx + 1]
            if childName:
                ids = childIdsNames.get(childName)
                if ids is None:
                    ids = childIdsNames[childName] = []
                ids.append(result[0])
        dbconn = self.dbconn
        rawconn = self.rawconn
        cursor = rawconn.cursor()
        registry = self.select.sourceClass.sqlmeta.registry
        for childName, ids in childIdsNames.items():
            klass = findClass(childName, registry)
            if len(ids) == 1:
                select = klass.select(klass.q.id == ids[0],
                                      childUpdate=True,
                                      connection=dbconn)
            else:
                select = klass.select(sqlbuilder.IN(klass.q.id, ids),
                                      childUpdate=True,
                                      connection=dbconn)
            query = dbconn.queryForSelect(select)
            if dbconn.debug:
                dbconn.printDebug(
                    rawconn, query,
                    'Select children of the class %s' % childName)
            self.dbconn._executeRetry(rawconn, cursor, query)
            for result in cursor.fetchall():
                # Inheritance child classes may have no own columns
                # (that makes sense when child class has a join
                # that does not apply to parent class objects).
                # In such cases result[1:] gives an empty tuple
                # which is interpreted as "no results fetched" in .get().
                # So .get() issues another query which is absolutely
                # meaningless (like "SELECT NULL FROM child WHERE id=1").
                # In order to avoid this, we replace empty results
                # with non-empty tuple.  Extra values in selectResults
                # are Ok - they will be ignored by ._SO_selectInit().
                self._childrenResults[result[0]] = result[1:] or (None, )
示例#9
0
文件: sqlobj.py 项目: initz/sqlobj
 def __init__(self,model,name=None,excCols=None,logPath='/dev/null'):
   self.model=model
   self.tableName=self.model.sqlmeta.table
   self.name=name or self.tableName
   self.joins={}
   self.logPath=logPath
   self.logger=LogUtil.getLogger(self.logPath,'sqlobj.Resource.{0}'.format(self.tableName))
   for k,v in self.model.sqlmeta.columns.items():
     if type(v)==col.SOForeignKey:
       model=findClass(v.foreignKey,self.model.sqlmeta.registry)
       fk=k[:-len(ID)]
       self.joins[fk]={'model':model}
       self.joins[fk]['joinOn']=self._createExpr('{0}.{1}'.format(fk,'id'))==self._createExpr(k)
   if excCols:
     self.excCols=excCols
示例#10
0
    def fetchChildren(self):
        """Prefetch childrens' data

        Fetch childrens' data for every subclass in one big .select()
        to avoid .get() fetching it one by one.
        """
        self._childrenResults = {}
        if self._childNameIdx is None:
            return
        childIdsNames = {}
        childNameIdx = self._childNameIdx
        for result in self._results:
            childName = result[childNameIdx + 1]
            if childName:
                ids = childIdsNames.get(childName)
                if ids is None:
                    ids = childIdsNames[childName] = []
                ids.append(result[0])
        dbconn = self.dbconn
        rawconn = self.rawconn
        cursor = rawconn.cursor()
        registry = self.select.sourceClass.sqlmeta.registry
        for childName, ids in childIdsNames.items():
            klass = findClass(childName, registry)
            if len(ids) == 1:
                select = klass.select(klass.q.id == ids[0],
                                      childUpdate=True, connection=dbconn)
            else:
                select = klass.select(sqlbuilder.IN(klass.q.id, ids),
                                      childUpdate=True, connection=dbconn)
            query = dbconn.queryForSelect(select)
            if dbconn.debug:
                dbconn.printDebug(rawconn, query,
                                  'Select children of the class %s' %
                                  childName)
            self.dbconn._executeRetry(rawconn, cursor, query)
            for result in cursor.fetchall():
                # Inheritance child classes may have no own columns
                # (that makes sense when child class has a join
                # that does not apply to parent class objects).
                # In such cases result[1:] gives an empty tuple
                # which is interpreted as "no results fetched" in .get().
                # So .get() issues another query which is absolutely
                # meaningless (like "SELECT NULL FROM child WHERE id=1").
                # In order to avoid this, we replace empty results
                # with non-empty tuple.  Extra values in selectResults
                # are Ok - they will be ignored by ._SO_selectInit().
                self._childrenResults[result[0]] = result[1:] or (None,)
示例#11
0
 def get_col_value(self, colname):
     """transform column name into a value or a
     new set if it's a foreign key (recursion).
     """
     from sqlobject.classregistry import findClass
     value = getattr(self.data, colname)
     if value is None:
         # this means that we are in a NULL foreign key
         # which could be perfectly legal.
         return None
         
     if self.foreign_key_class.has_key(colname):
         model = findClass(self.foreign_key_class[colname])
         rs = model.get(value, connection=self.connection)
         return SQLObjectFixtureSet(rs, model, connection=self.connection)
     else:
         return value
示例#12
0
    def get_col_value(self, colname):
        """transform column name into a value or a
        new set if it's a foreign key (recursion).
        """
        from sqlobject.classregistry import findClass
        value = getattr(self.data, colname)
        if value is None:
            # this means that we are in a NULL foreign key
            # which could be perfectly legal.
            return None

        if self.foreign_key_class.has_key(colname):
            model = findClass(self.foreign_key_class[colname])
            rs = model.get(value, connection=self.connection)
            return SQLObjectFixtureSet(rs, model, connection=self.connection)
        else:
            return value