Beispiel #1
0
    def doSearch(klass, query, startdate, enddate, room_id):
        query = query.strip()
        where = ['room_id = ?', room_id]

        if query != "":
            where = joinWheres(where, ['message like ?', "%" + query + "%"])
        if startdate != "":
            where = joinWheres(where, ['created_at >= ?', startdate])
        if enddate != "":
            where = joinWheres(where, ['created_at <= ?', enddate])
            
        return klass.find(where=where, orderby="created_at ASC")
Beispiel #2
0
    def test_joinWheres_precedence(self):
        yield User(first_name="Second").save()
        
        first = ['first_name = ?', "First"]
        last = ['last_name = ?', "Last"]
        second = ['first_name = ?', "Second"]

        last_or_second = utils.joinWheres(last, second, joiner='OR')
        where = utils.joinWheres(first, last_or_second, joiner='AND')

        results = yield User.count(where=where)
        self.assertEqual(1, results)
Beispiel #3
0
    def get(self, **kwargs):
        """
        Get the objects that caller has.

        @param kwargs: These could include C{limit}, C{orderby}, or any others included in
        C{InteractionBase.select}.  If a C{where} parameter is included, the conditions will
        be added to the ones already imposed by default in this method.  The argument
        C{join_where} will be applied to the join table, if provided.

        @return: A C{Deferred} with a callback value of a list of objects.
        """
        def _get(rows):
            if len(rows) == 0:
                return defer.succeed([])
            ids = [str(row[self.othername]) for row in rows]
            where = ["id IN (%s)" % ",".join(ids)]
            if kwargs.has_key('where'):
                kwargs['where'] = joinWheres(where, kwargs['where'])
            else:
                kwargs['where'] = where
            d = self.dbconfig.select(self.otherklass.tablename(), **kwargs)
            return d.addCallback(createInstances, self.otherklass)

        tablename = self.tablename()
        where = ["%s = ?" % self.thisname, self.inst.id]
        if kwargs.has_key('join_where'):
            where = joinWheres(where, kwargs.pop('join_where'))
        return self.dbconfig.select(tablename, where=where).addCallback(_get)
Beispiel #4
0
def uniquenessOf(obj, names, kwargs):
    """
    A validator to test whether or not some named properties are unique.
    For those named properties that are not unique, an error will
    be recorded in C{obj.errors}.

    @param obj: The object whose properties need to be tested.
    @param names: The names of the properties to test.
    @param kwargs: Keyword arguments.  Right now, all but a
    C{message} value are ignored.
    """
    message = kwargs.get('message', "is not unique.")

    def handle(results):
        for propname, value in results.items():
            if value is not None:
                obj.errors.add(propname, message)
    ds = {}
    for name in names:
        where = ["%s = ?" % name, getattr(obj, name, "")]
        if obj.id is not None:
            where = joinWheres(where, ["id != ?", obj.id])
        d = obj.__class__.find(where=where, limit=1)
        ds[name] = d
    return deferredDict(ds).addCallback(handle)
Beispiel #5
0
 def _get(rows):
     if len(rows) == 0:
         return defer.succeed(0)
     if not kwargs.has_key('where'):
         return defer.succeed(len(rows))
     ids = [str(row[self.othername]) for row in rows]
     where = ["id IN (%s)" % ",".join(ids)]
     if kwargs.has_key('where'):
         where = joinWheres(where, kwargs['where'])
     return self.dbconfig.count(self.otherklass.tablename(), where=where)
Beispiel #6
0
 def _get(rows):
     if len(rows) == 0:
         return defer.succeed(0)
     if "where" not in kwargs:
         return defer.succeed(len(rows))
     ids = [str(row[self.othername]) for row in rows]
     where = ["id IN (%s)" % ",".join(ids)]
     if "where" in kwargs:
         where = joinWheres(where, kwargs["where"])
     return self.dbconfig.count(self.otherklass.tablename(), where=where)
Beispiel #7
0
    def select(self, tablename, id=None, where=None, group=None, limit=None, orderby=None, select=None):
        """
        Select rows from a table.

        @param tablename: The tablename to select rows from.

        @param id: If given, only the row with the given id will be returned (or C{None} if not found).

        @param where: Conditional of the same form as the C{where} parameter in L{DBObject.find}.

        @param group: String describing how to group results.

        @param limit: Integer limit on the number of results.  If this value is 1, then the result
        will be a single dictionary.  Otherwise, if C{id} is not specified, an array will be returned.
        This can also be a tuple, where the first value is the integer limit and the second value is
        an integer offset.  In the case that an offset is specified, an array will always be returned.

        @param orderby: String describing how to order the results.

        @param select: Columns to select.  Default is C{*}.

        @return: If C{limit} is 1 or id is set, then the result is one dictionary or None if not found.
        Otherwise, an array of dictionaries are returned.
        """
        one = False
        cacheTableStructure = select is None
        select = select or "*"

        if id is not None:
            if where is None:
                where = ["id = ?", id]
            else:
                where = joinWheres(where, ["id = ?", id])
            one = True

        if not isinstance(limit, tuple) and limit is not None and int(limit) == 1:
            one = True

        q = "SELECT %s FROM %s" % (select, tablename)
        args = []
        if where is not None:
            wherestr, args = self.whereToString(where)
            q += " WHERE " + wherestr
        if group is not None:
            q += " GROUP BY " + group
        if orderby is not None:
            q += " ORDER BY " + orderby

        if isinstance(limit, tuple):
            q += " LIMIT %s OFFSET %s" % (limit[0], limit[1])
        elif limit is not None:
            q += " LIMIT " + str(limit)

        return self.runInteraction(self._doselect, q, args, tablename, one, cacheTableStructure)
Beispiel #8
0
 def _get(rows):
     if len(rows) == 0:
         return defer.succeed([])
     ids = [str(row[self.othername]) for row in rows]
     where = ["id IN (%s)" % ",".join(ids)]
     if kwargs.has_key('where'):
         kwargs['where'] = joinWheres(where, kwargs['where'])
     else:
         kwargs['where'] = where
     d = self.dbconfig.select(self.otherklass.tablename(), **kwargs)
     return d.addCallback(createInstances, self.otherklass)
Beispiel #9
0
    def _generateGetArgs(self, kwargs):
        if self.args.has_key('as'):
            w = "%s_id = ? AND %s_type = ?" % (self.args['as'], self.args['as'])
            where = [w, self.inst.id, self.thisclass.__name__]
        else:
            where = ["%s = ?" % self.thisname, self.inst.id]

        if kwargs.has_key('where'):
            kwargs['where'] = joinWheres(where, kwargs['where'])
        else:
            kwargs['where'] = where

        return kwargs
Beispiel #10
0
    def _generateGetArgs(self, kwargs):
        if self.args.has_key('as'):
            w = "%s_id = ? AND %s_type = ?" % (self.args['as'], self.args['as'])
            where = [w, self.inst.id, self.thisclass.__name__]
        else:
            where = ["%s = ?" % self.thisname, self.inst.id]

        if kwargs.has_key('where') and kwargs['where']:
            kwargs['where'] = joinWheres(where, kwargs['where'])
        else:
            kwargs['where'] = where

        return kwargs
Beispiel #11
0
    def _generateGetArgs(self, kwargs):
        if "as" in self.args:
            w = "%s_id = ? AND %s_type = ?" % (self.args["as"], self.args["as"])
            where = [w, self.inst.id, self.thisclass.__name__]
        else:
            where = ["%s = ?" % self.thisname, self.inst.id]

        if "where" in kwargs:
            kwargs["where"] = joinWheres(where, kwargs["where"])
        else:
            kwargs["where"] = where

        return kwargs
Beispiel #12
0
def uniquenessOf(obj, names, kwargs):
    """
    A validator to test whether or not some named properties are unique.
    For those named properties that are not unique, an error will
    be recorded in C{obj.errors}.

    @param obj: The object whose properties need to be tested.
    @param names: The names of the properties to test.
    @param kwargs: Keyword arguments.  Right now, all but a
    C{message} value are ignored.
    """
    message = kwargs.get('message', "is not unique.")    
    def handle(results):
        for propname, value in results.items():
            if value is not None:
                obj.errors.add(propname, message)
    ds = {}
    for name in names:
        where = ["%s = ?" % name, getattr(obj, name, "")]            
        if obj.id is not None:
            where = joinWheres(where, ["id != ?", obj.id])
        d = obj.__class__.find(where=where, limit=1)
        ds[name] = d
    return deferredDict(ds).addCallback(handle)
Beispiel #13
0
    def select(self,
               tablename,
               id=None,
               where=None,
               group=None,
               limit=None,
               orderby=None,
               select=None):
        """
        Select rows from a table.

        @param tablename: The tablename to select rows from.

        @param id: If given, only the row with the given id will be returned (or C{None} if not found).

        @param where: Conditional of the same form as the C{where} parameter in L{DBObject.find}.

        @param group: String describing how to group results.

        @param limit: Integer limit on the number of results.  If this value is 1, then the result
        will be a single dictionary.  Otherwise, if C{id} is not specified, an array will be returned.
        This can also be a tuple, where the first value is the integer limit and the second value is
        an integer offset.  In the case that an offset is specified, an array will always be returned.

        @param orderby: String describing how to order the results.

        @param select: Columns to select.  Default is C{*}.

        @return: If C{limit} is 1 or id is set, then the result is one dictionary or None if not found.
        Otherwise, an array of dictionaries are returned.
        """
        one = False
        cacheTableStructure = select is None
        select = select or "*"

        if id is not None:
            if where is None:
                where = ["id = ?", id]
            else:
                where = joinWheres(where, ["id = ?", id])
            one = True

        if not isinstance(limit,
                          tuple) and limit is not None and int(limit) == 1:
            one = True

        q = "SELECT %s FROM %s" % (select, tablename)
        args = []
        if where is not None:
            wherestr, args = self.whereToString(where)
            q += " WHERE " + wherestr
        if group is not None:
            q += " GROUP BY " + group
        if orderby is not None:
            q += " ORDER BY " + orderby

        if isinstance(limit, tuple):
            q += " LIMIT %s OFFSET %s" % (limit[0], limit[1])
        elif limit is not None:
            q += " LIMIT " + str(limit)

        return self.runInteraction(self._doselect, q, args, tablename, one,
                                   cacheTableStructure)