⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 expression.py

📁 SQLAlchemy. 经典的Python ORM框架。学习必看。
💻 PY
📖 第 1 页 / 共 5 页
字号:
    def __gt__(self, other):        return self.operate(operators.gt, other)    def __ge__(self, other):        return self.operate(operators.ge, other)    def concat(self, other):        return self.operate(operators.concat_op, other)    def like(self, other):        return self.operate(operators.like_op, other)    def ilike(self, other):        return self.operate(operators.ilike_op, other)    def in_(self, *other):        return self.operate(operators.in_op, other)    def startswith(self, other):        return self.operate(operators.startswith_op, other)    def endswith(self, other):        return self.operate(operators.endswith_op, other)    def contains(self, other):        return self.operate(operators.contains_op, other)    def desc(self):        return self.operate(operators.desc_op)    def asc(self):        return self.operate(operators.asc_op)    def __radd__(self, other):        return self.reverse_operate(operators.add, other)    def __rsub__(self, other):        return self.reverse_operate(operators.sub, other)    def __rmul__(self, other):        return self.reverse_operate(operators.mul, other)    def __rdiv__(self, other):        return self.reverse_operate(operators.div, other)    def between(self, cleft, cright):        return self.operate(operators.between_op, cleft, cright)    def distinct(self):        return self.operate(operators.distinct_op)    def __add__(self, other):        return self.operate(operators.add, other)    def __sub__(self, other):        return self.operate(operators.sub, other)    def __mul__(self, other):        return self.operate(operators.mul, other)    def __div__(self, other):        return self.operate(operators.div, other)    def __mod__(self, other):        return self.operate(operators.mod, other)    def __truediv__(self, other):        return self.operate(operators.truediv, other)class _CompareMixin(ColumnOperators):    """Defines comparison and math operations for ``ClauseElement`` instances."""    def __compare(self, op, obj, negate=None, reverse=False):        if obj is None or isinstance(obj, _Null):            if op == operators.eq:                return _BinaryExpression(self.expression_element(), null(), operators.is_, negate=operators.isnot)            elif op == operators.ne:                return _BinaryExpression(self.expression_element(), null(), operators.isnot, negate=operators.is_)            else:                raise exceptions.ArgumentError("Only '='/'!=' operators can be used with NULL")        else:            obj = self._check_literal(obj)        if reverse:            return _BinaryExpression(obj, self.expression_element(), op, type_=sqltypes.Boolean, negate=negate)        else:            return _BinaryExpression(self.expression_element(), obj, op, type_=sqltypes.Boolean, negate=negate)    def __operate(self, op, obj, reverse=False):        obj = self._check_literal(obj)        type_ = self._compare_type(obj)        if reverse:            return _BinaryExpression(obj, self.expression_element(), type_.adapt_operator(op), type_=type_)        else:            return _BinaryExpression(self.expression_element(), obj, type_.adapt_operator(op), type_=type_)    # a mapping of operators with the method they use, along with their negated    # operator for comparison operators    operators = {        operators.add : (__operate,),        operators.mul : (__operate,),        operators.sub : (__operate,),        operators.div : (__operate,),        operators.mod : (__operate,),        operators.truediv : (__operate,),        operators.lt : (__compare, operators.ge),        operators.le : (__compare, operators.gt),        operators.ne : (__compare, operators.eq),        operators.gt : (__compare, operators.le),        operators.ge : (__compare, operators.lt),        operators.eq : (__compare, operators.ne),        operators.like_op : (__compare, operators.notlike_op),        operators.ilike_op : (__compare, operators.notilike_op),    }    def operate(self, op, *other):        o = _CompareMixin.operators[op]        return o[0](self, op, other[0], *o[1:])    def reverse_operate(self, op, other):        o = _CompareMixin.operators[op]        return o[0](self, op, other, reverse=True, *o[1:])    def in_(self, *other):        return self._in_impl(operators.in_op, operators.notin_op, *other)    def _in_impl(self, op, negate_op, *other):        # Handle old style *args argument passing        if len(other) != 1 or not isinstance(other[0], Selectable) and (not hasattr(other[0], '__iter__') or isinstance(other[0], basestring)):            util.warn_deprecated('passing in_ arguments as varargs is deprecated, in_ takes a single argument that is a sequence or a selectable')            seq_or_selectable = other        else:            seq_or_selectable = other[0]        if isinstance(seq_or_selectable, Selectable):            return self.__compare( op, seq_or_selectable, negate=negate_op)        # Handle non selectable arguments as sequences        args = []        for o in seq_or_selectable:            if not _is_literal(o):                if not isinstance( o, _CompareMixin):                    raise exceptions.InvalidRequestError( "in() function accepts either a list of non-selectable values, or a selectable: "+repr(o) )            else:                o = self._bind_param(o)            args.append(o)        if len(args) == 0:            # Special case handling for empty IN's            return _Grouping(case([(self.__eq__(None), text('NULL'))], else_=text('0')).__eq__(text('1')))        return self.__compare(op, ClauseList(*args).self_group(against=op), negate=negate_op)    def startswith(self, other):        """Produce the clause ``LIKE '<other>%'``"""        # use __radd__ to force string concat behavior        return self.__compare(operators.like_op, literal_column("'%'", type_=sqltypes.String).__radd__(self._check_literal(other)))    def endswith(self, other):        """Produce the clause ``LIKE '%<other>'``"""        return self.__compare(operators.like_op, literal_column("'%'", type_=sqltypes.String) + self._check_literal(other))    def contains(self, other):        """Produce the clause ``LIKE '%<other>%'``"""        return self.__compare(operators.like_op, literal_column("'%'", type_=sqltypes.String) + self._check_literal(other) + literal_column("'%'", type_=sqltypes.String))    def label(self, name):        """Produce a column label, i.e. ``<columnname> AS <name>``.        if 'name' is None, an anonymous label name will be generated.        """        return _Label(name, self, self.type)    def desc(self):        """Produce a DESC clause, i.e. ``<columnname> DESC``"""        return desc(self)    def asc(self):        """Produce a ASC clause, i.e. ``<columnname> ASC``"""        return asc(self)    def distinct(self):        """Produce a DISTINCT clause, i.e. ``DISTINCT <columnname>``"""        return _UnaryExpression(self, operator=operators.distinct_op)    def between(self, cleft, cright):        """Produce a BETWEEN clause, i.e. ``<column> BETWEEN <cleft> AND <cright>``"""        return _BinaryExpression(self, ClauseList(self._check_literal(cleft), self._check_literal(cright), operator=operators.and_, group=False), operators.between_op)    def op(self, operator):        """produce a generic operator function.        e.g.::          somecolumn.op("*")(5)        produces::          somecolumn * 5        operator          a string which will be output as the infix operator between          this ``ClauseElement`` and the expression passed to the          generated function.        """        return lambda other: self.__operate(operator, other)    def _bind_param(self, obj):        return _BindParamClause(None, obj, type_=self.type, unique=True)    def _check_literal(self, other):        if isinstance(other, _BindParamClause) and isinstance(other.type, sqltypes.NullType):            other.type = self.type            return other        elif isinstance(other, Operators):            return other.expression_element()        elif _is_literal(other):            return self._bind_param(other)        else:            return other    def clause_element(self):        """Allow ``_CompareMixins`` to return the underlying ``ClauseElement``, for non-``ClauseElement`` ``_CompareMixins``."""        return self    def expression_element(self):        """Allow ``_CompareMixins`` to return the appropriate object to be used in expressions."""        return self    def _compare_type(self, obj):        """Allow subclasses to override the type used in constructing        ``_BinaryExpression`` objects.        Default return value is the type of the given object.        """        return obj.typeclass ColumnElement(ClauseElement, _CompareMixin):    """Represent an element that is usable within the "column clause" portion of a ``SELECT`` statement.    This includes columns associated with tables, aliases, and    subqueries, expressions, function calls, SQL keywords such as    ``NULL``, literals, etc.  ``ColumnElement`` is the ultimate base    class for all such elements.    ``ColumnElement`` supports the ability to be a *proxy* element,    which indicates that the ``ColumnElement`` may be associated with    a ``Selectable`` which was derived from another ``Selectable``.    An example of a "derived" ``Selectable`` is an ``Alias`` of a    ``Table``.    A ``ColumnElement``, by subclassing the ``_CompareMixin`` mixin    class, provides the ability to generate new ``ClauseElement``    objects using Python expressions.  See the ``_CompareMixin``    docstring for more details.    """    primary_key = False    foreign_keys = []    def base_columns(self):        if hasattr(self, '_base_columns'):            return self._base_columns        self._base_columns = util.Set([c for c in self.proxy_set if not hasattr(c, 'proxies')])        return self._base_columns    base_columns = property(base_columns)    def proxy_set(self):        if hasattr(self, '_proxy_set'):            return self._proxy_set        s = util.Set([self])        if hasattr(self, 'proxies'):            for c in self.proxies:                s = s.union(c.proxy_set)        self._proxy_set = s        return s    proxy_set = property(proxy_set)    def shares_lineage(self, othercolumn):        """Return True if the given ``ColumnElement`` has a common ancestor to this ``ColumnElement``.        """        return len(self.proxy_set.intersection(othercolumn.proxy_set)) > 0    def _make_proxy(self, selectable, name=None):        """Create a new ``ColumnElement`` representing this        ``ColumnElement`` as it appears in the select list of a        descending selectable.        """        if name is not None:            co = _ColumnClause(name, selectable, type_=getattr(self, 'type', None))            co.proxies = [self]            selectable.columns[name]= co            return co        else:            name = str(self)            co = _ColumnClause(self.anon_label.name, selectable, type_=getattr(self, 'type', None))            co.proxies = [self]            selectable.columns[name] = co            return co    def anon_label(self):        """provides a constant 'anonymous label' for this ColumnElement.        This is a label() expression which will be named at compile time.        The same label() is returned each time anon_label is called so        that expressions can reference anon_label multiple times, producing        the same label name at compile time.        the compiler uses this function automatically at compile time        for expressions that are known to be 'unnamed' like binary        expressions and function calls.        """        if not hasattr(self, '_ColumnElement__anon_label'):            self.__anon_label = self.label(None)        return self.__anon_label    anon_label = property(anon_label)class ColumnCollection(util.OrderedProperties):    """An ordered dictionary that stores a list of ColumnElement    instances.    Overrides the ``__eq__()`` method to produce SQL clauses between    sets of correlated columns.    """    def __init__(self, *cols):        super(ColumnCollection, self).__init__()        [self.add(c) for c in cols]    def __str__(self):        return repr([str(c) for c in self])    def replace(self, column):        """add the given column to this collection, removing unaliased versions of this column           as well as existing columns with the same key.            e.g.::                t = Table('sometable', Column('col1', Integer))                t.replace_unalised(Column('col1', Integer, key='columnone'))            will remove the original 'col1' from the collection, and add            the new column under the name 'columnname'.           Used by schema.Column to override columns during table reflection.        """        if column.name in self and column.key != column.name:            other = self[column.name]            if other.name == other.key:                del self[other.name]        util.OrderedProperties.__setitem__(self, column.key, column)    def add(self, column):        """Add a column to this collection.        The key attribute of the column will be used as the hash key        for this dictionary.        """        self[column.key] = column

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -