1409
1521
"SQL expression object or string expected."
1525
def _no_literals(element):
1526
if hasattr(element, '__clause_element__'):
1527
return element.__clause_element__()
1528
elif not isinstance(element, Visitable):
1529
raise exc.ArgumentError("Ambiguous literal: %r. Use the 'text()' "
1530
"function to indicate a SQL expression "
1531
"literal, or 'literal()' to indicate a "
1532
"bound value." % element)
1537
def _is_literal(element):
1538
return not isinstance(element, Visitable) and \
1539
not hasattr(element, '__clause_element__')
1542
def _only_column_elements_or_none(element, name):
1546
return _only_column_elements(element, name)
1549
def _only_column_elements(element, name):
1550
if hasattr(element, '__clause_element__'):
1551
element = element.__clause_element__()
1552
if not isinstance(element, ColumnElement):
1553
raise exc.ArgumentError(
1554
"Column-based expression object expected for argument "
1555
"'%s'; got: '%s', type %s" % (name, element, type(element)))
1559
def _literal_as_binds(element, name=None, type_=None):
1560
if hasattr(element, '__clause_element__'):
1561
return element.__clause_element__()
1562
elif not isinstance(element, Visitable):
1566
return _BindParamClause(name, element, type_=type_, unique=True)
1571
def _interpret_as_column_or_from(element):
1572
if isinstance(element, Visitable):
1574
elif hasattr(element, '__clause_element__'):
1575
return element.__clause_element__()
1577
insp = inspection.inspect(element, raiseerr=False)
1579
if isinstance(element, (util.NoneType, bool)):
1580
return _const_expr(element)
1581
elif hasattr(insp, "selectable"):
1582
return insp.selectable
1584
return literal_column(str(element))
1587
def _interpret_as_from(element):
1588
insp = inspection.inspect(element, raiseerr=False)
1590
if isinstance(element, basestring):
1591
return TextClause(unicode(element))
1592
elif hasattr(insp, "selectable"):
1593
return insp.selectable
1594
raise exc.ArgumentError("FROM expression expected")
1412
1597
def _const_expr(element):
1598
if isinstance(element, (Null, False_, True_)):
1600
elif element is None:
1415
1602
elif element is False:
1836
class _CompareMixin(ColumnOperators):
1837
"""Defines comparison and math operations for :class:`.ClauseElement`
1972
class _DefaultColumnComparator(operators.ColumnOperators):
1973
"""Defines comparison and math operations.
1840
1975
See :class:`.ColumnOperators` and :class:`.Operators` for descriptions
1841
1976
of all operations.
1845
def __compare(self, op, obj, negate=None, reverse=False,
1848
if obj is None or isinstance(obj, _Null):
1849
if op in (operators.eq, operators.is_):
1850
return _BinaryExpression(self, null(), operators.is_,
1851
negate=operators.isnot)
1852
elif op in (operators.ne, operators.isnot):
1853
return _BinaryExpression(self, null(), operators.isnot,
1854
negate=operators.is_)
1980
@util.memoized_property
1982
return self.expr.type
1984
def operate(self, op, *other, **kwargs):
1985
o = self.operators[op.__name__]
1986
return o[0](self, self.expr, op, *(other + o[1:]), **kwargs)
1988
def reverse_operate(self, op, other, **kwargs):
1989
o = self.operators[op.__name__]
1990
return o[0](self, self.expr, op, other, reverse=True, *o[1:], **kwargs)
1992
def _adapt_expression(self, op, other_comparator):
1993
"""evaluate the return type of <self> <op> <othertype>,
1994
and apply any adaptations to the given operator.
1996
This method determines the type of a resulting binary expression
1997
given two source types and an operator. For example, two
1998
:class:`.Column` objects, both of the type :class:`.Integer`, will
1999
produce a :class:`.BinaryExpression` that also has the type
2000
:class:`.Integer` when compared via the addition (``+``) operator.
2001
However, using the addition operator with an :class:`.Integer`
2002
and a :class:`.Date` object will produce a :class:`.Date`, assuming
2003
"days delta" behavior by the database (in reality, most databases
2004
other than Postgresql don't accept this particular operation).
2006
The method returns a tuple of the form <operator>, <type>.
2007
The resulting operator and type will be those applied to the
2008
resulting :class:`.BinaryExpression` as the final operator and the
2009
right-hand side of the expression.
2011
Note that only a subset of operators make usage of
2012
:meth:`._adapt_expression`,
2013
including math operators and user-defined operators, but not
2014
boolean comparison or special SQL keywords like MATCH or BETWEEN.
2017
return op, other_comparator.type
2019
def _boolean_compare(self, expr, op, obj, negate=None, reverse=False,
2020
_python_is_types=(util.NoneType, bool),
2023
if isinstance(obj, _python_is_types + (Null, True_, False_)):
2025
# allow x ==/!= True/False to be treated as a literal.
2026
# this comes out to "== / != true/false" or "1/0" if those
2027
# constants aren't supported and works on all platforms
2028
if op in (operators.eq, operators.ne) and \
2029
isinstance(obj, (bool, True_, False_)):
2030
return BinaryExpression(expr,
2033
type_=sqltypes.BOOLEANTYPE,
2034
negate=negate, modifiers=kwargs)
1856
raise exc.ArgumentError("Only '='/'!=' operators can "
1857
"be used with NULL")
2036
# all other None/True/False uses IS, IS NOT
2037
if op in (operators.eq, operators.is_):
2038
return BinaryExpression(expr, _const_expr(obj),
2040
negate=operators.isnot)
2041
elif op in (operators.ne, operators.isnot):
2042
return BinaryExpression(expr, _const_expr(obj),
2044
negate=operators.is_)
2046
raise exc.ArgumentError(
2047
"Only '=', '!=', 'is_()', 'isnot()' operators can "
2048
"be used with None/True/False")
1859
obj = self._check_literal(op, obj)
2050
obj = self._check_literal(expr, op, obj)
1862
return _BinaryExpression(obj,
2053
return BinaryExpression(obj,
1865
2056
type_=sqltypes.BOOLEANTYPE,
1866
2057
negate=negate, modifiers=kwargs)
1868
return _BinaryExpression(self,
2059
return BinaryExpression(expr,
1871
2062
type_=sqltypes.BOOLEANTYPE,
1872
2063
negate=negate, modifiers=kwargs)
1874
def __operate(self, op, obj, reverse=False):
1875
obj = self._check_literal(op, obj)
2065
def _binary_operate(self, expr, op, obj, reverse=False, result_type=None,
2067
obj = self._check_literal(expr, op, obj)
1878
left, right = obj, self
1880
left, right = self, obj
1882
if left.type is None:
1883
op, result_type = sqltypes.NULLTYPE._adapt_expression(op,
1885
elif right.type is None:
1886
op, result_type = left.type._adapt_expression(op,
1889
op, result_type = left.type._adapt_expression(op,
1891
return _BinaryExpression(left, right, op, type_=result_type)
1894
# a mapping of operators with the method they use, along with their negated
1895
# operator for comparison operators
1897
operators.add : (__operate,),
1898
operators.mul : (__operate,),
1899
operators.sub : (__operate,),
1901
operators.div : (__operate,),
1903
operators.mod : (__operate,),
1904
operators.truediv : (__operate,),
1905
operators.lt : (__compare, operators.ge),
1906
operators.le : (__compare, operators.gt),
1907
operators.ne : (__compare, operators.eq),
1908
operators.gt : (__compare, operators.le),
1909
operators.ge : (__compare, operators.lt),
1910
operators.eq : (__compare, operators.ne),
1911
operators.like_op : (__compare, operators.notlike_op),
1912
operators.ilike_op : (__compare, operators.notilike_op),
1913
operators.is_ : (__compare, operators.is_),
1914
operators.isnot : (__compare, operators.isnot),
1917
def operate(self, op, *other, **kwargs):
1918
o = _CompareMixin.operators[op]
1919
return o[0](self, op, other[0], *o[1:], **kwargs)
1921
def reverse_operate(self, op, other, **kwargs):
1922
o = _CompareMixin.operators[op]
1923
return o[0](self, op, other, reverse=True, *o[1:], **kwargs)
1925
def in_(self, other):
1926
"""See :meth:`.ColumnOperators.in_`."""
1927
return self._in_impl(operators.in_op, operators.notin_op, other)
1929
def _in_impl(self, op, negate_op, seq_or_selectable):
2070
left, right = obj, expr
2072
left, right = expr, obj
2074
if result_type is None:
2075
op, result_type = left.comparator._adapt_expression(
2076
op, right.comparator)
2078
return BinaryExpression(left, right, op, type_=result_type)
2080
def _scalar(self, expr, op, fn, **kw):
2083
def _in_impl(self, expr, op, seq_or_selectable, negate_op, **kw):
1930
2084
seq_or_selectable = _clause_element_as_expr(seq_or_selectable)
1932
if isinstance(seq_or_selectable, _ScalarSelect):
1933
return self.__compare(op, seq_or_selectable,
2086
if isinstance(seq_or_selectable, ScalarSelect):
2087
return self._boolean_compare(expr, op, seq_or_selectable,
1934
2088
negate=negate_op)
1935
elif isinstance(seq_or_selectable, _SelectBase):
2089
elif isinstance(seq_or_selectable, SelectBase):
1937
2091
# TODO: if we ever want to support (x, y, z) IN (select x,
1938
2092
# y, z from table), we would need a multi-column version of
1939
2093
# as_scalar() to produce a multi- column selectable that
1940
2094
# does not export itself as a FROM clause
1942
return self.__compare(op, seq_or_selectable.as_scalar(),
1944
elif isinstance(seq_or_selectable, (Selectable, _TextClause)):
1945
return self.__compare(op, seq_or_selectable,
2096
return self._boolean_compare(
2097
expr, op, seq_or_selectable.as_scalar(),
2098
negate=negate_op, **kw)
2099
elif isinstance(seq_or_selectable, (Selectable, TextClause)):
2100
return self._boolean_compare(expr, op, seq_or_selectable,
2101
negate=negate_op, **kw)
1949
2103
# Handle non selectable arguments as sequences
1952
2105
for o in seq_or_selectable:
1953
2106
if not _is_literal(o):
1954
if not isinstance(o, _CompareMixin):
2107
if not isinstance(o, ColumnOperators):
1955
2108
raise exc.InvalidRequestError('in() function accept'
1956
2109
's either a list of non-selectable values, '
1957
2110
'or a selectable: %r' % o)
1959
o = self._bind_param(op, o)
2114
o = expr._bind_param(op, o)
1961
2116
if len(args) == 0:
1970
2125
'empty sequence. This results in a '
1971
2126
'contradiction, which nonetheless can be '
1972
2127
'expensive to evaluate. Consider alternative '
1973
'strategies for improved performance.' % self)
2128
'strategies for improved performance.' % expr)
1976
return self.__compare(op,
2131
return self._boolean_compare(expr, op,
1977
2132
ClauseList(*args).self_group(against=op),
1978
2133
negate=negate_op)
2135
def _unsupported_impl(self, expr, op, *arg, **kw):
2136
raise NotImplementedError("Operator '%s' is not supported on "
2137
"this expression" % op.__name__)
2139
def _neg_impl(self, expr, op, **kw):
1981
2140
"""See :meth:`.ColumnOperators.__neg__`."""
1982
return _UnaryExpression(self, operator=operators.neg)
1984
def startswith(self, other, escape=None):
1985
"""See :meth:`.ColumnOperators.startswith`."""
1986
# use __radd__ to force string concat behavior
1987
return self.__compare(
1989
literal_column("'%'", type_=sqltypes.String).__radd__(
1990
self._check_literal(operators.like_op, other)
1994
def endswith(self, other, escape=None):
1995
"""See :meth:`.ColumnOperators.endswith`."""
1996
return self.__compare(
1998
literal_column("'%'", type_=sqltypes.String) +
1999
self._check_literal(operators.like_op, other),
2002
def contains(self, other, escape=None):
2003
"""See :meth:`.ColumnOperators.contains`."""
2004
return self.__compare(
2006
literal_column("'%'", type_=sqltypes.String) +
2007
self._check_literal(operators.like_op, other) +
2008
literal_column("'%'", type_=sqltypes.String),
2011
def match(self, other):
2141
return UnaryExpression(expr, operator=operators.neg)
2143
def _match_impl(self, expr, op, other, **kw):
2012
2144
"""See :meth:`.ColumnOperators.match`."""
2013
return self.__compare(operators.match_op,
2014
self._check_literal(operators.match_op,
2145
return self._boolean_compare(expr, operators.match_op,
2146
self._check_literal(expr, operators.match_op,
2017
def label(self, name):
2018
"""Produce a column label, i.e. ``<columnname> AS <name>``.
2020
This is a shortcut to the :func:`~.expression.label` function.
2022
if 'name' is None, an anonymous label name will be generated.
2025
return _Label(name, self, self.type)
2028
"""See :meth:`.ColumnOperators.desc`."""
2032
"""See :meth:`.ColumnOperators.asc`."""
2035
def nullsfirst(self):
2036
"""See :meth:`.ColumnOperators.nullsfirst`."""
2037
return nullsfirst(self)
2039
def nullslast(self):
2040
"""See :meth:`.ColumnOperators.nullslast`."""
2041
return nullslast(self)
2149
def _distinct_impl(self, expr, op, **kw):
2044
2150
"""See :meth:`.ColumnOperators.distinct`."""
2045
return _UnaryExpression(self, operator=operators.distinct_op,
2151
return UnaryExpression(expr, operator=operators.distinct_op,
2048
def between(self, cleft, cright):
2154
def _between_impl(self, expr, op, cleft, cright, **kw):
2049
2155
"""See :meth:`.ColumnOperators.between`."""
2050
return _BinaryExpression(
2156
return BinaryExpression(
2053
self._check_literal(operators.and_, cleft),
2054
self._check_literal(operators.and_, cright),
2159
self._check_literal(expr, operators.and_, cleft),
2160
self._check_literal(expr, operators.and_, cright),
2055
2161
operator=operators.and_,
2057
2163
operators.between_op)
2059
def collate(self, collation):
2060
"""See :meth:`.ColumnOperators.collate`."""
2062
return collate(self, collation)
2064
def op(self, operator):
2065
"""See :meth:`.ColumnOperators.op`."""
2067
return lambda other: self.__operate(operator, other)
2069
def _bind_param(self, operator, obj):
2070
return _BindParamClause(None, obj,
2071
_compared_to_operator=operator,
2072
_compared_to_type=self.type, unique=True)
2074
def _check_literal(self, operator, other):
2075
if isinstance(other, _BindParamClause) and \
2076
isinstance(other.type, sqltypes.NullType):
2077
# TODO: perhaps we should not mutate the incoming bindparam()
2078
# here and instead make a copy of it. this might
2079
# be the only place that we're mutating an incoming construct.
2080
other.type = self.type
2165
def _collate_impl(self, expr, op, other, **kw):
2166
return collate(expr, other)
2168
# a mapping of operators with the method they use, along with
2169
# their negated operator for comparison operators
2171
"add": (_binary_operate,),
2172
"mul": (_binary_operate,),
2173
"sub": (_binary_operate,),
2174
"div": (_binary_operate,),
2175
"mod": (_binary_operate,),
2176
"truediv": (_binary_operate,),
2177
"custom_op": (_binary_operate,),
2178
"concat_op": (_binary_operate,),
2179
"lt": (_boolean_compare, operators.ge),
2180
"le": (_boolean_compare, operators.gt),
2181
"ne": (_boolean_compare, operators.eq),
2182
"gt": (_boolean_compare, operators.le),
2183
"ge": (_boolean_compare, operators.lt),
2184
"eq": (_boolean_compare, operators.ne),
2185
"like_op": (_boolean_compare, operators.notlike_op),
2186
"ilike_op": (_boolean_compare, operators.notilike_op),
2187
"notlike_op": (_boolean_compare, operators.like_op),
2188
"notilike_op": (_boolean_compare, operators.ilike_op),
2189
"contains_op": (_boolean_compare, operators.notcontains_op),
2190
"startswith_op": (_boolean_compare, operators.notstartswith_op),
2191
"endswith_op": (_boolean_compare, operators.notendswith_op),
2192
"desc_op": (_scalar, desc),
2193
"asc_op": (_scalar, asc),
2194
"nullsfirst_op": (_scalar, nullsfirst),
2195
"nullslast_op": (_scalar, nullslast),
2196
"in_op": (_in_impl, operators.notin_op),
2197
"notin_op": (_in_impl, operators.in_op),
2198
"is_": (_boolean_compare, operators.is_),
2199
"isnot": (_boolean_compare, operators.isnot),
2200
"collate": (_collate_impl,),
2201
"match_op": (_match_impl,),
2202
"distinct_op": (_distinct_impl,),
2203
"between_op": (_between_impl, ),
2204
"neg": (_neg_impl,),
2205
"getitem": (_unsupported_impl,),
2206
"lshift": (_unsupported_impl,),
2207
"rshift": (_unsupported_impl,),
2210
def _check_literal(self, expr, operator, other):
2211
if isinstance(other, (ColumnElement, TextClause)):
2212
if isinstance(other, BindParameter) and \
2213
isinstance(other.type, sqltypes.NullType):
2214
# TODO: perhaps we should not mutate the incoming
2215
# bindparam() here and instead make a copy of it.
2216
# this might be the only place that we're mutating
2217
# an incoming construct.
2218
other.type = expr.type
2082
2220
elif hasattr(other, '__clause_element__'):
2083
2221
other = other.__clause_element__()
2084
if isinstance(other, (_SelectBase, Alias)):
2085
other = other.as_scalar()
2087
elif not isinstance(other, ClauseElement):
2088
return self._bind_param(operator, other)
2089
elif isinstance(other, (_SelectBase, Alias)):
2222
elif isinstance(other, sqltypes.TypeEngine.Comparator):
2225
if isinstance(other, (SelectBase, Alias)):
2090
2226
return other.as_scalar()
2227
elif not isinstance(other, (ColumnElement, TextClause)):
2228
return expr._bind_param(operator, other)
2095
class ColumnElement(ClauseElement, _CompareMixin):
2096
"""Represent an element that is usable within the "column clause" portion
2097
of a ``SELECT`` statement.
2099
This includes columns associated with tables, aliases, and
2100
subqueries, expressions, function calls, SQL keywords such as
2101
``NULL``, literals, etc. :class:`.ColumnElement` is the ultimate base
2102
class for all such elements.
2233
class ColumnElement(ClauseElement, ColumnOperators):
2234
"""Represent a column-oriented SQL expression suitable for usage in the
2235
"columns" clause, WHERE clause etc. of a statement.
2237
While the most familiar kind of :class:`.ColumnElement` is the
2238
:class:`.Column` object, :class:`.ColumnElement` serves as the basis
2239
for any unit that may be present in a SQL expression, including
2240
the expressions themselves, SQL functions, bound parameters,
2241
literal expressions, keywords such as ``NULL``, etc.
2242
:class:`.ColumnElement` is the ultimate base class for all such elements.
2244
A :class:`.ColumnElement` provides the ability to generate new
2245
:class:`.ColumnElement`
2246
objects using Python expressions. This means that Python operators
2247
such as ``==``, ``!=`` and ``<`` are overloaded to mimic SQL operations,
2248
and allow the instantiation of further :class:`.ColumnElement` instances
2249
which are composed from other, more fundamental :class:`.ColumnElement`
2250
objects. For example, two :class:`.ColumnClause` objects can be added
2251
together with the addition operator ``+`` to produce
2252
a :class:`.BinaryExpression`.
2253
Both :class:`.ColumnClause` and :class:`.BinaryExpression` are subclasses
2254
of :class:`.ColumnElement`::
2256
>>> from sqlalchemy.sql import column
2257
>>> column('a') + column('b')
2258
<sqlalchemy.sql.expression.BinaryExpression object at 0x101029dd0>
2259
>>> print column('a') + column('b')
2104
2262
:class:`.ColumnElement` supports the ability to be a *proxy* element,
2105
2263
which indicates that the :class:`.ColumnElement` may be associated with
2106
2264
a :class:`.Selectable` which was derived from another :class:`.Selectable`.
2107
2265
An example of a "derived" :class:`.Selectable` is an :class:`.Alias` of a
2108
:class:`~sqlalchemy.schema.Table`.
2110
A :class:`.ColumnElement`, by subclassing the :class:`_CompareMixin` mixin
2111
class, provides the ability to generate new :class:`.ClauseElement`
2112
objects using Python expressions. See the :class:`_CompareMixin`
2113
docstring for more details.
2266
:class:`~sqlalchemy.schema.Table`. For the ambitious, an in-depth
2267
discussion of this concept can be found at
2268
`Expression Transformations <http://techspot.zzzeek.org/2008/01/23/expression-transformations/>`_.
5193
5682
def correlate(self, *fromclauses):
5194
"""return a new select() construct which will correlate the given FROM
5195
clauses to that of an enclosing select(), if a match is found.
5197
By "match", the given fromclause must be present in this select's
5198
list of FROM objects and also present in an enclosing select's list of
5201
Calling this method turns off the select's default behavior of
5202
"auto-correlation". Normally, select() auto-correlates all of its FROM
5203
clauses to those of an embedded select when compiled.
5205
If the fromclause is None, correlation is disabled for the returned
5209
self._should_correlate = False
5210
if fromclauses and fromclauses[0] is None:
5211
self._correlate = set()
5213
self._correlate = self._correlate.union(fromclauses)
5683
"""return a new :class:`.Select` which will correlate the given FROM
5684
clauses to that of an enclosing :class:`.Select`.
5686
Calling this method turns off the :class:`.Select` object's
5687
default behavior of "auto-correlation". Normally, FROM elements
5688
which appear in a :class:`.Select` that encloses this one via
5689
its :term:`WHERE clause`, ORDER BY, HAVING or
5690
:term:`columns clause` will be omitted from this :class:`.Select`
5691
object's :term:`FROM clause`.
5692
Setting an explicit correlation collection using the
5693
:meth:`.Select.correlate` method provides a fixed list of FROM objects
5694
that can potentially take place in this process.
5696
When :meth:`.Select.correlate` is used to apply specific FROM clauses
5697
for correlation, the FROM elements become candidates for
5698
correlation regardless of how deeply nested this :class:`.Select`
5699
object is, relative to an enclosing :class:`.Select` which refers to
5700
the same FROM object. This is in contrast to the behavior of
5701
"auto-correlation" which only correlates to an immediate enclosing
5702
:class:`.Select`. Multi-level correlation ensures that the link
5703
between enclosed and enclosing :class:`.Select` is always via
5704
at least one WHERE/ORDER BY/HAVING/columns clause in order for
5705
correlation to take place.
5707
If ``None`` is passed, the :class:`.Select` object will correlate
5708
none of its FROM entries, and all will render unconditionally
5709
in the local FROM clause.
5711
:param \*fromclauses: a list of one or more :class:`.FromClause`
5712
constructs, or other compatible constructs (i.e. ORM-mapped
5713
classes) to become part of the correlate collection.
5715
.. versionchanged:: 0.8.0 ORM-mapped classes are accepted by
5716
:meth:`.Select.correlate`.
5718
.. versionchanged:: 0.8.0 The :meth:`.Select.correlate` method no
5719
longer unconditionally removes entries from the FROM clause; instead,
5720
the candidate FROM entries must also be matched by a FROM entry
5721
located in an enclosing :class:`.Select`, which ultimately encloses
5722
this one as present in the WHERE clause, ORDER BY clause, HAVING
5723
clause, or columns clause of an enclosing :meth:`.Select`.
5725
.. versionchanged:: 0.8.2 explicit correlation takes place
5726
via any level of nesting of :class:`.Select` objects; in previous
5727
0.8 versions, correlation would only occur relative to the immediate
5728
enclosing :class:`.Select` construct.
5732
:meth:`.Select.correlate_except`
5734
:ref:`correlated_subqueries`
5737
self._auto_correlate = False
5738
if fromclauses and fromclauses[0] is None:
5739
self._correlate = ()
5741
self._correlate = set(self._correlate).union(
5742
_interpret_as_from(f) for f in fromclauses)
5745
def correlate_except(self, *fromclauses):
5746
"""return a new :class:`.Select` which will omit the given FROM
5747
clauses from the auto-correlation process.
5749
Calling :meth:`.Select.correlate_except` turns off the
5750
:class:`.Select` object's default behavior of
5751
"auto-correlation" for the given FROM elements. An element
5752
specified here will unconditionally appear in the FROM list, while
5753
all other FROM elements remain subject to normal auto-correlation
5756
.. versionchanged:: 0.8.2 The :meth:`.Select.correlate_except`
5757
method was improved to fully prevent FROM clauses specified here
5758
from being omitted from the immediate FROM clause of this
5761
If ``None`` is passed, the :class:`.Select` object will correlate
5762
all of its FROM entries.
5764
.. versionchanged:: 0.8.2 calling ``correlate_except(None)`` will
5765
correctly auto-correlate all FROM clauses.
5767
:param \*fromclauses: a list of one or more :class:`.FromClause`
5768
constructs, or other compatible constructs (i.e. ORM-mapped
5769
classes) to become part of the correlate-exception collection.
5773
:meth:`.Select.correlate`
5775
:ref:`correlated_subqueries`
5779
self._auto_correlate = False
5780
if fromclauses and fromclauses[0] is None:
5781
self._correlate_except = ()
5783
self._correlate_except = set(self._correlate_except or ()).union(
5784
_interpret_as_from(f) for f in fromclauses)
5215
5786
def append_correlation(self, fromclause):
5216
5787
"""append the given correlation expression to this select()
5219
self._should_correlate = False
5220
self._correlate = self._correlate.union([fromclause])
5790
This is an **in-place** mutation method; the
5791
:meth:`~.Select.correlate` method is preferred, as it provides standard
5792
:term:`method chaining`.
5796
self._auto_correlate = False
5797
self._correlate = set(self._correlate).union(
5798
_interpret_as_from(f) for f in fromclause)
5222
5800
def append_column(self, column):
5223
5801
"""append the given column expression to the columns clause of this
5224
5802
select() construct.
5804
This is an **in-place** mutation method; the
5805
:meth:`~.Select.column` method is preferred, as it provides standard
5806
:term:`method chaining`.
5227
5809
self._reset_exported()
5228
column = _literal_as_column(column)
5810
column = _interpret_as_column_or_from(column)
5230
if isinstance(column, _ScalarSelect):
5812
if isinstance(column, ScalarSelect):
5231
5813
column = column.self_group(against=operators.comma_op)
5233
5815
self._raw_columns = self._raw_columns + [column]
5511
6183
users.update().where(users.c.id==5).values(name="some name")
5513
:param \*args: A single dictionary can be sent as the first positional
5514
argument. This allows non-string based keys, such as Column
5515
objects, to be used::
5517
users.insert().values({users.c.name : "some name"})
5519
users.update().where(users.c.id==5).values({users.c.name : "some name"})
6185
:param \*args: Alternatively, a dictionary, tuple or list
6186
of dictionaries or tuples can be passed as a single positional
6187
argument in order to form the VALUES or
6188
SET clause of the statement. The single dictionary form
6189
works the same as the kwargs form::
6191
users.insert().values({"name": "some name"})
6193
If a tuple is passed, the tuple should contain the same number
6194
of columns as the target :class:`.Table`::
6196
users.insert().values((5, "some name"))
6198
The :class:`.Insert` construct also supports multiply-rendered VALUES
6199
construct, for those backends which support this SQL syntax
6200
(SQLite, Postgresql, MySQL). This mode is indicated by passing a list
6201
of one or more dictionaries/tuples::
6203
users.insert().values([
6204
{"name": "some name"},
6205
{"name": "some other name"},
6206
{"name": "yet another name"},
6209
In the case of an :class:`.Update`
6210
construct, only the single dictionary/tuple form is accepted,
6211
else an exception is raised. It is also an exception case to
6212
attempt to mix the single-/multiple- value styles together,
6213
either through multiple :meth:`.ValuesBase.values` calls
6214
or by sending a list + kwargs at the same time.
6218
Passing a multiple values list is *not* the same
6219
as passing a multiple values list to the :meth:`.Connection.execute`
6220
method. Passing a list of parameter sets to :meth:`.ValuesBase.values`
6221
produces a construct of this form::
6223
INSERT INTO table (col1, col2, col3) VALUES
6224
(col1_0, col2_0, col3_0),
6225
(col1_1, col2_1, col3_1),
6228
whereas a multiple list passed to :meth:`.Connection.execute`
6229
has the effect of using the DBAPI
6230
`executemany() <http://www.python.org/dev/peps/pep-0249/#id18>`_
6231
method, which provides a high-performance system of invoking
6232
a single-row INSERT statement many times against a series
6233
of parameter sets. The "executemany" style is supported by
6234
all database backends, as it does not depend on a special SQL
6237
.. versionadded:: 0.8
6238
Support for multiple-VALUES INSERT statements.
5523
6243
:ref:`inserts_and_updates` - SQL Expression
5524
6244
Language Tutorial