desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Implement the ``~`` operator. When used with SQL expressions, results in a NOT operation, equivalent to :func:`~.expression.not_`, that is:: ~a is equivalent to:: from sqlalchemy import not_ not_(a)'
def __invert__(self):
return self.operate(inv)
'produce a generic operator function. e.g.:: somecolumn.op("*")(5) produces:: somecolumn * 5 This function can also be used to make bitwise operators explicit. For example:: somecolumn.op(\'&\')(0xff) is a bitwise AND of the value in ``somecolumn``. :param operator: a string which will be output as the infix operator b...
def op(self, opstring, precedence=0, is_comparison=False):
operator = custom_op(opstring, precedence, is_comparison) def against(other): return operator(self, other) return against
'Operate on an argument. This is the lowest level of operation, raises :class:`NotImplementedError` by default. Overriding this on a subclass can allow common behavior to be applied to all operations. For example, overriding :class:`.ColumnOperators` to apply ``func.lower()`` to the left and right side:: class MyCompar...
def operate(self, op, *other, **kwargs):
raise NotImplementedError(str(op))
'Reverse operate on an argument. Usage is the same as :meth:`operate`.'
def reverse_operate(self, op, other, **kwargs):
raise NotImplementedError(str(op))
'Implement the ``<`` operator. In a column context, produces the clause ``a < b``.'
def __lt__(self, other):
return self.operate(lt, other)
'Implement the ``<=`` operator. In a column context, produces the clause ``a <= b``.'
def __le__(self, other):
return self.operate(le, other)
'Implement the ``==`` operator. In a column context, produces the clause ``a = b``. If the target is ``None``, produces ``a IS NULL``.'
def __eq__(self, other):
return self.operate(eq, other)
'Implement the ``!=`` operator. In a column context, produces the clause ``a != b``. If the target is ``None``, produces ``a IS NOT NULL``.'
def __ne__(self, other):
return self.operate(ne, other)
'Implement the ``>`` operator. In a column context, produces the clause ``a > b``.'
def __gt__(self, other):
return self.operate(gt, other)
'Implement the ``>=`` operator. In a column context, produces the clause ``a >= b``.'
def __ge__(self, other):
return self.operate(ge, other)
'Implement the ``-`` operator. In a column context, produces the clause ``-a``.'
def __neg__(self):
return self.operate(neg)
'Implement the [] operator. This can be used by some database-specific types such as Postgresql ARRAY and HSTORE.'
def __getitem__(self, index):
return self.operate(getitem, index)
'implement the << operator. Not used by SQLAlchemy core, this is provided for custom operator systems which want to use << as an extension point.'
def __lshift__(self, other):
return self.operate(lshift, other)
'implement the >> operator. Not used by SQLAlchemy core, this is provided for custom operator systems which want to use >> as an extension point.'
def __rshift__(self, other):
return self.operate(rshift, other)
'Implement the \'concat\' operator. In a column context, produces the clause ``a || b``, or uses the ``concat()`` operator on MySQL.'
def concat(self, other):
return self.operate(concat_op, other)
'Implement the ``like`` operator. In a column context, produces the clause ``a LIKE other``. E.g.:: select([sometable]).where(sometable.c.column.like("%foobar%")) :param other: expression to be compared :param escape: optional escape character, renders the ``ESCAPE`` keyword, e.g.:: somecolumn.like("foo/%bar", escape="...
def like(self, other, escape=None):
return self.operate(like_op, other, escape=escape)
'Implement the ``ilike`` operator. In a column context, produces the clause ``a ILIKE other``. E.g.:: select([sometable]).where(sometable.c.column.ilike("%foobar%")) :param other: expression to be compared :param escape: optional escape character, renders the ``ESCAPE`` keyword, e.g.:: somecolumn.ilike("foo/%bar", esca...
def ilike(self, other, escape=None):
return self.operate(ilike_op, other, escape=escape)
'Implement the ``in`` operator. In a column context, produces the clause ``a IN other``. "other" may be a tuple/list of column expressions, or a :func:`~.expression.select` construct.'
def in_(self, other):
return self.operate(in_op, other)
'implement the ``NOT IN`` operator. This is equivalent to using negation with :meth:`.ColumnOperators.in_`, i.e. ``~x.in_(y)``. .. versionadded:: 0.8 .. seealso:: :meth:`.ColumnOperators.in_`'
def notin_(self, other):
return self.operate(notin_op, other)
'implement the ``NOT LIKE`` operator. This is equivalent to using negation with :meth:`.ColumnOperators.like`, i.e. ``~x.like(y)``. .. versionadded:: 0.8 .. seealso:: :meth:`.ColumnOperators.like`'
def notlike(self, other, escape=None):
return self.operate(notlike_op, other, escape=escape)
'implement the ``NOT ILIKE`` operator. This is equivalent to using negation with :meth:`.ColumnOperators.ilike`, i.e. ``~x.ilike(y)``. .. versionadded:: 0.8 .. seealso:: :meth:`.ColumnOperators.ilike`'
def notilike(self, other, escape=None):
return self.operate(notilike_op, other, escape=escape)
'Implement the ``IS`` operator. Normally, ``IS`` is generated automatically when comparing to a value of ``None``, which resolves to ``NULL``. However, explicit usage of ``IS`` may be desirable if comparing to boolean values on certain platforms. .. versionadded:: 0.7.9 .. seealso:: :meth:`.ColumnOperators.isnot`'
def is_(self, other):
return self.operate(is_, other)
'Implement the ``IS NOT`` operator. Normally, ``IS NOT`` is generated automatically when comparing to a value of ``None``, which resolves to ``NULL``. However, explicit usage of ``IS NOT`` may be desirable if comparing to boolean values on certain platforms. .. versionadded:: 0.7.9 .. seealso:: :meth:`.ColumnOperators...
def isnot(self, other):
return self.operate(isnot, other)
'Implement the ``startwith`` operator. In a column context, produces the clause ``LIKE \'<other>%\'``'
def startswith(self, other, **kwargs):
return self.operate(startswith_op, other, **kwargs)
'Implement the \'endswith\' operator. In a column context, produces the clause ``LIKE \'%<other>\'``'
def endswith(self, other, **kwargs):
return self.operate(endswith_op, other, **kwargs)
'Implement the \'contains\' operator. In a column context, produces the clause ``LIKE \'%<other>%\'``'
def contains(self, other, **kwargs):
return self.operate(contains_op, other, **kwargs)
'Implements the \'match\' operator. In a column context, this produces a MATCH clause, i.e. ``MATCH \'<other>\'``. The allowed contents of ``other`` are database backend specific.'
def match(self, other, **kwargs):
return self.operate(match_op, other, **kwargs)
'Produce a :func:`~.expression.desc` clause against the parent object.'
def desc(self):
return self.operate(desc_op)
'Produce a :func:`~.expression.asc` clause against the parent object.'
def asc(self):
return self.operate(asc_op)
'Produce a :func:`~.expression.nullsfirst` clause against the parent object.'
def nullsfirst(self):
return self.operate(nullsfirst_op)
'Produce a :func:`~.expression.nullslast` clause against the parent object.'
def nullslast(self):
return self.operate(nullslast_op)
'Produce a :func:`~.expression.collate` clause against the parent object, given the collation string.'
def collate(self, collation):
return self.operate(collate, collation)
'Implement the ``+`` operator in reverse. See :meth:`.ColumnOperators.__add__`.'
def __radd__(self, other):
return self.reverse_operate(add, other)
'Implement the ``-`` operator in reverse. See :meth:`.ColumnOperators.__sub__`.'
def __rsub__(self, other):
return self.reverse_operate(sub, other)
'Implement the ``*`` operator in reverse. See :meth:`.ColumnOperators.__mul__`.'
def __rmul__(self, other):
return self.reverse_operate(mul, other)
'Implement the ``/`` operator in reverse. See :meth:`.ColumnOperators.__div__`.'
def __rdiv__(self, other):
return self.reverse_operate(div, other)
'Produce a :func:`~.expression.between` clause against the parent object, given the lower and upper range.'
def between(self, cleft, cright):
return self.operate(between_op, cleft, cright)
'Produce a :func:`~.expression.distinct` clause against the parent object.'
def distinct(self):
return self.operate(distinct_op)
'Implement the ``+`` operator. In a column context, produces the clause ``a + b`` if the parent object has non-string affinity. If the parent object has a string affinity, produces the concatenation operator, ``a || b`` - see :meth:`.ColumnOperators.concat`.'
def __add__(self, other):
return self.operate(add, other)
'Implement the ``-`` operator. In a column context, produces the clause ``a - b``.'
def __sub__(self, other):
return self.operate(sub, other)
'Implement the ``*`` operator. In a column context, produces the clause ``a * b``.'
def __mul__(self, other):
return self.operate(mul, other)
'Implement the ``/`` operator. In a column context, produces the clause ``a / b``.'
def __div__(self, other):
return self.operate(div, other)
'Implement the ``%`` operator. In a column context, produces the clause ``a % b``.'
def __mod__(self, other):
return self.operate(mod, other)
'Implement the ``//`` operator. In a column context, produces the clause ``a / b``.'
def __truediv__(self, other):
return self.operate(truediv, other)
'Implement the ``//`` operator in reverse. See :meth:`.ColumnOperators.__truediv__`.'
def __rtruediv__(self, other):
return self.reverse_operate(truediv, other)
'Create a shallow copy of this ClauseElement. This method may be used by a generative API. Its also used as part of the "deep" copy afforded by a traversal that combines the _copy_internals() method.'
def _clone(self):
c = self.__class__.__new__(self.__class__) c.__dict__ = self.__dict__.copy() ClauseElement._cloned_set._reset(c) ColumnElement.comparator._reset(c) c._is_clone_of = self return c
'return the \'constructor\' for this ClauseElement. This is for the purposes for creating a new object of this type. Usually, its just the element\'s __class__. However, the "Annotated" version of the object overrides to return the class of its proxied element.'
@property def _constructor(self):
return self.__class__
'Return the set consisting all cloned ancestors of this ClauseElement. Includes this ClauseElement. This accessor tends to be used for FromClause objects to identify \'equivalent\' FROM clauses, regardless of transformative operations.'
@util.memoized_property def _cloned_set(self):
s = util.column_set() f = self while (f is not None): s.add(f) f = f._is_clone_of return s
'return a copy of this ClauseElement with annotations updated by the given dictionary.'
def _annotate(self, values):
return Annotated(self, values)
'return a copy of this ClauseElement with annotations replaced by the given dictionary.'
def _with_annotations(self, values):
return Annotated(self, values)
'return a copy of this :class:`.ClauseElement` with annotations removed. :param values: optional tuple of individual values to remove.'
def _deannotate(self, values=None, clone=False):
if clone: return self._clone() else: return self
'Return a copy with :func:`bindparam()` elements replaced. Same functionality as ``params()``, except adds `unique=True` to affected bind parameters so that multiple statements can be used.'
def unique_params(self, *optionaldict, **kwargs):
return self._params(True, optionaldict, kwargs)
'Return a copy with :func:`bindparam()` elements replaced. Returns a copy of this ClauseElement with :func:`bindparam()` elements replaced with values taken from the given dictionary:: >>> clause = column(\'x\') + bindparam(\'foo\') >>> print clause.compile().params {\'foo\':None} >>> print clause.params({\'foo\':7}).c...
def params(self, *optionaldict, **kwargs):
return self._params(False, optionaldict, kwargs)
'Compare this ClauseElement to the given ClauseElement. Subclasses should override the default behavior, which is a straight identity comparison. \**kw are arguments consumed by subclass compare() methods and may be used to modify the criteria for comparison. (see :class:`.ColumnElement`)'
def compare(self, other, **kw):
return (self is other)
'Reassign internal elements to be clones of themselves. Called during a copy-and-traverse operation on newly shallow-copied elements to create a deep copy. The given clone function should be used, which may be applying additional transformations to the element (i.e. replacement traversal, cloned traversal, annotations)...
def _copy_internals(self, clone=_clone, **kw):
pass
'Return immediate child elements of this :class:`.ClauseElement`. This is used for visit traversal. \**kwargs may contain flags that change the collection that is returned, for example to return a subset of items in order to cut down on larger traversals, or to return child items from a different context (such as schem...
def get_children(self, **kwargs):
return []
'Apply a \'grouping\' to this :class:`.ClauseElement`. This method is overridden by subclasses to return a "grouping" construct, i.e. parenthesis. In particular it\'s used by "binary" expressions to provide a grouping around themselves when placed into a larger expression, as well as by :func:`.select` constructs whe...
def self_group(self, against=None):
return self
'Compile this SQL expression. The return value is a :class:`~.Compiled` object. Calling ``str()`` or ``unicode()`` on the returned value will yield a string representation of the result. The :class:`~.Compiled` object also can return a dictionary of bind parameter names and values using the ``params`` accessor. :param ...
@util.dependencies(u'sqlalchemy.engine.default') def compile(self, default, bind=None, dialect=None, **kw):
if (not dialect): if bind: dialect = bind.dialect elif self.bind: dialect = self.bind.dialect bind = self.bind else: dialect = default.DefaultDialect() return self._compiler(dialect, bind=bind, **kw)
'Return a compiler appropriate for this ClauseElement, given a Dialect.'
def _compiler(self, dialect, **kw):
return dialect.statement_compiler(dialect, self, **kw)
'Return a column expression. Part of the inspection interface; returns self.'
@property def expression(self):
return self
'Return True if the given :class:`.ColumnElement` has a common ancestor to this :class:`.ColumnElement`.'
def shares_lineage(self, othercolumn):
return bool(self.proxy_set.intersection(othercolumn.proxy_set))
'Return True if the given column element compares to this one when targeting within a result row.'
def _compare_name_for_result(self, other):
return (hasattr(other, u'name') and hasattr(self, u'name') and (other.name == self.name))
'Create a new :class:`.ColumnElement` representing this :class:`.ColumnElement` as it appears in the select list of a descending selectable.'
def _make_proxy(self, selectable, name=None, name_is_truncatable=False, **kw):
if (name is None): name = self.anon_label if self.key: key = self.key else: try: key = str(self) except exc.UnsupportedCompilationError: key = self.anon_label else: key = name co = ColumnClause((_as_truncated...
'Compare this ColumnElement to another. Special arguments understood: :param use_proxies: when True, consider two columns that share a common base column as equivalent (i.e. shares_lineage()) :param equivalents: a dictionary of columns as keys mapped to sets of columns. If the given "other" column is present in this di...
def compare(self, other, use_proxies=False, equivalents=None, **kw):
to_compare = (other,) if (equivalents and (other in equivalents)): to_compare = equivalents[other].union(to_compare) for oth in to_compare: if (use_proxies and self.shares_lineage(oth)): return True elif (hash(oth) == hash(self)): return True else: ...
'Produce a column label, i.e. ``<columnname> AS <name>``. This is a shortcut to the :func:`~.expression.label` function. if \'name\' is None, an anonymous label name will be generated.'
def label(self, name):
return Label(name, self, self.type)
'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 thi...
@util.memoized_property def anon_label(self):
return _anonymous_label((u'%%(%d %s)s' % (id(self), getattr(self, u'name', u'anon'))))
'Produce a "bound expression". The return value is an instance of :class:`.BindParameter`; this is a :class:`.ColumnElement` subclass which represents a so-called "placeholder" value in a SQL expression, the value of which is supplied at the point at which the statement in executed against a database connection. In SQL...
def __init__(self, key, value=NO_ARG, type_=None, unique=False, required=NO_ARG, quote=None, callable_=None, isoutparam=False, _compared_to_operator=None, _compared_to_type=None):
if isinstance(key, ColumnClause): type_ = key.type key = key.name if (required is NO_ARG): required = ((value is NO_ARG) and (callable_ is None)) if (value is NO_ARG): value = None if (quote is not None): key = quoted_name(key, quote) if unique: self.k...
'Return a copy of this :class:`.BindParameter` with the given value set.'
def _with_value(self, value):
cloned = self._clone() cloned.value = value cloned.callable = None cloned.required = False if (cloned.type is type_api.NULLTYPE): cloned.type = type_api._type_map.get(type(value), type_api.NULLTYPE) return cloned
'Return the value of this bound parameter, taking into account if the ``callable`` parameter was set. The ``callable`` value will be evaluated and returned if present, else ``value``.'
@property def effective_value(self):
if self.callable: return self.callable() else: return self.value
'Compare this :class:`BindParameter` to the given clause.'
def compare(self, other, **kw):
return (isinstance(other, BindParameter) and self.type._compare_type_affinity(other.type) and (self.value == other.value))
'execute a deferred value for serialization purposes.'
def __getstate__(self):
d = self.__dict__.copy() v = self.value if self.callable: v = self.callable() d[u'callable'] = None d[u'value'] = v return d
'Construct a new :class:`.TextClause` clause, representing a textual SQL string directly. E.g.:: fom sqlalchemy import text t = text("SELECT * FROM users") result = connection.execute(t) The advantages :func:`.text` provides over a plain string are backend-neutral support for bind parameters, per-statement execution op...
@classmethod def _create_text(self, text, bind=None, bindparams=None, typemap=None, autocommit=None):
stmt = TextClause(text, bind=bind) if bindparams: stmt = stmt.bindparams(*bindparams) if typemap: stmt = stmt.columns(**typemap) if (autocommit is not None): util.warn_deprecated(u'autocommit on text() is deprecated. Use .execution_options(autocommit=True)')...
'Establish the values and/or types of bound parameters within this :class:`.TextClause` construct. Given a text construct such as:: from sqlalchemy import text stmt = text("SELECT id, name FROM user WHERE name=:name " "AND timestamp=:timestamp") the :meth:`.TextClause.bindparams` method can be used to establish the ini...
@_generative def bindparams(self, *binds, **names_to_values):
self._bindparams = new_params = self._bindparams.copy() for bind in binds: try: existing = new_params[bind.key] except KeyError: raise exc.ArgumentError((u"This text() construct doesn't define a bound parameter named %r" % bind.key)) els...
'Turn this :class:`.TextClause` object into a :class:`.TextAsFrom` object that can be embedded into another statement. This function essentially bridges the gap between an entirely textual SELECT statement and the SQL expression language concept of a "selectable":: from sqlalchemy.sql import column, text stmt = text("S...
@util.dependencies(u'sqlalchemy.sql.selectable') def columns(self, selectable, *cols, **types):
input_cols = ([(ColumnClause(col.key, types.pop(col.key)) if (col.key in types) else col) for col in cols] + [ColumnClause(key, type_) for (key, type_) in types.items()]) return selectable.TextAsFrom(self, input_cols)
'Return a constant :class:`.Null` construct.'
@classmethod def _singleton(cls):
return NULL
'Return a constant :class:`.False_` construct. E.g.:: >>> from sqlalchemy import false >>> print select([t.c.x]).where(false()) SELECT x FROM t WHERE false A backend which does not support true/false constants will render as an expression against 1 or 0:: >>> print select([t.c.x]).where(false()) SELECT x FROM t WHERE 0...
@classmethod def _singleton(cls):
return FALSE
'Return a constant :class:`.True_` construct. E.g.:: >>> from sqlalchemy import true >>> print select([t.c.x]).where(true()) SELECT x FROM t WHERE true A backend which does not support true/false constants will render as an expression against 1 or 0:: >>> print select([t.c.x]).where(true()) SELECT x FROM t WHERE 1 = 1 ...
@classmethod def _singleton(cls):
return TRUE
'Compare this :class:`.ClauseList` to the given :class:`.ClauseList`, including a comparison of all the clause items.'
def compare(self, other, **kw):
if ((not isinstance(other, ClauseList)) and (len(self.clauses) == 1)): return self.clauses[0].compare(other, **kw) elif (isinstance(other, ClauseList) and (len(self.clauses) == len(other.clauses))): for i in range(0, len(self.clauses)): if (not self.clauses[i].compare(other.clauses[i...
'Produce a conjunction of expressions joined by ``AND``. E.g.:: from sqlalchemy import and_ stmt = select([users_table]).where( and_( users_table.c.name == \'wendy\', users_table.c.enrolled == True The :func:`.and_` conjunction is also available using the Python ``&`` operator (though note that compound expressions nee...
@classmethod def and_(cls, *clauses):
return cls._construct(operators.and_, True_, False_, *clauses)
'Produce a conjunction of expressions joined by ``OR``. E.g.:: from sqlalchemy import or_ stmt = select([users_table]).where( or_( users_table.c.name == \'wendy\', users_table.c.name == \'jack\' The :func:`.or_` conjunction is also available using the Python ``|`` operator (though note that compound expressions need to...
@classmethod def or_(cls, *clauses):
return cls._construct(operators.or_, False_, True_, *clauses)
'Return a :class:`.Tuple`. Main usage is to produce a composite IN construct:: from sqlalchemy import tuple_ tuple_(table.c.col1, table.c.col2).in_( [(1, 2), (5, 12), (10, 19)] .. warning:: The composite IN construct is not supported by all backends, and is currently known to work on Postgresql and MySQL, but not SQLit...
def __init__(self, *clauses, **kw):
clauses = [_literal_as_binds(c) for c in clauses] self._type_tuple = [arg.type for arg in clauses] self.type = kw.pop(u'type_', (self._type_tuple[0] if self._type_tuple else type_api.NULLTYPE)) super(Tuple, self).__init__(*clauses, **kw)
'Produce a ``CASE`` expression. The ``CASE`` construct in SQL is a conditional object that acts somewhat analogously to an "if/then" construct in other languages. It returns an instance of :class:`.Case`. :func:`.case` in its usual form is passed a list of "when" contructs, that is, a list of conditions and results as...
def __init__(self, whens, value=None, else_=None):
try: whens = util.dictlike_iteritems(whens) except TypeError: pass if (value is not None): whenlist = [(_literal_as_binds(c).self_group(), _literal_as_binds(r)) for (c, r) in whens] else: whenlist = [(_no_literals(c).self_group(), _literal_as_binds(r)) for (c, r) in whens...
'Produce a ``CAST`` expression. :func:`.cast` returns an instance of :class:`.Cast`. E.g.:: from sqlalchemy import cast, Numeric stmt = select([ cast(product_table.c.unit_price, Numeric(10, 4)) The above statement will produce SQL resembling:: SELECT CAST(unit_price AS NUMERIC(10, 4)) FROM product The :func:`.cast` fun...
def __init__(self, expression, type_):
self.type = type_api.to_instance(type_) self.clause = _literal_as_binds(expression, type_=self.type) self.typeclause = TypeClause(self.type)
'Return a :class:`.Extract` construct. This is typically available as :func:`.extract` as well as ``func.extract`` from the :data:`.func` namespace.'
def __init__(self, field, expr, **kwargs):
self.type = type_api.INTEGERTYPE self.field = field self.expr = _literal_as_binds(expr, None)
'Produce the ``NULLS FIRST`` modifier for an ``ORDER BY`` expression. :func:`.nullsfirst` is intended to modify the expression produced by :func:`.asc` or :func:`.desc`, and indicates how NULL values should be handled when they are encountered during ordering:: from sqlalchemy import desc, nullsfirst stmt = select([use...
@classmethod def _create_nullsfirst(cls, column):
return UnaryExpression(_literal_as_text(column), modifier=operators.nullsfirst_op)
'Produce the ``NULLS LAST`` modifier for an ``ORDER BY`` expression. :func:`.nullslast` is intended to modify the expression produced by :func:`.asc` or :func:`.desc`, and indicates how NULL values should be handled when they are encountered during ordering:: from sqlalchemy import desc, nullslast stmt = select([users_...
@classmethod def _create_nullslast(cls, column):
return UnaryExpression(_literal_as_text(column), modifier=operators.nullslast_op)
'Produce a descending ``ORDER BY`` clause element. e.g.:: from sqlalchemy import desc stmt = select([users_table]).order_by(desc(users_table.c.name)) will produce SQL as:: SELECT id, name FROM user ORDER BY name DESC The :func:`.desc` function is a standalone version of the :meth:`.ColumnElement.desc` method available ...
@classmethod def _create_desc(cls, column):
return UnaryExpression(_literal_as_text(column), modifier=operators.desc_op)
'Produce an ascending ``ORDER BY`` clause element. e.g.:: from sqlalchemy import asc stmt = select([users_table]).order_by(asc(users_table.c.name)) will produce SQL as:: SELECT id, name FROM user ORDER BY name ASC The :func:`.asc` function is a standalone version of the :meth:`.ColumnElement.asc` method available on al...
@classmethod def _create_asc(cls, column):
return UnaryExpression(_literal_as_text(column), modifier=operators.asc_op)
'Produce an column-expression-level unary ``DISTINCT`` clause. This applies the ``DISTINCT`` keyword to an individual column expression, and is typically contained within an aggregate function, as in:: from sqlalchemy import distinct, func stmt = select([func.count(distinct(users_table.c.name))]) The above would produc...
@classmethod def _create_distinct(cls, expr):
expr = _literal_as_binds(expr) return UnaryExpression(expr, operator=operators.distinct_op, type_=expr.type)
'Compare this :class:`UnaryExpression` against the given :class:`.ClauseElement`.'
def compare(self, other, **kw):
return (isinstance(other, UnaryExpression) and (self.operator == other.operator) and (self.modifier == other.modifier) and self.element.compare(other.element, **kw))
'Compare this :class:`BinaryExpression` against the given :class:`BinaryExpression`.'
def compare(self, other, **kw):
return (isinstance(other, BinaryExpression) and (self.operator == other.operator) and ((self.left.compare(other.left, **kw) and self.right.compare(other.right, **kw)) or (operators.is_commutative(self.operator) and self.left.compare(other.right, **kw) and self.right.compare(other.left, **kw))))
'Produce an :class:`.Over` object against a function. Used against aggregate or so-called "window" functions, for database backends that support window functions. E.g.:: from sqlalchemy import over over(func.row_number(), order_by=\'x\') Would produce "ROW_NUMBER() OVER(ORDER BY x)". :param func: a :class:`.FunctionEle...
def __init__(self, func, partition_by=None, order_by=None):
self.func = func if (order_by is not None): self.order_by = ClauseList(*util.to_list(order_by)) if (partition_by is not None): self.partition_by = ClauseList(*util.to_list(partition_by))
'Return a :class:`Label` object for the given :class:`.ColumnElement`. A label changes the name of an element in the columns clause of a ``SELECT`` statement, typically via the ``AS`` SQL keyword. This functionality is more conveniently available via the :meth:`.ColumnElement.label` method on :class:`.ColumnElement`. :...
def __init__(self, name, element, type_=None):
while isinstance(element, Label): element = element.element if name: self.name = name else: self.name = _anonymous_label((u'%%(%d %s)s' % (id(self), getattr(element, u'name', u'anon')))) self.key = self._label = self._key_label = self.name self._element = element self....
'Produce a :class:`.ColumnClause` object. The :class:`.ColumnClause` is a lightweight analogue to the :class:`.Column` class. The :func:`.column` function can be invoked with just a name alone, as in:: from sqlalchemy.sql import column id, name = column("id"), column("name") stmt = select([id, name]).select_from("user...
def __init__(self, text, type_=None, is_literal=False, _selectable=None):
self.key = self.name = text self.table = _selectable self.type = type_api.to_instance(type_) self.is_literal = is_literal
'pull \'name\' from parent, if not present'
@util.memoized_property def name(self):
return self._Annotated__element.name
'pull \'table\' from parent, if not present'
@util.memoized_property def table(self):
return self._Annotated__element.table
'pull \'key\' from parent, if not present'
@util.memoized_property def key(self):
return self._Annotated__element.key
'Construct a :class:`.FunctionElement`.'
def __init__(self, *clauses, **kwargs):
args = [_literal_as_binds(c, self.name) for c in clauses] self.clause_expr = ClauseList(operator=operators.comma_op, group_contents=True, *args).self_group()
'Fulfill the \'columns\' contract of :class:`.ColumnElement`. Returns a single-element list consisting of this object.'
@property def columns(self):
return [self]
'Return the underlying :class:`.ClauseList` which contains the arguments for this :class:`.FunctionElement`.'
@util.memoized_property def clauses(self):
return self.clause_expr.element