summaryrefslogtreecommitdiff
path: root/lib/sqlalchemy/sql
diff options
context:
space:
mode:
authorBrian Jarrett <celttechie@gmail.com>2014-07-20 12:44:40 -0400
committerMike Bayer <mike_mp@zzzcomputing.com>2014-07-20 12:44:40 -0400
commitcca03097f47f22783d42d1853faac6cf84607c5a (patch)
tree4fe1a63d03a2d88d1cf37e1167759dfaf84f4ce7 /lib/sqlalchemy/sql
parent827329a0cca5351094a1a86b6b2be2b9182f0ae2 (diff)
downloadsqlalchemy-cca03097f47f22783d42d1853faac6cf84607c5a.tar.gz
- apply pep8 formatting to sqlalchemy/sql, sqlalchemy/util, sqlalchemy/dialects,
sqlalchemy/orm, sqlalchemy/event, sqlalchemy/testing
Diffstat (limited to 'lib/sqlalchemy/sql')
-rw-r--r--lib/sqlalchemy/sql/__init__.py6
-rw-r--r--lib/sqlalchemy/sql/annotation.py19
-rw-r--r--lib/sqlalchemy/sql/base.py109
-rw-r--r--lib/sqlalchemy/sql/compiler.py1019
-rw-r--r--lib/sqlalchemy/sql/ddl.py109
-rw-r--r--lib/sqlalchemy/sql/default_comparator.py107
-rw-r--r--lib/sqlalchemy/sql/dml.py183
-rw-r--r--lib/sqlalchemy/sql/elements.py542
-rw-r--r--lib/sqlalchemy/sql/expression.py46
-rw-r--r--lib/sqlalchemy/sql/functions.py33
-rw-r--r--lib/sqlalchemy/sql/naming.py22
-rw-r--r--lib/sqlalchemy/sql/operators.py34
-rw-r--r--lib/sqlalchemy/sql/schema.py631
-rw-r--r--lib/sqlalchemy/sql/selectable.py508
-rw-r--r--lib/sqlalchemy/sql/sqltypes.py234
-rw-r--r--lib/sqlalchemy/sql/type_api.py65
-rw-r--r--lib/sqlalchemy/sql/util.py116
-rw-r--r--lib/sqlalchemy/sql/visitors.py12
18 files changed, 1988 insertions, 1807 deletions
diff --git a/lib/sqlalchemy/sql/__init__.py b/lib/sqlalchemy/sql/__init__.py
index a24f0cffa..4d013859c 100644
--- a/lib/sqlalchemy/sql/__init__.py
+++ b/lib/sqlalchemy/sql/__init__.py
@@ -63,10 +63,11 @@ from .expression import (
union,
union_all,
update,
- )
+)
from .visitors import ClauseVisitor
+
def __go(lcls):
global __all__
from .. import util as _sa_util
@@ -74,7 +75,7 @@ def __go(lcls):
import inspect as _inspect
__all__ = sorted(name for name, obj in lcls.items()
- if not (name.startswith('_') or _inspect.ismodule(obj)))
+ if not (name.startswith('_') or _inspect.ismodule(obj)))
from .annotation import _prepare_annotations, Annotated
from .elements import AnnotatedColumnElement, ClauseList
@@ -88,4 +89,3 @@ def __go(lcls):
from . import naming
__go(locals())
-
diff --git a/lib/sqlalchemy/sql/annotation.py b/lib/sqlalchemy/sql/annotation.py
index 380624a9b..02f5c3c1c 100644
--- a/lib/sqlalchemy/sql/annotation.py
+++ b/lib/sqlalchemy/sql/annotation.py
@@ -6,13 +6,15 @@
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""The :class:`.Annotated` class and related routines; creates hash-equivalent
-copies of SQL constructs which contain context-specific markers and associations.
+copies of SQL constructs which contain context-specific markers and
+associations.
"""
from .. import util
from . import operators
+
class Annotated(object):
"""clones a ClauseElement and applies an 'annotations' dictionary.
@@ -66,7 +68,8 @@ class Annotated(object):
return self._with_annotations(_values)
def _compiler_dispatch(self, visitor, **kw):
- return self.__element.__class__._compiler_dispatch(self, visitor, **kw)
+ return self.__element.__class__._compiler_dispatch(
+ self, visitor, **kw)
@property
def _constructor(self):
@@ -93,14 +96,12 @@ class Annotated(object):
return hash(other) == hash(self)
-
# hard-generate Annotated subclasses. this technique
# is used instead of on-the-fly types (i.e. type.__new__())
# so that the resulting objects are pickleable.
annotated_classes = {}
-
def _deep_annotate(element, annotations, exclude=None):
"""Deep copy the given ClauseElement, annotating each element
with the given annotations dictionary.
@@ -110,8 +111,8 @@ def _deep_annotate(element, annotations, exclude=None):
"""
def clone(elem):
if exclude and \
- hasattr(elem, 'proxy_set') and \
- elem.proxy_set.intersection(exclude):
+ hasattr(elem, 'proxy_set') and \
+ elem.proxy_set.intersection(exclude):
newelem = elem._clone()
elif annotations != elem._annotations:
newelem = elem._annotate(annotations)
@@ -163,6 +164,7 @@ def _shallow_annotate(element, annotations):
element._copy_internals()
return element
+
def _new_annotation_type(cls, base_cls):
if issubclass(cls, Annotated):
return cls
@@ -178,11 +180,12 @@ def _new_annotation_type(cls, base_cls):
break
annotated_classes[cls] = anno_cls = type(
- "Annotated%s" % cls.__name__,
- (base_cls, cls), {})
+ "Annotated%s" % cls.__name__,
+ (base_cls, cls), {})
globals()["Annotated%s" % cls.__name__] = anno_cls
return anno_cls
+
def _prepare_annotations(target_hierarchy, base_cls):
stack = [target_hierarchy]
while stack:
diff --git a/lib/sqlalchemy/sql/base.py b/lib/sqlalchemy/sql/base.py
index 1e02b3fb0..5358d95b5 100644
--- a/lib/sqlalchemy/sql/base.py
+++ b/lib/sqlalchemy/sql/base.py
@@ -19,6 +19,7 @@ import collections
PARSE_AUTOCOMMIT = util.symbol('PARSE_AUTOCOMMIT')
NO_ARG = util.symbol('NO_ARG')
+
class Immutable(object):
"""mark a ClauseElement as 'immutable' when expressions are cloned."""
@@ -32,10 +33,10 @@ class Immutable(object):
return self
-
def _from_objects(*elements):
return itertools.chain(*[element._from_objects for element in elements])
+
@util.decorator
def _generative(fn, *args, **kw):
"""Mark a method as generative."""
@@ -50,6 +51,7 @@ class _DialectArgView(collections.MutableMapping):
<dialectname>_<argument_name>.
"""
+
def __init__(self, obj):
self.obj = obj
@@ -76,7 +78,7 @@ class _DialectArgView(collections.MutableMapping):
dialect, value_key = self._key(key)
except KeyError:
raise exc.ArgumentError(
- "Keys must be of the form <dialectname>_<argname>")
+ "Keys must be of the form <dialectname>_<argname>")
else:
self.obj.dialect_options[dialect][value_key] = value
@@ -86,15 +88,17 @@ class _DialectArgView(collections.MutableMapping):
def __len__(self):
return sum(len(args._non_defaults) for args in
- self.obj.dialect_options.values())
+ self.obj.dialect_options.values())
def __iter__(self):
return (
util.safe_kwarg("%s_%s" % (dialect_name, value_name))
for dialect_name in self.obj.dialect_options
- for value_name in self.obj.dialect_options[dialect_name]._non_defaults
+ for value_name in
+ self.obj.dialect_options[dialect_name]._non_defaults
)
+
class _DialectArgDict(collections.MutableMapping):
"""A dictionary view of dialect-level arguments for a specific
dialect.
@@ -103,6 +107,7 @@ class _DialectArgDict(collections.MutableMapping):
and dialect-specified default arguments.
"""
+
def __init__(self):
self._non_defaults = {}
self._defaults = {}
@@ -150,24 +155,26 @@ class DialectKWArgs(object):
some_index = Index('a', 'b', mydialect_length=5)
The :meth:`.DialectKWArgs.argument_for` method is a per-argument
- way adding extra arguments to the :attr:`.DefaultDialect.construct_arguments`
- dictionary. This dictionary provides a list of argument names accepted by
- various schema-level constructs on behalf of a dialect.
+ way adding extra arguments to the
+ :attr:`.DefaultDialect.construct_arguments` dictionary. This
+ dictionary provides a list of argument names accepted by various
+ schema-level constructs on behalf of a dialect.
- New dialects should typically specify this dictionary all at once as a data
- member of the dialect class. The use case for ad-hoc addition of
+ New dialects should typically specify this dictionary all at once as a
+ data member of the dialect class. The use case for ad-hoc addition of
argument names is typically for end-user code that is also using
a custom compilation scheme which consumes the additional arguments.
- :param dialect_name: name of a dialect. The dialect must be locatable,
- else a :class:`.NoSuchModuleError` is raised. The dialect must
- also include an existing :attr:`.DefaultDialect.construct_arguments` collection,
- indicating that it participates in the keyword-argument validation and
- default system, else :class:`.ArgumentError` is raised.
- If the dialect does not include this collection, then any keyword argument
- can be specified on behalf of this dialect already. All dialects
- packaged within SQLAlchemy include this collection, however for third
- party dialects, support may vary.
+ :param dialect_name: name of a dialect. The dialect must be
+ locatable, else a :class:`.NoSuchModuleError` is raised. The
+ dialect must also include an existing
+ :attr:`.DefaultDialect.construct_arguments` collection, indicating
+ that it participates in the keyword-argument validation and default
+ system, else :class:`.ArgumentError` is raised. If the dialect does
+ not include this collection, then any keyword argument can be
+ specified on behalf of this dialect already. All dialects packaged
+ within SQLAlchemy include this collection, however for third party
+ dialects, support may vary.
:param argument_name: name of the parameter.
@@ -179,9 +186,10 @@ class DialectKWArgs(object):
construct_arg_dictionary = DialectKWArgs._kw_registry[dialect_name]
if construct_arg_dictionary is None:
- raise exc.ArgumentError("Dialect '%s' does have keyword-argument "
- "validation and defaults enabled configured" %
- dialect_name)
+ raise exc.ArgumentError(
+ "Dialect '%s' does have keyword-argument "
+ "validation and defaults enabled configured" %
+ dialect_name)
if cls not in construct_arg_dictionary:
construct_arg_dictionary[cls] = {}
construct_arg_dictionary[cls][argument_name] = default
@@ -243,8 +251,8 @@ class DialectKWArgs(object):
options to this construct.
This is a two-level nested registry, keyed to ``<dialect_name>``
- and ``<argument_name>``. For example, the ``postgresql_where`` argument
- would be locatable as::
+ and ``<argument_name>``. For example, the ``postgresql_where``
+ argument would be locatable as::
arg = my_object.dialect_options['postgresql']['where']
@@ -257,8 +265,8 @@ class DialectKWArgs(object):
"""
return util.PopulateDict(
- util.portable_instancemethod(self._kw_reg_for_dialect_cls)
- )
+ util.portable_instancemethod(self._kw_reg_for_dialect_cls)
+ )
def _validate_dialect_kwargs(self, kwargs):
# validate remaining kwargs that they all specify DB prefixes
@@ -269,29 +277,30 @@ class DialectKWArgs(object):
for k in kwargs:
m = re.match('^(.+?)_(.+)$', k)
if not m:
- raise TypeError("Additional arguments should be "
- "named <dialectname>_<argument>, got '%s'" % k)
+ raise TypeError(
+ "Additional arguments should be "
+ "named <dialectname>_<argument>, got '%s'" % k)
dialect_name, arg_name = m.group(1, 2)
try:
construct_arg_dictionary = self.dialect_options[dialect_name]
except exc.NoSuchModuleError:
util.warn(
- "Can't validate argument %r; can't "
- "locate any SQLAlchemy dialect named %r" %
- (k, dialect_name))
+ "Can't validate argument %r; can't "
+ "locate any SQLAlchemy dialect named %r" %
+ (k, dialect_name))
self.dialect_options[dialect_name] = d = _DialectArgDict()
d._defaults.update({"*": None})
d._non_defaults[arg_name] = kwargs[k]
else:
if "*" not in construct_arg_dictionary and \
- arg_name not in construct_arg_dictionary:
+ arg_name not in construct_arg_dictionary:
raise exc.ArgumentError(
- "Argument %r is not accepted by "
- "dialect %r on behalf of %r" % (
- k,
- dialect_name, self.__class__
- ))
+ "Argument %r is not accepted by "
+ "dialect %r on behalf of %r" % (
+ k,
+ dialect_name, self.__class__
+ ))
else:
construct_arg_dictionary[arg_name] = kwargs[k]
@@ -424,11 +433,13 @@ class SchemaEventTarget(object):
self._set_parent(parent)
self.dispatch.after_parent_attach(self, parent)
+
class SchemaVisitor(ClauseVisitor):
"""Define the visiting for ``SchemaItem`` objects."""
__traverse_options__ = {'schema_visitor': True}
+
class ColumnCollection(util.OrderedProperties):
"""An ordered dictionary that stores a list of ColumnElement
instances.
@@ -478,11 +489,10 @@ class ColumnCollection(util.OrderedProperties):
self._data[column.key] = column
if remove_col is not None:
self._all_columns[:] = [column if c is remove_col
- else c for c in self._all_columns]
+ else c for c in self._all_columns]
else:
self._all_columns.append(column)
-
def add(self, column):
"""Add a column to this collection.
@@ -492,7 +502,7 @@ class ColumnCollection(util.OrderedProperties):
"""
if not column.key:
raise exc.ArgumentError(
- "Can't add unnamed column to column collection")
+ "Can't add unnamed column to column collection")
self[column.key] = column
def __delitem__(self, key):
@@ -512,8 +522,8 @@ class ColumnCollection(util.OrderedProperties):
if not existing.shares_lineage(value):
util.warn('Column %r on table %r being replaced by '
'%r, which has the same key. Consider '
- 'use_labels for select() statements.' % (key,
- getattr(existing, 'table', None), value))
+ 'use_labels for select() statements.' %
+ (key, getattr(existing, 'table', None), value))
# pop out memoized proxy_set as this
# operation may very well be occurring
@@ -530,17 +540,20 @@ class ColumnCollection(util.OrderedProperties):
def remove(self, column):
del self._data[column.key]
self._all_col_set.remove(column)
- self._all_columns[:] = [c for c in self._all_columns if c is not column]
+ self._all_columns[:] = [
+ c for c in self._all_columns if c is not column]
def update(self, iter):
cols = list(iter)
- self._all_columns.extend(c for label, c in cols if c not in self._all_col_set)
+ self._all_columns.extend(
+ c for label, c in cols if c not in self._all_col_set)
self._all_col_set.update(c for label, c in cols)
self._data.update((label, c) for label, c in cols)
def extend(self, iter):
cols = list(iter)
- self._all_columns.extend(c for c in cols if c not in self._all_col_set)
+ self._all_columns.extend(c for c in cols if c not in
+ self._all_col_set)
self._all_col_set.update(cols)
self._data.update((c.key, c) for c in cols)
@@ -574,7 +587,8 @@ class ColumnCollection(util.OrderedProperties):
return col in self._all_col_set
def as_immutable(self):
- return ImmutableColumnCollection(self._data, self._all_col_set, self._all_columns)
+ return ImmutableColumnCollection(
+ self._data, self._all_col_set, self._all_columns)
class ImmutableColumnCollection(util.ImmutableProperties, ColumnCollection):
@@ -609,6 +623,7 @@ class ColumnSet(util.ordered_column_set):
def __hash__(self):
return hash(tuple(x for x in self))
+
def _bind_or_error(schemaitem, msg=None):
bind = schemaitem.bind
if not bind:
@@ -621,7 +636,7 @@ def _bind_or_error(schemaitem, msg=None):
item = '%s object' % name
if msg is None:
msg = "%s is not bound to an Engine or Connection. "\
- "Execution can not proceed without a database to execute "\
- "against." % item
+ "Execution can not proceed without a database to execute "\
+ "against." % item
raise exc.UnboundExecutionError(msg)
return bind
diff --git a/lib/sqlalchemy/sql/compiler.py b/lib/sqlalchemy/sql/compiler.py
index 384cf27c2..ac45054ae 100644
--- a/lib/sqlalchemy/sql/compiler.py
+++ b/lib/sqlalchemy/sql/compiler.py
@@ -25,7 +25,7 @@ To generate user-defined SQL strings, see
import re
from . import schema, sqltypes, operators, functions, \
- util as sql_util, visitors, elements, selectable, base
+ util as sql_util, visitors, elements, selectable, base
from .. import util, exc
import decimal
import itertools
@@ -158,7 +158,9 @@ COMPOUND_KEYWORDS = {
selectable.CompoundSelect.INTERSECT_ALL: 'INTERSECT ALL'
}
+
class Compiled(object):
+
"""Represent a compiled SQL or DDL expression.
The ``__str__`` method of the ``Compiled`` object should produce
@@ -174,7 +176,7 @@ class Compiled(object):
_cached_metadata = None
def __init__(self, dialect, statement, bind=None,
- compile_kwargs=util.immutabledict()):
+ compile_kwargs=util.immutabledict()):
"""Construct a new ``Compiled`` object.
:param dialect: ``Dialect`` to compile against.
@@ -199,7 +201,7 @@ class Compiled(object):
self.string = self.process(self.statement, **compile_kwargs)
@util.deprecated("0.7", ":class:`.Compiled` objects now compile "
- "within the constructor.")
+ "within the constructor.")
def compile(self):
"""Produce the internal string representation of this element.
"""
@@ -247,8 +249,8 @@ class Compiled(object):
e = self.bind
if e is None:
raise exc.UnboundExecutionError(
- "This Compiled object is not bound to any Engine "
- "or Connection.")
+ "This Compiled object is not bound to any Engine "
+ "or Connection.")
return e._execute_compiled(self, multiparams, params)
def scalar(self, *multiparams, **params):
@@ -259,6 +261,7 @@ class Compiled(object):
class TypeCompiler(object):
+
"""Produces DDL specification for TypeEngine objects."""
def __init__(self, dialect):
@@ -268,8 +271,8 @@ class TypeCompiler(object):
return type_._compiler_dispatch(self)
-
class _CompileLabel(visitors.Visitable):
+
"""lightweight label object which acts as an expression.Label."""
__visit_name__ = 'label'
@@ -290,6 +293,7 @@ class _CompileLabel(visitors.Visitable):
class SQLCompiler(Compiled):
+
"""Default implementation of Compiled.
Compiles ClauseElements into SQL strings. Uses a similar visit
@@ -333,7 +337,7 @@ class SQLCompiler(Compiled):
"""
def __init__(self, dialect, statement, column_keys=None,
- inline=False, **kwargs):
+ inline=False, **kwargs):
"""Construct a new ``DefaultCompiler`` object.
dialect
@@ -412,19 +416,19 @@ class SQLCompiler(Compiled):
def _apply_numbered_params(self):
poscount = itertools.count(1)
self.string = re.sub(
- r'\[_POSITION\]',
- lambda m: str(util.next(poscount)),
- self.string)
+ r'\[_POSITION\]',
+ lambda m: str(util.next(poscount)),
+ self.string)
@util.memoized_property
def _bind_processors(self):
return dict(
- (key, value) for key, value in
- ((self.bind_names[bindparam],
- bindparam.type._cached_bind_processor(self.dialect))
- for bindparam in self.bind_names)
- if value is not None
- )
+ (key, value) for key, value in
+ ((self.bind_names[bindparam],
+ bindparam.type._cached_bind_processor(self.dialect))
+ for bindparam in self.bind_names)
+ if value is not None
+ )
def is_subquery(self):
return len(self.stack) > 1
@@ -491,15 +495,16 @@ class SQLCompiler(Compiled):
return "(" + grouping.element._compiler_dispatch(self, **kwargs) + ")"
def visit_label(self, label,
- add_to_result_map=None,
- within_label_clause=False,
- within_columns_clause=False,
- render_label_as_label=None,
- **kw):
+ add_to_result_map=None,
+ within_label_clause=False,
+ within_columns_clause=False,
+ render_label_as_label=None,
+ **kw):
# only render labels within the columns clause
# or ORDER BY clause of a select. dialect-specific compilers
# can modify this behavior.
- render_label_with_as = within_columns_clause and not within_label_clause
+ render_label_with_as = (within_columns_clause and not
+ within_label_clause)
render_label_only = render_label_as_label is label
if render_label_only or render_label_with_as:
@@ -511,27 +516,25 @@ class SQLCompiler(Compiled):
if render_label_with_as:
if add_to_result_map is not None:
add_to_result_map(
- labelname,
- label.name,
- (label, labelname, ) + label._alt_names,
- label.type
+ labelname,
+ label.name,
+ (label, labelname, ) + label._alt_names,
+ label.type
)
- return label.element._compiler_dispatch(self,
- within_columns_clause=True,
- within_label_clause=True,
- **kw) + \
- OPERATORS[operators.as_] + \
- self.preparer.format_label(label, labelname)
+ return label.element._compiler_dispatch(
+ self, within_columns_clause=True,
+ within_label_clause=True, **kw) + \
+ OPERATORS[operators.as_] + \
+ self.preparer.format_label(label, labelname)
elif render_label_only:
return self.preparer.format_label(label, labelname)
else:
- return label.element._compiler_dispatch(self,
- within_columns_clause=False,
- **kw)
+ return label.element._compiler_dispatch(
+ self, within_columns_clause=False, **kw)
def visit_column(self, column, add_to_result_map=None,
- include_table=True, **kwargs):
+ include_table=True, **kwargs):
name = orig_name = column.name
if name is None:
raise exc.CompileError("Cannot compile Column object until "
@@ -567,8 +570,8 @@ class SQLCompiler(Compiled):
tablename = self._truncated_identifier("alias", tablename)
return schema_prefix + \
- self.preparer.quote(tablename) + \
- "." + name
+ self.preparer.quote(tablename) + \
+ "." + name
def escape_literal_column(self, text):
"""provide escaping for the literal_column() construct."""
@@ -597,37 +600,38 @@ class SQLCompiler(Compiled):
return self.bindparam_string(name, **kw)
# un-escape any \:params
- return BIND_PARAMS_ESC.sub(lambda m: m.group(1),
- BIND_PARAMS.sub(do_bindparam,
- self.post_process_text(textclause.text))
+ return BIND_PARAMS_ESC.sub(
+ lambda m: m.group(1),
+ BIND_PARAMS.sub(
+ do_bindparam,
+ self.post_process_text(textclause.text))
)
def visit_text_as_from(self, taf, iswrapper=False,
- compound_index=0, force_result_map=False,
- asfrom=False,
- parens=True, **kw):
+ compound_index=0, force_result_map=False,
+ asfrom=False,
+ parens=True, **kw):
toplevel = not self.stack
entry = self._default_stack_entry if toplevel else self.stack[-1]
populate_result_map = force_result_map or (
- compound_index == 0 and (
- toplevel or \
- entry['iswrapper']
- )
- )
+ compound_index == 0 and (
+ toplevel or
+ entry['iswrapper']
+ )
+ )
if populate_result_map:
for c in taf.column_args:
self.process(c, within_columns_clause=True,
- add_to_result_map=self._add_to_result_map)
+ add_to_result_map=self._add_to_result_map)
text = self.process(taf.element, **kw)
if asfrom and parens:
text = "(%s)" % text
return text
-
def visit_null(self, expr, **kw):
return 'NULL'
@@ -646,7 +650,7 @@ class SQLCompiler(Compiled):
def visit_clauselist(self, clauselist, order_by_select=None, **kw):
if order_by_select is not None:
return self._order_by_clauselist(
- clauselist, order_by_select, **kw)
+ clauselist, order_by_select, **kw)
sep = clauselist.operator
if sep is None:
@@ -654,11 +658,11 @@ class SQLCompiler(Compiled):
else:
sep = OPERATORS[clauselist.operator]
return sep.join(
- s for s in
- (
- c._compiler_dispatch(self, **kw)
- for c in clauselist.clauses)
- if s)
+ s for s in
+ (
+ c._compiler_dispatch(self, **kw)
+ for c in clauselist.clauses)
+ if s)
def _order_by_clauselist(self, clauselist, order_by_select, **kw):
# look through raw columns collection for labels.
@@ -667,21 +671,21 @@ class SQLCompiler(Compiled):
# label expression in the columns clause.
raw_col = set(l._order_by_label_element.name
- for l in order_by_select._raw_columns
- if l._order_by_label_element is not None)
+ for l in order_by_select._raw_columns
+ if l._order_by_label_element is not None)
return ", ".join(
- s for s in
- (
- c._compiler_dispatch(self,
- render_label_as_label=
- c._order_by_label_element if
- c._order_by_label_element is not None and
- c._order_by_label_element.name in raw_col
- else None,
- **kw)
- for c in clauselist.clauses)
- if s)
+ s for s in
+ (
+ c._compiler_dispatch(
+ self,
+ render_label_as_label=c._order_by_label_element if
+ c._order_by_label_element is not None and
+ c._order_by_label_element.name in raw_col
+ else None,
+ **kw)
+ for c in clauselist.clauses)
+ if s)
def visit_case(self, clause, **kwargs):
x = "CASE "
@@ -689,38 +693,38 @@ class SQLCompiler(Compiled):
x += clause.value._compiler_dispatch(self, **kwargs) + " "
for cond, result in clause.whens:
x += "WHEN " + cond._compiler_dispatch(
- self, **kwargs
- ) + " THEN " + result._compiler_dispatch(
- self, **kwargs) + " "
+ self, **kwargs
+ ) + " THEN " + result._compiler_dispatch(
+ self, **kwargs) + " "
if clause.else_ is not None:
x += "ELSE " + clause.else_._compiler_dispatch(
- self, **kwargs
- ) + " "
+ self, **kwargs
+ ) + " "
x += "END"
return x
def visit_cast(self, cast, **kwargs):
return "CAST(%s AS %s)" % \
- (cast.clause._compiler_dispatch(self, **kwargs),
- cast.typeclause._compiler_dispatch(self, **kwargs))
+ (cast.clause._compiler_dispatch(self, **kwargs),
+ cast.typeclause._compiler_dispatch(self, **kwargs))
def visit_over(self, over, **kwargs):
return "%s OVER (%s)" % (
over.func._compiler_dispatch(self, **kwargs),
' '.join(
- '%s BY %s' % (word, clause._compiler_dispatch(self, **kwargs))
- for word, clause in (
- ('PARTITION', over.partition_by),
- ('ORDER', over.order_by)
- )
- if clause is not None and len(clause)
+ '%s BY %s' % (word, clause._compiler_dispatch(self, **kwargs))
+ for word, clause in (
+ ('PARTITION', over.partition_by),
+ ('ORDER', over.order_by)
+ )
+ if clause is not None and len(clause)
)
)
def visit_extract(self, extract, **kwargs):
field = self.extract_map.get(extract.field, extract.field)
- return "EXTRACT(%s FROM %s)" % (field,
- extract.expr._compiler_dispatch(self, **kwargs))
+ return "EXTRACT(%s FROM %s)" % (
+ field, extract.expr._compiler_dispatch(self, **kwargs))
def visit_function(self, func, add_to_result_map=None, **kwargs):
if add_to_result_map is not None:
@@ -734,7 +738,7 @@ class SQLCompiler(Compiled):
else:
name = FUNCTIONS.get(func.__class__, func.name + "%(expr)s")
return ".".join(list(func.packagenames) + [name]) % \
- {'expr': self.function_argspec(func, **kwargs)}
+ {'expr': self.function_argspec(func, **kwargs)}
def visit_next_value_func(self, next_value, **kw):
return self.visit_sequence(next_value.sequence)
@@ -748,39 +752,38 @@ class SQLCompiler(Compiled):
def function_argspec(self, func, **kwargs):
return func.clause_expr._compiler_dispatch(self, **kwargs)
-
def visit_compound_select(self, cs, asfrom=False,
- parens=True, compound_index=0, **kwargs):
+ parens=True, compound_index=0, **kwargs):
toplevel = not self.stack
entry = self._default_stack_entry if toplevel else self.stack[-1]
self.stack.append(
- {
- 'correlate_froms': entry['correlate_froms'],
- 'iswrapper': toplevel,
- 'asfrom_froms': entry['asfrom_froms']
- })
+ {
+ 'correlate_froms': entry['correlate_froms'],
+ 'iswrapper': toplevel,
+ 'asfrom_froms': entry['asfrom_froms']
+ })
keyword = self.compound_keywords.get(cs.keyword)
text = (" " + keyword + " ").join(
- (c._compiler_dispatch(self,
- asfrom=asfrom, parens=False,
- compound_index=i, **kwargs)
- for i, c in enumerate(cs.selects))
- )
+ (c._compiler_dispatch(self,
+ asfrom=asfrom, parens=False,
+ compound_index=i, **kwargs)
+ for i, c in enumerate(cs.selects))
+ )
group_by = cs._group_by_clause._compiler_dispatch(
- self, asfrom=asfrom, **kwargs)
+ self, asfrom=asfrom, **kwargs)
if group_by:
text += " GROUP BY " + group_by
text += self.order_by_clause(cs, **kwargs)
text += (cs._limit_clause is not None or cs._offset_clause is not None) and \
- self.limit_clause(cs) or ""
+ self.limit_clause(cs) or ""
if self.ctes and \
- compound_index == 0 and toplevel:
+ compound_index == 0 and toplevel:
text = self._render_cte_clause() + text
self.stack.pop(-1)
@@ -793,26 +796,26 @@ class SQLCompiler(Compiled):
if unary.operator:
if unary.modifier:
raise exc.CompileError(
- "Unary expression does not support operator "
- "and modifier simultaneously")
+ "Unary expression does not support operator "
+ "and modifier simultaneously")
disp = getattr(self, "visit_%s_unary_operator" %
- unary.operator.__name__, None)
+ unary.operator.__name__, None)
if disp:
return disp(unary, unary.operator, **kw)
else:
- return self._generate_generic_unary_operator(unary,
- OPERATORS[unary.operator], **kw)
+ return self._generate_generic_unary_operator(
+ unary, OPERATORS[unary.operator], **kw)
elif unary.modifier:
disp = getattr(self, "visit_%s_unary_modifier" %
- unary.modifier.__name__, None)
+ unary.modifier.__name__, None)
if disp:
return disp(unary, unary.modifier, **kw)
else:
- return self._generate_generic_unary_modifier(unary,
- OPERATORS[unary.modifier], **kw)
+ return self._generate_generic_unary_modifier(
+ unary, OPERATORS[unary.modifier], **kw)
else:
raise exc.CompileError(
- "Unary expression has no operator or modifier")
+ "Unary expression has no operator or modifier")
def visit_istrue_unary_operator(self, element, operator, **kw):
if self.dialect.supports_native_boolean:
@@ -829,8 +832,8 @@ class SQLCompiler(Compiled):
def visit_binary(self, binary, **kw):
# don't allow "? = ?" to render
if self.ansi_bind_rules and \
- isinstance(binary.left, elements.BindParameter) and \
- isinstance(binary.right, elements.BindParameter):
+ isinstance(binary.left, elements.BindParameter) and \
+ isinstance(binary.right, elements.BindParameter):
kw['literal_binds'] = True
operator = binary.operator
@@ -846,21 +849,21 @@ class SQLCompiler(Compiled):
return self._generate_generic_binary(binary, opstring, **kw)
def visit_custom_op_binary(self, element, operator, **kw):
- return self._generate_generic_binary(element,
- " " + operator.opstring + " ", **kw)
+ return self._generate_generic_binary(
+ element, " " + operator.opstring + " ", **kw)
def visit_custom_op_unary_operator(self, element, operator, **kw):
- return self._generate_generic_unary_operator(element,
- operator.opstring + " ", **kw)
+ return self._generate_generic_unary_operator(
+ element, operator.opstring + " ", **kw)
def visit_custom_op_unary_modifier(self, element, operator, **kw):
- return self._generate_generic_unary_modifier(element,
- " " + operator.opstring, **kw)
+ return self._generate_generic_unary_modifier(
+ element, " " + operator.opstring, **kw)
def _generate_generic_binary(self, binary, opstring, **kw):
return binary.left._compiler_dispatch(self, **kw) + \
- opstring + \
- binary.right._compiler_dispatch(self, **kw)
+ opstring + \
+ binary.right._compiler_dispatch(self, **kw)
def _generate_generic_unary_operator(self, unary, opstring, **kw):
return opstring + unary.element._compiler_dispatch(self, **kw)
@@ -888,16 +891,16 @@ class SQLCompiler(Compiled):
binary = binary._clone()
percent = self._like_percent_literal
binary.right = percent.__radd__(
- binary.right
- )
+ binary.right
+ )
return self.visit_like_op_binary(binary, operator, **kw)
def visit_notstartswith_op_binary(self, binary, operator, **kw):
binary = binary._clone()
percent = self._like_percent_literal
binary.right = percent.__radd__(
- binary.right
- )
+ binary.right
+ )
return self.visit_notlike_op_binary(binary, operator, **kw)
def visit_endswith_op_binary(self, binary, operator, **kw):
@@ -917,77 +920,77 @@ class SQLCompiler(Compiled):
# TODO: use ternary here, not "and"/ "or"
return '%s LIKE %s' % (
- binary.left._compiler_dispatch(self, **kw),
- binary.right._compiler_dispatch(self, **kw)) \
+ binary.left._compiler_dispatch(self, **kw),
+ binary.right._compiler_dispatch(self, **kw)) \
+ (
' ESCAPE ' +
self.render_literal_value(escape, sqltypes.STRINGTYPE)
if escape else ''
- )
+ )
def visit_notlike_op_binary(self, binary, operator, **kw):
escape = binary.modifiers.get("escape", None)
return '%s NOT LIKE %s' % (
- binary.left._compiler_dispatch(self, **kw),
- binary.right._compiler_dispatch(self, **kw)) \
+ binary.left._compiler_dispatch(self, **kw),
+ binary.right._compiler_dispatch(self, **kw)) \
+ (
' ESCAPE ' +
self.render_literal_value(escape, sqltypes.STRINGTYPE)
if escape else ''
- )
+ )
def visit_ilike_op_binary(self, binary, operator, **kw):
escape = binary.modifiers.get("escape", None)
return 'lower(%s) LIKE lower(%s)' % (
- binary.left._compiler_dispatch(self, **kw),
- binary.right._compiler_dispatch(self, **kw)) \
+ binary.left._compiler_dispatch(self, **kw),
+ binary.right._compiler_dispatch(self, **kw)) \
+ (
' ESCAPE ' +
self.render_literal_value(escape, sqltypes.STRINGTYPE)
if escape else ''
- )
+ )
def visit_notilike_op_binary(self, binary, operator, **kw):
escape = binary.modifiers.get("escape", None)
return 'lower(%s) NOT LIKE lower(%s)' % (
- binary.left._compiler_dispatch(self, **kw),
- binary.right._compiler_dispatch(self, **kw)) \
+ binary.left._compiler_dispatch(self, **kw),
+ binary.right._compiler_dispatch(self, **kw)) \
+ (
' ESCAPE ' +
self.render_literal_value(escape, sqltypes.STRINGTYPE)
if escape else ''
- )
+ )
def visit_between_op_binary(self, binary, operator, **kw):
symmetric = binary.modifiers.get("symmetric", False)
return self._generate_generic_binary(
- binary, " BETWEEN SYMMETRIC "
- if symmetric else " BETWEEN ", **kw)
+ binary, " BETWEEN SYMMETRIC "
+ if symmetric else " BETWEEN ", **kw)
def visit_notbetween_op_binary(self, binary, operator, **kw):
symmetric = binary.modifiers.get("symmetric", False)
return self._generate_generic_binary(
- binary, " NOT BETWEEN SYMMETRIC "
- if symmetric else " NOT BETWEEN ", **kw)
+ binary, " NOT BETWEEN SYMMETRIC "
+ if symmetric else " NOT BETWEEN ", **kw)
def visit_bindparam(self, bindparam, within_columns_clause=False,
- literal_binds=False,
- skip_bind_expression=False,
- **kwargs):
+ literal_binds=False,
+ skip_bind_expression=False,
+ **kwargs):
if not skip_bind_expression and bindparam.type._has_bind_expression:
bind_expression = bindparam.type.bind_expression(bindparam)
return self.process(bind_expression,
skip_bind_expression=True)
if literal_binds or \
- (within_columns_clause and \
+ (within_columns_clause and
self.ansi_bind_rules):
if bindparam.value is None and bindparam.callable is None:
raise exc.CompileError("Bind parameter '%s' without a "
- "renderable value not allowed here."
- % bindparam.key)
- return self.render_literal_bindparam(bindparam,
- within_columns_clause=True, **kwargs)
+ "renderable value not allowed here."
+ % bindparam.key)
+ return self.render_literal_bindparam(
+ bindparam, within_columns_clause=True, **kwargs)
name = self._truncate_bindparam(bindparam)
@@ -995,13 +998,13 @@ class SQLCompiler(Compiled):
existing = self.binds[name]
if existing is not bindparam:
if (existing.unique or bindparam.unique) and \
- not existing.proxy_set.intersection(
- bindparam.proxy_set):
+ not existing.proxy_set.intersection(
+ bindparam.proxy_set):
raise exc.CompileError(
- "Bind parameter '%s' conflicts with "
- "unique bind parameter of the same name" %
- bindparam.key
- )
+ "Bind parameter '%s' conflicts with "
+ "unique bind parameter of the same name" %
+ bindparam.key
+ )
elif existing._is_crud or bindparam._is_crud:
raise exc.CompileError(
"bindparam() name '%s' is reserved "
@@ -1009,8 +1012,8 @@ class SQLCompiler(Compiled):
"clause of this "
"insert/update statement. Please use a "
"name other than column name when using bindparam() "
- "with insert() or update() (for example, 'b_%s')."
- % (bindparam.key, bindparam.key)
+ "with insert() or update() (for example, 'b_%s')." %
+ (bindparam.key, bindparam.key)
)
self.binds[bindparam.key] = self.binds[name] = bindparam
@@ -1037,7 +1040,7 @@ class SQLCompiler(Compiled):
return processor(value)
else:
raise NotImplementedError(
- "Don't know how to literal-quote value %r" % value)
+ "Don't know how to literal-quote value %r" % value)
def _truncate_bindparam(self, bindparam):
if bindparam in self.bind_names:
@@ -1061,7 +1064,7 @@ class SQLCompiler(Compiled):
if len(anonname) > self.label_length:
counter = self.truncated_names.get(ident_class, 1)
truncname = anonname[0:max(self.label_length - 6, 0)] + \
- "_" + hex(counter)[2:]
+ "_" + hex(counter)[2:]
self.truncated_names[ident_class] = counter + 1
else:
truncname = anonname
@@ -1086,8 +1089,8 @@ class SQLCompiler(Compiled):
return self.bindtemplate % {'name': name}
def visit_cte(self, cte, asfrom=False, ashint=False,
- fromhints=None,
- **kwargs):
+ fromhints=None,
+ **kwargs):
self._init_cte_state()
if isinstance(cte.name, elements._truncated_label):
@@ -1108,9 +1111,9 @@ class SQLCompiler(Compiled):
del self.ctes[existing_cte]
else:
raise exc.CompileError(
- "Multiple, unrelated CTEs found with "
- "the same name: %r" %
- cte_name)
+ "Multiple, unrelated CTEs found with "
+ "the same name: %r" %
+ cte_name)
self.ctes_by_name[cte_name] = cte
@@ -1120,7 +1123,8 @@ class SQLCompiler(Compiled):
self.visit_cte(orig_cte)
cte_alias_name = cte._cte_alias.name
if isinstance(cte_alias_name, elements._truncated_label):
- cte_alias_name = self._truncated_identifier("alias", cte_alias_name)
+ cte_alias_name = self._truncated_identifier(
+ "alias", cte_alias_name)
else:
orig_cte = cte
cte_alias_name = None
@@ -1136,20 +1140,20 @@ class SQLCompiler(Compiled):
else:
assert False
recur_cols = [c for c in
- util.unique_list(col_source.inner_columns)
- if c is not None]
+ util.unique_list(col_source.inner_columns)
+ if c is not None]
text += "(%s)" % (", ".join(
- self.preparer.format_column(ident)
- for ident in recur_cols))
+ self.preparer.format_column(ident)
+ for ident in recur_cols))
if self.positional:
kwargs['positional_names'] = self.cte_positional[cte] = []
text += " AS \n" + \
- cte.original._compiler_dispatch(
- self, asfrom=True, **kwargs
- )
+ cte.original._compiler_dispatch(
+ self, asfrom=True, **kwargs
+ )
self.ctes[cte] = text
@@ -1162,8 +1166,8 @@ class SQLCompiler(Compiled):
return text
def visit_alias(self, alias, asfrom=False, ashint=False,
- iscrud=False,
- fromhints=None, **kwargs):
+ iscrud=False,
+ fromhints=None, **kwargs):
if asfrom or ashint:
if isinstance(alias.name, elements._truncated_label):
alias_name = self._truncated_identifier("alias", alias.name)
@@ -1174,13 +1178,13 @@ class SQLCompiler(Compiled):
return self.preparer.format_alias(alias, alias_name)
elif asfrom:
ret = alias.original._compiler_dispatch(self,
- asfrom=True, **kwargs) + \
- " AS " + \
- self.preparer.format_alias(alias, alias_name)
+ asfrom=True, **kwargs) + \
+ " AS " + \
+ self.preparer.format_alias(alias, alias_name)
if fromhints and alias in fromhints:
ret = self.format_from_hint_text(ret, alias,
- fromhints[alias], iscrud)
+ fromhints[alias], iscrud)
return ret
else:
@@ -1201,19 +1205,19 @@ class SQLCompiler(Compiled):
self.result_map[keyname] = name, objects, type_
def _label_select_column(self, select, column,
- populate_result_map,
- asfrom, column_clause_args,
- name=None,
- within_columns_clause=True):
+ populate_result_map,
+ asfrom, column_clause_args,
+ name=None,
+ within_columns_clause=True):
"""produce labeled columns present in a select()."""
if column.type._has_column_expression and \
populate_result_map:
col_expr = column.type.column_expression(column)
add_to_result_map = lambda keyname, name, objects, type_: \
- self._add_to_result_map(
- keyname, name,
- objects + (column,), type_)
+ self._add_to_result_map(
+ keyname, name,
+ objects + (column,), type_)
else:
col_expr = column
if populate_result_map:
@@ -1226,19 +1230,19 @@ class SQLCompiler(Compiled):
elif isinstance(column, elements.Label):
if col_expr is not column:
result_expr = _CompileLabel(
- col_expr,
- column.name,
- alt_names=(column.element,)
- )
+ col_expr,
+ column.name,
+ alt_names=(column.element,)
+ )
else:
result_expr = col_expr
elif select is not None and name:
result_expr = _CompileLabel(
- col_expr,
- name,
- alt_names=(column._key_label,)
- )
+ col_expr,
+ name,
+ alt_names=(column._key_label,)
+ )
elif \
asfrom and \
@@ -1247,30 +1251,30 @@ class SQLCompiler(Compiled):
column.table is not None and \
not isinstance(column.table, selectable.Select):
result_expr = _CompileLabel(col_expr,
- elements._as_truncated(column.name),
- alt_names=(column.key,))
+ elements._as_truncated(column.name),
+ alt_names=(column.key,))
elif not isinstance(column,
- (elements.UnaryExpression, elements.TextClause)) \
- and (not hasattr(column, 'name') or \
- isinstance(column, functions.Function)):
+ (elements.UnaryExpression, elements.TextClause)) \
+ and (not hasattr(column, 'name') or
+ isinstance(column, functions.Function)):
result_expr = _CompileLabel(col_expr, column.anon_label)
elif col_expr is not column:
# TODO: are we sure "column" has a .name and .key here ?
# assert isinstance(column, elements.ColumnClause)
result_expr = _CompileLabel(col_expr,
- elements._as_truncated(column.name),
- alt_names=(column.key,))
+ elements._as_truncated(column.name),
+ alt_names=(column.key,))
else:
result_expr = col_expr
column_clause_args.update(
- within_columns_clause=within_columns_clause,
- add_to_result_map=add_to_result_map
- )
+ within_columns_clause=within_columns_clause,
+ add_to_result_map=add_to_result_map
+ )
return result_expr._compiler_dispatch(
- self,
- **column_clause_args
- )
+ self,
+ **column_clause_args
+ )
def format_from_hint_text(self, sqltext, table, hint, iscrud):
hinttext = self.get_from_hint_text(table, hint)
@@ -1307,7 +1311,7 @@ class SQLCompiler(Compiled):
newelem = cloned[element] = element._clone()
if newelem.is_selectable and newelem._is_join and \
- isinstance(newelem.right, selectable.FromGrouping):
+ isinstance(newelem.right, selectable.FromGrouping):
newelem._reset_exported()
newelem.left = visit(newelem.left, **kw)
@@ -1376,24 +1380,24 @@ class SQLCompiler(Compiled):
return visit(select)
- def _transform_result_map_for_nested_joins(self, select, transformed_select):
+ def _transform_result_map_for_nested_joins(
+ self, select, transformed_select):
inner_col = dict((c._key_label, c) for
- c in transformed_select.inner_columns)
+ c in transformed_select.inner_columns)
d = dict(
- (inner_col[c._key_label], c)
- for c in select.inner_columns
- )
+ (inner_col[c._key_label], c)
+ for c in select.inner_columns
+ )
for key, (name, objs, typ) in list(self.result_map.items()):
objs = tuple([d.get(col, col) for col in objs])
self.result_map[key] = (name, objs, typ)
-
_default_stack_entry = util.immutabledict([
- ('iswrapper', False),
- ('correlate_froms', frozenset()),
- ('asfrom_froms', frozenset())
- ])
+ ('iswrapper', False),
+ ('correlate_froms', frozenset()),
+ ('asfrom_froms', frozenset())
+ ])
def _display_froms_for_select(self, select, asfrom):
# utility method to help external dialects
@@ -1408,53 +1412,53 @@ class SQLCompiler(Compiled):
if asfrom:
froms = select._get_display_froms(
- explicit_correlate_froms=\
- correlate_froms.difference(asfrom_froms),
- implicit_correlate_froms=())
+ explicit_correlate_froms=correlate_froms.difference(
+ asfrom_froms),
+ implicit_correlate_froms=())
else:
froms = select._get_display_froms(
- explicit_correlate_froms=correlate_froms,
- implicit_correlate_froms=asfrom_froms)
+ explicit_correlate_froms=correlate_froms,
+ implicit_correlate_froms=asfrom_froms)
return froms
def visit_select(self, select, asfrom=False, parens=True,
- iswrapper=False, fromhints=None,
- compound_index=0,
- force_result_map=False,
- nested_join_translation=False,
- **kwargs):
+ iswrapper=False, fromhints=None,
+ compound_index=0,
+ force_result_map=False,
+ nested_join_translation=False,
+ **kwargs):
needs_nested_translation = \
- select.use_labels and \
- not nested_join_translation and \
- not self.stack and \
- not self.dialect.supports_right_nested_joins
+ select.use_labels and \
+ not nested_join_translation and \
+ not self.stack and \
+ not self.dialect.supports_right_nested_joins
if needs_nested_translation:
- transformed_select = self._transform_select_for_nested_joins(select)
+ transformed_select = self._transform_select_for_nested_joins(
+ select)
text = self.visit_select(
- transformed_select, asfrom=asfrom, parens=parens,
- iswrapper=iswrapper, fromhints=fromhints,
- compound_index=compound_index,
- force_result_map=force_result_map,
- nested_join_translation=True, **kwargs
- )
+ transformed_select, asfrom=asfrom, parens=parens,
+ iswrapper=iswrapper, fromhints=fromhints,
+ compound_index=compound_index,
+ force_result_map=force_result_map,
+ nested_join_translation=True, **kwargs
+ )
toplevel = not self.stack
entry = self._default_stack_entry if toplevel else self.stack[-1]
-
populate_result_map = force_result_map or (
- compound_index == 0 and (
- toplevel or \
- entry['iswrapper']
- )
- )
+ compound_index == 0 and (
+ toplevel or
+ entry['iswrapper']
+ )
+ )
if needs_nested_translation:
if populate_result_map:
self._transform_result_map_for_nested_joins(
- select, transformed_select)
+ select, transformed_select)
return text
correlate_froms = entry['correlate_froms']
@@ -1462,48 +1466,49 @@ class SQLCompiler(Compiled):
if asfrom:
froms = select._get_display_froms(
- explicit_correlate_froms=
- correlate_froms.difference(asfrom_froms),
- implicit_correlate_froms=())
+ explicit_correlate_froms=correlate_froms.difference(
+ asfrom_froms),
+ implicit_correlate_froms=())
else:
froms = select._get_display_froms(
- explicit_correlate_froms=correlate_froms,
- implicit_correlate_froms=asfrom_froms)
+ explicit_correlate_froms=correlate_froms,
+ implicit_correlate_froms=asfrom_froms)
new_correlate_froms = set(selectable._from_objects(*froms))
all_correlate_froms = new_correlate_froms.union(correlate_froms)
new_entry = {
- 'asfrom_froms': new_correlate_froms,
- 'iswrapper': iswrapper,
- 'correlate_froms': all_correlate_froms
- }
+ 'asfrom_froms': new_correlate_froms,
+ 'iswrapper': iswrapper,
+ 'correlate_froms': all_correlate_froms
+ }
self.stack.append(new_entry)
column_clause_args = kwargs.copy()
column_clause_args.update({
- 'within_label_clause': False,
- 'within_columns_clause': False
- })
+ 'within_label_clause': False,
+ 'within_columns_clause': False
+ })
text = "SELECT " # we're off to a good start !
if select._hints:
byfrom = dict([
- (from_, hinttext % {
- 'name':from_._compiler_dispatch(
- self, ashint=True)
- })
- for (from_, dialect), hinttext in
- select._hints.items()
- if dialect in ('*', self.dialect.name)
- ])
+ (from_, hinttext % {
+ 'name': from_._compiler_dispatch(
+ self, ashint=True)
+ })
+ for (from_, dialect), hinttext in
+ select._hints.items()
+ if dialect in ('*', self.dialect.name)
+ ])
hint_text = self.get_select_hint_text(byfrom)
if hint_text:
text += hint_text + " "
if select._prefixes:
- text += self._generate_prefixes(select, select._prefixes, **kwargs)
+ text += self._generate_prefixes(
+ select, select._prefixes, **kwargs)
text += self.get_select_precolumns(select)
@@ -1511,12 +1516,12 @@ class SQLCompiler(Compiled):
inner_columns = [
c for c in [
self._label_select_column(select,
- column,
- populate_result_map, asfrom,
- column_clause_args,
- name=name)
+ column,
+ populate_result_map, asfrom,
+ column_clause_args,
+ name=name)
for name, column in select._columns_plus_names
- ]
+ ]
if c is not None
]
@@ -1526,14 +1531,14 @@ class SQLCompiler(Compiled):
text += " \nFROM "
if select._hints:
- text += ', '.join([f._compiler_dispatch(self,
- asfrom=True, fromhints=byfrom,
- **kwargs)
- for f in froms])
+ text += ', '.join(
+ [f._compiler_dispatch(self, asfrom=True,
+ fromhints=byfrom, **kwargs)
+ for f in froms])
else:
- text += ', '.join([f._compiler_dispatch(self,
- asfrom=True, **kwargs)
- for f in froms])
+ text += ', '.join(
+ [f._compiler_dispatch(self, asfrom=True, **kwargs)
+ for f in froms])
else:
text += self.default_from()
@@ -1544,7 +1549,7 @@ class SQLCompiler(Compiled):
if select._group_by_clause.clauses:
group_by = select._group_by_clause._compiler_dispatch(
- self, **kwargs)
+ self, **kwargs)
if group_by:
text += " GROUP BY " + group_by
@@ -1559,17 +1564,18 @@ class SQLCompiler(Compiled):
else:
order_by_select = None
- text += self.order_by_clause(select,
- order_by_select=order_by_select, **kwargs)
+ text += self.order_by_clause(
+ select, order_by_select=order_by_select, **kwargs)
- if select._limit_clause is not None or select._offset_clause is not None:
+ if (select._limit_clause is not None or
+ select._offset_clause is not None):
text += self.limit_clause(select)
if select._for_update_arg is not None:
text += self.for_update_clause(select)
if self.ctes and \
- compound_index == 0 and toplevel:
+ compound_index == 0 and toplevel:
text = self._render_cte_clause() + text
self.stack.pop(-1)
@@ -1581,11 +1587,11 @@ class SQLCompiler(Compiled):
def _generate_prefixes(self, stmt, prefixes, **kw):
clause = " ".join(
- prefix._compiler_dispatch(self, **kw)
- for prefix, dialect_name in prefixes
- if dialect_name is None or
- dialect_name == self.dialect.name
- )
+ prefix._compiler_dispatch(self, **kw)
+ for prefix, dialect_name in prefixes
+ if dialect_name is None or
+ dialect_name == self.dialect.name
+ )
if clause:
clause += " "
return clause
@@ -1593,9 +1599,9 @@ class SQLCompiler(Compiled):
def _render_cte_clause(self):
if self.positional:
self.positiontup = sum([
- self.cte_positional[cte]
- for cte in self.ctes], []) + \
- self.positiontup
+ self.cte_positional[cte]
+ for cte in self.ctes], []) + \
+ self.positiontup
cte_text = self.get_cte_preamble(self.ctes_recursive) + " "
cte_text += ", \n".join(
[txt for txt in self.ctes.values()]
@@ -1628,8 +1634,8 @@ class SQLCompiler(Compiled):
def returning_clause(self, stmt, returning_cols):
raise exc.CompileError(
- "RETURNING is not supported by this "
- "dialect's statement compiler.")
+ "RETURNING is not supported by this "
+ "dialect's statement compiler.")
def limit_clause(self, select):
text = ""
@@ -1642,16 +1648,16 @@ class SQLCompiler(Compiled):
return text
def visit_table(self, table, asfrom=False, iscrud=False, ashint=False,
- fromhints=None, **kwargs):
+ fromhints=None, **kwargs):
if asfrom or ashint:
if getattr(table, "schema", None):
ret = self.preparer.quote_schema(table.schema) + \
- "." + self.preparer.quote(table.name)
+ "." + self.preparer.quote(table.name)
else:
ret = self.preparer.quote(table.name)
if fromhints and table in fromhints:
ret = self.format_from_hint_text(ret, table,
- fromhints[table], iscrud)
+ fromhints[table], iscrud)
return ret
else:
return ""
@@ -1673,21 +1679,21 @@ class SQLCompiler(Compiled):
not self.dialect.supports_default_values and \
not self.dialect.supports_empty_insert:
raise exc.CompileError("The '%s' dialect with current database "
- "version settings does not support empty "
- "inserts." %
- self.dialect.name)
+ "version settings does not support empty "
+ "inserts." %
+ self.dialect.name)
if insert_stmt._has_multi_parameters:
if not self.dialect.supports_multivalues_insert:
- raise exc.CompileError("The '%s' dialect with current database "
- "version settings does not support "
- "in-place multirow inserts." %
- self.dialect.name)
+ raise exc.CompileError(
+ "The '%s' dialect with current database "
+ "version settings does not support "
+ "in-place multirow inserts." %
+ self.dialect.name)
colparams_single = colparams[0]
else:
colparams_single = colparams
-
preparer = self.preparer
supports_default_values = self.dialect.supports_default_values
@@ -1695,7 +1701,7 @@ class SQLCompiler(Compiled):
if insert_stmt._prefixes:
text += self._generate_prefixes(insert_stmt,
- insert_stmt._prefixes, **kw)
+ insert_stmt._prefixes, **kw)
text += "INTO "
table_text = preparer.format_table(insert_stmt.table)
@@ -1709,22 +1715,22 @@ class SQLCompiler(Compiled):
])
if insert_stmt.table in dialect_hints:
table_text = self.format_from_hint_text(
- table_text,
- insert_stmt.table,
- dialect_hints[insert_stmt.table],
- True
- )
+ table_text,
+ insert_stmt.table,
+ dialect_hints[insert_stmt.table],
+ True
+ )
text += table_text
if colparams_single or not supports_default_values:
text += " (%s)" % ', '.join([preparer.format_column(c[0])
- for c in colparams_single])
+ for c in colparams_single])
if self.returning or insert_stmt._returning:
self.returning = self.returning or insert_stmt._returning
returning_clause = self.returning_clause(
- insert_stmt, self.returning)
+ insert_stmt, self.returning)
if self.returning_precedes_values:
text += " " + returning_clause
@@ -1735,16 +1741,16 @@ class SQLCompiler(Compiled):
text += " DEFAULT VALUES"
elif insert_stmt._has_multi_parameters:
text += " VALUES %s" % (
- ", ".join(
- "(%s)" % (
- ', '.join(c[1] for c in colparam_set)
- )
- for colparam_set in colparams
- )
- )
+ ", ".join(
+ "(%s)" % (
+ ', '.join(c[1] for c in colparam_set)
+ )
+ for colparam_set in colparams
+ )
+ )
else:
text += " VALUES (%s)" % \
- ', '.join([c[1] for c in colparams])
+ ', '.join([c[1] for c in colparams])
if self.returning and not self.returning_precedes_values:
text += " " + returning_clause
@@ -1756,7 +1762,7 @@ class SQLCompiler(Compiled):
return None
def update_tables_clause(self, update_stmt, from_table,
- extra_froms, **kw):
+ extra_froms, **kw):
"""Provide a hook to override the initial table clause
in an UPDATE statement.
@@ -1764,12 +1770,12 @@ class SQLCompiler(Compiled):
"""
return from_table._compiler_dispatch(self, asfrom=True,
- iscrud=True, **kw)
+ iscrud=True, **kw)
def update_from_clause(self, update_stmt,
- from_table, extra_froms,
- from_hints,
- **kw):
+ from_table, extra_froms,
+ from_hints,
+ **kw):
"""Provide a hook to override the generation of an
UPDATE..FROM clause.
@@ -1777,15 +1783,15 @@ class SQLCompiler(Compiled):
"""
return "FROM " + ', '.join(
- t._compiler_dispatch(self, asfrom=True,
- fromhints=from_hints, **kw)
- for t in extra_froms)
+ t._compiler_dispatch(self, asfrom=True,
+ fromhints=from_hints, **kw)
+ for t in extra_froms)
def visit_update(self, update_stmt, **kw):
self.stack.append(
- {'correlate_froms': set([update_stmt.table]),
- "iswrapper": False,
- "asfrom_froms": set([update_stmt.table])})
+ {'correlate_froms': set([update_stmt.table]),
+ "iswrapper": False,
+ "asfrom_froms": set([update_stmt.table])})
self.isupdate = True
@@ -1795,7 +1801,7 @@ class SQLCompiler(Compiled):
if update_stmt._prefixes:
text += self._generate_prefixes(update_stmt,
- update_stmt._prefixes, **kw)
+ update_stmt._prefixes, **kw)
table_text = self.update_tables_clause(update_stmt, update_stmt.table,
extra_froms, **kw)
@@ -1811,11 +1817,11 @@ class SQLCompiler(Compiled):
])
if update_stmt.table in dialect_hints:
table_text = self.format_from_hint_text(
- table_text,
- update_stmt.table,
- dialect_hints[update_stmt.table],
- True
- )
+ table_text,
+ update_stmt.table,
+ dialect_hints[update_stmt.table],
+ True
+ )
else:
dialect_hints = None
@@ -1823,26 +1829,26 @@ class SQLCompiler(Compiled):
text += ' SET '
include_table = extra_froms and \
- self.render_table_with_column_in_update_from
+ self.render_table_with_column_in_update_from
text += ', '.join(
- c[0]._compiler_dispatch(self,
- include_table=include_table) +
- '=' + c[1] for c in colparams
- )
+ c[0]._compiler_dispatch(self,
+ include_table=include_table) +
+ '=' + c[1] for c in colparams
+ )
if self.returning or update_stmt._returning:
if not self.returning:
self.returning = update_stmt._returning
if self.returning_precedes_values:
text += " " + self.returning_clause(
- update_stmt, self.returning)
+ update_stmt, self.returning)
if extra_froms:
extra_from_text = self.update_from_clause(
- update_stmt,
- update_stmt.table,
- extra_froms,
- dialect_hints, **kw)
+ update_stmt,
+ update_stmt.table,
+ extra_froms,
+ dialect_hints, **kw)
if extra_from_text:
text += " " + extra_from_text
@@ -1857,7 +1863,7 @@ class SQLCompiler(Compiled):
if self.returning and not self.returning_precedes_values:
text += " " + self.returning_clause(
- update_stmt, self.returning)
+ update_stmt, self.returning)
self.stack.pop(-1)
@@ -1867,7 +1873,7 @@ class SQLCompiler(Compiled):
if name is None:
name = col.key
bindparam = elements.BindParameter(name, value,
- type_=col.type, required=required)
+ type_=col.type, required=required)
bindparam._is_crud = True
return bindparam._compiler_dispatch(self)
@@ -1881,17 +1887,20 @@ class SQLCompiler(Compiled):
# allowing the most compatibility with a non-multi-table
# statement.
_et = set(self.statement._extra_froms)
+
def _column_as_key(key):
str_key = elements._column_as_key(key)
if hasattr(key, 'table') and key.table in _et:
return (key.table.name, str_key)
else:
return str_key
+
def _getattr_col_key(col):
if col.table in _et:
return (col.table.name, col.key)
else:
return col.key
+
def _col_bind_name(col):
if col.table in _et:
return "%s_%s" % (col.table.name, col.key)
@@ -1923,10 +1932,10 @@ class SQLCompiler(Compiled):
# compiled params - return binds for all columns
if self.column_keys is None and stmt.parameters is None:
return [
- (c, self._create_crud_bind_param(c,
- None, required=True))
- for c in stmt.table.columns
- ]
+ (c, self._create_crud_bind_param(c,
+ None, required=True))
+ for c in stmt.table.columns
+ ]
if stmt._has_multi_parameters:
stmt_parameters = stmt.parameters[0]
@@ -1937,7 +1946,7 @@ class SQLCompiler(Compiled):
# but in the case of mysql multi-table update, the rules for
# .key must conditionally take tablename into account
_column_as_key, _getattr_col_key, _col_bind_name = \
- self._key_getters_for_crud_column
+ self._key_getters_for_crud_column
# if we have statement parameters - set defaults in the
# compiled params
@@ -1963,26 +1972,27 @@ class SQLCompiler(Compiled):
# coercing right side to bound param
if elements._is_literal(v):
v = self.process(
- elements.BindParameter(None, v, type_=k.type),
- **kw)
+ elements.BindParameter(None, v, type_=k.type),
+ **kw)
else:
v = self.process(v.self_group(), **kw)
values.append((k, v))
need_pks = self.isinsert and \
- not self.inline and \
- not stmt._returning
+ not self.inline and \
+ not stmt._returning
implicit_returning = need_pks and \
- self.dialect.implicit_returning and \
- stmt.table.implicit_returning
+ self.dialect.implicit_returning and \
+ stmt.table.implicit_returning
if self.isinsert:
- implicit_return_defaults = implicit_returning and stmt._return_defaults
+ implicit_return_defaults = (implicit_returning and
+ stmt._return_defaults)
elif self.isupdate:
- implicit_return_defaults = self.dialect.implicit_returning and \
- stmt.table.implicit_returning and \
- stmt._return_defaults
+ implicit_return_defaults = (self.dialect.implicit_returning and
+ stmt.table.implicit_returning and
+ stmt._return_defaults)
else:
implicit_return_defaults = False
@@ -2025,20 +2035,21 @@ class SQLCompiler(Compiled):
for c in t.c:
if c in normalized_params:
continue
- elif c.onupdate is not None and not c.onupdate.is_sequence:
+ elif (c.onupdate is not None and not
+ c.onupdate.is_sequence):
if c.onupdate.is_clause_element:
values.append(
(c, self.process(
- c.onupdate.arg.self_group(),
- **kw)
- )
+ c.onupdate.arg.self_group(),
+ **kw)
+ )
)
self.postfetch.append(c)
else:
values.append(
(c, self._create_crud_bind_param(
- c, None, name=_col_bind_name(c)
- )
+ c, None, name=_col_bind_name(c)
+ )
)
)
self.prefetch.append(c)
@@ -2049,7 +2060,7 @@ class SQLCompiler(Compiled):
# for an insert from select, we can only use names that
# are given, so only select for those names.
cols = (stmt.table.c[_column_as_key(name)]
- for name in stmt.select_names)
+ for name in stmt.select_names)
else:
# iterate through all table columns to maintain
# ordering, even for those cols that aren't included
@@ -2061,14 +2072,14 @@ class SQLCompiler(Compiled):
value = parameters.pop(col_key)
if elements._is_literal(value):
value = self._create_crud_bind_param(
- c, value, required=value is REQUIRED,
- name=_col_bind_name(c)
- if not stmt._has_multi_parameters
- else "%s_0" % _col_bind_name(c)
- )
+ c, value, required=value is REQUIRED,
+ name=_col_bind_name(c)
+ if not stmt._has_multi_parameters
+ else "%s_0" % _col_bind_name(c)
+ )
else:
if isinstance(value, elements.BindParameter) and \
- value.type._isnull:
+ value.type._isnull:
value = value._clone()
value.type = c.type
@@ -2076,7 +2087,7 @@ class SQLCompiler(Compiled):
self.returning.append(c)
value = self.process(value.self_group(), **kw)
elif implicit_return_defaults and \
- c in implicit_return_defaults:
+ c in implicit_return_defaults:
self.returning.append(c)
value = self.process(value.self_group(), **kw)
else:
@@ -2086,26 +2097,26 @@ class SQLCompiler(Compiled):
elif self.isinsert:
if c.primary_key and \
- need_pks and \
- (
- implicit_returning or
- not postfetch_lastrowid or
- c is not stmt.table._autoincrement_column
- ):
+ need_pks and \
+ (
+ implicit_returning or
+ not postfetch_lastrowid or
+ c is not stmt.table._autoincrement_column
+ ):
if implicit_returning:
if c.default is not None:
if c.default.is_sequence:
if self.dialect.supports_sequences and \
- (not c.default.optional or \
- not self.dialect.sequences_optional):
+ (not c.default.optional or
+ not self.dialect.sequences_optional):
proc = self.process(c.default, **kw)
values.append((c, proc))
self.returning.append(c)
elif c.default.is_clause_element:
values.append(
- (c,
- self.process(c.default.arg.self_group(), **kw))
+ (c, self.process(
+ c.default.arg.self_group(), **kw))
)
self.returning.append(c)
else:
@@ -2117,16 +2128,14 @@ class SQLCompiler(Compiled):
self.returning.append(c)
else:
if (
- c.default is not None and
- (
- not c.default.is_sequence or
- self.dialect.supports_sequences
- )
- ) or \
- c is stmt.table._autoincrement_column and (
- self.dialect.supports_sequences or
- self.dialect.preexecute_autoincrement_sequences
- ):
+ (c.default is not None and
+ (not c.default.is_sequence or
+ self.dialect.supports_sequences)) or
+ c is stmt.table._autoincrement_column and
+ (self.dialect.supports_sequences or
+ self.dialect.
+ preexecute_autoincrement_sequences)
+ ):
values.append(
(c, self._create_crud_bind_param(c, None))
@@ -2137,22 +2146,23 @@ class SQLCompiler(Compiled):
elif c.default is not None:
if c.default.is_sequence:
if self.dialect.supports_sequences and \
- (not c.default.optional or \
- not self.dialect.sequences_optional):
+ (not c.default.optional or
+ not self.dialect.sequences_optional):
proc = self.process(c.default, **kw)
values.append((c, proc))
if implicit_return_defaults and \
- c in implicit_return_defaults:
+ c in implicit_return_defaults:
self.returning.append(c)
elif not c.primary_key:
self.postfetch.append(c)
elif c.default.is_clause_element:
values.append(
- (c, self.process(c.default.arg.self_group(), **kw))
+ (c, self.process(
+ c.default.arg.self_group(), **kw))
)
if implicit_return_defaults and \
- c in implicit_return_defaults:
+ c in implicit_return_defaults:
self.returning.append(c)
elif not c.primary_key:
# don't add primary key column to postfetch
@@ -2164,22 +2174,23 @@ class SQLCompiler(Compiled):
self.prefetch.append(c)
elif c.server_default is not None:
if implicit_return_defaults and \
- c in implicit_return_defaults:
+ c in implicit_return_defaults:
self.returning.append(c)
elif not c.primary_key:
self.postfetch.append(c)
elif implicit_return_defaults and \
c in implicit_return_defaults:
- self.returning.append(c)
+ self.returning.append(c)
elif self.isupdate:
if c.onupdate is not None and not c.onupdate.is_sequence:
if c.onupdate.is_clause_element:
values.append(
- (c, self.process(c.onupdate.arg.self_group(), **kw))
+ (c, self.process(
+ c.onupdate.arg.self_group(), **kw))
)
if implicit_return_defaults and \
- c in implicit_return_defaults:
+ c in implicit_return_defaults:
self.returning.append(c)
else:
self.postfetch.append(c)
@@ -2190,13 +2201,13 @@ class SQLCompiler(Compiled):
self.prefetch.append(c)
elif c.server_onupdate is not None:
if implicit_return_defaults and \
- c in implicit_return_defaults:
+ c in implicit_return_defaults:
self.returning.append(c)
else:
self.postfetch.append(c)
elif implicit_return_defaults and \
c in implicit_return_defaults:
- self.returning.append(c)
+ self.returning.append(c)
if parameters and stmt_parameters:
check = set(parameters).intersection(
@@ -2216,13 +2227,13 @@ class SQLCompiler(Compiled):
[
(
c,
- (self._create_crud_bind_param(
- c, row[c.key],
- name="%s_%d" % (c.key, i + 1)
- ) if elements._is_literal(row[c.key])
- else self.process(
- row[c.key].self_group(), **kw))
- if c.key in row else param
+ (self._create_crud_bind_param(
+ c, row[c.key],
+ name="%s_%d" % (c.key, i + 1)
+ ) if elements._is_literal(row[c.key])
+ else self.process(
+ row[c.key].self_group(), **kw))
+ if c.key in row else param
)
for (c, param) in values_0
]
@@ -2233,19 +2244,19 @@ class SQLCompiler(Compiled):
def visit_delete(self, delete_stmt, **kw):
self.stack.append({'correlate_froms': set([delete_stmt.table]),
- "iswrapper": False,
- "asfrom_froms": set([delete_stmt.table])})
+ "iswrapper": False,
+ "asfrom_froms": set([delete_stmt.table])})
self.isdelete = True
text = "DELETE "
if delete_stmt._prefixes:
text += self._generate_prefixes(delete_stmt,
- delete_stmt._prefixes, **kw)
+ delete_stmt._prefixes, **kw)
text += "FROM "
- table_text = delete_stmt.table._compiler_dispatch(self,
- asfrom=True, iscrud=True)
+ table_text = delete_stmt.table._compiler_dispatch(
+ self, asfrom=True, iscrud=True)
if delete_stmt._hints:
dialect_hints = dict([
@@ -2256,11 +2267,11 @@ class SQLCompiler(Compiled):
])
if delete_stmt.table in dialect_hints:
table_text = self.format_from_hint_text(
- table_text,
- delete_stmt.table,
- dialect_hints[delete_stmt.table],
- True
- )
+ table_text,
+ delete_stmt.table,
+ dialect_hints[delete_stmt.table],
+ True
+ )
else:
dialect_hints = None
@@ -2271,7 +2282,7 @@ class SQLCompiler(Compiled):
self.returning = delete_stmt._returning
if self.returning_precedes_values:
text += " " + self.returning_clause(
- delete_stmt, delete_stmt._returning)
+ delete_stmt, delete_stmt._returning)
if delete_stmt._whereclause is not None:
t = delete_stmt._whereclause._compiler_dispatch(self)
@@ -2280,7 +2291,7 @@ class SQLCompiler(Compiled):
if self.returning and not self.returning_precedes_values:
text += " " + self.returning_clause(
- delete_stmt, delete_stmt._returning)
+ delete_stmt, delete_stmt._returning)
self.stack.pop(-1)
@@ -2291,11 +2302,11 @@ class SQLCompiler(Compiled):
def visit_rollback_to_savepoint(self, savepoint_stmt):
return "ROLLBACK TO SAVEPOINT %s" % \
- self.preparer.format_savepoint(savepoint_stmt)
+ self.preparer.format_savepoint(savepoint_stmt)
def visit_release_savepoint(self, savepoint_stmt):
return "RELEASE SAVEPOINT %s" % \
- self.preparer.format_savepoint(savepoint_stmt)
+ self.preparer.format_savepoint(savepoint_stmt)
class DDLCompiler(Compiled):
@@ -2349,11 +2360,11 @@ class DDLCompiler(Compiled):
table = create.element
preparer = self.dialect.identifier_preparer
- text = "\n" + " ".join(['CREATE'] + \
- table._prefixes + \
- ['TABLE',
- preparer.format_table(table),
- "("])
+ text = "\n" + " ".join(['CREATE'] +
+ table._prefixes +
+ ['TABLE',
+ preparer.format_table(table),
+ "("])
separator = "\n"
# if only one primary key, specify it along with the column
@@ -2362,8 +2373,8 @@ class DDLCompiler(Compiled):
column = create_column.element
try:
processed = self.process(create_column,
- first_pk=column.primary_key
- and not first_pk)
+ first_pk=column.primary_key
+ and not first_pk)
if processed is not None:
text += separator
separator = ", \n"
@@ -2372,11 +2383,10 @@ class DDLCompiler(Compiled):
first_pk = True
except exc.CompileError as ce:
util.raise_from_cause(
- exc.CompileError(util.u("(in table '%s', column '%s'): %s") % (
- table.description,
- column.name,
- ce.args[0]
- )))
+ exc.CompileError(
+ util.u("(in table '%s', column '%s'): %s") %
+ (table.description, column.name, ce.args[0])
+ ))
const = self.create_table_constraints(table)
if const:
@@ -2392,11 +2402,11 @@ class DDLCompiler(Compiled):
return None
text = self.get_column_specification(
- column,
- first_pk=first_pk
- )
- const = " ".join(self.process(constraint) \
- for constraint in column.constraints)
+ column,
+ first_pk=first_pk
+ )
+ const = " ".join(self.process(constraint)
+ for constraint in column.constraints)
if const:
text += " " + const
@@ -2411,19 +2421,19 @@ class DDLCompiler(Compiled):
constraints.append(table.primary_key)
constraints.extend([c for c in table._sorted_constraints
- if c is not table.primary_key])
+ if c is not table.primary_key])
return ", \n\t".join(p for p in
- (self.process(constraint)
- for constraint in constraints
- if (
- constraint._create_rule is None or
- constraint._create_rule(self))
- and (
- not self.dialect.supports_alter or
- not getattr(constraint, 'use_alter', False)
- )) if p is not None
- )
+ (self.process(constraint)
+ for constraint in constraints
+ if (
+ constraint._create_rule is None or
+ constraint._create_rule(self))
+ and (
+ not self.dialect.supports_alter or
+ not getattr(constraint, 'use_alter', False)
+ )) if p is not None
+ )
def visit_drop_table(self, drop):
return "\nDROP TABLE " + self.preparer.format_table(drop.element)
@@ -2431,15 +2441,13 @@ class DDLCompiler(Compiled):
def visit_drop_view(self, drop):
return "\nDROP VIEW " + self.preparer.format_table(drop.element)
-
def _verify_index_table(self, index):
if index.table is None:
raise exc.CompileError("Index '%s' is not associated "
- "with any table." % index.name)
-
+ "with any table." % index.name)
def visit_create_index(self, create, include_schema=False,
- include_table_schema=True):
+ include_table_schema=True):
index = create.element
self._verify_index_table(index)
preparer = self.preparer
@@ -2447,22 +2455,22 @@ class DDLCompiler(Compiled):
if index.unique:
text += "UNIQUE "
text += "INDEX %s ON %s (%s)" \
- % (
- self._prepared_index_name(index,
- include_schema=include_schema),
- preparer.format_table(index.table,
- use_schema=include_table_schema),
- ', '.join(
- self.sql_compiler.process(expr,
- include_table=False, literal_binds=True) for
- expr in index.expressions)
- )
+ % (
+ self._prepared_index_name(index,
+ include_schema=include_schema),
+ preparer.format_table(index.table,
+ use_schema=include_table_schema),
+ ', '.join(
+ self.sql_compiler.process(
+ expr, include_table=False, literal_binds=True) for
+ expr in index.expressions)
+ )
return text
def visit_drop_index(self, drop):
index = drop.element
- return "\nDROP INDEX " + self._prepared_index_name(index,
- include_schema=True)
+ return "\nDROP INDEX " + self._prepared_index_name(
+ index, include_schema=True)
def _prepared_index_name(self, index, include_schema=False):
if include_schema and index.table is not None and index.table.schema:
@@ -2474,10 +2482,10 @@ class DDLCompiler(Compiled):
ident = index.name
if isinstance(ident, elements._truncated_label):
max_ = self.dialect.max_index_name_length or \
- self.dialect.max_identifier_length
+ self.dialect.max_identifier_length
if len(ident) > max_:
ident = ident[0:max_ - 8] + \
- "_" + util.md5_hex(ident)[-4:]
+ "_" + util.md5_hex(ident)[-4:]
else:
self.dialect.validate_identifier(ident)
@@ -2495,7 +2503,7 @@ class DDLCompiler(Compiled):
def visit_create_sequence(self, create):
text = "CREATE SEQUENCE %s" % \
- self.preparer.format_sequence(create.element)
+ self.preparer.format_sequence(create.element)
if create.element.increment is not None:
text += " INCREMENT BY %d" % create.element.increment
if create.element.start is not None:
@@ -2504,7 +2512,7 @@ class DDLCompiler(Compiled):
def visit_drop_sequence(self, drop):
return "DROP SEQUENCE %s" % \
- self.preparer.format_sequence(drop.element)
+ self.preparer.format_sequence(drop.element)
def visit_drop_constraint(self, drop):
return "ALTER TABLE %s DROP CONSTRAINT %s%s" % (
@@ -2515,7 +2523,7 @@ class DDLCompiler(Compiled):
def get_column_specification(self, column, **kwargs):
colspec = self.preparer.format_column(column) + " " + \
- self.dialect.type_compiler.process(column.type)
+ self.dialect.type_compiler.process(column.type)
default = self.get_column_default_string(column)
if default is not None:
colspec += " DEFAULT " + default
@@ -2543,8 +2551,8 @@ class DDLCompiler(Compiled):
if formatted_name is not None:
text += "CONSTRAINT %s " % formatted_name
text += "CHECK (%s)" % self.sql_compiler.process(constraint.sqltext,
- include_table=False,
- literal_binds=True)
+ include_table=False,
+ literal_binds=True)
text += self.define_constraint_deferrability(constraint)
return text
@@ -2568,7 +2576,7 @@ class DDLCompiler(Compiled):
text += "CONSTRAINT %s " % formatted_name
text += "PRIMARY KEY "
text += "(%s)" % ', '.join(self.preparer.quote(c.name)
- for c in constraint)
+ for c in constraint)
text += self.define_constraint_deferrability(constraint)
return text
@@ -2607,7 +2615,7 @@ class DDLCompiler(Compiled):
text += "CONSTRAINT %s " % formatted_name
text += "UNIQUE (%s)" % (
', '.join(self.preparer.quote(c.name)
- for c in constraint))
+ for c in constraint))
text += self.define_constraint_deferrability(constraint)
return text
@@ -2650,22 +2658,22 @@ class GenericTypeCompiler(TypeCompiler):
return "NUMERIC"
elif type_.scale is None:
return "NUMERIC(%(precision)s)" % \
- {'precision': type_.precision}
+ {'precision': type_.precision}
else:
return "NUMERIC(%(precision)s, %(scale)s)" % \
- {'precision': type_.precision,
- 'scale': type_.scale}
+ {'precision': type_.precision,
+ 'scale': type_.scale}
def visit_DECIMAL(self, type_):
if type_.precision is None:
return "DECIMAL"
elif type_.scale is None:
return "DECIMAL(%(precision)s)" % \
- {'precision': type_.precision}
+ {'precision': type_.precision}
else:
return "DECIMAL(%(precision)s, %(scale)s)" % \
- {'precision': type_.precision,
- 'scale': type_.scale}
+ {'precision': type_.precision,
+ 'scale': type_.scale}
def visit_INTEGER(self, type_):
return "INTEGER"
@@ -2780,8 +2788,8 @@ class GenericTypeCompiler(TypeCompiler):
def visit_null(self, type_):
raise exc.CompileError("Can't generate DDL for %r; "
- "did you forget to specify a "
- "type on this Column?" % type_)
+ "did you forget to specify a "
+ "type on this Column?" % type_)
def visit_type_decorator(self, type_):
return self.process(type_.type_engine(self.dialect))
@@ -2791,6 +2799,7 @@ class GenericTypeCompiler(TypeCompiler):
class IdentifierPreparer(object):
+
"""Handle quoting and case-folding of identifiers based on options."""
reserved_words = RESERVED_WORDS
@@ -2800,7 +2809,7 @@ class IdentifierPreparer(object):
illegal_initial_characters = ILLEGAL_INITIAL_CHARACTERS
def __init__(self, dialect, initial_quote='"',
- final_quote=None, escape_quote='"', omit_schema=False):
+ final_quote=None, escape_quote='"', omit_schema=False):
"""Construct a new ``IdentifierPreparer`` object.
initial_quote
@@ -2849,8 +2858,8 @@ class IdentifierPreparer(object):
"""
return self.initial_quote + \
- self._escape_identifier(value) + \
- self.final_quote
+ self._escape_identifier(value) + \
+ self.final_quote
def _requires_quotes(self, value):
"""Return True if the given identifier requires quoting."""
@@ -2895,7 +2904,8 @@ class IdentifierPreparer(object):
def format_sequence(self, sequence, use_schema=True):
name = self.quote(sequence.name)
- if not self.omit_schema and use_schema and sequence.schema is not None:
+ if (not self.omit_schema and use_schema and
+ sequence.schema is not None):
name = self.quote_schema(sequence.schema) + "." + name
return name
@@ -2912,7 +2922,7 @@ class IdentifierPreparer(object):
def format_constraint(self, naming, constraint):
if isinstance(constraint.name, elements._defer_name):
name = naming._constraint_name_for_table(
- constraint, constraint.table)
+ constraint, constraint.table)
if name:
return self.quote(name)
elif isinstance(constraint.name, elements._defer_none_name):
@@ -2926,7 +2936,7 @@ class IdentifierPreparer(object):
name = table.name
result = self.quote(name)
if not self.omit_schema and use_schema \
- and getattr(table, "schema", None):
+ and getattr(table, "schema", None):
result = self.quote_schema(table.schema) + "." + result
return result
@@ -2936,7 +2946,7 @@ class IdentifierPreparer(object):
return self.quote(name, quote)
def format_column(self, column, use_table=False,
- name=None, table_name=None):
+ name=None, table_name=None):
"""Prepare a quoted column name."""
if name is None:
@@ -2944,8 +2954,8 @@ class IdentifierPreparer(object):
if not getattr(column, 'is_literal', False):
if use_table:
return self.format_table(
- column.table, use_schema=False,
- name=table_name) + "." + self.quote(name)
+ column.table, use_schema=False,
+ name=table_name) + "." + self.quote(name)
else:
return self.quote(name)
else:
@@ -2953,8 +2963,9 @@ class IdentifierPreparer(object):
# which shouldn't get quoted
if use_table:
- return self.format_table(column.table,
- use_schema=False, name=table_name) + '.' + name
+ return self.format_table(
+ column.table, use_schema=False,
+ name=table_name) + '.' + name
else:
return name
@@ -2975,9 +2986,9 @@ class IdentifierPreparer(object):
@util.memoized_property
def _r_identifiers(self):
initial, final, escaped_final = \
- [re.escape(s) for s in
- (self.initial_quote, self.final_quote,
- self._escape_identifier(self.final_quote))]
+ [re.escape(s) for s in
+ (self.initial_quote, self.final_quote,
+ self._escape_identifier(self.final_quote))]
r = re.compile(
r'(?:'
r'(?:%(initial)s((?:%(escaped)s|[^%(final)s])+)%(final)s'
diff --git a/lib/sqlalchemy/sql/ddl.py b/lib/sqlalchemy/sql/ddl.py
index d8627a08d..1f2c448ea 100644
--- a/lib/sqlalchemy/sql/ddl.py
+++ b/lib/sqlalchemy/sql/ddl.py
@@ -18,6 +18,7 @@ from ..util import topological
from .. import event
from .. import exc
+
class _DDLCompiles(ClauseElement):
def _compiler(self, dialect, **kw):
"""Return a compiler appropriate for this ClauseElement, given a
@@ -57,7 +58,7 @@ class DDLElement(Executable, _DDLCompiles):
"""
_execution_options = Executable.\
- _execution_options.union({'autocommit': True})
+ _execution_options.union({'autocommit': True})
target = None
on = None
@@ -96,10 +97,10 @@ class DDLElement(Executable, _DDLCompiles):
return bind.execute(self.against(target))
else:
bind.engine.logger.info(
- "DDL execution skipped, criteria not met.")
+ "DDL execution skipped, criteria not met.")
@util.deprecated("0.7", "See :class:`.DDLEvents`, as well as "
- ":meth:`.DDLElement.execute_if`.")
+ ":meth:`.DDLElement.execute_if`.")
def execute_at(self, event_name, target):
"""Link execution of this DDL to the DDL lifecycle of a SchemaItem.
@@ -130,7 +131,7 @@ class DDLElement(Executable, _DDLCompiles):
def call_event(target, connection, **kw):
if self._should_execute_deprecated(event_name,
- target, connection, **kw):
+ target, connection, **kw):
return connection.execute(self.against(target))
event.listen(target, "" + event_name.replace('-', '_'), call_event)
@@ -212,7 +213,7 @@ class DDLElement(Executable, _DDLCompiles):
def _should_execute(self, target, bind, **kw):
if self.on is not None and \
- not self._should_execute_deprecated(None, target, bind, **kw):
+ not self._should_execute_deprecated(None, target, bind, **kw):
return False
if isinstance(self.dialect, util.string_types):
@@ -221,8 +222,9 @@ class DDLElement(Executable, _DDLCompiles):
elif isinstance(self.dialect, (tuple, list, set)):
if bind.engine.name not in self.dialect:
return False
- if self.callable_ is not None and \
- not self.callable_(self, target, bind, state=self.state, **kw):
+ if (self.callable_ is not None and
+ not self.callable_(self, target, bind,
+ state=self.state, **kw)):
return False
return True
@@ -246,7 +248,7 @@ class DDLElement(Executable, _DDLCompiles):
def _check_ddl_on(self, on):
if (on is not None and
(not isinstance(on, util.string_types + (tuple, list, set)) and
- not util.callable(on))):
+ not util.callable(on))):
raise exc.ArgumentError(
"Expected the name of a database dialect, a tuple "
"of names, or a callable for "
@@ -393,7 +395,6 @@ class DDL(DDLElement):
if getattr(self, key)]))
-
class _CreateDropBase(DDLElement):
"""Base class for DDL constructs that represent CREATE and DROP or
equivalents.
@@ -474,8 +475,8 @@ class CreateTable(_CreateDropBase):
"""
super(CreateTable, self).__init__(element, on=on, bind=bind)
self.columns = [CreateColumn(column)
- for column in element.columns
- ]
+ for column in element.columns
+ ]
class _DropView(_CreateDropBase):
@@ -561,9 +562,10 @@ class CreateColumn(_DDLCompiles):
as an implicitly-present "system" column.
For example, suppose we wish to produce a :class:`.Table` which skips
- rendering of the Postgresql ``xmin`` column against the Postgresql backend,
- but on other backends does render it, in anticipation of a triggered rule.
- A conditional compilation rule could skip this name only on Postgresql::
+ rendering of the Postgresql ``xmin`` column against the Postgresql
+ backend, but on other backends does render it, in anticipation of a
+ triggered rule. A conditional compilation rule could skip this name only
+ on Postgresql::
from sqlalchemy.schema import CreateColumn
@@ -585,7 +587,8 @@ class CreateColumn(_DDLCompiles):
will be omitted, but only against the Postgresql backend.
.. versionadded:: 0.8.3 The :class:`.CreateColumn` construct supports
- skipping of columns by returning ``None`` from a custom compilation rule.
+ skipping of columns by returning ``None`` from a custom compilation
+ rule.
.. versionadded:: 0.8 The :class:`.CreateColumn` construct was added
to support custom column creation styles.
@@ -635,7 +638,7 @@ class AddConstraint(_CreateDropBase):
def __init__(self, element, *args, **kw):
super(AddConstraint, self).__init__(element, *args, **kw)
element._create_rule = util.portable_instancemethod(
- self._create_rule_disable)
+ self._create_rule_disable)
class DropConstraint(_CreateDropBase):
@@ -647,7 +650,7 @@ class DropConstraint(_CreateDropBase):
self.cascade = cascade
super(DropConstraint, self).__init__(element, **kw)
element._create_rule = util.portable_instancemethod(
- self._create_rule_disable)
+ self._create_rule_disable)
class DDLBase(SchemaVisitor):
@@ -671,21 +674,21 @@ class SchemaGenerator(DDLBase):
if table.schema:
self.dialect.validate_identifier(table.schema)
return not self.checkfirst or \
- not self.dialect.has_table(self.connection,
- table.name, schema=table.schema)
+ not self.dialect.has_table(self.connection,
+ table.name, schema=table.schema)
def _can_create_sequence(self, sequence):
return self.dialect.supports_sequences and \
(
(not self.dialect.sequences_optional or
not sequence.optional) and
- (
- not self.checkfirst or
- not self.dialect.has_sequence(
- self.connection,
- sequence.name,
- schema=sequence.schema)
- )
+ (
+ not self.checkfirst or
+ not self.dialect.has_sequence(
+ self.connection,
+ sequence.name,
+ schema=sequence.schema)
+ )
)
def visit_metadata(self, metadata):
@@ -694,14 +697,14 @@ class SchemaGenerator(DDLBase):
else:
tables = list(metadata.tables.values())
collection = [t for t in sort_tables(tables)
- if self._can_create_table(t)]
+ if self._can_create_table(t)]
seq_coll = [s for s in metadata._sequences.values()
- if s.column is None and self._can_create_sequence(s)]
+ if s.column is None and self._can_create_sequence(s)]
metadata.dispatch.before_create(metadata, self.connection,
- tables=collection,
- checkfirst=self.checkfirst,
- _ddl_runner=self)
+ tables=collection,
+ checkfirst=self.checkfirst,
+ _ddl_runner=self)
for seq in seq_coll:
self.traverse_single(seq, create_ok=True)
@@ -710,17 +713,17 @@ class SchemaGenerator(DDLBase):
self.traverse_single(table, create_ok=True)
metadata.dispatch.after_create(metadata, self.connection,
- tables=collection,
- checkfirst=self.checkfirst,
- _ddl_runner=self)
+ tables=collection,
+ checkfirst=self.checkfirst,
+ _ddl_runner=self)
def visit_table(self, table, create_ok=False):
if not create_ok and not self._can_create_table(table):
return
table.dispatch.before_create(table, self.connection,
- checkfirst=self.checkfirst,
- _ddl_runner=self)
+ checkfirst=self.checkfirst,
+ _ddl_runner=self)
for column in table.columns:
if column.default is not None:
@@ -733,8 +736,8 @@ class SchemaGenerator(DDLBase):
self.traverse_single(index)
table.dispatch.after_create(table, self.connection,
- checkfirst=self.checkfirst,
- _ddl_runner=self)
+ checkfirst=self.checkfirst,
+ _ddl_runner=self)
def visit_sequence(self, sequence, create_ok=False):
if not create_ok and not self._can_create_sequence(sequence):
@@ -792,19 +795,19 @@ class SchemaDropper(DDLBase):
self.dialect.validate_identifier(table.name)
if table.schema:
self.dialect.validate_identifier(table.schema)
- return not self.checkfirst or self.dialect.has_table(self.connection,
- table.name, schema=table.schema)
+ return not self.checkfirst or self.dialect.has_table(
+ self.connection, table.name, schema=table.schema)
def _can_drop_sequence(self, sequence):
return self.dialect.supports_sequences and \
((not self.dialect.sequences_optional or
- not sequence.optional) and
+ not sequence.optional) and
(not self.checkfirst or
- self.dialect.has_sequence(
- self.connection,
- sequence.name,
- schema=sequence.schema))
- )
+ self.dialect.has_sequence(
+ self.connection,
+ sequence.name,
+ schema=sequence.schema))
+ )
def visit_index(self, index):
self.connection.execute(DropIndex(index))
@@ -814,8 +817,8 @@ class SchemaDropper(DDLBase):
return
table.dispatch.before_drop(table, self.connection,
- checkfirst=self.checkfirst,
- _ddl_runner=self)
+ checkfirst=self.checkfirst,
+ _ddl_runner=self)
for column in table.columns:
if column.default is not None:
@@ -824,14 +827,15 @@ class SchemaDropper(DDLBase):
self.connection.execute(DropTable(table))
table.dispatch.after_drop(table, self.connection,
- checkfirst=self.checkfirst,
- _ddl_runner=self)
+ checkfirst=self.checkfirst,
+ _ddl_runner=self)
def visit_sequence(self, sequence, drop_ok=False):
if not drop_ok and not self._can_drop_sequence(sequence):
return
self.connection.execute(DropSequence(sequence))
+
def sort_tables(tables, skip_fn=None, extra_dependencies=None):
"""sort a collection of Table objects in order of
their foreign-key dependency."""
@@ -854,12 +858,11 @@ def sort_tables(tables, skip_fn=None, extra_dependencies=None):
for table in tables:
traverse(table,
- {'schema_visitor': True},
- {'foreign_key': visit_foreign_key})
+ {'schema_visitor': True},
+ {'foreign_key': visit_foreign_key})
tuples.extend(
[parent, table] for parent in table._extra_dependencies
)
return list(topological.sort(tuples, tables))
-
diff --git a/lib/sqlalchemy/sql/default_comparator.py b/lib/sqlalchemy/sql/default_comparator.py
index 977ed25c2..4f53e2979 100644
--- a/lib/sqlalchemy/sql/default_comparator.py
+++ b/lib/sqlalchemy/sql/default_comparator.py
@@ -12,11 +12,12 @@ from .. import exc, util
from . import operators
from . import type_api
from .elements import BindParameter, True_, False_, BinaryExpression, \
- Null, _const_expr, _clause_element_as_expr, \
- ClauseList, ColumnElement, TextClause, UnaryExpression, \
- collate, _is_literal, _literal_as_text, ClauseElement, and_, or_
+ Null, _const_expr, _clause_element_as_expr, \
+ ClauseList, ColumnElement, TextClause, UnaryExpression, \
+ collate, _is_literal, _literal_as_text, ClauseElement, and_, or_
from .selectable import SelectBase, Alias, Selectable, ScalarSelect
+
class _DefaultColumnComparator(operators.ColumnOperators):
"""Defines comparison and math operations.
@@ -35,7 +36,8 @@ class _DefaultColumnComparator(operators.ColumnOperators):
def reverse_operate(self, op, other, **kwargs):
o = self.operators[op.__name__]
- return o[0](self, self.expr, op, other, reverse=True, *o[1:], **kwargs)
+ return o[0](self, self.expr, op, other,
+ reverse=True, *o[1:], **kwargs)
def _adapt_expression(self, op, other_comparator):
"""evaluate the return type of <self> <op> <othertype>,
@@ -65,8 +67,8 @@ class _DefaultColumnComparator(operators.ColumnOperators):
return op, other_comparator.type
def _boolean_compare(self, expr, op, obj, negate=None, reverse=False,
- _python_is_types=(util.NoneType, bool),
- **kwargs):
+ _python_is_types=(util.NoneType, bool),
+ **kwargs):
if isinstance(obj, _python_is_types + (Null, True_, False_)):
@@ -76,20 +78,20 @@ class _DefaultColumnComparator(operators.ColumnOperators):
if op in (operators.eq, operators.ne) and \
isinstance(obj, (bool, True_, False_)):
return BinaryExpression(expr,
- _literal_as_text(obj),
- op,
- type_=type_api.BOOLEANTYPE,
- negate=negate, modifiers=kwargs)
+ _literal_as_text(obj),
+ op,
+ type_=type_api.BOOLEANTYPE,
+ negate=negate, modifiers=kwargs)
else:
# all other None/True/False uses IS, IS NOT
if op in (operators.eq, operators.is_):
return BinaryExpression(expr, _const_expr(obj),
- operators.is_,
- negate=operators.isnot)
+ operators.is_,
+ negate=operators.isnot)
elif op in (operators.ne, operators.isnot):
return BinaryExpression(expr, _const_expr(obj),
- operators.isnot,
- negate=operators.is_)
+ operators.isnot,
+ negate=operators.is_)
else:
raise exc.ArgumentError(
"Only '=', '!=', 'is_()', 'isnot()' operators can "
@@ -99,19 +101,19 @@ class _DefaultColumnComparator(operators.ColumnOperators):
if reverse:
return BinaryExpression(obj,
- expr,
- op,
- type_=type_api.BOOLEANTYPE,
- negate=negate, modifiers=kwargs)
+ expr,
+ op,
+ type_=type_api.BOOLEANTYPE,
+ negate=negate, modifiers=kwargs)
else:
return BinaryExpression(expr,
- obj,
- op,
- type_=type_api.BOOLEANTYPE,
- negate=negate, modifiers=kwargs)
+ obj,
+ op,
+ type_=type_api.BOOLEANTYPE,
+ negate=negate, modifiers=kwargs)
def _binary_operate(self, expr, op, obj, reverse=False, result_type=None,
- **kw):
+ **kw):
obj = self._check_literal(expr, op, obj)
if reverse:
@@ -121,7 +123,7 @@ class _DefaultColumnComparator(operators.ColumnOperators):
if result_type is None:
op, result_type = left.comparator._adapt_expression(
- op, right.comparator)
+ op, right.comparator)
return BinaryExpression(left, right, op, type_=result_type)
@@ -141,7 +143,7 @@ class _DefaultColumnComparator(operators.ColumnOperators):
if isinstance(seq_or_selectable, ScalarSelect):
return self._boolean_compare(expr, op, seq_or_selectable,
- negate=negate_op)
+ negate=negate_op)
elif isinstance(seq_or_selectable, SelectBase):
# TODO: if we ever want to support (x, y, z) IN (select x,
@@ -154,20 +156,22 @@ class _DefaultColumnComparator(operators.ColumnOperators):
negate=negate_op, **kw)
elif isinstance(seq_or_selectable, (Selectable, TextClause)):
return self._boolean_compare(expr, op, seq_or_selectable,
- negate=negate_op, **kw)
+ negate=negate_op, **kw)
elif isinstance(seq_or_selectable, ClauseElement):
- raise exc.InvalidRequestError('in_() accepts'
- ' either a list of expressions '
- 'or a selectable: %r' % seq_or_selectable)
+ raise exc.InvalidRequestError(
+ 'in_() accepts'
+ ' either a list of expressions '
+ 'or a selectable: %r' % seq_or_selectable)
# Handle non selectable arguments as sequences
args = []
for o in seq_or_selectable:
if not _is_literal(o):
if not isinstance(o, operators.ColumnOperators):
- raise exc.InvalidRequestError('in_() accepts'
- ' either a list of expressions '
- 'or a selectable: %r' % o)
+ raise exc.InvalidRequestError(
+ 'in_() accepts'
+ ' either a list of expressions '
+ 'or a selectable: %r' % o)
elif o is None:
o = Null()
else:
@@ -192,12 +196,12 @@ class _DefaultColumnComparator(operators.ColumnOperators):
return expr == expr
return self._boolean_compare(expr, op,
- ClauseList(*args).self_group(against=op),
- negate=negate_op)
+ ClauseList(*args).self_group(against=op),
+ negate=negate_op)
def _unsupported_impl(self, expr, op, *arg, **kw):
raise NotImplementedError("Operator '%s' is not supported on "
- "this expression" % op.__name__)
+ "this expression" % op.__name__)
def _inv_impl(self, expr, op, **kw):
"""See :meth:`.ColumnOperators.__inv__`."""
@@ -212,29 +216,31 @@ class _DefaultColumnComparator(operators.ColumnOperators):
def _match_impl(self, expr, op, other, **kw):
"""See :meth:`.ColumnOperators.match`."""
- return self._boolean_compare(expr, operators.match_op,
- self._check_literal(expr, operators.match_op,
- other), **kw)
+ return self._boolean_compare(
+ expr, operators.match_op,
+ self._check_literal(
+ expr, operators.match_op, other),
+ **kw)
def _distinct_impl(self, expr, op, **kw):
"""See :meth:`.ColumnOperators.distinct`."""
return UnaryExpression(expr, operator=operators.distinct_op,
- type_=expr.type)
+ type_=expr.type)
def _between_impl(self, expr, op, cleft, cright, **kw):
"""See :meth:`.ColumnOperators.between`."""
return BinaryExpression(
- expr,
- ClauseList(
- self._check_literal(expr, operators.and_, cleft),
- self._check_literal(expr, operators.and_, cright),
- operator=operators.and_,
- group=False, group_contents=False),
- op,
- negate=operators.notbetween_op
- if op is operators.between_op
- else operators.between_op,
- modifiers=kw)
+ expr,
+ ClauseList(
+ self._check_literal(expr, operators.and_, cleft),
+ self._check_literal(expr, operators.and_, cright),
+ operator=operators.and_,
+ group=False, group_contents=False),
+ op,
+ negate=operators.notbetween_op
+ if op is operators.between_op
+ else operators.between_op,
+ modifiers=kw)
def _collate_impl(self, expr, op, other, **kw):
return collate(expr, other)
@@ -303,4 +309,3 @@ class _DefaultColumnComparator(operators.ColumnOperators):
return expr._bind_param(operator, other)
else:
return other
-
diff --git a/lib/sqlalchemy/sql/dml.py b/lib/sqlalchemy/sql/dml.py
index 2368c3eec..f7e033d85 100644
--- a/lib/sqlalchemy/sql/dml.py
+++ b/lib/sqlalchemy/sql/dml.py
@@ -15,6 +15,7 @@ from .selectable import _interpret_as_from, _interpret_as_select, HasPrefixes
from .. import util
from .. import exc
+
class UpdateBase(DialectKWArgs, HasPrefixes, Executable, ClauseElement):
"""Form the base for ``INSERT``, ``UPDATE``, and ``DELETE`` statements.
@@ -37,9 +38,8 @@ class UpdateBase(DialectKWArgs, HasPrefixes, Executable, ClauseElement):
else:
return p
- if isinstance(parameters, (list, tuple)) and \
- parameters and \
- isinstance(parameters[0], (list, tuple, dict)):
+ if (isinstance(parameters, (list, tuple)) and parameters and
+ isinstance(parameters[0], (list, tuple, dict))):
if not self._supports_multi_parameters:
raise exc.InvalidRequestError(
@@ -83,7 +83,8 @@ class UpdateBase(DialectKWArgs, HasPrefixes, Executable, ClauseElement):
stmt = table.update().\\
where(table.c.data == 'value').\\
values(status='X').\\
- returning(table.c.server_flag, table.c.updated_timestamp)
+ returning(table.c.server_flag,
+ table.c.updated_timestamp)
for server_flag, updated_timestamp in connection.execute(stmt):
print(server_flag, updated_timestamp)
@@ -94,21 +95,20 @@ class UpdateBase(DialectKWArgs, HasPrefixes, Executable, ClauseElement):
objects are typical, the elements can also be expressions::
stmt = table.insert().returning(
- (table.c.first_name + " " + table.c.last_name).label('fullname')
- )
+ (table.c.first_name + " " + table.c.last_name).
+ label('fullname'))
Upon compilation, a RETURNING clause, or database equivalent,
will be rendered within the statement. For INSERT and UPDATE,
the values are the newly inserted/updated values. For DELETE,
the values are those of the rows which were deleted.
- Upon execution, the values of the columns to be returned
- are made available via the result set and can be iterated
- using :meth:`.ResultProxy.fetchone` and similar. For DBAPIs which do not
- natively support returning values (i.e. cx_oracle),
- SQLAlchemy will approximate this behavior at the result level
- so that a reasonable amount of behavioral neutrality is
- provided.
+ Upon execution, the values of the columns to be returned are made
+ available via the result set and can be iterated using
+ :meth:`.ResultProxy.fetchone` and similar. For DBAPIs which do not
+ natively support returning values (i.e. cx_oracle), SQLAlchemy will
+ approximate this behavior at the result level so that a reasonable
+ amount of behavioral neutrality is provided.
Note that not all databases/DBAPIs
support RETURNING. For those backends with no support,
@@ -129,7 +129,6 @@ class UpdateBase(DialectKWArgs, HasPrefixes, Executable, ClauseElement):
"""
self._returning = cols
-
@_generative
def with_hint(self, text, selectable=None, dialect_name="*"):
"""Add a table hint for a single table to this
@@ -167,7 +166,7 @@ class UpdateBase(DialectKWArgs, HasPrefixes, Executable, ClauseElement):
selectable = self.table
self._hints = self._hints.union(
- {(selectable, dialect_name): text})
+ {(selectable, dialect_name): text})
class ValuesBase(UpdateBase):
@@ -183,7 +182,7 @@ class ValuesBase(UpdateBase):
def __init__(self, table, values, prefixes):
self.table = _interpret_as_from(table)
self.parameters, self._has_multi_parameters = \
- self._process_colparams(values)
+ self._process_colparams(values)
if prefixes:
self._setup_prefixes(prefixes)
@@ -194,9 +193,9 @@ class ValuesBase(UpdateBase):
Note that the :class:`.Insert` and :class:`.Update` constructs support
per-execution time formatting of the VALUES and/or SET clauses,
- based on the arguments passed to :meth:`.Connection.execute`. However,
- the :meth:`.ValuesBase.values` method can be used to "fix" a particular
- set of parameters into the statement.
+ based on the arguments passed to :meth:`.Connection.execute`.
+ However, the :meth:`.ValuesBase.values` method can be used to "fix" a
+ particular set of parameters into the statement.
Multiple calls to :meth:`.ValuesBase.values` will produce a new
construct, each one with the parameter list modified to include
@@ -229,8 +228,8 @@ class ValuesBase(UpdateBase):
The :class:`.Insert` construct also supports multiply-rendered VALUES
construct, for those backends which support this SQL syntax
- (SQLite, Postgresql, MySQL). This mode is indicated by passing a list
- of one or more dictionaries/tuples::
+ (SQLite, Postgresql, MySQL). This mode is indicated by passing a
+ list of one or more dictionaries/tuples::
users.insert().values([
{"name": "some name"},
@@ -248,9 +247,10 @@ class ValuesBase(UpdateBase):
.. note::
Passing a multiple values list is *not* the same
- as passing a multiple values list to the :meth:`.Connection.execute`
- method. Passing a list of parameter sets to :meth:`.ValuesBase.values`
- produces a construct of this form::
+ as passing a multiple values list to the
+ :meth:`.Connection.execute` method. Passing a list of parameter
+ sets to :meth:`.ValuesBase.values` produces a construct of this
+ form::
INSERT INTO table (col1, col2, col3) VALUES
(col1_0, col2_0, col3_0),
@@ -282,23 +282,23 @@ class ValuesBase(UpdateBase):
"""
if self.select is not None:
raise exc.InvalidRequestError(
- "This construct already inserts from a SELECT")
+ "This construct already inserts from a SELECT")
if self._has_multi_parameters and kwargs:
raise exc.InvalidRequestError(
- "This construct already has multiple parameter sets.")
+ "This construct already has multiple parameter sets.")
if args:
if len(args) > 1:
raise exc.ArgumentError(
- "Only a single dictionary/tuple or list of "
- "dictionaries/tuples is accepted positionally.")
+ "Only a single dictionary/tuple or list of "
+ "dictionaries/tuples is accepted positionally.")
v = args[0]
else:
v = {}
if self.parameters is None:
self.parameters, self._has_multi_parameters = \
- self._process_colparams(v)
+ self._process_colparams(v)
else:
if self._has_multi_parameters:
self.parameters = list(self.parameters)
@@ -321,8 +321,8 @@ class ValuesBase(UpdateBase):
if kwargs:
if self._has_multi_parameters:
raise exc.ArgumentError(
- "Can't pass kwargs and multiple parameter sets "
- "simultaenously")
+ "Can't pass kwargs and multiple parameter sets "
+ "simultaenously")
else:
self.parameters.update(kwargs)
@@ -340,40 +340,40 @@ class ValuesBase(UpdateBase):
server_created_at = result.returned_defaults['created_at']
When used against a backend that supports RETURNING, all column
- values generated by SQL expression or server-side-default will be added
- to any existing RETURNING clause, provided that
- :meth:`.UpdateBase.returning` is not used simultaneously. The column values
- will then be available on the result using the
- :attr:`.ResultProxy.returned_defaults` accessor as a
- dictionary, referring to values keyed to the :class:`.Column` object
- as well as its ``.key``.
+ values generated by SQL expression or server-side-default will be
+ added to any existing RETURNING clause, provided that
+ :meth:`.UpdateBase.returning` is not used simultaneously. The column
+ values will then be available on the result using the
+ :attr:`.ResultProxy.returned_defaults` accessor as a dictionary,
+ referring to values keyed to the :class:`.Column` object as well as
+ its ``.key``.
This method differs from :meth:`.UpdateBase.returning` in these ways:
1. :meth:`.ValuesBase.return_defaults` is only intended for use with
an INSERT or an UPDATE statement that matches exactly one row.
- While the RETURNING construct in the general sense supports multiple
- rows for a multi-row UPDATE or DELETE statement, or for special
- cases of INSERT that return multiple rows (e.g. INSERT from SELECT,
- multi-valued VALUES clause), :meth:`.ValuesBase.return_defaults`
- is intended only
- for an "ORM-style" single-row INSERT/UPDATE statement. The row
- returned by the statement is also consumed implcitly when
+ While the RETURNING construct in the general sense supports
+ multiple rows for a multi-row UPDATE or DELETE statement, or for
+ special cases of INSERT that return multiple rows (e.g. INSERT from
+ SELECT, multi-valued VALUES clause),
+ :meth:`.ValuesBase.return_defaults` is intended only for an
+ "ORM-style" single-row INSERT/UPDATE statement. The row returned
+ by the statement is also consumed implcitly when
:meth:`.ValuesBase.return_defaults` is used. By contrast,
- :meth:`.UpdateBase.returning` leaves the RETURNING result-set intact
- with a collection of any number of rows.
+ :meth:`.UpdateBase.returning` leaves the RETURNING result-set
+ intact with a collection of any number of rows.
2. It is compatible with the existing logic to fetch auto-generated
- primary key values, also known as "implicit returning". Backends that
- support RETURNING will automatically make use of RETURNING in order
- to fetch the value of newly generated primary keys; while the
+ primary key values, also known as "implicit returning". Backends
+ that support RETURNING will automatically make use of RETURNING in
+ order to fetch the value of newly generated primary keys; while the
:meth:`.UpdateBase.returning` method circumvents this behavior,
:meth:`.ValuesBase.return_defaults` leaves it intact.
3. It can be called against any backend. Backends that don't support
RETURNING will skip the usage of the feature, rather than raising
- an exception. The return value of :attr:`.ResultProxy.returned_defaults`
- will be ``None``
+ an exception. The return value of
+ :attr:`.ResultProxy.returned_defaults` will be ``None``
:meth:`.ValuesBase.return_defaults` is used by the ORM to provide
an efficient implementation for the ``eager_defaults`` feature of
@@ -411,21 +411,22 @@ class Insert(ValuesBase):
_supports_multi_parameters = True
def __init__(self,
- table,
- values=None,
- inline=False,
- bind=None,
- prefixes=None,
- returning=None,
- return_defaults=False,
- **dialect_kw):
+ table,
+ values=None,
+ inline=False,
+ bind=None,
+ prefixes=None,
+ returning=None,
+ return_defaults=False,
+ **dialect_kw):
"""Construct an :class:`.Insert` object.
Similar functionality is available via the
:meth:`~.TableClause.insert` method on
:class:`~.schema.Table`.
- :param table: :class:`.TableClause` which is the subject of the insert.
+ :param table: :class:`.TableClause` which is the subject of the
+ insert.
:param values: collection of values to be inserted; see
:meth:`.Insert.values` for a description of allowed formats here.
@@ -433,15 +434,16 @@ class Insert(ValuesBase):
dynamically render the VALUES clause at execution time based on
the parameters passed to :meth:`.Connection.execute`.
- :param inline: if True, SQL defaults will be compiled 'inline' into the
- statement and not pre-executed.
+ :param inline: if True, SQL defaults will be compiled 'inline' into
+ the statement and not pre-executed.
If both `values` and compile-time bind parameters are present, the
compile-time bind parameters override the information specified
within `values` on a per-key basis.
- The keys within `values` can be either :class:`~sqlalchemy.schema.Column`
- objects or their string identifiers. Each key may reference one of:
+ The keys within `values` can be either
+ :class:`~sqlalchemy.schema.Column` objects or their string
+ identifiers. Each key may reference one of:
* a literal data value (i.e. string, number, etc.);
* a Column object;
@@ -498,8 +500,9 @@ class Insert(ValuesBase):
Depending on backend, it may be necessary for the :class:`.Insert`
statement to be constructed using the ``inline=True`` flag; this
flag will prevent the implicit usage of ``RETURNING`` when the
- ``INSERT`` statement is rendered, which isn't supported on a backend
- such as Oracle in conjunction with an ``INSERT..SELECT`` combination::
+ ``INSERT`` statement is rendered, which isn't supported on a
+ backend such as Oracle in conjunction with an ``INSERT..SELECT``
+ combination::
sel = select([table1.c.a, table1.c.b]).where(table1.c.c > 5)
ins = table2.insert(inline=True).from_select(['a', 'b'], sel)
@@ -516,10 +519,10 @@ class Insert(ValuesBase):
"""
if self.parameters:
raise exc.InvalidRequestError(
- "This construct already inserts value expressions")
+ "This construct already inserts value expressions")
self.parameters, self._has_multi_parameters = \
- self._process_colparams(dict((n, Null()) for n in names))
+ self._process_colparams(dict((n, Null()) for n in names))
self.select_names = names
self.select = _interpret_as_select(select)
@@ -534,21 +537,22 @@ class Insert(ValuesBase):
class Update(ValuesBase):
"""Represent an Update construct.
- The :class:`.Update` object is created using the :func:`update()` function.
+ The :class:`.Update` object is created using the :func:`update()`
+ function.
"""
__visit_name__ = 'update'
def __init__(self,
- table,
- whereclause=None,
- values=None,
- inline=False,
- bind=None,
- prefixes=None,
- returning=None,
- return_defaults=False,
- **dialect_kw):
+ table,
+ whereclause=None,
+ values=None,
+ inline=False,
+ bind=None,
+ prefixes=None,
+ returning=None,
+ return_defaults=False,
+ **dialect_kw):
"""Construct an :class:`.Update` object.
E.g.::
@@ -662,7 +666,6 @@ class Update(ValuesBase):
self._validate_dialect_kwargs(dialect_kw)
self._return_defaults = return_defaults
-
def get_children(self, **kwargs):
if self._whereclause is not None:
return self._whereclause,
@@ -682,7 +685,7 @@ class Update(ValuesBase):
"""
if self._whereclause is not None:
self._whereclause = and_(self._whereclause,
- _literal_as_text(whereclause))
+ _literal_as_text(whereclause))
else:
self._whereclause = _literal_as_text(whereclause)
@@ -705,19 +708,20 @@ class Update(ValuesBase):
class Delete(UpdateBase):
"""Represent a DELETE construct.
- The :class:`.Delete` object is created using the :func:`delete()` function.
+ The :class:`.Delete` object is created using the :func:`delete()`
+ function.
"""
__visit_name__ = 'delete'
def __init__(self,
- table,
- whereclause=None,
- bind=None,
- returning=None,
- prefixes=None,
- **dialect_kw):
+ table,
+ whereclause=None,
+ bind=None,
+ returning=None,
+ prefixes=None,
+ **dialect_kw):
"""Construct :class:`.Delete` object.
Similar functionality is available via the
@@ -761,11 +765,10 @@ class Delete(UpdateBase):
if self._whereclause is not None:
self._whereclause = and_(self._whereclause,
- _literal_as_text(whereclause))
+ _literal_as_text(whereclause))
else:
self._whereclause = _literal_as_text(whereclause)
def _copy_internals(self, clone=_clone, **kw):
# TODO: coverage
self._whereclause = clone(self._whereclause, **kw)
-
diff --git a/lib/sqlalchemy/sql/elements.py b/lib/sqlalchemy/sql/elements.py
index ab07efee3..6114460dc 100644
--- a/lib/sqlalchemy/sql/elements.py
+++ b/lib/sqlalchemy/sql/elements.py
@@ -24,9 +24,11 @@ from .base import _generative, Generative
import re
import operator
+
def _clone(element, **kw):
return element._clone()
+
def collate(expression, collation):
"""Return the clause ``expression COLLATE collation``.
@@ -46,6 +48,7 @@ def collate(expression, collation):
_literal_as_text(collation),
operators.collate, type_=expr.type)
+
def between(expr, lower_bound, upper_bound, symmetric=False):
"""Produce a ``BETWEEN`` predicate clause.
@@ -80,8 +83,8 @@ def between(expr, lower_bound, upper_bound, symmetric=False):
into a column expression, serving as the left side of the ``BETWEEN``
expression.
- :param lower_bound: a column or Python scalar expression serving as the lower
- bound of the right side of the ``BETWEEN`` expression.
+ :param lower_bound: a column or Python scalar expression serving as the
+ lower bound of the right side of the ``BETWEEN`` expression.
:param upper_bound: a column or Python scalar expression serving as the
upper bound of the right side of the ``BETWEEN`` expression.
@@ -99,15 +102,15 @@ def between(expr, lower_bound, upper_bound, symmetric=False):
expr = _literal_as_binds(expr)
return expr.between(lower_bound, upper_bound, symmetric=symmetric)
+
def literal(value, type_=None):
"""Return a literal clause, bound to a bind parameter.
- Literal clauses are created automatically when non- :class:`.ClauseElement`
- objects (such as strings, ints, dates, etc.) are used in a comparison
- operation with a :class:`.ColumnElement`
- subclass, such as a :class:`~sqlalchemy.schema.Column` object.
- Use this function to force the
- generation of a literal clause, which will be created as a
+ Literal clauses are created automatically when non-
+ :class:`.ClauseElement` objects (such as strings, ints, dates, etc.) are
+ used in a comparison operation with a :class:`.ColumnElement` subclass,
+ such as a :class:`~sqlalchemy.schema.Column` object. Use this function
+ to force the generation of a literal clause, which will be created as a
:class:`BindParameter` with a bound value.
:param value: the value to be bound. Can be any Python object supported by
@@ -120,7 +123,6 @@ def literal(value, type_=None):
return BindParameter(None, value, type_=type_, unique=True)
-
def type_coerce(expression, type_):
"""Associate a SQL expression with a particular type, without rendering
``CAST``.
@@ -155,8 +157,9 @@ def type_coerce(expression, type_):
except that it does not render the ``CAST`` expression in the resulting
statement.
- :param expression: A SQL expression, such as a :class:`.ColumnElement` expression
- or a Python string which will be coerced into a bound literal value.
+ :param expression: A SQL expression, such as a :class:`.ColumnElement`
+ expression or a Python string which will be coerced into a bound literal
+ value.
:param type_: A :class:`.TypeEngine` class or instance indicating
the type to which the expression is coerced.
@@ -183,9 +186,6 @@ def type_coerce(expression, type_):
return Label(None, expression, type_=type_)
-
-
-
def outparam(key, type_=None):
"""Create an 'OUT' parameter for usage in functions (stored procedures),
for databases which support them.
@@ -197,9 +197,7 @@ def outparam(key, type_=None):
"""
return BindParameter(
- key, None, type_=type_, unique=False, isoutparam=True)
-
-
+ key, None, type_=type_, unique=False, isoutparam=True)
def not_(clause):
@@ -213,7 +211,6 @@ def not_(clause):
return operators.inv(_literal_as_binds(clause))
-
@inspection._self_inspects
class ClauseElement(Visitable):
"""Base class for elements of a programmatically constructed SQL
@@ -451,8 +448,8 @@ class ClauseElement(Visitable):
:param dialect: A ``Dialect`` instance from which a ``Compiled``
will be acquired. This argument takes precedence over the `bind`
- argument as well as this :class:`.ClauseElement`'s bound engine, if
- any.
+ argument as well as this :class:`.ClauseElement`'s bound engine,
+ if any.
:param inline: Used for INSERT statements, for a dialect which does
not support inline retrieval of newly generated primary key
@@ -532,16 +529,15 @@ class ClauseElement(Visitable):
def _negate(self):
return UnaryExpression(
- self.self_group(against=operators.inv),
- operator=operators.inv,
- negate=None)
+ self.self_group(against=operators.inv),
+ operator=operators.inv,
+ negate=None)
def __bool__(self):
raise TypeError("Boolean value of this clause is not defined")
__nonzero__ = __bool__
-
def __repr__(self):
friendly = getattr(self, 'description', None)
if friendly is None:
@@ -562,40 +558,42 @@ class ColumnElement(operators.ColumnOperators, ClauseElement):
literal expressions, keywords such as ``NULL``, etc.
:class:`.ColumnElement` is the ultimate base class for all such elements.
- A wide variety of SQLAlchemy Core functions work at the SQL expression level,
- and are intended to accept instances of :class:`.ColumnElement` as arguments.
- These functions will typically document that they accept a "SQL expression"
- as an argument. What this means in terms of SQLAlchemy usually refers
- to an input which is either already in the form of a :class:`.ColumnElement`
- object, or a value which can be **coerced** into one. The coercion
- rules followed by most, but not all, SQLAlchemy Core functions with regards
- to SQL expressions are as follows:
+ A wide variety of SQLAlchemy Core functions work at the SQL expression
+ level, and are intended to accept instances of :class:`.ColumnElement` as
+ arguments. These functions will typically document that they accept a
+ "SQL expression" as an argument. What this means in terms of SQLAlchemy
+ usually refers to an input which is either already in the form of a
+ :class:`.ColumnElement` object, or a value which can be **coerced** into
+ one. The coercion rules followed by most, but not all, SQLAlchemy Core
+ functions with regards to SQL expressions are as follows:
* a literal Python value, such as a string, integer or floating
point value, boolean, datetime, ``Decimal`` object, or virtually
- any other Python object, will be coerced into a "literal bound value".
- This generally means that a :func:`.bindparam` will be produced
- featuring the given value embedded into the construct; the resulting
- :class:`.BindParameter` object is an instance of :class:`.ColumnElement`.
- The Python value will ultimately be sent to the DBAPI at execution time as a
- paramterized argument to the ``execute()`` or ``executemany()`` methods,
- after SQLAlchemy type-specific converters (e.g. those provided by
- any associated :class:`.TypeEngine` objects) are applied to the value.
-
- * any special object value, typically ORM-level constructs, which feature
- a method called ``__clause_element__()``. The Core expression system
- looks for this method when an object of otherwise unknown type is passed
- to a function that is looking to coerce the argument into a :class:`.ColumnElement`
- expression. The ``__clause_element__()`` method, if present, should
- return a :class:`.ColumnElement` instance. The primary use of
- ``__clause_element__()`` within SQLAlchemy is that of class-bound attributes
- on ORM-mapped classes; a ``User`` class which contains a mapped attribute
- named ``.name`` will have a method ``User.name.__clause_element__()``
- which when invoked returns the :class:`.Column` called ``name`` associated
- with the mapped table.
-
- * The Python ``None`` value is typically interpreted as ``NULL``, which
- in SQLAlchemy Core produces an instance of :func:`.null`.
+ any other Python object, will be coerced into a "literal bound
+ value". This generally means that a :func:`.bindparam` will be
+ produced featuring the given value embedded into the construct; the
+ resulting :class:`.BindParameter` object is an instance of
+ :class:`.ColumnElement`. The Python value will ultimately be sent
+ to the DBAPI at execution time as a paramterized argument to the
+ ``execute()`` or ``executemany()`` methods, after SQLAlchemy
+ type-specific converters (e.g. those provided by any associated
+ :class:`.TypeEngine` objects) are applied to the value.
+
+ * any special object value, typically ORM-level constructs, which
+ feature a method called ``__clause_element__()``. The Core
+ expression system looks for this method when an object of otherwise
+ unknown type is passed to a function that is looking to coerce the
+ argument into a :class:`.ColumnElement` expression. The
+ ``__clause_element__()`` method, if present, should return a
+ :class:`.ColumnElement` instance. The primary use of
+ ``__clause_element__()`` within SQLAlchemy is that of class-bound
+ attributes on ORM-mapped classes; a ``User`` class which contains a
+ mapped attribute named ``.name`` will have a method
+ ``User.name.__clause_element__()`` which when invoked returns the
+ :class:`.Column` called ``name`` associated with the mapped table.
+
+ * The Python ``None`` value is typically interpreted as ``NULL``,
+ which in SQLAlchemy Core produces an instance of :func:`.null`.
A :class:`.ColumnElement` provides the ability to generate new
:class:`.ColumnElement`
@@ -631,8 +629,9 @@ class ColumnElement(operators.ColumnOperators, ClauseElement):
_alt_names = ()
def self_group(self, against=None):
- if against in (operators.and_, operators.or_, operators._asbool) and \
- self.type._type_affinity is type_api.BOOLEANTYPE._type_affinity:
+ if (against in (operators.and_, operators.or_, operators._asbool) and
+ self.type._type_affinity
+ is type_api.BOOLEANTYPE._type_affinity):
return AsBoolean(self, operators.istrue, operators.isfalse)
else:
return self
@@ -656,7 +655,7 @@ class ColumnElement(operators.ColumnOperators, ClauseElement):
return getattr(self.comparator, key)
except AttributeError:
raise AttributeError(
- 'Neither %r object nor %r object has an attribute %r' % (
+ 'Neither %r object nor %r object has an attribute %r' % (
type(self).__name__,
type(self.comparator).__name__,
key)
@@ -670,8 +669,8 @@ class ColumnElement(operators.ColumnOperators, ClauseElement):
def _bind_param(self, operator, obj):
return BindParameter(None, obj,
- _compared_to_operator=operator,
- _compared_to_type=self.type, unique=True)
+ _compared_to_operator=operator,
+ _compared_to_type=self.type, unique=True)
@property
def expression(self):
@@ -689,7 +688,7 @@ class ColumnElement(operators.ColumnOperators, ClauseElement):
@util.memoized_property
def base_columns(self):
return util.column_set(c for c in self.proxy_set
- if not hasattr(c, '_proxies'))
+ if not hasattr(c, '_proxies'))
@util.memoized_property
def proxy_set(self):
@@ -710,9 +709,10 @@ class ColumnElement(operators.ColumnOperators, ClauseElement):
when targeting within a result row."""
return hasattr(other, 'name') and hasattr(self, 'name') and \
- other.name == self.name
+ other.name == self.name
- def _make_proxy(self, selectable, name=None, name_is_truncatable=False, **kw):
+ def _make_proxy(
+ self, selectable, name=None, name_is_truncatable=False, **kw):
"""Create a new :class:`.ColumnElement` representing this
:class:`.ColumnElement` as it appears in the select list of a
descending selectable.
@@ -731,10 +731,10 @@ class ColumnElement(operators.ColumnOperators, ClauseElement):
else:
key = name
co = ColumnClause(
- _as_truncated(name) if name_is_truncatable else name,
- type_=getattr(self, 'type', None),
- _selectable=selectable
- )
+ _as_truncated(name) if name_is_truncatable else name,
+ type_=getattr(self, 'type', None),
+ _selectable=selectable
+ )
co._proxies = [self]
if selectable._is_clone_of is not None:
co._is_clone_of = \
@@ -752,8 +752,8 @@ class ColumnElement(operators.ColumnOperators, ClauseElement):
:param equivalents: a dictionary of columns as keys mapped to sets
of columns. If the given "other" column is present in this
- dictionary, if any of the columns in the corresponding set() pass the
- comparison test, the result is True. This is used to expand the
+ dictionary, if any of the columns in the corresponding set() pass
+ the comparison test, the result is True. This is used to expand the
comparison to other columns that may be known to be equivalent to
this one via foreign key or other criterion.
@@ -794,8 +794,9 @@ class ColumnElement(operators.ColumnOperators, ClauseElement):
expressions and function calls.
"""
- return _anonymous_label('%%(%d %s)s' % (id(self), getattr(self,
- 'name', 'anon')))
+ return _anonymous_label(
+ '%%(%d %s)s' % (id(self), getattr(self, 'name', 'anon'))
+ )
class BindParameter(ColumnElement):
@@ -823,18 +824,18 @@ class BindParameter(ColumnElement):
_is_crud = False
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):
+ unique=False, required=NO_ARG,
+ quote=None, callable_=None,
+ isoutparam=False,
+ _compared_to_operator=None,
+ _compared_to_type=None):
"""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.
+ "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 SQLAlchemy, the :func:`.bindparam` construct has
the ability to carry along the actual value that will be ultimately
@@ -870,27 +871,29 @@ class BindParameter(ColumnElement):
where the WHERE criterion of the statement is to change on each
invocation, such as::
- stmt = users_table.update().\\
- where(user_table.c.name == bindparam('username')).\\
- values(fullname=bindparam('fullname'))
+ stmt = (users_table.update().
+ where(user_table.c.name == bindparam('username')).
+ values(fullname=bindparam('fullname'))
+ )
- connection.execute(stmt, [
- {"username": "wendy", "fullname": "Wendy Smith"},
- {"username": "jack", "fullname": "Jack Jones"},
- ])
+ connection.execute(
+ stmt, [{"username": "wendy", "fullname": "Wendy Smith"},
+ {"username": "jack", "fullname": "Jack Jones"},
+ ]
+ )
- SQLAlchemy's Core expression system makes wide use of :func:`.bindparam`
- in an implicit sense. It is typical that Python literal values passed to
- virtually all SQL expression functions are coerced into fixed
- :func:`.bindparam` constructs. For example, given a comparison operation
- such as::
+ SQLAlchemy's Core expression system makes wide use of
+ :func:`.bindparam` in an implicit sense. It is typical that Python
+ literal values passed to virtually all SQL expression functions are
+ coerced into fixed :func:`.bindparam` constructs. For example, given
+ a comparison operation such as::
expr = users_table.c.name == 'Wendy'
The above expression will produce a :class:`.BinaryExpression`
construct, where the left side is the :class:`.Column` object
- representing the ``name`` column, and the right side is a :class:`.BindParameter`
- representing the literal value::
+ representing the ``name`` column, and the right side is a
+ :class:`.BindParameter` representing the literal value::
print(repr(expr.right))
BindParameter('%(4327771088 name)s', 'Wendy', type_=String())
@@ -921,8 +924,8 @@ class BindParameter(ColumnElement):
Similarly, :func:`.bindparam` is invoked automatically
when working with :term:`CRUD` statements as far as the "VALUES"
portion is concerned. The :func:`.insert` construct produces an
- ``INSERT`` expression which will, at statement execution time, generate
- bound placeholders based on the arguments passed, as in::
+ ``INSERT`` expression which will, at statement execution time,
+ generate bound placeholders based on the arguments passed, as in::
stmt = users_table.insert()
result = connection.execute(stmt, name='Wendy')
@@ -989,8 +992,8 @@ class BindParameter(ColumnElement):
If ``True``, a value is required at execution time. If not passed,
it defaults to ``True`` if neither :paramref:`.bindparam.value`
or :paramref:`.bindparam.callable` were passed. If either of these
- parameters are present, then :paramref:`.bindparam.required` defaults
- to ``False``.
+ parameters are present, then :paramref:`.bindparam.required`
+ defaults to ``False``.
.. versionchanged:: 0.8 If the ``required`` flag is not specified,
it will be set automatically to ``True`` or ``False`` depending
@@ -1030,10 +1033,10 @@ class BindParameter(ColumnElement):
if unique:
self.key = _anonymous_label('%%(%d %s)s' % (id(self), key
- or 'param'))
+ or 'param'))
else:
self.key = key or _anonymous_label('%%(%d param)s'
- % id(self))
+ % id(self))
# identifying key that won't change across
# clones, used to identify the bind's logical
@@ -1056,21 +1059,23 @@ class BindParameter(ColumnElement):
_compared_to_operator, value)
else:
self.type = type_api._type_map.get(type(value),
- type_api.NULLTYPE)
+ type_api.NULLTYPE)
elif isinstance(type_, type):
self.type = type_()
else:
self.type = type_
def _with_value(self, value):
- """Return a copy of this :class:`.BindParameter` with the given value set."""
+ """Return a copy of this :class:`.BindParameter` with the given value
+ set.
+ """
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)
+ type_api.NULLTYPE)
return cloned
@property
@@ -1092,14 +1097,14 @@ class BindParameter(ColumnElement):
c = ClauseElement._clone(self)
if self.unique:
c.key = _anonymous_label('%%(%d %s)s' % (id(c), c._orig_key
- or 'param'))
+ or 'param'))
return c
def _convert_to_unique(self):
if not self.unique:
self.unique = True
- self.key = _anonymous_label('%%(%d %s)s' % (id(self),
- self._orig_key or 'param'))
+ self.key = _anonymous_label(
+ '%%(%d %s)s' % (id(self), self._orig_key or 'param'))
def compare(self, other, **kw):
"""Compare this :class:`BindParameter` to the given
@@ -1122,7 +1127,7 @@ class BindParameter(ColumnElement):
def __repr__(self):
return 'BindParameter(%r, %r, type_=%r)' % (self.key,
- self.value, self.type)
+ self.value, self.type)
class TypeClause(ClauseElement):
@@ -1176,9 +1181,9 @@ class TextClause(Executable, ClauseElement):
_hide_froms = []
def __init__(
- self,
- text,
- bind=None):
+ self,
+ text,
+ bind=None):
self._bind = bind
self._bindparams = {}
@@ -1192,7 +1197,7 @@ class TextClause(Executable, ClauseElement):
@classmethod
def _create_text(self, text, bind=None, bindparams=None,
- typemap=None, autocommit=None):
+ typemap=None, autocommit=None):
"""Construct a new :class:`.TextClause` clause, representing
a textual SQL string directly.
@@ -1226,10 +1231,10 @@ class TextClause(Executable, ClauseElement):
The :class:`.TextClause` construct includes methods which can
provide information about the bound parameters as well as the column
values which would be returned from the textual statement, assuming
- it's an executable SELECT type of statement. The :meth:`.TextClause.bindparams`
- method is used to provide bound parameter detail, and
- :meth:`.TextClause.columns` method allows specification of
- return columns including names and types::
+ it's an executable SELECT type of statement. The
+ :meth:`.TextClause.bindparams` method is used to provide bound
+ parameter detail, and :meth:`.TextClause.columns` method allows
+ specification of return columns including names and types::
t = text("SELECT * FROM users WHERE id=:user_id").\\
bindparams(user_id=7).\\
@@ -1252,8 +1257,8 @@ class TextClause(Executable, ClauseElement):
to it as an :class:`.Executable` object, and it supports
the :meth:`Executable.execution_options` method. For example,
a :func:`.text` construct that should be subject to "autocommit"
- can be set explicitly so using the :paramref:`.Connection.execution_options.autocommit`
- option::
+ can be set explicitly so using the
+ :paramref:`.Connection.execution_options.autocommit` option::
t = text("EXEC my_procedural_thing()").\\
execution_options(autocommit=True)
@@ -1298,9 +1303,10 @@ class TextClause(Executable, ClauseElement):
represented in the columns clause of a ``SELECT`` statement
to type objects,
which will be used to perform post-processing on columns within
- the result set. This parameter now invokes the :meth:`.TextClause.columns`
- method, which returns a :class:`.TextAsFrom` construct that gains
- a ``.c`` collection and can be embedded in other expressions. E.g.::
+ the result set. This parameter now invokes the
+ :meth:`.TextClause.columns` method, which returns a
+ :class:`.TextAsFrom` construct that gains a ``.c`` collection and
+ can be embedded in other expressions. E.g.::
stmt = text("SELECT * FROM table",
typemap={'id': Integer, 'name': String},
@@ -1308,7 +1314,8 @@ class TextClause(Executable, ClauseElement):
Is equivalent to::
- stmt = text("SELECT * FROM table").columns(id=Integer, name=String)
+ stmt = text("SELECT * FROM table").columns(id=Integer,
+ name=String)
Or alternatively::
@@ -1361,8 +1368,8 @@ class TextClause(Executable, ClauseElement):
When specific typing behavior is needed, the positional ``*binds``
argument can be used in which to specify :func:`.bindparam` constructs
- directly. These constructs must include at least the ``key`` argument,
- then an optional value and type::
+ directly. These constructs must include at least the ``key``
+ argument, then an optional value and type::
from sqlalchemy import bindparam
stmt = stmt.bindparams(
@@ -1370,9 +1377,10 @@ class TextClause(Executable, ClauseElement):
bindparam('timestamp', type_=DateTime)
)
- Above, we specified the type of :class:`.DateTime` for the ``timestamp``
- bind, and the type of :class:`.String` for the ``name`` bind. In
- the case of ``name`` we also set the default value of ``"jack"``.
+ Above, we specified the type of :class:`.DateTime` for the
+ ``timestamp`` bind, and the type of :class:`.String` for the ``name``
+ bind. In the case of ``name`` we also set the default value of
+ ``"jack"``.
Additional bound parameters can be supplied at statement execution
time, e.g.::
@@ -1380,26 +1388,27 @@ class TextClause(Executable, ClauseElement):
result = connection.execute(stmt,
timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5))
- The :meth:`.TextClause.bindparams` method can be called repeatedly, where
- it will re-use existing :class:`.BindParameter` objects to add new information.
- For example, we can call :meth:`.TextClause.bindparams` first with
- typing information, and a second time with value information, and it
- will be combined::
+ The :meth:`.TextClause.bindparams` method can be called repeatedly,
+ where it will re-use existing :class:`.BindParameter` objects to add
+ new information. For example, we can call
+ :meth:`.TextClause.bindparams` first with typing information, and a
+ second time with value information, and it will be combined::
stmt = text("SELECT id, name FROM user WHERE name=:name "
"AND timestamp=:timestamp")
stmt = stmt.bindparams(
- bindparam('name', type_=String),
- bindparam('timestamp', type_=DateTime)
- )
+ bindparam('name', type_=String),
+ bindparam('timestamp', type_=DateTime)
+ )
stmt = stmt.bindparams(
- name='jack',
- timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5)
- )
+ name='jack',
+ timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5)
+ )
- .. versionadded:: 0.9.0 The :meth:`.TextClause.bindparams` method supersedes
- the argument ``bindparams`` passed to :func:`~.expression.text`.
+ .. versionadded:: 0.9.0 The :meth:`.TextClause.bindparams` method
+ supersedes the argument ``bindparams`` passed to
+ :func:`~.expression.text`.
"""
@@ -1410,8 +1419,8 @@ class TextClause(Executable, ClauseElement):
existing = new_params[bind.key]
except KeyError:
raise exc.ArgumentError(
- "This text() construct doesn't define a "
- "bound parameter named %r" % bind.key)
+ "This text() construct doesn't define a "
+ "bound parameter named %r" % bind.key)
else:
new_params[existing.key] = bind
@@ -1420,13 +1429,11 @@ class TextClause(Executable, ClauseElement):
existing = new_params[key]
except KeyError:
raise exc.ArgumentError(
- "This text() construct doesn't define a "
- "bound parameter named %r" % key)
+ "This text() construct doesn't define a "
+ "bound parameter named %r" % key)
else:
new_params[key] = existing._with_value(value)
-
-
@util.dependencies('sqlalchemy.sql.selectable')
def columns(self, selectable, *cols, **types):
"""Turn this :class:`.TextClause` object into a :class:`.TextAsFrom`
@@ -1447,8 +1454,8 @@ class TextClause(Executable, ClauseElement):
).where(stmt.c.id > 5)
Above, we used untyped :func:`.column` elements. These can also have
- types specified, which will impact how the column behaves in expressions
- as well as determining result set behavior::
+ types specified, which will impact how the column behaves in
+ expressions as well as determining result set behavior::
stmt = text("SELECT id, name, timestamp FROM some_table")
stmt = stmt.columns(
@@ -1460,8 +1467,9 @@ class TextClause(Executable, ClauseElement):
for id, name, timestamp in connection.execute(stmt):
print(id, name, timestamp)
- Keyword arguments allow just the names and types of columns to be specified,
- where the :func:`.column` elements will be generated automatically::
+ Keyword arguments allow just the names and types of columns to be
+ specified, where the :func:`.column` elements will be generated
+ automatically::
stmt = text("SELECT id, name, timestamp FROM some_table")
stmt = stmt.columns(
@@ -1474,24 +1482,24 @@ class TextClause(Executable, ClauseElement):
print(id, name, timestamp)
The :meth:`.TextClause.columns` method provides a direct
- route to calling :meth:`.FromClause.alias` as well as :meth:`.SelectBase.cte`
- against a textual SELECT statement::
+ route to calling :meth:`.FromClause.alias` as well as
+ :meth:`.SelectBase.cte` against a textual SELECT statement::
stmt = stmt.columns(id=Integer, name=String).cte('st')
stmt = select([sometable]).where(sometable.c.id == stmt.c.id)
- .. versionadded:: 0.9.0 :func:`.text` can now be converted into a fully
- featured "selectable" construct using the :meth:`.TextClause.columns`
- method. This method supersedes the ``typemap`` argument to
- :func:`.text`.
+ .. versionadded:: 0.9.0 :func:`.text` can now be converted into a
+ fully featured "selectable" construct using the
+ :meth:`.TextClause.columns` method. This method supersedes the
+ ``typemap`` argument to :func:`.text`.
"""
input_cols = [
ColumnClause(col.key, types.pop(col.key))
- if col.key in types
- else col
+ 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)
@@ -1512,7 +1520,7 @@ class TextClause(Executable, ClauseElement):
def _copy_internals(self, clone=_clone, **kw):
self._bindparams = dict((b.key, clone(b, **kw))
- for b in self._bindparams.values())
+ for b in self._bindparams.values())
def get_children(self, **kwargs):
return list(self._bindparams.values())
@@ -1520,6 +1528,7 @@ class TextClause(Executable, ClauseElement):
def compare(self, other):
return isinstance(other, TextClause) and other.text == self.text
+
class Null(ColumnElement):
"""Represent the NULL keyword in a SQL statement.
@@ -1602,6 +1611,7 @@ class False_(ColumnElement):
def compare(self, other):
return isinstance(other, False_)
+
class True_(ColumnElement):
"""Represent the ``true`` keyword, or equivalent, in a SQL statement.
@@ -1671,6 +1681,7 @@ NULL = Null()
FALSE = False_()
TRUE = True_()
+
class ClauseList(ClauseElement):
"""Describe a list of clauses, separated by an operator.
@@ -1704,7 +1715,7 @@ class ClauseList(ClauseElement):
def append(self, clause):
if self.group_contents:
- self.clauses.append(_literal_as_text(clause).\
+ self.clauses.append(_literal_as_text(clause).
self_group(against=self.operator))
else:
self.clauses.append(_literal_as_text(clause))
@@ -1743,13 +1754,12 @@ class ClauseList(ClauseElement):
return False
-
class BooleanClauseList(ClauseList, ColumnElement):
__visit_name__ = 'clauselist'
def __init__(self, *arg, **kw):
raise NotImplementedError(
- "BooleanClauseList has a private constructor")
+ "BooleanClauseList has a private constructor")
@classmethod
def _construct(cls, operator, continue_on, skip_on, *clauses, **kw):
@@ -1772,7 +1782,7 @@ class BooleanClauseList(ClauseList, ColumnElement):
return clauses[0].self_group(against=operators._asbool)
convert_clauses = [c.self_group(against=operator)
- for c in convert_clauses]
+ for c in convert_clauses]
self = cls.__new__(cls)
self.clauses = convert_clauses
@@ -1872,6 +1882,7 @@ class BooleanClauseList(ClauseList, ColumnElement):
and_ = BooleanClauseList.and_
or_ = BooleanClauseList.or_
+
class Tuple(ClauseList, ColumnElement):
"""Represent a SQL tuple."""
@@ -1899,7 +1910,7 @@ class Tuple(ClauseList, ColumnElement):
clauses = [_literal_as_binds(c) for c in clauses]
self._type_tuple = [arg.type for arg in clauses]
self.type = kw.pop('type_', self._type_tuple[0]
- if self._type_tuple else type_api.NULLTYPE)
+ if self._type_tuple else type_api.NULLTYPE)
super(Tuple, self).__init__(*clauses, **kw)
@@ -1910,7 +1921,7 @@ class Tuple(ClauseList, ColumnElement):
def _bind_param(self, operator, obj):
return Tuple(*[
BindParameter(None, o, _compared_to_operator=operator,
- _compared_to_type=type_, unique=True)
+ _compared_to_type=type_, unique=True)
for o, type_ in zip(obj, self._type_tuple)
]).self_group()
@@ -1981,9 +1992,9 @@ class Case(ColumnElement):
used via the
:paramref:`.case.value` parameter, which is passed a column
expression to be compared. In this form, the :paramref:`.case.whens`
- parameter is passed as a dictionary containing expressions to be compared
- against keyed to result expressions. The statement below is equivalent
- to the preceding statement::
+ parameter is passed as a dictionary containing expressions to be
+ compared against keyed to result expressions. The statement below is
+ equivalent to the preceding statement::
stmt = select([users_table]).\\
where(
@@ -2028,23 +2039,24 @@ class Case(ColumnElement):
ELSE 'lessthan10'
END
- :param whens: The criteria to be compared against, :paramref:`.case.whens`
- accepts two different forms, based on whether or not :paramref:`.case.value`
- is used.
+ :param whens: The criteria to be compared against,
+ :paramref:`.case.whens` accepts two different forms, based on
+ whether or not :paramref:`.case.value` is used.
- In the first form, it accepts a list of 2-tuples; each 2-tuple consists
- of ``(<sql expression>, <value>)``, where the SQL expression is a
- boolean expression and "value" is a resulting value, e.g.::
+ In the first form, it accepts a list of 2-tuples; each 2-tuple
+ consists of ``(<sql expression>, <value>)``, where the SQL
+ expression is a boolean expression and "value" is a resulting value,
+ e.g.::
case([
(users_table.c.name == 'wendy', 'W'),
(users_table.c.name == 'jack', 'J')
])
- In the second form, it accepts a Python dictionary of comparison values
- mapped to a resulting value; this form requires :paramref:`.case.value`
- to be present, and values will be compared using the ``==`` operator,
- e.g.::
+ In the second form, it accepts a Python dictionary of comparison
+ values mapped to a resulting value; this form requires
+ :paramref:`.case.value` to be present, and values will be compared
+ using the ``==`` operator, e.g.::
case(
{"wendy": "W", "jack": "J"},
@@ -2072,12 +2084,12 @@ class Case(ColumnElement):
if value is not None:
whenlist = [
(_literal_as_binds(c).self_group(),
- _literal_as_binds(r)) for (c, r) in whens
+ _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
+ _literal_as_binds(r)) for (c, r) in whens
]
if whenlist:
@@ -2101,7 +2113,7 @@ class Case(ColumnElement):
if self.value is not None:
self.value = clone(self.value, **kw)
self.whens = [(clone(x, **kw), clone(y, **kw))
- for x, y in self.whens]
+ for x, y in self.whens]
if self.else_ is not None:
self.else_ = clone(self.else_, **kw)
@@ -2117,7 +2129,7 @@ class Case(ColumnElement):
@property
def _from_objects(self):
return list(itertools.chain(*[x._from_objects for x in
- self.get_children()]))
+ self.get_children()]))
def literal_column(text, type_=None):
@@ -2144,7 +2156,6 @@ def literal_column(text, type_=None):
return ColumnClause(text, type_=type_, is_literal=True)
-
class Cast(ColumnElement):
"""Represent a ``CAST`` expression.
@@ -2276,10 +2287,11 @@ class UnaryExpression(ColumnElement):
__visit_name__ = 'unary'
def __init__(self, element, operator=None, modifier=None,
- type_=None, negate=None):
+ type_=None, negate=None):
self.operator = operator
self.modifier = modifier
- self.element = element.self_group(against=self.operator or self.modifier)
+ self.element = element.self_group(
+ against=self.operator or self.modifier)
self.type = type_api.to_instance(type_)
self.negate = negate
@@ -2302,11 +2314,13 @@ class UnaryExpression(ColumnElement):
SELECT id, name FROM user ORDER BY name DESC NULLS FIRST
Like :func:`.asc` and :func:`.desc`, :func:`.nullsfirst` is typically
- invoked from the column expression itself using :meth:`.ColumnElement.nullsfirst`,
- rather than as its standalone function version, as in::
+ invoked from the column expression itself using
+ :meth:`.ColumnElement.nullsfirst`, rather than as its standalone
+ function version, as in::
- stmt = select([users_table]).\\
- order_by(users_table.c.name.desc().nullsfirst())
+ stmt = (select([users_table]).
+ order_by(users_table.c.name.desc().nullsfirst())
+ )
.. seealso::
@@ -2320,8 +2334,7 @@ class UnaryExpression(ColumnElement):
"""
return UnaryExpression(
- _literal_as_text(column), modifier=operators.nullsfirst_op)
-
+ _literal_as_text(column), modifier=operators.nullsfirst_op)
@classmethod
def _create_nullslast(cls, column):
@@ -2342,8 +2355,9 @@ class UnaryExpression(ColumnElement):
SELECT id, name FROM user ORDER BY name DESC NULLS LAST
Like :func:`.asc` and :func:`.desc`, :func:`.nullslast` is typically
- invoked from the column expression itself using :meth:`.ColumnElement.nullslast`,
- rather than as its standalone function version, as in::
+ invoked from the column expression itself using
+ :meth:`.ColumnElement.nullslast`, rather than as its standalone
+ function version, as in::
stmt = select([users_table]).\\
order_by(users_table.c.name.desc().nullslast())
@@ -2362,7 +2376,6 @@ class UnaryExpression(ColumnElement):
return UnaryExpression(
_literal_as_text(column), modifier=operators.nullslast_op)
-
@classmethod
def _create_desc(cls, column):
"""Produce a descending ``ORDER BY`` clause element.
@@ -2475,8 +2488,8 @@ class UnaryExpression(ColumnElement):
"""
expr = _literal_as_binds(expr)
- return UnaryExpression(expr,
- operator=operators.distinct_op, type_=expr.type)
+ return UnaryExpression(
+ expr, operator=operators.distinct_op, type_=expr.type)
@util.memoized_property
def _order_by_label_element(self):
@@ -2557,7 +2570,7 @@ class BinaryExpression(ColumnElement):
__visit_name__ = 'binary'
def __init__(self, left, right, operator, type_=None,
- negate=None, modifiers=None):
+ negate=None, modifiers=None):
# allow compatibility with libraries that
# refer to BinaryExpression directly and pass strings
if isinstance(operator, util.string_types):
@@ -2634,8 +2647,6 @@ class BinaryExpression(ColumnElement):
return super(BinaryExpression, self)._negate()
-
-
class Grouping(ColumnElement):
"""Represent a grouping within a column expression"""
@@ -2747,7 +2758,7 @@ class Over(ColumnElement):
return list(itertools.chain(
*[c._from_objects for c in
(self.func, self.partition_by, self.order_by)
- if c is not None]
+ if c is not None]
))
@@ -2781,8 +2792,9 @@ class Label(ColumnElement):
if name:
self.name = name
else:
- self.name = _anonymous_label('%%(%d %s)s' % (id(self),
- getattr(element, 'name', 'anon')))
+ self.name = _anonymous_label(
+ '%%(%d %s)s' % (id(self), getattr(element, 'name', 'anon'))
+ )
self.key = self._label = self._key_label = self.name
self._element = element
self._type = type_
@@ -2798,8 +2810,8 @@ class Label(ColumnElement):
@util.memoized_property
def type(self):
return type_api.to_instance(
- self._type or getattr(self._element, 'type', None)
- )
+ self._type or getattr(self._element, 'type', None)
+ )
@util.memoized_property
def element(self):
@@ -2809,8 +2821,8 @@ class Label(ColumnElement):
sub_element = self._element.self_group(against=against)
if sub_element is not self._element:
return Label(self.name,
- sub_element,
- type_=self._type)
+ sub_element,
+ type_=self._type)
else:
return self
@@ -2834,7 +2846,7 @@ class Label(ColumnElement):
def _make_proxy(self, selectable, name=None, **kw):
e = self.element._make_proxy(selectable,
- name=name if name else self.name)
+ name=name if name else self.name)
e._proxies.append(self)
if self._type is not None:
e.type = self._type
@@ -2861,10 +2873,10 @@ class ColumnClause(Immutable, ColumnElement):
:class:`.Column` object. While the :class:`.Column` class has all the
same capabilities as :class:`.ColumnClause`, the :class:`.ColumnClause`
class is usable by itself in those cases where behavioral requirements
- are limited to simple SQL expression generation. The object has none of the
- associations with schema-level metadata or with execution-time behavior
- that :class:`.Column` does, so in that sense is a "lightweight" version
- of :class:`.Column`.
+ are limited to simple SQL expression generation. The object has none of
+ the associations with schema-level metadata or with execution-time
+ behavior that :class:`.Column` does, so in that sense is a "lightweight"
+ version of :class:`.Column`.
Full details on :class:`.ColumnClause` usage is at :func:`.column`.
@@ -2897,8 +2909,8 @@ class ColumnClause(Immutable, ColumnElement):
SELECT id, name FROM user
- Once constructed, :func:`.column` may be used like any other SQL expression
- element such as within :func:`.select` constructs::
+ Once constructed, :func:`.column` may be used like any other SQL
+ expression element such as within :func:`.select` constructs::
from sqlalchemy.sql import column
@@ -2932,8 +2944,9 @@ class ColumnClause(Immutable, ColumnElement):
A :func:`.column` / :func:`.table` construct like that illustrated
above can be created in an
- ad-hoc fashion and is not associated with any :class:`.schema.MetaData`,
- DDL, or events, unlike its :class:`.Table` counterpart.
+ ad-hoc fashion and is not associated with any
+ :class:`.schema.MetaData`, DDL, or events, unlike its
+ :class:`.Table` counterpart.
:param text: the text of the element.
@@ -2943,8 +2956,8 @@ class ColumnClause(Immutable, ColumnElement):
:param is_literal: if True, the :class:`.ColumnClause` is assumed to
be an exact expression that will be delivered to the output with no
quoting rules applied regardless of case sensitive settings. the
- :func:`.literal_column()` function essentially invokes :func:`.column`
- while passing ``is_literal=True``.
+ :func:`.literal_column()` function essentially invokes
+ :func:`.column` while passing ``is_literal=True``.
.. seealso::
@@ -2965,13 +2978,13 @@ class ColumnClause(Immutable, ColumnElement):
def _compare_name_for_result(self, other):
if self.is_literal or \
- self.table is None or self.table._textual or \
- not hasattr(other, 'proxy_set') or (
- isinstance(other, ColumnClause) and
- (other.is_literal or
- other.table is None or
- other.table._textual)
- ):
+ self.table is None or self.table._textual or \
+ not hasattr(other, 'proxy_set') or (
+ isinstance(other, ColumnClause) and
+ (other.is_literal or
+ other.table is None or
+ other.table._textual)
+ ):
return (hasattr(other, 'name') and self.name == other.name) or \
(hasattr(other, '_label') and self._label == other._label)
else:
@@ -3020,7 +3033,7 @@ class ColumnClause(Immutable, ColumnElement):
elif t is not None and t.named_with_column:
if getattr(t, 'schema', None):
label = t.schema.replace('.', '_') + "_" + \
- t.name + "_" + name
+ t.name + "_" + name
else:
label = t.name + "_" + name
@@ -3053,23 +3066,23 @@ class ColumnClause(Immutable, ColumnElement):
def _bind_param(self, operator, obj):
return BindParameter(self.name, obj,
- _compared_to_operator=operator,
- _compared_to_type=self.type,
- unique=True)
+ _compared_to_operator=operator,
+ _compared_to_type=self.type,
+ unique=True)
def _make_proxy(self, selectable, name=None, attach=True,
- name_is_truncatable=False, **kw):
+ name_is_truncatable=False, **kw):
# propagate the "is_literal" flag only if we are keeping our name,
# otherwise its considered to be a label
is_literal = self.is_literal and (name is None or name == self.name)
c = self._constructor(
- _as_truncated(name or self.name) if \
- name_is_truncatable else \
- (name or self.name),
- type_=self.type,
- _selectable=selectable,
- is_literal=is_literal
- )
+ _as_truncated(name or self.name) if
+ name_is_truncatable else
+ (name or self.name),
+ type_=self.type,
+ _selectable=selectable,
+ is_literal=is_literal
+ )
if name is None:
c.key = self.key
c._proxies = [self]
@@ -3128,11 +3141,11 @@ class quoted_name(util.text_type):
such a backend.
The :class:`.quoted_name` object is normally created automatically
- when specifying the name for key schema constructs such as :class:`.Table`,
- :class:`.Column`, and others. The class can also be passed explicitly
- as the name to any function that receives a name which can be quoted.
- Such as to use the :meth:`.Engine.has_table` method with an unconditionally
- quoted name::
+ when specifying the name for key schema constructs such as
+ :class:`.Table`, :class:`.Column`, and others. The class can also be
+ passed explicitly as the name to any function that receives a name which
+ can be quoted. Such as to use the :meth:`.Engine.has_table` method with
+ an unconditionally quoted name::
from sqlaclchemy import create_engine
from sqlalchemy.sql.elements import quoted_name
@@ -3157,8 +3170,8 @@ class quoted_name(util.text_type):
# elif not sprcls and quote is None:
# return value
elif isinstance(value, cls) and (
- quote is None or value.quote == quote
- ):
+ quote is None or value.quote == quote
+ ):
return value
self = super(quoted_name, cls).__new__(cls, value)
self.quote = quote
@@ -3187,13 +3200,14 @@ class quoted_name(util.text_type):
backslashed = backslashed.decode('ascii')
return "'%s'" % backslashed
+
class _truncated_label(quoted_name):
"""A unicode subclass used to identify symbolic "
"names that may require truncation."""
def __new__(cls, value, quote=None):
quote = getattr(value, "quote", quote)
- #return super(_truncated_label, cls).__new__(cls, value, quote, True)
+ # return super(_truncated_label, cls).__new__(cls, value, quote, True)
return super(_truncated_label, cls).__new__(cls, value, quote)
def __reduce__(self):
@@ -3281,17 +3295,17 @@ class _anonymous_label(_truncated_label):
def __add__(self, other):
return _anonymous_label(
- quoted_name(
- util.text_type.__add__(self, util.text_type(other)),
- self.quote)
- )
+ quoted_name(
+ util.text_type.__add__(self, util.text_type(other)),
+ self.quote)
+ )
def __radd__(self, other):
return _anonymous_label(
- quoted_name(
- util.text_type.__add__(util.text_type(other), self),
- self.quote)
- )
+ quoted_name(
+ util.text_type.__add__(util.text_type(other), self),
+ self.quote)
+ )
def apply_map(self, map_):
if self.quote is not None:
@@ -3353,10 +3367,11 @@ def _cloned_intersection(a, b):
return set(elem for elem in a
if all_overlap.intersection(elem._cloned_set))
+
def _cloned_difference(a, b):
all_overlap = set(_expand_cloned(a)).intersection(_expand_cloned(b))
return set(elem for elem in a
- if not all_overlap.intersection(elem._cloned_set))
+ if not all_overlap.intersection(elem._cloned_set))
def _labeled(element):
@@ -3438,7 +3453,7 @@ def _no_literals(element):
def _is_literal(element):
return not isinstance(element, Visitable) and \
- not hasattr(element, '__clause_element__')
+ not hasattr(element, '__clause_element__')
def _only_column_elements_or_none(element, name):
@@ -3453,10 +3468,11 @@ def _only_column_elements(element, name):
element = element.__clause_element__()
if not isinstance(element, ColumnElement):
raise exc.ArgumentError(
- "Column-based expression object expected for argument "
- "'%s'; got: '%s', type %s" % (name, element, type(element)))
+ "Column-based expression object expected for argument "
+ "'%s'; got: '%s', type %s" % (name, element, type(element)))
return element
+
def _literal_as_binds(element, name=None, type_=None):
if hasattr(element, '__clause_element__'):
return element.__clause_element__()
@@ -3509,18 +3525,18 @@ def _type_from_args(args):
def _corresponding_column_or_error(fromclause, column,
- require_embedded=False):
+ require_embedded=False):
c = fromclause.corresponding_column(column,
- require_embedded=require_embedded)
+ require_embedded=require_embedded)
if c is None:
raise exc.InvalidRequestError(
- "Given column '%s', attached to table '%s', "
- "failed to locate a corresponding column from table '%s'"
- %
- (column,
- getattr(column, 'table', None),
- fromclause.description)
- )
+ "Given column '%s', attached to table '%s', "
+ "failed to locate a corresponding column from table '%s'"
+ %
+ (column,
+ getattr(column, 'table', None),
+ fromclause.description)
+ )
return c
diff --git a/lib/sqlalchemy/sql/expression.py b/lib/sqlalchemy/sql/expression.py
index c2fd0907d..fd57f9be8 100644
--- a/lib/sqlalchemy/sql/expression.py
+++ b/lib/sqlalchemy/sql/expression.py
@@ -31,23 +31,23 @@ from .visitors import Visitable
from .functions import func, modifier, FunctionElement, Function
from ..util.langhelpers import public_factory
from .elements import ClauseElement, ColumnElement,\
- BindParameter, UnaryExpression, BooleanClauseList, \
- Label, Cast, Case, ColumnClause, TextClause, Over, Null, \
- True_, False_, BinaryExpression, Tuple, TypeClause, Extract, \
- Grouping, not_, \
- collate, literal_column, between,\
- literal, outparam, type_coerce, ClauseList
+ BindParameter, UnaryExpression, BooleanClauseList, \
+ Label, Cast, Case, ColumnClause, TextClause, Over, Null, \
+ True_, False_, BinaryExpression, Tuple, TypeClause, Extract, \
+ Grouping, not_, \
+ collate, literal_column, between,\
+ literal, outparam, type_coerce, ClauseList
from .elements import SavepointClause, RollbackToSavepointClause, \
- ReleaseSavepointClause
+ ReleaseSavepointClause
from .base import ColumnCollection, Generative, Executable, \
- PARSE_AUTOCOMMIT
+ PARSE_AUTOCOMMIT
from .selectable import Alias, Join, Select, Selectable, TableClause, \
- CompoundSelect, CTE, FromClause, FromGrouping, SelectBase, \
- alias, GenerativeSelect, \
- subquery, HasPrefixes, Exists, ScalarSelect, TextAsFrom
+ CompoundSelect, CTE, FromClause, FromGrouping, SelectBase, \
+ alias, GenerativeSelect, \
+ subquery, HasPrefixes, Exists, ScalarSelect, TextAsFrom
from .dml import Insert, Update, Delete, UpdateBase, ValuesBase
@@ -71,17 +71,24 @@ cast = public_factory(Cast, ".expression.cast")
extract = public_factory(Extract, ".expression.extract")
tuple_ = public_factory(Tuple, ".expression.tuple_")
except_ = public_factory(CompoundSelect._create_except, ".expression.except_")
-except_all = public_factory(CompoundSelect._create_except_all, ".expression.except_all")
-intersect = public_factory(CompoundSelect._create_intersect, ".expression.intersect")
-intersect_all = public_factory(CompoundSelect._create_intersect_all, ".expression.intersect_all")
+except_all = public_factory(
+ CompoundSelect._create_except_all, ".expression.except_all")
+intersect = public_factory(
+ CompoundSelect._create_intersect, ".expression.intersect")
+intersect_all = public_factory(
+ CompoundSelect._create_intersect_all, ".expression.intersect_all")
union = public_factory(CompoundSelect._create_union, ".expression.union")
-union_all = public_factory(CompoundSelect._create_union_all, ".expression.union_all")
+union_all = public_factory(
+ CompoundSelect._create_union_all, ".expression.union_all")
exists = public_factory(Exists, ".expression.exists")
-nullsfirst = public_factory(UnaryExpression._create_nullsfirst, ".expression.nullsfirst")
-nullslast = public_factory(UnaryExpression._create_nullslast, ".expression.nullslast")
+nullsfirst = public_factory(
+ UnaryExpression._create_nullsfirst, ".expression.nullsfirst")
+nullslast = public_factory(
+ UnaryExpression._create_nullslast, ".expression.nullslast")
asc = public_factory(UnaryExpression._create_asc, ".expression.asc")
desc = public_factory(UnaryExpression._create_desc, ".expression.desc")
-distinct = public_factory(UnaryExpression._create_distinct, ".expression.distinct")
+distinct = public_factory(
+ UnaryExpression._create_distinct, ".expression.distinct")
true = public_factory(True_._singleton, ".expression.true")
false = public_factory(False_._singleton, ".expression.false")
null = public_factory(Null._singleton, ".expression.null")
@@ -96,14 +103,13 @@ delete = public_factory(Delete, ".expression.delete")
# these might be better off in some other namespace
from .base import _from_objects
from .elements import _literal_as_text, _clause_element_as_expr,\
- _is_column, _labeled, _only_column_elements, _string_or_unprintable, \
+ _is_column, _labeled, _only_column_elements, _string_or_unprintable, \
_truncated_label, _clone, _cloned_difference, _cloned_intersection,\
_column_as_key, _literal_as_binds, _select_iterables, \
_corresponding_column_or_error
from .selectable import _interpret_as_from
-
# old names for compatibility
_Executable = Executable
_BindParamClause = BindParameter
diff --git a/lib/sqlalchemy/sql/functions.py b/lib/sqlalchemy/sql/functions.py
index a18ebf7e2..11e758364 100644
--- a/lib/sqlalchemy/sql/functions.py
+++ b/lib/sqlalchemy/sql/functions.py
@@ -11,8 +11,8 @@
from . import sqltypes, schema
from .base import Executable
from .elements import ClauseList, Cast, Extract, _literal_as_binds, \
- literal_column, _type_from_args, ColumnElement, _clone,\
- Over, BindParameter
+ literal_column, _type_from_args, ColumnElement, _clone,\
+ Over, BindParameter
from .selectable import FromClause, Select
from . import operators
@@ -58,9 +58,9 @@ class FunctionElement(Executable, ColumnElement, FromClause):
"""
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()
+ operator=operators.comma_op,
+ group_contents=True, *args).\
+ self_group()
def _execute_on_connection(self, connection, multiparams, params):
return connection._execute_function(self, multiparams, params)
@@ -160,7 +160,7 @@ class FunctionElement(Executable, ColumnElement, FromClause):
def _bind_param(self, operator, obj):
return BindParameter(None, obj, _compared_to_operator=operator,
- _compared_to_type=self.type, unique=True)
+ _compared_to_type=self.type, unique=True)
class _FunctionGenerator(object):
@@ -271,16 +271,18 @@ func = _FunctionGenerator()
.. note::
The :data:`.func` construct has only limited support for calling
- standalone "stored procedures", especially those with special parameterization
- concerns.
+ standalone "stored procedures", especially those with special
+ parameterization concerns.
See the section :ref:`stored_procedures` for details on how to use
- the DBAPI-level ``callproc()`` method for fully traditional stored procedures.
+ the DBAPI-level ``callproc()`` method for fully traditional stored
+ procedures.
"""
modifier = _FunctionGenerator(group=False)
+
class Function(FunctionElement):
"""Describe a named SQL function.
@@ -315,9 +317,10 @@ class Function(FunctionElement):
def _bind_param(self, operator, obj):
return BindParameter(self.name, obj,
- _compared_to_operator=operator,
- _compared_to_type=self.type,
- unique=True)
+ _compared_to_operator=operator,
+ _compared_to_type=self.type,
+ unique=True)
+
class _GenericMeta(VisitableType):
def __init__(cls, clsname, bases, clsdict):
@@ -413,8 +416,8 @@ class GenericFunction(util.with_metaclass(_GenericMeta, Function)):
self.packagenames = []
self._bind = kwargs.get('bind', None)
self.clause_expr = ClauseList(
- operator=operators.comma_op,
- group_contents=True, *parsed_args).self_group()
+ operator=operators.comma_op,
+ group_contents=True, *parsed_args).self_group()
self.type = sqltypes.to_instance(
kwargs.pop("type_", None) or getattr(self, 'type', None))
@@ -436,7 +439,7 @@ class next_value(GenericFunction):
def __init__(self, seq, **kw):
assert isinstance(seq, schema.Sequence), \
- "next_value() accepts a Sequence object as input."
+ "next_value() accepts a Sequence object as input."
self._bind = kw.get('bind', None)
self.sequence = seq
diff --git a/lib/sqlalchemy/sql/naming.py b/lib/sqlalchemy/sql/naming.py
index 053db3e34..9e57418b0 100644
--- a/lib/sqlalchemy/sql/naming.py
+++ b/lib/sqlalchemy/sql/naming.py
@@ -11,7 +11,7 @@
"""
from .schema import Constraint, ForeignKeyConstraint, PrimaryKeyConstraint, \
- UniqueConstraint, CheckConstraint, Index, Table, Column
+ UniqueConstraint, CheckConstraint, Index, Table, Column
from .. import event, events
from .. import exc
from .elements import _truncated_label, _defer_name, _defer_none_name, conv
@@ -19,6 +19,7 @@ import re
class ConventionDict(object):
+
def __init__(self, const, table, convention):
self.const = const
self._is_fk = isinstance(const, ForeignKeyConstraint)
@@ -94,6 +95,7 @@ _prefix_dict = {
ForeignKeyConstraint: "fk"
}
+
def _get_convention(dict_, key):
for super_ in key.__mro__:
@@ -104,6 +106,7 @@ def _get_convention(dict_, key):
else:
return None
+
def _constraint_name_for_table(const, table):
metadata = table.metadata
convention = _get_convention(metadata.naming_convention, type(const))
@@ -111,16 +114,17 @@ def _constraint_name_for_table(const, table):
if isinstance(const.name, conv):
return const.name
elif convention is not None and (
- const.name is None or not isinstance(const.name, conv) and
- "constraint_name" in convention
- ):
+ const.name is None or not isinstance(const.name, conv) and
+ "constraint_name" in convention
+ ):
return conv(
- convention % ConventionDict(const, table,
- metadata.naming_convention)
- )
+ convention % ConventionDict(const, table,
+ metadata.naming_convention)
+ )
elif isinstance(convention, _defer_none_name):
return None
+
@event.listens_for(Constraint, "after_parent_attach")
@event.listens_for(Index, "after_parent_attach")
def _constraint_name(const, table):
@@ -129,8 +133,8 @@ def _constraint_name(const, table):
# to link the column attached to the table as this constraint
# associated with the table.
event.listen(table, "after_parent_attach",
- lambda col, table: _constraint_name(const, table)
- )
+ lambda col, table: _constraint_name(const, table)
+ )
elif isinstance(table, Table):
if isinstance(const.name, (conv, _defer_name)):
return
diff --git a/lib/sqlalchemy/sql/operators.py b/lib/sqlalchemy/sql/operators.py
index 50293d239..945356328 100644
--- a/lib/sqlalchemy/sql/operators.py
+++ b/lib/sqlalchemy/sql/operators.py
@@ -16,7 +16,7 @@ from .. import util
from operator import (
and_, or_, inv, add, mul, sub, mod, truediv, lt, le, ne, gt, ge, eq, neg,
getitem, lshift, rshift
- )
+)
if util.py2k:
from operator import div
@@ -24,11 +24,11 @@ else:
div = truediv
-
class Operators(object):
"""Base of comparison and logical operators.
- Implements base methods :meth:`~sqlalchemy.sql.operators.Operators.operate` and
+ Implements base methods
+ :meth:`~sqlalchemy.sql.operators.Operators.operate` and
:meth:`~sqlalchemy.sql.operators.Operators.reverse_operate`, as well as
:meth:`~sqlalchemy.sql.operators.Operators.__and__`,
:meth:`~sqlalchemy.sql.operators.Operators.__or__`,
@@ -38,6 +38,7 @@ class Operators(object):
:class:`.ColumnOperators`.
"""
+
def __and__(self, other):
"""Implement the ``&`` operator.
@@ -136,13 +137,13 @@ class Operators(object):
.. versionadded:: 0.8 - added the 'precedence' argument.
:param is_comparison: if True, the operator will be considered as a
- "comparison" operator, that is which evaulates to a boolean true/false
- value, like ``==``, ``>``, etc. This flag should be set so that
- ORM relationships can establish that the operator is a comparison
- operator when used in a custom join condition.
+ "comparison" operator, that is which evaulates to a boolean
+ true/false value, like ``==``, ``>``, etc. This flag should be set
+ so that ORM relationships can establish that the operator is a
+ comparison operator when used in a custom join condition.
- .. versionadded:: 0.9.2 - added the :paramref:`.Operators.op.is_comparison`
- flag.
+ .. versionadded:: 0.9.2 - added the
+ :paramref:`.Operators.op.is_comparison` flag.
.. seealso::
@@ -422,8 +423,8 @@ class ColumnOperators(Operators):
def notin_(self, other):
"""implement the ``NOT IN`` operator.
- This is equivalent to using negation with :meth:`.ColumnOperators.in_`,
- i.e. ``~x.in_(y)``.
+ This is equivalent to using negation with
+ :meth:`.ColumnOperators.in_`, i.e. ``~x.in_(y)``.
.. versionadded:: 0.8
@@ -681,9 +682,11 @@ def exists():
def istrue(a):
raise NotImplementedError()
+
def isfalse(a):
raise NotImplementedError()
+
def is_(a, b):
return a.is_(b)
@@ -719,6 +722,7 @@ def notilike_op(a, b, escape=None):
def between_op(a, b, c, symmetric=False):
return a.between(b, c, symmetric=symmetric)
+
def notbetween_op(a, b, c, symmetric=False):
return a.notbetween(b, c, symmetric=symmetric)
@@ -803,7 +807,7 @@ def is_commutative(op):
def is_ordering_modifier(op):
return op in (asc_op, desc_op,
- nullsfirst_op, nullslast_op)
+ nullsfirst_op, nullslast_op)
_associative = _commutative.union([concat_op, and_, or_])
@@ -875,6 +879,6 @@ def is_precedent(operator, against):
return False
else:
return (_PRECEDENCE.get(operator,
- getattr(operator, 'precedence', _smallest)) <=
- _PRECEDENCE.get(against,
- getattr(against, 'precedence', _largest)))
+ getattr(operator, 'precedence', _smallest)) <=
+ _PRECEDENCE.get(against,
+ getattr(against, 'precedence', _largest)))
diff --git a/lib/sqlalchemy/sql/schema.py b/lib/sqlalchemy/sql/schema.py
index 3e8b72ec5..f3af46c40 100644
--- a/lib/sqlalchemy/sql/schema.py
+++ b/lib/sqlalchemy/sql/schema.py
@@ -37,8 +37,8 @@ from . import visitors
from . import type_api
from .base import _bind_or_error, ColumnCollection
from .elements import ClauseElement, ColumnClause, _truncated_label, \
- _as_truncated, TextClause, _literal_as_text,\
- ColumnElement, _find_columns, quoted_name
+ _as_truncated, TextClause, _literal_as_text,\
+ ColumnElement, _find_columns, quoted_name
from .selectable import TableClause
import collections
import sqlalchemy
@@ -55,7 +55,6 @@ def _get_table_key(name, schema):
return schema + "." + name
-
@inspection._self_inspects
class SchemaItem(SchemaEventTarget, visitors.Visitable):
"""Base class for items that define a database schema."""
@@ -189,7 +188,8 @@ class Table(DialectKWArgs, SchemaItem, TableClause):
If ``extend_existing`` or ``keep_existing`` are not set, an error is
raised if additional table modifiers are specified when
- the given :class:`.Table` is already present in the :class:`.MetaData`.
+ the given :class:`.Table` is already present in the
+ :class:`.MetaData`.
.. versionchanged:: 0.7.4
``extend_existing`` will work in conjunction
@@ -241,7 +241,8 @@ class Table(DialectKWArgs, SchemaItem, TableClause):
If extend_existing or keep_existing are not set, an error is
raised if additional table modifiers are specified when
- the given :class:`.Table` is already present in the :class:`.MetaData`.
+ the given :class:`.Table` is already present in the
+ :class:`.MetaData`.
:param listeners: A list of tuples of the form ``(<eventname>, <fn>)``
which will be passed to :func:`.event.listen` upon construction.
@@ -287,8 +288,8 @@ class Table(DialectKWArgs, SchemaItem, TableClause):
``name`` parameter, in that quoting is applied for reserved words or
case-sensitive names; to enable unconditional quoting for the
schema name, specify the flag
- ``quote_schema=True`` to the constructor, or use the :class:`.quoted_name`
- construct to specify the name.
+ ``quote_schema=True`` to the constructor, or use the
+ :class:`.quoted_name` construct to specify the name.
:param useexisting: Deprecated. Use extend_existing.
@@ -357,7 +358,6 @@ class Table(DialectKWArgs, SchemaItem, TableClause):
metadata._remove_table(name, schema)
raise
-
@property
@util.deprecated('0.9', 'Use ``table.schema.quote``')
def quote_schema(self):
@@ -379,7 +379,8 @@ class Table(DialectKWArgs, SchemaItem, TableClause):
# calling the superclass constructor.
def _init(self, name, metadata, *args, **kwargs):
- super(Table, self).__init__(quoted_name(name, kwargs.pop('quote', None)))
+ super(Table, self).__init__(
+ quoted_name(name, kwargs.pop('quote', None)))
self.metadata = metadata
self.schema = kwargs.pop('schema', None)
@@ -438,16 +439,17 @@ class Table(DialectKWArgs, SchemaItem, TableClause):
self, include_columns, exclude_columns
)
else:
- bind = _bind_or_error(metadata,
- msg="No engine is bound to this Table's MetaData. "
- "Pass an engine to the Table via "
- "autoload_with=<someengine>, "
- "or associate the MetaData with an engine via "
- "metadata.bind=<someengine>")
+ bind = _bind_or_error(
+ metadata,
+ msg="No engine is bound to this Table's MetaData. "
+ "Pass an engine to the Table via "
+ "autoload_with=<someengine>, "
+ "or associate the MetaData with an engine via "
+ "metadata.bind=<someengine>")
bind.run_callable(
- bind.dialect.reflecttable,
- self, include_columns, exclude_columns
- )
+ bind.dialect.reflecttable,
+ self, include_columns, exclude_columns
+ )
@property
def _sorted_constraints(self):
@@ -488,7 +490,8 @@ class Table(DialectKWArgs, SchemaItem, TableClause):
else:
exclude_columns = ()
self._autoload(
- self.metadata, autoload_with, include_columns, exclude_columns)
+ self.metadata, autoload_with,
+ include_columns, exclude_columns)
self._extra_kwargs(**kwargs)
self._init_items(*args)
@@ -502,12 +505,14 @@ class Table(DialectKWArgs, SchemaItem, TableClause):
@util.memoized_property
def _autoincrement_column(self):
for col in self.primary_key:
- if col.autoincrement and \
- col.type._type_affinity is not None and \
- issubclass(col.type._type_affinity, type_api.INTEGERTYPE._type_affinity) and \
- (not col.foreign_keys or col.autoincrement == 'ignore_fk') and \
- isinstance(col.default, (type(None), Sequence)) and \
- (col.server_default is None or col.server_default.reflected):
+ if (col.autoincrement and col.type._type_affinity is not None and
+ issubclass(col.type._type_affinity,
+ type_api.INTEGERTYPE._type_affinity) and
+ (not col.foreign_keys or
+ col.autoincrement == 'ignore_fk') and
+ isinstance(col.default, (type(None), Sequence)) and
+ (col.server_default is None or
+ col.server_default.reflected)):
return col
@property
@@ -516,8 +521,9 @@ class Table(DialectKWArgs, SchemaItem, TableClause):
This value is used as the dictionary key within the
:attr:`.MetaData.tables` collection. It is typically the same
- as that of :attr:`.Table.name` for a table with no :attr:`.Table.schema`
- set; otherwise it is typically of the form ``schemaname.tablename``.
+ as that of :attr:`.Table.name` for a table with no
+ :attr:`.Table.schema` set; otherwise it is typically of the form
+ ``schemaname.tablename``.
"""
return _get_table_key(self.name, self.schema)
@@ -612,7 +618,7 @@ class Table(DialectKWArgs, SchemaItem, TableClause):
self.metadata = metadata
def get_children(self, column_collections=True,
- schema_visitor=False, **kw):
+ schema_visitor=False, **kw):
if not schema_visitor:
return TableClause.get_children(
self, column_collections=column_collections, **kw)
@@ -629,7 +635,7 @@ class Table(DialectKWArgs, SchemaItem, TableClause):
bind = _bind_or_error(self)
return bind.run_callable(bind.dialect.has_table,
- self.name, schema=self.schema)
+ self.name, schema=self.schema)
def create(self, bind=None, checkfirst=False):
"""Issue a ``CREATE`` statement for this
@@ -645,8 +651,8 @@ class Table(DialectKWArgs, SchemaItem, TableClause):
if bind is None:
bind = _bind_or_error(self)
bind._run_visitor(ddl.SchemaGenerator,
- self,
- checkfirst=checkfirst)
+ self,
+ checkfirst=checkfirst)
def drop(self, bind=None, checkfirst=False):
"""Issue a ``DROP`` statement for this
@@ -661,10 +667,11 @@ class Table(DialectKWArgs, SchemaItem, TableClause):
if bind is None:
bind = _bind_or_error(self)
bind._run_visitor(ddl.SchemaDropper,
- self,
- checkfirst=checkfirst)
+ self,
+ checkfirst=checkfirst)
- def tometadata(self, metadata, schema=RETAIN_SCHEMA, referred_schema_fn=None):
+ def tometadata(self, metadata, schema=RETAIN_SCHEMA,
+ referred_schema_fn=None):
"""Return a copy of this :class:`.Table` associated with a different
:class:`.MetaData`.
@@ -703,9 +710,10 @@ class Table(DialectKWArgs, SchemaItem, TableClause):
in order to provide for the schema name that should be assigned
to the referenced table of a :class:`.ForeignKeyConstraint`.
The callable accepts this parent :class:`.Table`, the
- target schema that we are changing to, the :class:`.ForeignKeyConstraint`
- object, and the existing "target schema" of that constraint. The
- function should return the string schema name that should be applied.
+ target schema that we are changing to, the
+ :class:`.ForeignKeyConstraint` object, and the existing
+ "target schema" of that constraint. The function should return the
+ string schema name that should be applied.
E.g.::
def referred_schema_fn(table, to_schema,
@@ -738,18 +746,22 @@ class Table(DialectKWArgs, SchemaItem, TableClause):
table = Table(
self.name, metadata, schema=schema,
*args, **self.kwargs
- )
+ )
for c in self.constraints:
if isinstance(c, ForeignKeyConstraint):
referred_schema = c._referred_schema
if referred_schema_fn:
- fk_constraint_schema = referred_schema_fn(self, schema, c, referred_schema)
+ fk_constraint_schema = referred_schema_fn(
+ self, schema, c, referred_schema)
else:
- fk_constraint_schema = schema if referred_schema == self.schema else None
- table.append_constraint(c.copy(schema=fk_constraint_schema, target_table=table))
+ fk_constraint_schema = (
+ schema if referred_schema == self.schema else None)
+ table.append_constraint(
+ c.copy(schema=fk_constraint_schema, target_table=table))
else:
- table.append_constraint(c.copy(schema=schema, target_table=table))
+ table.append_constraint(
+ c.copy(schema=schema, target_table=table))
for index in self.indexes:
# skip indexes that would be generated
# by the 'index' flag on Column
@@ -802,13 +814,13 @@ class Column(SchemaItem, ColumnClause):
The ``type`` argument may be the second positional argument
or specified by keyword.
- If the ``type`` is ``None`` or is omitted, it will first default to the special
- type :class:`.NullType`. If and when this :class:`.Column` is
- made to refer to another column using :class:`.ForeignKey`
- and/or :class:`.ForeignKeyConstraint`, the type of the remote-referenced
- column will be copied to this column as well, at the moment that
- the foreign key is resolved against that remote :class:`.Column`
- object.
+ If the ``type`` is ``None`` or is omitted, it will first default to
+ the special type :class:`.NullType`. If and when this
+ :class:`.Column` is made to refer to another column using
+ :class:`.ForeignKey` and/or :class:`.ForeignKeyConstraint`, the type
+ of the remote-referenced column will be copied to this column as
+ well, at the moment that the foreign key is resolved against that
+ remote :class:`.Column` object.
.. versionchanged:: 0.9.0
Support for propagation of type to a :class:`.Column` from its
@@ -952,8 +964,8 @@ class Column(SchemaItem, ColumnClause):
y DATETIME DEFAULT NOW()
- Strings and text() will be converted into a :class:`.DefaultClause`
- object upon initialization.
+ Strings and text() will be converted into a
+ :class:`.DefaultClause` object upon initialization.
Use :class:`.FetchedValue` to indicate that an already-existing
column will generate a default value on the database side which
@@ -988,9 +1000,9 @@ class Column(SchemaItem, ColumnClause):
database, and should not be included in the columns list for a
``CREATE TABLE`` statement.
- For more elaborate scenarios where columns should be conditionally
- rendered differently on different backends, consider custom
- compilation rules for :class:`.CreateColumn`.
+ For more elaborate scenarios where columns should be
+ conditionally rendered differently on different backends,
+ consider custom compilation rules for :class:`.CreateColumn`.
..versionadded:: 0.8.3 Added the ``system=True`` parameter to
:class:`.Column`.
@@ -1019,7 +1031,7 @@ class Column(SchemaItem, ColumnClause):
name = quoted_name(name, kwargs.pop('quote', None))
elif "quote" in kwargs:
raise exc.ArgumentError("Explicit 'name' is required when "
- "sending 'quote' argument")
+ "sending 'quote' argument")
super(Column, self).__init__(name, type_)
self.key = kwargs.pop('key', name)
@@ -1076,7 +1088,7 @@ class Column(SchemaItem, ColumnClause):
args.append(self.server_onupdate._as_for_update(True))
else:
args.append(DefaultClause(self.server_onupdate,
- for_update=True))
+ for_update=True))
self._init_items(*args)
util.set_creation_order(self)
@@ -1135,7 +1147,7 @@ class Column(SchemaItem, ColumnClause):
[repr(x) for x in self.foreign_keys if x is not None] +
[repr(x) for x in self.constraints] +
[(self.table is not None and "table=<%s>" %
- self.table.description or "table=None")] +
+ self.table.description or "table=None")] +
["%s=%s" % (k, repr(getattr(self, k))) for k in kwarg])
def _set_parent(self, table):
@@ -1149,8 +1161,8 @@ class Column(SchemaItem, ColumnClause):
existing = getattr(self, 'table', None)
if existing is not None and existing is not table:
raise exc.ArgumentError(
- "Column object already assigned to Table '%s'" %
- existing.description)
+ "Column object already assigned to Table '%s'" %
+ existing.description)
if self.key in table._columns:
col = table._columns.get(self.key)
@@ -1172,7 +1184,7 @@ class Column(SchemaItem, ColumnClause):
raise exc.ArgumentError(
"Trying to redefine primary-key column '%s' as a "
"non-primary-key column on table '%s'" % (
- self.key, table.fullname))
+ self.key, table.fullname))
self.table = table
if self.index:
@@ -1219,27 +1231,27 @@ class Column(SchemaItem, ColumnClause):
type_ = type_.copy(**kw)
c = self._constructor(
- name=self.name,
- type_=type_,
- key=self.key,
- primary_key=self.primary_key,
- nullable=self.nullable,
- unique=self.unique,
- system=self.system,
- #quote=self.quote,
- index=self.index,
- autoincrement=self.autoincrement,
- default=self.default,
- server_default=self.server_default,
- onupdate=self.onupdate,
- server_onupdate=self.server_onupdate,
- doc=self.doc,
- *args
- )
+ name=self.name,
+ type_=type_,
+ key=self.key,
+ primary_key=self.primary_key,
+ nullable=self.nullable,
+ unique=self.unique,
+ system=self.system,
+ # quote=self.quote,
+ index=self.index,
+ autoincrement=self.autoincrement,
+ default=self.default,
+ server_default=self.server_default,
+ onupdate=self.onupdate,
+ server_onupdate=self.server_onupdate,
+ doc=self.doc,
+ *args
+ )
return self._schema_item_copy(c)
def _make_proxy(self, selectable, name=None, key=None,
- name_is_truncatable=False, **kw):
+ name_is_truncatable=False, **kw):
"""Create a *proxy* for this column.
This is a copy of this ``Column`` referenced by a different parent
@@ -1249,15 +1261,16 @@ class Column(SchemaItem, ColumnClause):
"""
fk = [ForeignKey(f.column, _constraint=f.constraint)
- for f in self.foreign_keys]
+ for f in self.foreign_keys]
if name is None and self.name is None:
- raise exc.InvalidRequestError("Cannot initialize a sub-selectable"
- " with this Column object until its 'name' has "
- "been assigned.")
+ raise exc.InvalidRequestError(
+ "Cannot initialize a sub-selectable"
+ " with this Column object until its 'name' has "
+ "been assigned.")
try:
c = self._constructor(
- _as_truncated(name or self.name) if \
- name_is_truncatable else (name or self.name),
+ _as_truncated(name or self.name) if
+ name_is_truncatable else (name or self.name),
self.type,
key=key if key else name if name else self.key,
primary_key=self.primary_key,
@@ -1271,7 +1284,7 @@ class Column(SchemaItem, ColumnClause):
"attribute or method which accepts the "
"standard Column constructor arguments, or "
"references the Column class itself." % self.__class__)
- )
+ )
c.table = selectable
selectable._columns.add(c)
@@ -1331,9 +1344,9 @@ class ForeignKey(DialectKWArgs, SchemaItem):
__visit_name__ = 'foreign_key'
def __init__(self, column, _constraint=None, use_alter=False, name=None,
- onupdate=None, ondelete=None, deferrable=None,
- initially=None, link_to_name=False, match=None,
- **dialect_kw):
+ onupdate=None, ondelete=None, deferrable=None,
+ initially=None, link_to_name=False, match=None,
+ **dialect_kw):
"""
Construct a column-level FOREIGN KEY.
@@ -1375,19 +1388,20 @@ class ForeignKey(DialectKWArgs, SchemaItem):
assigned ``key``.
:param use_alter: passed to the underlying
- :class:`.ForeignKeyConstraint` to indicate the constraint should be
- generated/dropped externally from the CREATE TABLE/ DROP TABLE
+ :class:`.ForeignKeyConstraint` to indicate the constraint should
+ be generated/dropped externally from the CREATE TABLE/ DROP TABLE
statement. See that classes' constructor for details.
:param match: Optional string. If set, emit MATCH <value> when issuing
DDL for this constraint. Typical values include SIMPLE, PARTIAL
and FULL.
- :param \**dialect_kw: Additional keyword arguments are dialect specific,
- and passed in the form ``<dialectname>_<argname>``. The arguments
- are ultimately handled by a corresponding :class:`.ForeignKeyConstraint`.
- See the documentation regarding an individual dialect at
- :ref:`dialect_toplevel` for detail on documented arguments.
+ :param \**dialect_kw: Additional keyword arguments are dialect
+ specific, and passed in the form ``<dialectname>_<argname>``. The
+ arguments are ultimately handled by a corresponding
+ :class:`.ForeignKeyConstraint`. See the documentation regarding
+ an individual dialect at :ref:`dialect_toplevel` for detail on
+ documented arguments.
.. versionadded:: 0.9.2
@@ -1404,13 +1418,14 @@ class ForeignKey(DialectKWArgs, SchemaItem):
if not isinstance(self._table_column, ColumnClause):
raise exc.ArgumentError(
- "String, Column, or Column-bound argument "
- "expected, got %r" % self._table_column)
- elif not isinstance(self._table_column.table, (util.NoneType, TableClause)):
+ "String, Column, or Column-bound argument "
+ "expected, got %r" % self._table_column)
+ elif not isinstance(
+ self._table_column.table, (util.NoneType, TableClause)):
raise exc.ArgumentError(
- "ForeignKey received Column not bound "
- "to a Table, got: %r" % self._table_column.table
- )
+ "ForeignKey received Column not bound "
+ "to a Table, got: %r" % self._table_column.table
+ )
# the linked ForeignKeyConstraint.
# ForeignKey will create this when parent Column
@@ -1449,20 +1464,19 @@ class ForeignKey(DialectKWArgs, SchemaItem):
"""
fk = ForeignKey(
- self._get_colspec(schema=schema),
- use_alter=self.use_alter,
- name=self.name,
- onupdate=self.onupdate,
- ondelete=self.ondelete,
- deferrable=self.deferrable,
- initially=self.initially,
- link_to_name=self.link_to_name,
- match=self.match,
- **self._unvalidated_dialect_kw
- )
+ self._get_colspec(schema=schema),
+ use_alter=self.use_alter,
+ name=self.name,
+ onupdate=self.onupdate,
+ ondelete=self.ondelete,
+ deferrable=self.deferrable,
+ initially=self.initially,
+ link_to_name=self.link_to_name,
+ match=self.match,
+ **self._unvalidated_dialect_kw
+ )
return self._schema_item_copy(fk)
-
def _get_colspec(self, schema=None):
"""Return a string based 'column specification' for this
:class:`.ForeignKey`.
@@ -1476,7 +1490,7 @@ class ForeignKey(DialectKWArgs, SchemaItem):
return "%s.%s.%s" % (schema, tname, colname)
elif self._table_column is not None:
return "%s.%s" % (
- self._table_column.table.fullname, self._table_column.key)
+ self._table_column.table.fullname, self._table_column.key)
else:
return self._colspec
@@ -1484,7 +1498,6 @@ class ForeignKey(DialectKWArgs, SchemaItem):
def _referred_schema(self):
return self._column_tokens[0]
-
def _table_key(self):
if self._table_column is not None:
if self._table_column.table is None:
@@ -1495,8 +1508,6 @@ class ForeignKey(DialectKWArgs, SchemaItem):
schema, tname, colname = self._column_tokens
return _get_table_key(tname, schema)
-
-
target_fullname = property(_get_colspec)
def references(self, table):
@@ -1550,13 +1561,13 @@ class ForeignKey(DialectKWArgs, SchemaItem):
def _resolve_col_tokens(self):
if self.parent is None:
raise exc.InvalidRequestError(
- "this ForeignKey object does not yet have a "
- "parent Column associated with it.")
+ "this ForeignKey object does not yet have a "
+ "parent Column associated with it.")
elif self.parent.table is None:
raise exc.InvalidRequestError(
- "this ForeignKey's parent column is not yet associated "
- "with a Table.")
+ "this ForeignKey's parent column is not yet associated "
+ "with a Table.")
parenttable = self.parent.table
@@ -1580,7 +1591,6 @@ class ForeignKey(DialectKWArgs, SchemaItem):
tablekey = _get_table_key(tname, schema)
return parenttable, tablekey, colname
-
def _link_to_col_by_colstring(self, parenttable, table, colname):
if not hasattr(self.constraint, '_referred_table'):
self.constraint._referred_table = table
@@ -1606,9 +1616,10 @@ class ForeignKey(DialectKWArgs, SchemaItem):
if _column is None:
raise exc.NoReferencedColumnError(
- "Could not initialize target column for ForeignKey '%s' on table '%s': "
- "table '%s' has no column named '%s'" % (
- self._colspec, parenttable.name, table.name, key),
+ "Could not initialize target column "
+ "for ForeignKey '%s' on table '%s': "
+ "table '%s' has no column named '%s'" %
+ (self._colspec, parenttable.name, table.name, key),
table.name, key)
self._set_target_column(_column)
@@ -1664,7 +1675,7 @@ class ForeignKey(DialectKWArgs, SchemaItem):
"Could not initialize target column for "
"ForeignKey '%s' on table '%s': "
"table '%s' has no column named '%s'" % (
- self._colspec, parenttable.name, tablekey, colname),
+ self._colspec, parenttable.name, tablekey, colname),
tablekey, colname)
elif hasattr(self._colspec, '__clause_element__'):
_column = self._colspec.__clause_element__()
@@ -1676,7 +1687,7 @@ class ForeignKey(DialectKWArgs, SchemaItem):
def _set_parent(self, column):
if self.parent is not None and self.parent is not column:
raise exc.InvalidRequestError(
- "This ForeignKey already has a parent !")
+ "This ForeignKey already has a parent !")
self.parent = column
self.parent.foreign_keys.add(self)
self.parent._on_table_attach(self._set_table)
@@ -1704,7 +1715,7 @@ class ForeignKey(DialectKWArgs, SchemaItem):
deferrable=self.deferrable, initially=self.initially,
match=self.match,
**self._unvalidated_dialect_kw
- )
+ )
self.constraint._elements[self.parent] = self
self.constraint._set_parent_with_dispatch(table)
table.foreign_keys.add(self)
@@ -1717,7 +1728,8 @@ class ForeignKey(DialectKWArgs, SchemaItem):
if table_key in parenttable.metadata.tables:
table = parenttable.metadata.tables[table_key]
try:
- self._link_to_col_by_colstring(parenttable, table, colname)
+ self._link_to_col_by_colstring(
+ parenttable, table, colname)
except exc.NoReferencedColumnError:
# this is OK, we'll try later
pass
@@ -1730,12 +1742,11 @@ class ForeignKey(DialectKWArgs, SchemaItem):
self._set_target_column(_column)
-
class _NotAColumnExpr(object):
def _not_a_column_expr(self):
raise exc.InvalidRequestError(
- "This %s cannot be used directly "
- "as a column expression." % self.__class__.__name__)
+ "This %s cannot be used directly "
+ "as a column expression." % self.__class__.__name__)
__clause_element__ = self_group = lambda self: self._not_a_column_expr()
_from_objects = property(lambda self: self._not_a_column_expr())
@@ -1841,8 +1852,8 @@ class ColumnDefault(DefaultGenerator):
@util.memoized_property
def is_scalar(self):
return not self.is_callable and \
- not self.is_clause_element and \
- not self.is_sequence
+ not self.is_clause_element and \
+ not self.is_sequence
def _maybe_wrap_callable(self, fn):
"""Wrap callables that don't accept a context.
@@ -1890,8 +1901,10 @@ class Sequence(DefaultGenerator):
The :class:`.Sequence` is typically associated with a primary key column::
- some_table = Table('some_table', metadata,
- Column('id', Integer, Sequence('some_table_seq'), primary_key=True)
+ some_table = Table(
+ 'some_table', metadata,
+ Column('id', Integer, Sequence('some_table_seq'),
+ primary_key=True)
)
When CREATE TABLE is emitted for the above :class:`.Table`, if the
@@ -1938,8 +1951,8 @@ class Sequence(DefaultGenerator):
creates a sequence for us automatically".
:param quote: boolean value, when ``True`` or ``False``, explicitly
forces quoting of the schema name on or off. When left at its
- default of ``None``, normal quoting rules based on casing and reserved
- words take place.
+ default of ``None``, normal quoting rules based on casing and
+ reserved words take place.
:param quote_schema: set the quoting preferences for the ``schema``
name.
:param metadata: optional :class:`.MetaData` object which will be
@@ -2023,8 +2036,8 @@ class Sequence(DefaultGenerator):
if bind is None:
bind = _bind_or_error(self)
bind._run_visitor(ddl.SchemaGenerator,
- self,
- checkfirst=checkfirst)
+ self,
+ checkfirst=checkfirst)
def drop(self, bind=None, checkfirst=True):
"""Drops this sequence from the database."""
@@ -2032,16 +2045,16 @@ class Sequence(DefaultGenerator):
if bind is None:
bind = _bind_or_error(self)
bind._run_visitor(ddl.SchemaDropper,
- self,
- checkfirst=checkfirst)
+ self,
+ checkfirst=checkfirst)
def _not_a_column_expr(self):
raise exc.InvalidRequestError(
- "This %s cannot be used directly "
- "as a column expression. Use func.next_value(sequence) "
- "to produce a 'next value' function that's usable "
- "as a column element."
- % self.__class__.__name__)
+ "This %s cannot be used directly "
+ "as a column expression. Use func.next_value(sequence) "
+ "to produce a 'next value' function that's usable "
+ "as a column element."
+ % self.__class__.__name__)
@inspection._self_inspects
@@ -2129,7 +2142,7 @@ class DefaultClause(FetchedValue):
def __repr__(self):
return "DefaultClause(%r, for_update=%r)" % \
- (self.arg, self.for_update)
+ (self.arg, self.for_update)
class PassiveDefault(DefaultClause):
@@ -2140,9 +2153,9 @@ class PassiveDefault(DefaultClause):
Use :class:`.DefaultClause`.
"""
@util.deprecated("0.6",
- ":class:`.PassiveDefault` is deprecated. "
- "Use :class:`.DefaultClause`.",
- False)
+ ":class:`.PassiveDefault` is deprecated. "
+ "Use :class:`.DefaultClause`.",
+ False)
def __init__(self, *arg, **kw):
DefaultClause.__init__(self, *arg, **kw)
@@ -2153,8 +2166,8 @@ class Constraint(DialectKWArgs, SchemaItem):
__visit_name__ = 'constraint'
def __init__(self, name=None, deferrable=None, initially=None,
- _create_rule=None,
- **dialect_kw):
+ _create_rule=None,
+ **dialect_kw):
"""Create a SQL constraint.
:param name:
@@ -2185,10 +2198,10 @@ class Constraint(DialectKWArgs, SchemaItem):
_create_rule is used by some types to create constraints.
Currently, its call signature is subject to change at any time.
- :param \**dialect_kw: Additional keyword arguments are dialect specific,
- and passed in the form ``<dialectname>_<argname>``. See the
- documentation regarding an individual dialect at :ref:`dialect_toplevel`
- for detail on documented arguments.
+ :param \**dialect_kw: Additional keyword arguments are dialect
+ specific, and passed in the form ``<dialectname>_<argname>``. See
+ the documentation regarding an individual dialect at
+ :ref:`dialect_toplevel` for detail on documented arguments.
"""
@@ -2207,8 +2220,8 @@ class Constraint(DialectKWArgs, SchemaItem):
except AttributeError:
pass
raise exc.InvalidRequestError(
- "This constraint is not bound to a table. Did you "
- "mean to call table.append_constraint(constraint) ?")
+ "This constraint is not bound to a table. Did you "
+ "mean to call table.append_constraint(constraint) ?")
def _set_parent(self, parent):
self.parent = parent
@@ -2239,7 +2252,7 @@ class ColumnCollectionMixin(object):
def __init__(self, *columns):
self.columns = ColumnCollection()
self._pending_colargs = [_to_schema_column_or_string(c)
- for c in columns]
+ for c in columns]
if self._pending_colargs and \
isinstance(self._pending_colargs[0], Column) and \
isinstance(self._pending_colargs[0].table, Table):
@@ -2287,7 +2300,7 @@ class ColumnCollectionConstraint(ColumnCollectionMixin, Constraint):
def copy(self, **kw):
c = self.__class__(name=self.name, deferrable=self.deferrable,
- initially=self.initially, *self.columns.keys())
+ initially=self.initially, *self.columns.keys())
return self._schema_item_copy(c)
def contains_column(self, col):
@@ -2311,8 +2324,8 @@ class CheckConstraint(Constraint):
"""
def __init__(self, sqltext, name=None, deferrable=None,
- initially=None, table=None, _create_rule=None,
- _autoattach=True):
+ initially=None, table=None, _create_rule=None,
+ _autoattach=True):
"""Construct a CHECK constraint.
:param sqltext:
@@ -2337,17 +2350,17 @@ class CheckConstraint(Constraint):
"""
super(CheckConstraint, self).\
- __init__(name, deferrable, initially, _create_rule)
+ __init__(name, deferrable, initially, _create_rule)
self.sqltext = _literal_as_text(sqltext)
if table is not None:
self._set_parent_with_dispatch(table)
elif _autoattach:
cols = _find_columns(self.sqltext)
tables = set([c.table for c in cols
- if isinstance(c.table, Table)])
+ if isinstance(c.table, Table)])
if len(tables) == 1:
self._set_parent_with_dispatch(
- tables.pop())
+ tables.pop())
def __visit_name__(self):
if isinstance(self.parent, Table):
@@ -2367,12 +2380,12 @@ class CheckConstraint(Constraint):
else:
sqltext = self.sqltext
c = CheckConstraint(sqltext,
- name=self.name,
- initially=self.initially,
- deferrable=self.deferrable,
- _create_rule=self._create_rule,
- table=target_table,
- _autoattach=False)
+ name=self.name,
+ initially=self.initially,
+ deferrable=self.deferrable,
+ _create_rule=self._create_rule,
+ table=target_table,
+ _autoattach=False)
return self._schema_item_copy(c)
@@ -2381,8 +2394,9 @@ class ForeignKeyConstraint(Constraint):
Defines a single column or composite FOREIGN KEY ... REFERENCES
constraint. For a no-frills, single column foreign key, adding a
- :class:`.ForeignKey` to the definition of a :class:`.Column` is a shorthand
- equivalent for an unnamed, single column :class:`.ForeignKeyConstraint`.
+ :class:`.ForeignKey` to the definition of a :class:`.Column` is a
+ shorthand equivalent for an unnamed, single column
+ :class:`.ForeignKeyConstraint`.
Examples of foreign key configuration are in :ref:`metadata_foreignkeys`.
@@ -2390,8 +2404,9 @@ class ForeignKeyConstraint(Constraint):
__visit_name__ = 'foreign_key_constraint'
def __init__(self, columns, refcolumns, name=None, onupdate=None,
- ondelete=None, deferrable=None, initially=None, use_alter=False,
- link_to_name=False, match=None, table=None, **dialect_kw):
+ ondelete=None, deferrable=None, initially=None,
+ use_alter=False, link_to_name=False, match=None,
+ table=None, **dialect_kw):
"""Construct a composite-capable FOREIGN KEY.
:param columns: A sequence of local column names. The named columns
@@ -2427,25 +2442,25 @@ class ForeignKeyConstraint(Constraint):
ALTER TABLE statement issued after the full collection of tables
have been created, and drop it via an ALTER TABLE statement before
the full collection of tables are dropped. This is shorthand for the
- usage of :class:`.AddConstraint` and :class:`.DropConstraint` applied
- as "after-create" and "before-drop" events on the MetaData object.
- This is normally used to generate/drop constraints on objects that
- are mutually dependent on each other.
+ usage of :class:`.AddConstraint` and :class:`.DropConstraint`
+ applied as "after-create" and "before-drop" events on the MetaData
+ object. This is normally used to generate/drop constraints on
+ objects that are mutually dependent on each other.
:param match: Optional string. If set, emit MATCH <value> when issuing
- DDL for this constraint. Typical values include SIMPLE, PARTIAL
- and FULL.
+ DDL for this constraint. Typical values include SIMPLE, PARTIAL
+ and FULL.
- :param \**dialect_kw: Additional keyword arguments are dialect specific,
- and passed in the form ``<dialectname>_<argname>``. See the
- documentation regarding an individual dialect at :ref:`dialect_toplevel`
- for detail on documented arguments.
+ :param \**dialect_kw: Additional keyword arguments are dialect
+ specific, and passed in the form ``<dialectname>_<argname>``. See
+ the documentation regarding an individual dialect at
+ :ref:`dialect_toplevel` for detail on documented arguments.
.. versionadded:: 0.9.2
"""
super(ForeignKeyConstraint, self).\
- __init__(name, deferrable, initially, **dialect_kw)
+ __init__(name, deferrable, initially, **dialect_kw)
self.onupdate = onupdate
self.ondelete = ondelete
@@ -2463,18 +2478,18 @@ class ForeignKeyConstraint(Constraint):
# to the Table for string-specified names
for col, refcol in zip(columns, refcolumns):
self._elements[col] = ForeignKey(
- refcol,
- _constraint=self,
- name=self.name,
- onupdate=self.onupdate,
- ondelete=self.ondelete,
- use_alter=self.use_alter,
- link_to_name=self.link_to_name,
- match=self.match,
- deferrable=self.deferrable,
- initially=self.initially,
- **self.dialect_kwargs
- )
+ refcol,
+ _constraint=self,
+ name=self.name,
+ onupdate=self.onupdate,
+ ondelete=self.ondelete,
+ use_alter=self.use_alter,
+ link_to_name=self.link_to_name,
+ match=self.match,
+ deferrable=self.deferrable,
+ initially=self.initially,
+ **self.dialect_kwargs
+ )
if table is not None:
self._set_parent_with_dispatch(table)
@@ -2491,17 +2506,18 @@ class ForeignKeyConstraint(Constraint):
return None
def _validate_dest_table(self, table):
- table_keys = set([elem._table_key() for elem in self._elements.values()])
+ table_keys = set([elem._table_key()
+ for elem in self._elements.values()])
if None not in table_keys and len(table_keys) > 1:
elem0, elem1 = sorted(table_keys)[0:2]
raise exc.ArgumentError(
'ForeignKeyConstraint on %s(%s) refers to '
'multiple remote tables: %s and %s' % (
- table.fullname,
- self._col_description,
- elem0,
- elem1
- ))
+ table.fullname,
+ self._col_description,
+ elem0,
+ elem1
+ ))
@property
def _col_description(self):
@@ -2539,7 +2555,7 @@ class ForeignKeyConstraint(Constraint):
if self.use_alter:
def supports_alter(ddl, event, schema_item, bind, **kw):
return table in set(kw['tables']) and \
- bind.dialect.supports_alter
+ bind.dialect.supports_alter
event.listen(table.metadata, "after_create",
ddl.AddConstraint(self, on=supports_alter))
@@ -2548,20 +2564,21 @@ class ForeignKeyConstraint(Constraint):
def copy(self, schema=None, **kw):
fkc = ForeignKeyConstraint(
- [x.parent.key for x in self._elements.values()],
- [x._get_colspec(schema=schema) for x in self._elements.values()],
- name=self.name,
- onupdate=self.onupdate,
- ondelete=self.ondelete,
- use_alter=self.use_alter,
- deferrable=self.deferrable,
- initially=self.initially,
- link_to_name=self.link_to_name,
- match=self.match
- )
+ [x.parent.key for x in self._elements.values()],
+ [x._get_colspec(schema=schema)
+ for x in self._elements.values()],
+ name=self.name,
+ onupdate=self.onupdate,
+ ondelete=self.ondelete,
+ use_alter=self.use_alter,
+ deferrable=self.deferrable,
+ initially=self.initially,
+ link_to_name=self.link_to_name,
+ match=self.match
+ )
for self_fk, other_fk in zip(
- self._elements.values(),
- fkc._elements.values()):
+ self._elements.values(),
+ fkc._elements.values()):
self_fk._schema_item_copy(other_fk)
return self._schema_item_copy(fkc)
@@ -2581,8 +2598,10 @@ class PrimaryKeyConstraint(ColumnCollectionConstraint):
... )
>>> my_table.primary_key
PrimaryKeyConstraint(
- Column('id', Integer(), table=<mytable>, primary_key=True, nullable=False),
- Column('version_id', Integer(), table=<mytable>, primary_key=True, nullable=False)
+ Column('id', Integer(), table=<mytable>,
+ primary_key=True, nullable=False),
+ Column('version_id', Integer(), table=<mytable>,
+ primary_key=True, nullable=False)
)
The primary key of a :class:`.Table` can also be specified by using
@@ -2594,7 +2613,8 @@ class PrimaryKeyConstraint(ColumnCollectionConstraint):
Column('id', Integer),
Column('version_id', Integer),
Column('data', String(50)),
- PrimaryKeyConstraint('id', 'version_id', name='mytable_pk')
+ PrimaryKeyConstraint('id', 'version_id',
+ name='mytable_pk')
)
The two styles of column-specification should generally not be mixed.
@@ -2602,9 +2622,9 @@ class PrimaryKeyConstraint(ColumnCollectionConstraint):
:class:`.PrimaryKeyConstraint`
don't match the columns that were marked as ``primary_key=True``, if both
are present; in this case, the columns are taken strictly from the
- :class:`.PrimaryKeyConstraint` declaration, and those columns otherwise marked
- as ``primary_key=True`` are ignored. This behavior is intended to be
- backwards compatible with previous behavior.
+ :class:`.PrimaryKeyConstraint` declaration, and those columns otherwise
+ marked as ``primary_key=True`` are ignored. This behavior is intended to
+ be backwards compatible with previous behavior.
.. versionchanged:: 0.9.2 Using a mixture of columns within a
:class:`.PrimaryKeyConstraint` in addition to columns marked as
@@ -2614,23 +2634,26 @@ class PrimaryKeyConstraint(ColumnCollectionConstraint):
may raise an exception in a future release.
For the use case where specific options are to be specified on the
- :class:`.PrimaryKeyConstraint`, but the usual style of using ``primary_key=True``
- flags is still desirable, an empty :class:`.PrimaryKeyConstraint` may be
- specified, which will take on the primary key column collection from
- the :class:`.Table` based on the flags::
+ :class:`.PrimaryKeyConstraint`, but the usual style of using
+ ``primary_key=True`` flags is still desirable, an empty
+ :class:`.PrimaryKeyConstraint` may be specified, which will take on the
+ primary key column collection from the :class:`.Table` based on the
+ flags::
my_table = Table('mytable', metadata,
Column('id', Integer, primary_key=True),
Column('version_id', Integer, primary_key=True),
Column('data', String(50)),
- PrimaryKeyConstraint(name='mytable_pk', mssql_clustered=True)
+ PrimaryKeyConstraint(name='mytable_pk',
+ mssql_clustered=True)
)
.. versionadded:: 0.9.2 an empty :class:`.PrimaryKeyConstraint` may now
- be specified for the purposes of establishing keyword arguments with the
- constraint, independently of the specification of "primary key" columns
- within the :class:`.Table` itself; columns marked as ``primary_key=True``
- will be gathered into the empty constraint's column collection.
+ be specified for the purposes of establishing keyword arguments with
+ the constraint, independently of the specification of "primary key"
+ columns within the :class:`.Table` itself; columns marked as
+ ``primary_key=True`` will be gathered into the empty constraint's
+ column collection.
"""
@@ -2646,19 +2669,19 @@ class PrimaryKeyConstraint(ColumnCollectionConstraint):
table_pks = [c for c in table.c if c.primary_key]
if self.columns and table_pks and \
- set(table_pks) != set(self.columns.values()):
+ set(table_pks) != set(self.columns.values()):
util.warn(
- "Table '%s' specifies columns %s as primary_key=True, "
- "not matching locally specified columns %s; setting the "
- "current primary key columns to %s. This warning "
- "may become an exception in a future release" %
- (
- table.name,
- ", ".join("'%s'" % c.name for c in table_pks),
- ", ".join("'%s'" % c.name for c in self.columns),
- ", ".join("'%s'" % c.name for c in self.columns)
- )
+ "Table '%s' specifies columns %s as primary_key=True, "
+ "not matching locally specified columns %s; setting the "
+ "current primary key columns to %s. This warning "
+ "may become an exception in a future release" %
+ (
+ table.name,
+ ", ".join("'%s'" % c.name for c in table_pks),
+ ", ".join("'%s'" % c.name for c in self.columns),
+ ", ".join("'%s'" % c.name for c in self.columns)
)
+ )
table_pks[:] = []
for c in self.columns:
@@ -2745,9 +2768,9 @@ class Index(DialectKWArgs, ColumnCollectionMixin, SchemaItem):
.. versionadded:: 0.8 support for functional and expression-based indexes.
An :class:`.Index` can also be manually associated with a :class:`.Table`,
- either through inline declaration or using :meth:`.Table.append_constraint`.
- When this approach is used, the names of the indexed columns can be specified
- as strings::
+ either through inline declaration or using
+ :meth:`.Table.append_constraint`. When this approach is used, the names
+ of the indexed columns can be specified as strings::
Table("sometable", metadata,
Column("name", String(50)),
@@ -2775,8 +2798,8 @@ class Index(DialectKWArgs, ColumnCollectionMixin, SchemaItem):
:ref:`schema_indexes` - General information on :class:`.Index`.
- :ref:`postgresql_indexes` - PostgreSQL-specific options available for the
- :class:`.Index` construct.
+ :ref:`postgresql_indexes` - PostgreSQL-specific options available for
+ the :class:`.Index` construct.
:ref:`mysql_indexes` - MySQL-specific options available for the
:class:`.Index` construct.
@@ -2809,9 +2832,10 @@ class Index(DialectKWArgs, ColumnCollectionMixin, SchemaItem):
:paramref:`.Column.quote`.
:param \**kw: Additional keyword arguments not mentioned above are
- dialect specific, and passed in the form ``<dialectname>_<argname>``.
- See the documentation regarding an individual dialect at
- :ref:`dialect_toplevel` for detail on documented arguments.
+ dialect specific, and passed in the form
+ ``<dialectname>_<argname>``. See the documentation regarding an
+ individual dialect at :ref:`dialect_toplevel` for detail on
+ documented arguments.
"""
self.table = None
@@ -2835,7 +2859,6 @@ class Index(DialectKWArgs, ColumnCollectionMixin, SchemaItem):
# objects are present
ColumnCollectionMixin.__init__(self, *columns)
-
def _set_parent(self, table):
ColumnCollectionMixin._set_parent(self, table)
@@ -2860,7 +2883,8 @@ class Index(DialectKWArgs, ColumnCollectionMixin, SchemaItem):
self.expressions = [
expr if isinstance(expr, ClauseElement)
else colexpr
- for expr, colexpr in util.zip_longest(self.expressions, self.columns)
+ for expr, colexpr in util.zip_longest(self.expressions,
+ self.columns)
]
@property
@@ -2900,11 +2924,11 @@ class Index(DialectKWArgs, ColumnCollectionMixin, SchemaItem):
def __repr__(self):
return 'Index(%s)' % (
- ", ".join(
- [repr(self.name)] +
- [repr(e) for e in self.expressions] +
- (self.unique and ["unique=True"] or [])
- ))
+ ", ".join(
+ [repr(self.name)] +
+ [repr(e) for e in self.expressions] +
+ (self.unique and ["unique=True"] or [])
+ ))
DEFAULT_NAMING_CONVENTION = util.immutabledict({
@@ -2925,9 +2949,9 @@ class MetaData(SchemaItem):
The :class:`.Table` objects themselves are stored in the
:attr:`.MetaData.tables` dictionary.
- :class:`.MetaData` is a thread-safe object for read operations. Construction
- of new tables within a single :class:`.MetaData` object, either explicitly
- or via reflection, may not be completely thread-safe.
+ :class:`.MetaData` is a thread-safe object for read operations.
+ Construction of new tables within a single :class:`.MetaData` object,
+ either explicitly or via reflection, may not be completely thread-safe.
.. seealso::
@@ -2940,7 +2964,7 @@ class MetaData(SchemaItem):
def __init__(self, bind=None, reflect=False, schema=None,
quote_schema=None,
naming_convention=DEFAULT_NAMING_CONVENTION
- ):
+ ):
"""Create a new MetaData object.
:param bind:
@@ -2985,9 +3009,9 @@ class MetaData(SchemaItem):
The values associated with each "constraint class" or "constraint
mnemonic" key are string naming templates, such as
``"uq_%(table_name)s_%(column_0_name)s"``,
- which describe how the name should be composed. The values associated
- with user-defined "token" keys should be callables of the form
- ``fn(constraint, table)``, which accepts the constraint/index
+ which describe how the name should be composed. The values
+ associated with user-defined "token" keys should be callables of the
+ form ``fn(constraint, table)``, which accepts the constraint/index
object and :class:`.Table` as arguments, returning a string
result.
@@ -3011,14 +3035,15 @@ class MetaData(SchemaItem):
index position "0", e.g. :attr:`.Column.key`
* ``%(referred_column_0_name)s`` - the name of a :class:`.Column`
- at index position "0" referenced by a :class:`.ForeignKeyConstraint`.
+ at index position "0" referenced by a
+ :class:`.ForeignKeyConstraint`.
- * ``%(constraint_name)s`` - a special key that refers to the existing
- name given to the constraint. When this key is present, the
- :class:`.Constraint` object's existing name will be replaced with
- one that is composed from template string that uses this token.
- When this token is present, it is required that the :class:`.Constraint`
- is given an expicit name ahead of time.
+ * ``%(constraint_name)s`` - a special key that refers to the
+ existing name given to the constraint. When this key is
+ present, the :class:`.Constraint` object's existing name will be
+ replaced with one that is composed from template string that
+ uses this token. When this token is present, it is required that
+ the :class:`.Constraint` is given an expicit name ahead of time.
* user-defined: any additional token may be implemented by passing
it along with a ``fn(constraint, table)`` callable to the
@@ -3042,7 +3067,7 @@ class MetaData(SchemaItem):
self.bind = bind
if reflect:
util.warn_deprecated("reflect=True is deprecate; please "
- "use the reflect() method.")
+ "use the reflect() method.")
if not bind:
raise exc.ArgumentError(
"A bind must be supplied in conjunction "
@@ -3077,8 +3102,6 @@ class MetaData(SchemaItem):
if schema:
self._schemas.add(schema)
-
-
def _remove_table(self, name, schema):
key = _get_table_key(name, schema)
removed = dict.pop(self.tables, key, None)
@@ -3087,9 +3110,8 @@ class MetaData(SchemaItem):
fk._remove_from_metadata(self)
if self._schemas:
self._schemas = set([t.schema
- for t in self.tables.values()
- if t.schema is not None])
-
+ for t in self.tables.values()
+ if t.schema is not None])
def __getstate__(self):
return {'tables': self.tables,
@@ -3172,9 +3194,9 @@ class MetaData(SchemaItem):
return ddl.sort_tables(self.tables.values())
def reflect(self, bind=None, schema=None, views=False, only=None,
- extend_existing=False,
- autoload_replace=True,
- **dialect_kwargs):
+ extend_existing=False,
+ autoload_replace=True,
+ **dialect_kwargs):
"""Load all available table definitions from the database.
Automatically creates ``Table`` entries in this ``MetaData`` for any
@@ -3219,13 +3241,15 @@ class MetaData(SchemaItem):
.. versionadded:: 0.9.1
- :param \**dialect_kwargs: Additional keyword arguments not mentioned above are
- dialect specific, and passed in the form ``<dialectname>_<argname>``.
- See the documentation regarding an individual dialect at
- :ref:`dialect_toplevel` for detail on documented arguments.
+ :param \**dialect_kwargs: Additional keyword arguments not mentioned
+ above are dialect specific, and passed in the form
+ ``<dialectname>_<argname>``. See the documentation regarding an
+ individual dialect at :ref:`dialect_toplevel` for detail on
+ documented arguments.
- .. versionadded:: 0.9.2 - Added :paramref:`.MetaData.reflect.**dialect_kwargs`
- to support dialect-level reflection options for all :class:`.Table`
+ .. versionadded:: 0.9.2 - Added
+ :paramref:`.MetaData.reflect.**dialect_kwargs` to support
+ dialect-level reflection options for all :class:`.Table`
objects reflected.
"""
@@ -3249,8 +3273,8 @@ class MetaData(SchemaItem):
if schema is not None:
reflect_opts['schema'] = schema
- available = util.OrderedSet(bind.engine.table_names(schema,
- connection=conn))
+ available = util.OrderedSet(
+ bind.engine.table_names(schema, connection=conn))
if views:
available.update(
bind.dialect.get_view_names(conn, schema)
@@ -3258,7 +3282,7 @@ class MetaData(SchemaItem):
if schema is not None:
available_w_schema = util.OrderedSet(["%s.%s" % (schema, name)
- for name in available])
+ for name in available])
else:
available_w_schema = available
@@ -3270,9 +3294,9 @@ class MetaData(SchemaItem):
if extend_existing or schname not in current]
elif util.callable(only):
load = [name for name, schname in
- zip(available, available_w_schema)
- if (extend_existing or schname not in current)
- and only(name, self)]
+ zip(available, available_w_schema)
+ if (extend_existing or schname not in current)
+ and only(name, self)]
else:
missing = [name for name in only if name not in available]
if missing:
@@ -3282,7 +3306,7 @@ class MetaData(SchemaItem):
'in %s%s: (%s)' %
(bind.engine.url, s, ', '.join(missing)))
load = [name for name in only if extend_existing or
- name not in current]
+ name not in current]
for name in load:
Table(name, self, **reflect_opts)
@@ -3323,9 +3347,9 @@ class MetaData(SchemaItem):
if bind is None:
bind = _bind_or_error(self)
bind._run_visitor(ddl.SchemaGenerator,
- self,
- checkfirst=checkfirst,
- tables=tables)
+ self,
+ checkfirst=checkfirst,
+ tables=tables)
def drop_all(self, bind=None, tables=None, checkfirst=True):
"""Drop all tables stored in this metadata.
@@ -3350,9 +3374,9 @@ class MetaData(SchemaItem):
if bind is None:
bind = _bind_or_error(self)
bind._run_visitor(ddl.SchemaDropper,
- self,
- checkfirst=checkfirst,
- tables=tables)
+ self,
+ checkfirst=checkfirst,
+ tables=tables)
class ThreadLocalMetaData(MetaData):
@@ -3418,6 +3442,3 @@ class ThreadLocalMetaData(MetaData):
for e in self.__engines.values():
if hasattr(e, 'dispose'):
e.dispose()
-
-
-
diff --git a/lib/sqlalchemy/sql/selectable.py b/lib/sqlalchemy/sql/selectable.py
index a57f1ecc3..4808a3935 100644
--- a/lib/sqlalchemy/sql/selectable.py
+++ b/lib/sqlalchemy/sql/selectable.py
@@ -11,14 +11,14 @@ SQL tables and derived rowsets.
"""
from .elements import ClauseElement, TextClause, ClauseList, \
- and_, Grouping, UnaryExpression, literal_column, BindParameter
+ and_, Grouping, UnaryExpression, literal_column, BindParameter
from .elements import _clone, \
- _literal_as_text, _interpret_as_column_or_from, _expand_cloned,\
- _select_iterables, _anonymous_label, _clause_element_as_expr,\
- _cloned_intersection, _cloned_difference, True_, _only_column_elements,\
- TRUE
+ _literal_as_text, _interpret_as_column_or_from, _expand_cloned,\
+ _select_iterables, _anonymous_label, _clause_element_as_expr,\
+ _cloned_intersection, _cloned_difference, True_, _only_column_elements,\
+ TRUE
from .base import Immutable, Executable, _generative, \
- ColumnCollection, ColumnSet, _from_objects, Generative
+ ColumnCollection, ColumnSet, _from_objects, Generative
from . import type_api
from .. import inspection
from .. import util
@@ -41,6 +41,7 @@ def _interpret_as_from(element):
return insp.selectable
raise exc.ArgumentError("FROM expression expected")
+
def _interpret_as_select(element):
element = _interpret_as_from(element)
if isinstance(element, Alias):
@@ -49,11 +50,13 @@ def _interpret_as_select(element):
element = element.select()
return element
+
class _OffsetLimitParam(BindParameter):
@property
def _limit_offset_value(self):
return self.effective_value
+
def _offset_or_limit_clause(element, name=None, type_=None):
"""Convert the given value to an "offset or limit" clause.
@@ -71,6 +74,7 @@ def _offset_or_limit_clause(element, name=None, type_=None):
value = util.asint(element)
return _OffsetLimitParam(name, value, type_=type_, unique=True)
+
def _offset_or_limit_clause_asint(clause, attrname):
"""Convert the "offset or limit" clause of a select construct to an
integer.
@@ -85,11 +89,12 @@ def _offset_or_limit_clause_asint(clause, attrname):
value = clause._limit_offset_value
except AttributeError:
raise exc.CompileError(
- "This SELECT structure does not use a simple "
- "integer value for %s" % attrname)
+ "This SELECT structure does not use a simple "
+ "integer value for %s" % attrname)
else:
return util.asint(value)
+
def subquery(alias, *args, **kwargs):
"""Return an :class:`.Alias` object derived
from a :class:`.Select`.
@@ -106,7 +111,6 @@ def subquery(alias, *args, **kwargs):
return Select(*args, **kwargs).alias(alias)
-
def alias(selectable, name=None, flat=False):
"""Return an :class:`.Alias` object.
@@ -194,8 +198,9 @@ class FromClause(Selectable):
schema = None
"""Define the 'schema' attribute for this :class:`.FromClause`.
- This is typically ``None`` for most objects except that of :class:`.Table`,
- where it is taken as the value of the :paramref:`.Table.schema` argument.
+ This is typically ``None`` for most objects except that of
+ :class:`.Table`, where it is taken as the value of the
+ :paramref:`.Table.schema` argument.
"""
@@ -211,10 +216,10 @@ class FromClause(Selectable):
else:
col = list(self.columns)[0]
return Select(
- [functions.func.count(col).label('tbl_row_count')],
- whereclause,
- from_obj=[self],
- **params)
+ [functions.func.count(col).label('tbl_row_count')],
+ whereclause,
+ from_obj=[self],
+ **params)
def select(self, whereclause=None, **params):
"""return a SELECT of this :class:`.FromClause`.
@@ -245,9 +250,10 @@ class FromClause(Selectable):
SELECT user.id, user.name FROM user
JOIN address ON user.id = address.user_id
- :param right: the right side of the join; this is any :class:`.FromClause`
- object such as a :class:`.Table` object, and may also be a selectable-compatible
- object such as an ORM-mapped class.
+ :param right: the right side of the join; this is any
+ :class:`.FromClause` object such as a :class:`.Table` object, and
+ may also be a selectable-compatible object such as an ORM-mapped
+ class.
:param onclause: a SQL expression representing the ON clause of the
join. If left at ``None``, :meth:`.FromClause.join` will attempt to
@@ -279,12 +285,15 @@ class FromClause(Selectable):
The above is equivalent to::
- j = user_table.join(address_table,
- user_table.c.id == address_table.c.user_id, isouter=True)
+ j = user_table.join(
+ address_table,
+ user_table.c.id == address_table.c.user_id,
+ isouter=True)
- :param right: the right side of the join; this is any :class:`.FromClause`
- object such as a :class:`.Table` object, and may also be a selectable-compatible
- object such as an ORM-mapped class.
+ :param right: the right side of the join; this is any
+ :class:`.FromClause` object such as a :class:`.Table` object, and
+ may also be a selectable-compatible object such as an ORM-mapped
+ class.
:param onclause: a SQL expression representing the ON clause of the
join. If left at ``None``, :meth:`.FromClause.join` will attempt to
@@ -368,8 +377,8 @@ class FromClause(Selectable):
:param column: the target :class:`.ColumnElement` to be matched
:param require_embedded: only return corresponding columns for
- the given :class:`.ColumnElement`, if the given :class:`.ColumnElement`
- is actually present within a sub-element
+ the given :class:`.ColumnElement`, if the given
+ :class:`.ColumnElement` is actually present within a sub-element
of this :class:`.FromClause`. Normally the column will match if
it merely shares a common ancestor with one of the exported
columns of this :class:`.FromClause`.
@@ -379,7 +388,7 @@ class FromClause(Selectable):
def embedded(expanded_proxy_set, target_set):
for t in target_set.difference(expanded_proxy_set):
if not set(_expand_cloned([t])
- ).intersection(expanded_proxy_set):
+ ).intersection(expanded_proxy_set):
return False
return True
@@ -419,12 +428,14 @@ class FromClause(Selectable):
# columns that have no reference to the target
# column (also occurs with CompoundSelect)
- col_distance = util.reduce(operator.add,
- [sc._annotations.get('weight', 1) for sc in
- col.proxy_set if sc.shares_lineage(column)])
- c_distance = util.reduce(operator.add,
- [sc._annotations.get('weight', 1) for sc in
- c.proxy_set if sc.shares_lineage(column)])
+ col_distance = util.reduce(
+ operator.add,
+ [sc._annotations.get('weight', 1) for sc in
+ col.proxy_set if sc.shares_lineage(column)])
+ c_distance = util.reduce(
+ operator.add,
+ [sc._annotations.get('weight', 1) for sc in
+ c.proxy_set if sc.shares_lineage(column)])
if c_distance < col_distance:
col, intersect = c, i
return col
@@ -480,7 +491,7 @@ class FromClause(Selectable):
return self.foreign_keys
c = property(attrgetter('columns'),
- doc="An alias for the :attr:`.columns` attribute.")
+ doc="An alias for the :attr:`.columns` attribute.")
_select_iterable = property(attrgetter('columns'))
def _init_collections(self):
@@ -531,7 +542,8 @@ class FromClause(Selectable):
"""
if not self._cols_populated:
return None
- elif column.key in self.columns and self.columns[column.key] is column:
+ elif (column.key in self.columns and
+ self.columns[column.key] is column):
return column
else:
return None
@@ -599,7 +611,6 @@ class Join(FromClause):
"""
return cls(left, right, onclause, isouter=True)
-
@classmethod
def _create_join(cls, left, right, onclause=None, isouter=False):
"""Produce a :class:`.Join` object, given two :class:`.FromClause`
@@ -607,7 +618,8 @@ class Join(FromClause):
E.g.::
- j = join(user_table, address_table, user_table.c.id == address_table.c.user_id)
+ j = join(user_table, address_table,
+ user_table.c.id == address_table.c.user_id)
stmt = select([user_table]).select_from(j)
would emit SQL along the lines of::
@@ -615,15 +627,16 @@ class Join(FromClause):
SELECT user.id, user.name FROM user
JOIN address ON user.id = address.user_id
- Similar functionality is available given any :class:`.FromClause` object
- (e.g. such as a :class:`.Table`) using the :meth:`.FromClause.join`
- method.
+ Similar functionality is available given any
+ :class:`.FromClause` object (e.g. such as a :class:`.Table`) using
+ the :meth:`.FromClause.join` method.
:param left: The left side of the join.
- :param right: the right side of the join; this is any :class:`.FromClause`
- object such as a :class:`.Table` object, and may also be a selectable-compatible
- object such as an ORM-mapped class.
+ :param right: the right side of the join; this is any
+ :class:`.FromClause` object such as a :class:`.Table` object, and
+ may also be a selectable-compatible object such as an ORM-mapped
+ class.
:param onclause: a SQL expression representing the ON clause of the
join. If left at ``None``, :meth:`.FromClause.join` will attempt to
@@ -641,7 +654,6 @@ class Join(FromClause):
return cls(left, right, onclause, isouter)
-
@property
def description(self):
return "Join object on %s(%d) and %s(%d)" % (
@@ -652,8 +664,8 @@ class Join(FromClause):
def is_derived_from(self, fromclause):
return fromclause is self or \
- self.left.is_derived_from(fromclause) or \
- self.right.is_derived_from(fromclause)
+ self.left.is_derived_from(fromclause) or \
+ self.right.is_derived_from(fromclause)
def self_group(self, against=None):
return FromGrouping(self)
@@ -661,13 +673,13 @@ class Join(FromClause):
@util.dependencies("sqlalchemy.sql.util")
def _populate_column_collection(self, sqlutil):
columns = [c for c in self.left.columns] + \
- [c for c in self.right.columns]
+ [c for c in self.right.columns]
self.primary_key.extend(sqlutil.reduce_columns(
- (c for c in columns if c.primary_key), self.onclause))
+ (c for c in columns if c.primary_key), self.onclause))
self._columns.update((col._label, col) for col in columns)
self.foreign_keys.update(itertools.chain(
- *[col.foreign_keys for col in columns]))
+ *[col.foreign_keys for col in columns]))
def _refresh_for_new_column(self, column):
col = self.left._refresh_for_new_column(column)
@@ -734,10 +746,10 @@ class Join(FromClause):
if left is None:
continue
for fk in sorted(
- b.foreign_keys,
- key=lambda fk: fk.parent._creation_order):
+ b.foreign_keys,
+ key=lambda fk: fk.parent._creation_order):
if consider_as_foreign_keys is not None and \
- fk.parent not in consider_as_foreign_keys:
+ fk.parent not in consider_as_foreign_keys:
continue
try:
col = fk.get_referent(left)
@@ -751,10 +763,10 @@ class Join(FromClause):
constraints[fk.constraint].append((col, fk.parent))
if left is not b:
for fk in sorted(
- left.foreign_keys,
- key=lambda fk: fk.parent._creation_order):
+ left.foreign_keys,
+ key=lambda fk: fk.parent._creation_order):
if consider_as_foreign_keys is not None and \
- fk.parent not in consider_as_foreign_keys:
+ fk.parent not in consider_as_foreign_keys:
continue
try:
col = fk.get_referent(b)
@@ -777,7 +789,8 @@ class Join(FromClause):
# "consider_as_foreign_keys".
if consider_as_foreign_keys:
for const in list(constraints):
- if set(f.parent for f in const.elements) != set(consider_as_foreign_keys):
+ if set(f.parent for f in const.elements) != set(
+ consider_as_foreign_keys):
del constraints[const]
# if still multiple constraints, but
@@ -799,12 +812,13 @@ class Join(FromClause):
if len(constraints) == 0:
if isinstance(b, FromGrouping):
hint = " Perhaps you meant to convert the right side to a "\
- "subquery using alias()?"
+ "subquery using alias()?"
else:
hint = ""
raise exc.NoForeignKeysError(
"Can't find any foreign key relationships "
- "between '%s' and '%s'.%s" % (a.description, b.description, hint))
+ "between '%s' and '%s'.%s" %
+ (a.description, b.description, hint))
crit = [(x == y) for x, y in list(constraints.values())[0]]
if len(crit) == 1:
@@ -812,7 +826,6 @@ class Join(FromClause):
else:
return and_(*crit)
-
def select(self, whereclause=None, **kwargs):
"""Create a :class:`.Select` from this :class:`.Join`.
@@ -877,8 +890,8 @@ class Join(FromClause):
columns as that of the two individual selectables presented under
a single name - the individual columns are "auto-labeled", meaning
the ``.c.`` collection of the resulting :class:`.Alias` represents
- the names of the individual columns using a ``<tablename>_<columname>``
- scheme::
+ the names of the individual columns using a
+ ``<tablename>_<columname>`` scheme::
j.c.table_a_id
j.c.table_b_a_id
@@ -941,26 +954,26 @@ class Join(FromClause):
if flat:
assert name is None, "Can't send name argument with flat"
left_a, right_a = self.left.alias(flat=True), \
- self.right.alias(flat=True)
+ self.right.alias(flat=True)
adapter = sqlutil.ClauseAdapter(left_a).\
- chain(sqlutil.ClauseAdapter(right_a))
+ chain(sqlutil.ClauseAdapter(right_a))
- return left_a.join(right_a,
- adapter.traverse(self.onclause), isouter=self.isouter)
+ return left_a.join(right_a, adapter.traverse(self.onclause),
+ isouter=self.isouter)
else:
return self.select(use_labels=True, correlate=False).alias(name)
@property
def _hide_froms(self):
return itertools.chain(*[_from_objects(x.left, x.right)
- for x in self._cloned_set])
+ for x in self._cloned_set])
@property
def _from_objects(self):
return [self] + \
- self.onclause._from_objects + \
- self.left._from_objects + \
- self.right._from_objects
+ self.onclause._from_objects + \
+ self.left._from_objects + \
+ self.right._from_objects
class Alias(FromClause):
@@ -970,9 +983,9 @@ class Alias(FromClause):
sub-select within a SQL statement using the ``AS`` keyword (or
without the keyword on certain databases such as Oracle).
- This object is constructed from the :func:`~.expression.alias` module level
- function as well as the :meth:`.FromClause.alias` method available on all
- :class:`.FromClause` subclasses.
+ This object is constructed from the :func:`~.expression.alias` module
+ level function as well as the :meth:`.FromClause.alias` method available
+ on all :class:`.FromClause` subclasses.
"""
@@ -994,10 +1007,9 @@ class Alias(FromClause):
if self.original.named_with_column:
name = getattr(self.original, 'name', None)
name = _anonymous_label('%%(%d %s)s' % (id(self), name
- or 'anon'))
+ or 'anon'))
self.name = name
-
@property
def description(self):
if util.py3k:
@@ -1072,10 +1084,10 @@ class CTE(Alias):
__visit_name__ = 'cte'
def __init__(self, selectable,
- name=None,
- recursive=False,
- _cte_alias=None,
- _restates=frozenset()):
+ name=None,
+ recursive=False,
+ _cte_alias=None,
+ _restates=frozenset()):
self.recursive = recursive
self._cte_alias = _cte_alias
self._restates = _restates
@@ -1087,7 +1099,7 @@ class CTE(Alias):
name=name,
recursive=self.recursive,
_cte_alias=self,
- )
+ )
def union(self, other):
return CTE(
@@ -1106,8 +1118,6 @@ class CTE(Alias):
)
-
-
class FromGrouping(FromClause):
"""Represent a grouping of a FROM clause"""
__visit_name__ = 'grouping'
@@ -1159,6 +1169,7 @@ class FromGrouping(FromClause):
def __setstate__(self, state):
self.element = state['element']
+
class TableClause(Immutable, FromClause):
"""Represents a minimal "table" construct.
@@ -1257,10 +1268,10 @@ class TableClause(Immutable, FromClause):
else:
col = list(self.columns)[0]
return Select(
- [functions.func.count(col).label('tbl_row_count')],
- whereclause,
- from_obj=[self],
- **params)
+ [functions.func.count(col).label('tbl_row_count')],
+ whereclause,
+ from_obj=[self],
+ **params)
@util.dependencies("sqlalchemy.sql.dml")
def insert(self, dml, values=None, inline=False, **kwargs):
@@ -1278,7 +1289,8 @@ class TableClause(Immutable, FromClause):
return dml.Insert(self, values=values, inline=inline, **kwargs)
@util.dependencies("sqlalchemy.sql.dml")
- def update(self, dml, whereclause=None, values=None, inline=False, **kwargs):
+ def update(
+ self, dml, whereclause=None, values=None, inline=False, **kwargs):
"""Generate an :func:`.update` construct against this
:class:`.TableClause`.
@@ -1291,7 +1303,7 @@ class TableClause(Immutable, FromClause):
"""
return dml.Update(self, whereclause=whereclause,
- values=values, inline=inline, **kwargs)
+ values=values, inline=inline, **kwargs)
@util.dependencies("sqlalchemy.sql.dml")
def delete(self, dml, whereclause=None, **kwargs):
@@ -1377,7 +1389,7 @@ class ForUpdateArg(ClauseElement):
self.read = read
if of is not None:
self.of = [_interpret_as_column_or_from(elem)
- for elem in util.to_list(of)]
+ for elem in util.to_list(of)]
else:
self.of = None
@@ -1405,7 +1417,6 @@ class SelectBase(Executable, FromClause):
"""
return ScalarSelect(self)
-
def label(self, name):
"""return a 'scalar' representation of this selectable, embedded as a
subquery with a label.
@@ -1449,8 +1460,8 @@ class SelectBase(Executable, FromClause):
Example 1, non recursive::
- from sqlalchemy import Table, Column, String, Integer, MetaData, \\
- select, func
+ from sqlalchemy import (Table, Column, String, Integer,
+ MetaData, select, func)
metadata = MetaData()
@@ -1488,8 +1499,8 @@ class SelectBase(Executable, FromClause):
Example 2, WITH RECURSIVE::
- from sqlalchemy import Table, Column, String, Integer, MetaData, \\
- select, func
+ from sqlalchemy import (Table, Column, String, Integer,
+ MetaData, select, func)
metadata = MetaData()
@@ -1530,7 +1541,8 @@ class SelectBase(Executable, FromClause):
.. seealso::
- :meth:`.orm.query.Query.cte` - ORM version of :meth:`.SelectBase.cte`.
+ :meth:`.orm.query.Query.cte` - ORM version of
+ :meth:`.SelectBase.cte`.
"""
return CTE(self, name=name, recursive=recursive)
@@ -1561,21 +1573,22 @@ class SelectBase(Executable, FromClause):
def _from_objects(self):
return [self]
+
class GenerativeSelect(SelectBase):
"""Base class for SELECT statements where additional elements can be
added.
This serves as the base for :class:`.Select` and :class:`.CompoundSelect`
- where elements such as ORDER BY, GROUP BY can be added and column rendering
- can be controlled. Compare to :class:`.TextAsFrom`, which, while it
- subclasses :class:`.SelectBase` and is also a SELECT construct, represents
- a fixed textual string which cannot be altered at this level, only
- wrapped as a subquery.
+ where elements such as ORDER BY, GROUP BY can be added and column
+ rendering can be controlled. Compare to :class:`.TextAsFrom`, which,
+ while it subclasses :class:`.SelectBase` and is also a SELECT construct,
+ represents a fixed textual string which cannot be altered at this level,
+ only wrapped as a subquery.
.. versionadded:: 0.9.0 :class:`.GenerativeSelect` was added to
- provide functionality specific to :class:`.Select` and :class:`.CompoundSelect`
- while allowing :class:`.SelectBase` to be used for other SELECT-like
- objects, e.g. :class:`.TextAsFrom`.
+ provide functionality specific to :class:`.Select` and
+ :class:`.CompoundSelect` while allowing :class:`.SelectBase` to be
+ used for other SELECT-like objects, e.g. :class:`.TextAsFrom`.
"""
_order_by_clause = ClauseList()
@@ -1585,18 +1598,19 @@ class GenerativeSelect(SelectBase):
_for_update_arg = None
def __init__(self,
- use_labels=False,
- for_update=False,
- limit=None,
- offset=None,
- order_by=None,
- group_by=None,
- bind=None,
- autocommit=None):
+ use_labels=False,
+ for_update=False,
+ limit=None,
+ offset=None,
+ order_by=None,
+ group_by=None,
+ bind=None,
+ autocommit=None):
self.use_labels = use_labels
if for_update is not False:
- self._for_update_arg = ForUpdateArg.parse_legacy_select(for_update)
+ self._for_update_arg = (ForUpdateArg.
+ parse_legacy_select(for_update))
if autocommit is not None:
util.warn_deprecated('autocommit on select() is '
@@ -1604,7 +1618,7 @@ class GenerativeSelect(SelectBase):
'utocommit=True)')
self._execution_options = \
self._execution_options.union(
- {'autocommit': autocommit})
+ {'autocommit': autocommit})
if limit is not None:
self._limit_clause = _offset_or_limit_clause(limit)
if offset is not None:
@@ -1652,8 +1666,8 @@ class GenerativeSelect(SelectBase):
provided which allow for common database-specific
variants.
- :param nowait: boolean; will render ``FOR UPDATE NOWAIT`` on Oracle and
- Postgresql dialects.
+ :param nowait: boolean; will render ``FOR UPDATE NOWAIT`` on Oracle
+ and Postgresql dialects.
:param read: boolean; will render ``LOCK IN SHARE MODE`` on MySQL,
``FOR SHARE`` on Postgresql. On Postgresql, when combined with
@@ -1761,8 +1775,8 @@ class GenerativeSelect(SelectBase):
The criterion will be appended to any pre-existing ORDER BY criterion.
This is an **in-place** mutation method; the
- :meth:`~.GenerativeSelect.order_by` method is preferred, as it provides standard
- :term:`method chaining`.
+ :meth:`~.GenerativeSelect.order_by` method is preferred, as it
+ provides standard :term:`method chaining`.
"""
if len(clauses) == 1 and clauses[0] is None:
@@ -1778,8 +1792,8 @@ class GenerativeSelect(SelectBase):
The criterion will be appended to any pre-existing GROUP BY criterion.
This is an **in-place** mutation method; the
- :meth:`~.GenerativeSelect.group_by` method is preferred, as it provides standard
- :term:`method chaining`.
+ :meth:`~.GenerativeSelect.group_by` method is preferred, as it
+ provides standard :term:`method chaining`.
"""
if len(clauses) == 1 and clauses[0] is None:
@@ -1789,13 +1803,13 @@ class GenerativeSelect(SelectBase):
clauses = list(self._group_by_clause) + list(clauses)
self._group_by_clause = ClauseList(*clauses)
-
def _copy_internals(self, clone=_clone, **kw):
if self._limit_clause is not None:
self._limit_clause = clone(self._limit_clause, **kw)
if self._offset_clause is not None:
self._offset_clause = clone(self._offset_clause, **kw)
+
class CompoundSelect(GenerativeSelect):
"""Forms the basis of ``UNION``, ``UNION ALL``, and other
SELECT-based set operations.
@@ -1842,11 +1856,14 @@ class CompoundSelect(GenerativeSelect):
if not numcols:
numcols = len(s.c._all_columns)
elif len(s.c._all_columns) != numcols:
- raise exc.ArgumentError('All selectables passed to '
- 'CompoundSelect must have identical numbers of '
- 'columns; select #%d has %d columns, select '
- '#%d has %d' % (1, len(self.selects[0].c._all_columns), n
- + 1, len(s.c._all_columns)))
+ raise exc.ArgumentError(
+ 'All selectables passed to '
+ 'CompoundSelect must have identical numbers of '
+ 'columns; select #%d has %d columns, select '
+ '#%d has %d' %
+ (1, len(self.selects[0].c._all_columns),
+ n + 1, len(s.c._all_columns))
+ )
self.selects.append(s.self_group(self))
@@ -1892,7 +1909,6 @@ class CompoundSelect(GenerativeSelect):
"""
return CompoundSelect(CompoundSelect.UNION_ALL, *selects, **kwargs)
-
@classmethod
def _create_except(cls, *selects, **kwargs):
"""Return an ``EXCEPT`` of multiple selectables.
@@ -1910,7 +1926,6 @@ class CompoundSelect(GenerativeSelect):
"""
return CompoundSelect(CompoundSelect.EXCEPT, *selects, **kwargs)
-
@classmethod
def _create_except_all(cls, *selects, **kwargs):
"""Return an ``EXCEPT ALL`` of multiple selectables.
@@ -1928,7 +1943,6 @@ class CompoundSelect(GenerativeSelect):
"""
return CompoundSelect(CompoundSelect.EXCEPT_ALL, *selects, **kwargs)
-
@classmethod
def _create_intersect(cls, *selects, **kwargs):
"""Return an ``INTERSECT`` of multiple selectables.
@@ -1946,7 +1960,6 @@ class CompoundSelect(GenerativeSelect):
"""
return CompoundSelect(CompoundSelect.INTERSECT, *selects, **kwargs)
-
@classmethod
def _create_intersect_all(cls, *selects, **kwargs):
"""Return an ``INTERSECT ALL`` of multiple selectables.
@@ -1962,8 +1975,8 @@ class CompoundSelect(GenerativeSelect):
:func:`select`.
"""
- return CompoundSelect(CompoundSelect.INTERSECT_ALL, *selects, **kwargs)
-
+ return CompoundSelect(
+ CompoundSelect.INTERSECT_ALL, *selects, **kwargs)
def _scalar_type(self):
return self.selects[0]._scalar_type()
@@ -1990,9 +2003,9 @@ class CompoundSelect(GenerativeSelect):
# ForeignKeys in. this would allow the union() to have all
# those fks too.
- proxy = cols[0]._make_proxy(self,
- name=cols[0]._label if self.use_labels else None,
- key=cols[0]._key_label if self.use_labels else None)
+ proxy = cols[0]._make_proxy(
+ self, name=cols[0]._label if self.use_labels else None,
+ key=cols[0]._key_label if self.use_labels else None)
# hand-construct the "_proxies" collection to include all
# derived columns place a 'weight' annotation corresponding
@@ -2000,8 +2013,8 @@ class CompoundSelect(GenerativeSelect):
# that the corresponding_column() operation can resolve
# conflicts
- proxy._proxies = [c._annotate({'weight': i + 1}) for (i,
- c) in enumerate(cols)]
+ proxy._proxies = [
+ c._annotate({'weight': i + 1}) for (i, c) in enumerate(cols)]
def _refresh_for_new_column(self, column):
for s in self.selects:
@@ -2011,7 +2024,8 @@ class CompoundSelect(GenerativeSelect):
return None
raise NotImplementedError("CompoundSelect constructs don't support "
- "addition of columns to underlying selectables")
+ "addition of columns to underlying "
+ "selectables")
def _copy_internals(self, clone=_clone, **kw):
super(CompoundSelect, self)._copy_internals(clone, **kw)
@@ -2019,7 +2033,8 @@ class CompoundSelect(GenerativeSelect):
self.selects = [clone(s, **kw) for s in self.selects]
if hasattr(self, '_col_map'):
del self._col_map
- for attr in ('_order_by_clause', '_group_by_clause', '_for_update_arg'):
+ for attr in (
+ '_order_by_clause', '_group_by_clause', '_for_update_arg'):
if getattr(self, attr) is not None:
setattr(self, attr, clone(getattr(self, attr), **kw))
@@ -2072,13 +2087,12 @@ class HasPrefixes(object):
dialect = kw.pop('dialect', None)
if kw:
raise exc.ArgumentError("Unsupported argument(s): %s" %
- ",".join(kw))
+ ",".join(kw))
self._setup_prefixes(expr, dialect)
def _setup_prefixes(self, prefixes, dialect=None):
self._prefixes = self._prefixes + tuple(
- [(_literal_as_text(p), dialect) for p in prefixes])
-
+ [(_literal_as_text(p), dialect) for p in prefixes])
class Select(HasPrefixes, GenerativeSelect):
@@ -2098,21 +2112,21 @@ class Select(HasPrefixes, GenerativeSelect):
_is_select = True
def __init__(self,
- columns=None,
- whereclause=None,
- from_obj=None,
- distinct=False,
- having=None,
- correlate=True,
- prefixes=None,
- **kwargs):
+ columns=None,
+ whereclause=None,
+ from_obj=None,
+ distinct=False,
+ having=None,
+ correlate=True,
+ prefixes=None,
+ **kwargs):
"""Construct a new :class:`.Select`.
- Similar functionality is also available via the :meth:`.FromClause.select`
- method on any :class:`.FromClause`.
+ Similar functionality is also available via the
+ :meth:`.FromClause.select` method on any :class:`.FromClause`.
- All arguments which accept :class:`.ClauseElement` arguments also accept
- string arguments, which will be converted as appropriate into
+ All arguments which accept :class:`.ClauseElement` arguments also
+ accept string arguments, which will be converted as appropriate into
either :func:`text()` or :func:`literal_column()` constructs.
.. seealso::
@@ -2124,12 +2138,12 @@ class Select(HasPrefixes, GenerativeSelect):
A list of :class:`.ClauseElement` objects, typically
:class:`.ColumnElement` objects or subclasses, which will form the
columns clause of the resulting statement. For all members which are
- instances of :class:`.Selectable`, the individual :class:`.ColumnElement`
- members of the :class:`.Selectable` will be added individually to the
- columns clause. For example, specifying a
+ instances of :class:`.Selectable`, the individual
+ :class:`.ColumnElement` members of the :class:`.Selectable` will be
+ added individually to the columns clause. For example, specifying a
:class:`~sqlalchemy.schema.Table` instance will result in all the
- contained :class:`~sqlalchemy.schema.Column` objects within to be added
- to the columns clause.
+ contained :class:`~sqlalchemy.schema.Column` objects within to be
+ added to the columns clause.
This argument is not present on the form of :func:`select()`
available on :class:`~sqlalchemy.schema.Table`.
@@ -2140,14 +2154,14 @@ class Select(HasPrefixes, GenerativeSelect):
:param from_obj:
A list of :class:`.ClauseElement` objects which will be added to the
- ``FROM`` clause of the resulting statement. Note that "from" objects are
- automatically located within the columns and whereclause ClauseElements.
- Use this parameter to explicitly specify "from" objects which are not
- automatically locatable. This could include
- :class:`~sqlalchemy.schema.Table` objects that aren't otherwise present,
- or :class:`.Join` objects whose presence will supersede that of the
- :class:`~sqlalchemy.schema.Table` objects already located in the other
- clauses.
+ ``FROM`` clause of the resulting statement. Note that "from" objects
+ are automatically located within the columns and whereclause
+ ClauseElements. Use this parameter to explicitly specify "from"
+ objects which are not automatically locatable. This could include
+ :class:`~sqlalchemy.schema.Table` objects that aren't otherwise
+ present, or :class:`.Join` objects whose presence will supersede
+ that of the :class:`~sqlalchemy.schema.Table` objects already
+ located in the other clauses.
:param autocommit:
Deprecated. Use .execution_options(autocommit=<True|False>)
@@ -2156,19 +2170,19 @@ class Select(HasPrefixes, GenerativeSelect):
:param bind=None:
an :class:`~.Engine` or :class:`~.Connection` instance
to which the
- resulting :class:`.Select` object will be bound. The :class:`.Select`
- object will otherwise automatically bind to whatever
- :class:`~.base.Connectable` instances can be located within its contained
- :class:`.ClauseElement` members.
+ resulting :class:`.Select` object will be bound. The
+ :class:`.Select` object will otherwise automatically bind to
+ whatever :class:`~.base.Connectable` instances can be located within
+ its contained :class:`.ClauseElement` members.
:param correlate=True:
indicates that this :class:`.Select` object should have its
contained :class:`.FromClause` elements "correlated" to an enclosing
- :class:`.Select` object. This means that any :class:`.ClauseElement`
- instance within the "froms" collection of this :class:`.Select`
- which is also present in the "froms" collection of an
- enclosing select will not be rendered in the ``FROM`` clause
- of this select statement.
+ :class:`.Select` object. This means that any
+ :class:`.ClauseElement` instance within the "froms" collection of
+ this :class:`.Select` which is also present in the "froms"
+ collection of an enclosing select will not be rendered in the
+ ``FROM`` clause of this select statement.
:param distinct=False:
when ``True``, applies a ``DISTINCT`` qualifier to the columns
@@ -2186,8 +2200,9 @@ class Select(HasPrefixes, GenerativeSelect):
when ``True``, applies ``FOR UPDATE`` to the end of the
resulting statement.
- .. deprecated:: 0.9.0 - use :meth:`.GenerativeSelect.with_for_update`
- to specify the structure of the ``FOR UPDATE`` clause.
+ .. deprecated:: 0.9.0 - use
+ :meth:`.GenerativeSelect.with_for_update` to specify the
+ structure of the ``FOR UPDATE`` clause.
``for_update`` accepts various string values interpreted by
specific backends, including:
@@ -2237,8 +2252,8 @@ class Select(HasPrefixes, GenerativeSelect):
collection of the resulting :class:`.Select` object will use these
names as well for targeting column members.
- use_labels is also available via the :meth:`~.GenerativeSelect.apply_labels`
- generative method.
+ use_labels is also available via the
+ :meth:`~.GenerativeSelect.apply_labels` generative method.
"""
self._auto_correlate = correlate
@@ -2247,14 +2262,14 @@ class Select(HasPrefixes, GenerativeSelect):
self._distinct = True
else:
self._distinct = [
- _literal_as_text(e)
- for e in util.to_list(distinct)
- ]
+ _literal_as_text(e)
+ for e in util.to_list(distinct)
+ ]
if from_obj is not None:
self._from_obj = util.OrderedSet(
- _interpret_as_from(f)
- for f in util.to_list(from_obj))
+ _interpret_as_from(f)
+ for f in util.to_list(from_obj))
else:
self._from_obj = util.OrderedSet()
@@ -2262,7 +2277,7 @@ class Select(HasPrefixes, GenerativeSelect):
cols_present = bool(columns)
except TypeError:
raise exc.ArgumentError("columns argument to select() must "
- "be a Python list or other iterable")
+ "be a Python list or other iterable")
if cols_present:
self._raw_columns = []
@@ -2275,12 +2290,14 @@ class Select(HasPrefixes, GenerativeSelect):
self._raw_columns = []
if whereclause is not None:
- self._whereclause = _literal_as_text(whereclause).self_group(against=operators._asbool)
+ self._whereclause = _literal_as_text(
+ whereclause).self_group(against=operators._asbool)
else:
self._whereclause = None
if having is not None:
- self._having = _literal_as_text(having).self_group(against=operators._asbool)
+ self._having = _literal_as_text(
+ having).self_group(against=operators._asbool)
else:
self._having = None
@@ -2303,7 +2320,7 @@ class Select(HasPrefixes, GenerativeSelect):
for item in items:
if item is self:
raise exc.InvalidRequestError(
- "select() construct refers to itself as a FROM")
+ "select() construct refers to itself as a FROM")
if translate and item in translate:
item = translate[item]
if not seen.intersection(item._cloned_set):
@@ -2318,7 +2335,7 @@ class Select(HasPrefixes, GenerativeSelect):
return froms
def _get_display_froms(self, explicit_correlate_froms=None,
- implicit_correlate_froms=None):
+ implicit_correlate_froms=None):
"""Return the full list of 'from' clauses to be displayed.
Takes into account a set of existing froms which may be
@@ -2330,8 +2347,8 @@ class Select(HasPrefixes, GenerativeSelect):
froms = self._froms
toremove = set(itertools.chain(*[
- _expand_cloned(f._hide_froms)
- for f in froms]))
+ _expand_cloned(f._hide_froms)
+ for f in froms]))
if toremove:
# if we're maintaining clones of froms,
# add the copies out to the toremove list. only include
@@ -2352,7 +2369,8 @@ class Select(HasPrefixes, GenerativeSelect):
froms = [
f for f in froms if f not in
_cloned_intersection(
- _cloned_intersection(froms, explicit_correlate_froms or ()),
+ _cloned_intersection(
+ froms, explicit_correlate_froms or ()),
to_correlate
)
]
@@ -2362,14 +2380,15 @@ class Select(HasPrefixes, GenerativeSelect):
froms = [
f for f in froms if f not in
_cloned_difference(
- _cloned_intersection(froms, explicit_correlate_froms or ()),
+ _cloned_intersection(
+ froms, explicit_correlate_froms or ()),
self._correlate_except
)
]
if self._auto_correlate and \
- implicit_correlate_froms and \
- len(froms) > 1:
+ implicit_correlate_froms and \
+ len(froms) > 1:
froms = [
f for f in froms if f not in
@@ -2378,10 +2397,11 @@ class Select(HasPrefixes, GenerativeSelect):
if not len(froms):
raise exc.InvalidRequestError("Select statement '%s"
- "' returned no FROM clauses due to "
- "auto-correlation; specify "
- "correlate(<tables>) to control "
- "correlation manually." % self)
+ "' returned no FROM clauses "
+ "due to auto-correlation; "
+ "specify correlate(<tables>) "
+ "to control correlation "
+ "manually." % self)
return froms
@@ -2422,18 +2442,20 @@ class Select(HasPrefixes, GenerativeSelect):
and Sybase simultaneously::
select([mytable]).\\
- with_hint(mytable, "+ index(%(name)s ix_mytable)", 'oracle').\\
+ with_hint(
+ mytable, "+ index(%(name)s ix_mytable)", 'oracle').\\
with_hint(mytable, "WITH INDEX ix_mytable", 'sybase')
"""
self._hints = self._hints.union(
- {(selectable, dialect_name): text})
+ {(selectable, dialect_name): text})
@property
def type(self):
raise exc.InvalidRequestError("Select objects don't have a type. "
- "Call as_scalar() on this Select object "
- "to return a 'scalar' version of this Select.")
+ "Call as_scalar() on this Select "
+ "object to return a 'scalar' version "
+ "of this Select.")
@_memoized_property.method
def locate_all_froms(self):
@@ -2478,12 +2500,12 @@ class Select(HasPrefixes, GenerativeSelect):
# as of 0.7.4 we also put the current version of _froms, which
# gets cleared on each generation. previously we were "baking"
# _froms into self._from_obj.
- self._from_cloned = from_cloned = dict((f, clone(f, **kw))
- for f in self._from_obj.union(self._froms))
+ self._from_cloned = from_cloned = dict(
+ (f, clone(f, **kw)) for f in self._from_obj.union(self._froms))
# 3. update persistent _from_obj with the cloned versions.
self._from_obj = util.OrderedSet(from_cloned[f] for f in
- self._from_obj)
+ self._from_obj)
# the _correlate collection is done separately, what can happen
# here is the same item is _correlate as in _from_obj but the
@@ -2501,7 +2523,7 @@ class Select(HasPrefixes, GenerativeSelect):
# present here.
self._raw_columns = [clone(c, **kw) for c in self._raw_columns]
for attr in '_whereclause', '_having', '_order_by_clause', \
- '_group_by_clause', '_for_update_arg':
+ '_group_by_clause', '_for_update_arg':
if getattr(self, attr) is not None:
setattr(self, attr, clone(getattr(self, attr), **kw))
@@ -2517,7 +2539,7 @@ class Select(HasPrefixes, GenerativeSelect):
[x for x in
(self._whereclause, self._having,
self._order_by_clause, self._group_by_clause)
- if x is not None]
+ if x is not None]
@_generative
def column(self, column):
@@ -2552,12 +2574,12 @@ class Select(HasPrefixes, GenerativeSelect):
"""
return self.with_only_columns(
- sqlutil.reduce_columns(
- self.inner_columns,
- only_synonyms=only_synonyms,
- *(self._whereclause, ) + tuple(self._from_obj)
- )
+ sqlutil.reduce_columns(
+ self.inner_columns,
+ only_synonyms=only_synonyms,
+ *(self._whereclause, ) + tuple(self._from_obj)
)
+ )
@_generative
def with_only_columns(self, columns):
@@ -2764,16 +2786,16 @@ class Select(HasPrefixes, GenerativeSelect):
:meth:`.Select.correlate`.
.. versionchanged:: 0.8.0 The :meth:`.Select.correlate` method no
- longer unconditionally removes entries from the FROM clause; instead,
- the candidate FROM entries must also be matched by a FROM entry
- located in an enclosing :class:`.Select`, which ultimately encloses
- this one as present in the WHERE clause, ORDER BY clause, HAVING
- clause, or columns clause of an enclosing :meth:`.Select`.
+ longer unconditionally removes entries from the FROM clause;
+ instead, the candidate FROM entries must also be matched by a FROM
+ entry located in an enclosing :class:`.Select`, which ultimately
+ encloses this one as present in the WHERE clause, ORDER BY clause,
+ HAVING clause, or columns clause of an enclosing :meth:`.Select`.
.. versionchanged:: 0.8.2 explicit correlation takes place
via any level of nesting of :class:`.Select` objects; in previous
- 0.8 versions, correlation would only occur relative to the immediate
- enclosing :class:`.Select` construct.
+ 0.8 versions, correlation would only occur relative to the
+ immediate enclosing :class:`.Select` construct.
.. seealso::
@@ -2787,7 +2809,7 @@ class Select(HasPrefixes, GenerativeSelect):
self._correlate = ()
else:
self._correlate = set(self._correlate).union(
- _interpret_as_from(f) for f in fromclauses)
+ _interpret_as_from(f) for f in fromclauses)
@_generative
def correlate_except(self, *fromclauses):
@@ -2829,21 +2851,21 @@ class Select(HasPrefixes, GenerativeSelect):
self._correlate_except = ()
else:
self._correlate_except = set(self._correlate_except or ()).union(
- _interpret_as_from(f) for f in fromclauses)
+ _interpret_as_from(f) for f in fromclauses)
def append_correlation(self, fromclause):
"""append the given correlation expression to this select()
construct.
This is an **in-place** mutation method; the
- :meth:`~.Select.correlate` method is preferred, as it provides standard
- :term:`method chaining`.
+ :meth:`~.Select.correlate` method is preferred, as it provides
+ standard :term:`method chaining`.
"""
self._auto_correlate = False
self._correlate = set(self._correlate).union(
- _interpret_as_from(f) for f in fromclause)
+ _interpret_as_from(f) for f in fromclause)
def append_column(self, column):
"""append the given column expression to the columns clause of this
@@ -2867,8 +2889,8 @@ class Select(HasPrefixes, GenerativeSelect):
construct.
This is an **in-place** mutation method; the
- :meth:`~.Select.prefix_with` method is preferred, as it provides standard
- :term:`method chaining`.
+ :meth:`~.Select.prefix_with` method is preferred, as it provides
+ standard :term:`method chaining`.
"""
clause = _literal_as_text(clause)
@@ -2887,7 +2909,8 @@ class Select(HasPrefixes, GenerativeSelect):
"""
self._reset_exported()
- self._whereclause = and_(True_._ifnone(self._whereclause), whereclause)
+ self._whereclause = and_(
+ True_._ifnone(self._whereclause), whereclause)
def append_having(self, having):
"""append the given expression to this select() construct's HAVING
@@ -2908,19 +2931,19 @@ class Select(HasPrefixes, GenerativeSelect):
FROM clause.
This is an **in-place** mutation method; the
- :meth:`~.Select.select_from` method is preferred, as it provides standard
- :term:`method chaining`.
+ :meth:`~.Select.select_from` method is preferred, as it provides
+ standard :term:`method chaining`.
"""
self._reset_exported()
fromclause = _interpret_as_from(fromclause)
self._from_obj = self._from_obj.union([fromclause])
-
@_memoized_property
def _columns_plus_names(self):
if self.use_labels:
names = set()
+
def name_for_col(c):
if c._label is None:
return (None, c)
@@ -2933,12 +2956,14 @@ class Select(HasPrefixes, GenerativeSelect):
return [
name_for_col(c)
- for c in util.unique_list(_select_iterables(self._raw_columns))
+ for c in util.unique_list(
+ _select_iterables(self._raw_columns))
]
else:
return [
(None, c)
- for c in util.unique_list(_select_iterables(self._raw_columns))
+ for c in util.unique_list(
+ _select_iterables(self._raw_columns))
]
def _populate_column_collection(self):
@@ -2955,8 +2980,8 @@ class Select(HasPrefixes, GenerativeSelect):
key = None
c._make_proxy(self, key=key,
- name=name,
- name_is_truncatable=True)
+ name=name,
+ name_is_truncatable=True)
def _refresh_for_new_column(self, column):
for fromclause in self._froms:
@@ -2965,7 +2990,8 @@ class Select(HasPrefixes, GenerativeSelect):
if col in self.inner_columns and self._cols_populated:
our_label = col._key_label if self.use_labels else col.key
if our_label not in self.c:
- return col._make_proxy(self,
+ return col._make_proxy(
+ self,
name=col._label if self.use_labels else None,
key=col._key_label if self.use_labels else None,
name_is_truncatable=True)
@@ -3059,8 +3085,8 @@ class ScalarSelect(Generative, Grouping):
@property
def columns(self):
raise exc.InvalidRequestError('Scalar Select expression has no '
- 'columns; use this object directly within a '
- 'column-level expression.')
+ 'columns; use this object directly '
+ 'within a column-level expression.')
c = columns
@_generative
@@ -3082,7 +3108,6 @@ class Exists(UnaryExpression):
__visit_name__ = UnaryExpression.__visit_name__
_from_objects = []
-
def __init__(self, *args, **kwargs):
"""Construct a new :class:`.Exists` against an existing
:class:`.Select` object.
@@ -3109,7 +3134,7 @@ class Exists(UnaryExpression):
s = Select(*args, **kwargs).as_scalar().self_group()
UnaryExpression.__init__(self, s, operator=operators.exists,
- type_=type_api.BOOLEANTYPE)
+ type_=type_api.BOOLEANTYPE)
def select(self, whereclause=None, **params):
return Select([self], whereclause, **params)
@@ -3148,8 +3173,8 @@ class TextAsFrom(SelectBase):
"""Wrap a :class:`.TextClause` construct within a :class:`.SelectBase`
interface.
- This allows the :class:`.TextClause` object to gain a ``.c`` collection and
- other FROM-like capabilities such as :meth:`.FromClause.alias`,
+ This allows the :class:`.TextClause` object to gain a ``.c`` collection
+ and other FROM-like capabilities such as :meth:`.FromClause.alias`,
:meth:`.SelectBase.cte`, etc.
The :class:`.TextAsFrom` construct is produced via the
@@ -3191,11 +3216,10 @@ class TextAsFrom(SelectBase):
def _scalar_type(self):
return self.column_args[0].type
+
class AnnotatedFromClause(Annotated):
def __init__(self, element, values):
# force FromClause to generate their internal
# collections into __dict__
element.c
Annotated.__init__(self, element, values)
-
-
diff --git a/lib/sqlalchemy/sql/sqltypes.py b/lib/sqlalchemy/sql/sqltypes.py
index 52e5053ef..a7f25bbfa 100644
--- a/lib/sqlalchemy/sql/sqltypes.py
+++ b/lib/sqlalchemy/sql/sqltypes.py
@@ -25,7 +25,9 @@ import decimal
if util.jython:
import array
+
class _DateAffinity(object):
+
"""Mixin date/time specific expression adaptations.
Rules are implemented within Date,Time,Interval,DateTime, Numeric,
@@ -43,19 +45,28 @@ class _DateAffinity(object):
def _adapt_expression(self, op, other_comparator):
othertype = other_comparator.type._type_affinity
- return op, \
- to_instance(self.type._expression_adaptations.get(op, self._blank_dict).\
+ return (
+ op, to_instance(
+ self.type._expression_adaptations.
+ get(op, self._blank_dict).
get(othertype, NULLTYPE))
+ )
comparator_factory = Comparator
+
class Concatenable(object):
+
"""A mixin that marks a type as supporting 'concatenation',
typically strings."""
class Comparator(TypeEngine.Comparator):
+
def _adapt_expression(self, op, other_comparator):
- if op is operators.add and isinstance(other_comparator,
- (Concatenable.Comparator, NullType.Comparator)):
+ if (op is operators.add and
+ isinstance(
+ other_comparator,
+ (Concatenable.Comparator, NullType.Comparator)
+ )):
return operators.concat_op, self.expr.type
else:
return op, self.expr.type
@@ -64,6 +75,7 @@ class Concatenable(object):
class String(Concatenable, TypeEngine):
+
"""The base for all string and character types.
In SQL, corresponds to VARCHAR. Can also take Python unicode objects
@@ -79,10 +91,10 @@ class String(Concatenable, TypeEngine):
__visit_name__ = 'string'
def __init__(self, length=None, collation=None,
- convert_unicode=False,
- unicode_error=None,
- _warn_on_bytestring=False
- ):
+ convert_unicode=False,
+ unicode_error=None,
+ _warn_on_bytestring=False
+ ):
"""
Create a string-holding type.
@@ -147,7 +159,7 @@ class String(Concatenable, TypeEngine):
"""
if unicode_error is not None and convert_unicode != 'force':
raise exc.ArgumentError("convert_unicode must be 'force' "
- "when unicode_error is set.")
+ "when unicode_error is set.")
self.length = length
self.collation = collation
@@ -164,12 +176,12 @@ class String(Concatenable, TypeEngine):
def bind_processor(self, dialect):
if self.convert_unicode or dialect.convert_unicode:
if dialect.supports_unicode_binds and \
- self.convert_unicode != 'force':
+ self.convert_unicode != 'force':
if self._warn_on_bytestring:
def process(value):
if isinstance(value, util.binary_type):
- util.warn("Unicode type received non-unicode bind "
- "param value.")
+ util.warn("Unicode type received non-unicode"
+ "bind param value.")
return value
return process
else:
@@ -192,23 +204,23 @@ class String(Concatenable, TypeEngine):
def result_processor(self, dialect, coltype):
wants_unicode = self.convert_unicode or dialect.convert_unicode
needs_convert = wants_unicode and \
- (dialect.returns_unicode_strings is not True or
- self.convert_unicode in ('force', 'force_nocheck'))
+ (dialect.returns_unicode_strings is not True or
+ self.convert_unicode in ('force', 'force_nocheck'))
needs_isinstance = (
- needs_convert and
- dialect.returns_unicode_strings and
- self.convert_unicode != 'force_nocheck'
- )
+ needs_convert and
+ dialect.returns_unicode_strings and
+ self.convert_unicode != 'force_nocheck'
+ )
if needs_convert:
to_unicode = processors.to_unicode_processor_factory(
- dialect.encoding, self.unicode_error)
+ dialect.encoding, self.unicode_error)
if needs_isinstance:
return processors.to_conditional_unicode_processor_factory(
- dialect.encoding, self.unicode_error)
+ dialect.encoding, self.unicode_error)
else:
return processors.to_unicode_processor_factory(
- dialect.encoding, self.unicode_error)
+ dialect.encoding, self.unicode_error)
else:
return None
@@ -224,6 +236,7 @@ class String(Concatenable, TypeEngine):
class Text(String):
+
"""A variably sized string type.
In SQL, usually corresponds to CLOB or TEXT. Can also take Python
@@ -237,6 +250,7 @@ class Text(String):
class Unicode(String):
+
"""A variable length Unicode string type.
The :class:`.Unicode` type is a :class:`.String` subclass
@@ -308,6 +322,7 @@ class Unicode(String):
class UnicodeText(Text):
+
"""An unbounded-length Unicode string type.
See :class:`.Unicode` for details on the unicode
@@ -336,6 +351,7 @@ class UnicodeText(Text):
class Integer(_DateAffinity, TypeEngine):
+
"""A type for ``int`` integers."""
__visit_name__ = 'integer'
@@ -382,8 +398,8 @@ class Integer(_DateAffinity, TypeEngine):
}
-
class SmallInteger(Integer):
+
"""A type for smaller ``int`` integers.
Typically generates a ``SMALLINT`` in DDL, and otherwise acts like
@@ -395,6 +411,7 @@ class SmallInteger(Integer):
class BigInteger(Integer):
+
"""A type for bigger ``int`` integers.
Typically generates a ``BIGINT`` in DDL, and otherwise acts like
@@ -405,13 +422,13 @@ class BigInteger(Integer):
__visit_name__ = 'big_integer'
-
class Numeric(_DateAffinity, TypeEngine):
+
"""A type for fixed precision numbers, such as ``NUMERIC`` or ``DECIMAL``.
- This type returns Python ``decimal.Decimal`` objects by default, unless the
- :paramref:`.Numeric.asdecimal` flag is set to False, in which case they
- are coerced to Python ``float`` objects.
+ This type returns Python ``decimal.Decimal`` objects by default, unless
+ the :paramref:`.Numeric.asdecimal` flag is set to False, in which case
+ they are coerced to Python ``float`` objects.
.. note::
@@ -421,8 +438,8 @@ class Numeric(_DateAffinity, TypeEngine):
type (e.g. ``FLOAT``, ``REAL``, others).
If the database column on the server is in fact a floating-point type
type, such as ``FLOAT`` or ``REAL``, use the :class:`.Float`
- type or a subclass, otherwise numeric coercion between ``float``/``Decimal``
- may or may not function as expected.
+ type or a subclass, otherwise numeric coercion between
+ ``float``/``Decimal`` may or may not function as expected.
.. note::
@@ -450,7 +467,7 @@ class Numeric(_DateAffinity, TypeEngine):
_default_decimal_return_scale = 10
def __init__(self, precision=None, scale=None,
- decimal_return_scale=None, asdecimal=True):
+ decimal_return_scale=None, asdecimal=True):
"""
Construct a Numeric.
@@ -471,9 +488,10 @@ class Numeric(_DateAffinity, TypeEngine):
database types don't have a notion of "scale", so by default the
float type looks for the first ten decimal places when converting.
Specfiying this value will override that length. Types which
- do include an explicit ".scale" value, such as the base :class:`.Numeric`
- as well as the MySQL float types, will use the value of ".scale"
- as the default for decimal_return_scale, if not otherwise specified.
+ do include an explicit ".scale" value, such as the base
+ :class:`.Numeric` as well as the MySQL float types, will use the
+ value of ".scale" as the default for decimal_return_scale, if not
+ otherwise specified.
.. versionadded:: 0.9.0
@@ -545,9 +563,9 @@ class Numeric(_DateAffinity, TypeEngine):
# we're a "numeric", DBAPI returns floats, convert.
return processors.to_decimal_processor_factory(
- decimal.Decimal,
- self.scale if self.scale is not None
- else self._default_decimal_return_scale)
+ decimal.Decimal,
+ self.scale if self.scale is not None
+ else self._default_decimal_return_scale)
else:
if dialect.supports_native_decimal:
return processors.to_float
@@ -582,6 +600,7 @@ class Numeric(_DateAffinity, TypeEngine):
class Float(Numeric):
+
"""Type representing floating point types, such as ``FLOAT`` or ``REAL``.
This type returns Python ``float`` objects by default, unless the
@@ -596,8 +615,8 @@ class Float(Numeric):
and not a decimal type (e.g. ``DECIMAL``, ``NUMERIC``, others).
If the database column on the server is in fact a Numeric
type, such as ``DECIMAL`` or ``NUMERIC``, use the :class:`.Numeric`
- type or a subclass, otherwise numeric coercion between ``float``/``Decimal``
- may or may not function as expected.
+ type or a subclass, otherwise numeric coercion between
+ ``float``/``Decimal`` may or may not function as expected.
"""
@@ -606,7 +625,7 @@ class Float(Numeric):
scale = None
def __init__(self, precision=None, asdecimal=False,
- decimal_return_scale=None, **kwargs):
+ decimal_return_scale=None, **kwargs):
"""
Construct a Float.
@@ -640,13 +659,13 @@ class Float(Numeric):
self.decimal_return_scale = decimal_return_scale
if kwargs:
util.warn_deprecated("Additional keyword arguments "
- "passed to Float ignored.")
+ "passed to Float ignored.")
def result_processor(self, dialect, coltype):
if self.asdecimal:
return processors.to_decimal_processor_factory(
- decimal.Decimal,
- self._effective_decimal_return_scale)
+ decimal.Decimal,
+ self._effective_decimal_return_scale)
else:
return None
@@ -673,6 +692,7 @@ class Float(Numeric):
class DateTime(_DateAffinity, TypeEngine):
+
"""A type for ``datetime.datetime()`` objects.
Date and time types return objects from the Python ``datetime``
@@ -717,6 +737,7 @@ class DateTime(_DateAffinity, TypeEngine):
class Date(_DateAffinity, TypeEngine):
+
"""A type for ``datetime.date()`` objects."""
__visit_name__ = 'date'
@@ -754,6 +775,7 @@ class Date(_DateAffinity, TypeEngine):
class Time(_DateAffinity, TypeEngine):
+
"""A type for ``datetime.time()`` objects."""
__visit_name__ = 'time'
@@ -783,6 +805,7 @@ class Time(_DateAffinity, TypeEngine):
class _Binary(TypeEngine):
+
"""Define base behavior for binary types."""
def __init__(self, length=None):
@@ -850,6 +873,7 @@ class _Binary(TypeEngine):
class LargeBinary(_Binary):
+
"""A type for large binary byte data.
The Binary type generates BLOB or BYTEA when tables are created,
@@ -878,6 +902,7 @@ class LargeBinary(_Binary):
class Binary(LargeBinary):
+
"""Deprecated. Renamed to LargeBinary."""
def __init__(self, *arg, **kw):
@@ -886,8 +911,8 @@ class Binary(LargeBinary):
LargeBinary.__init__(self, *arg, **kw)
-
class SchemaType(SchemaEventTarget):
+
"""Mark a type as possibly requiring schema-level DDL for usage.
Supports types that must be explicitly created/dropped (i.e. PG ENUM type)
@@ -910,7 +935,7 @@ class SchemaType(SchemaEventTarget):
"""
def __init__(self, name=None, schema=None, metadata=None,
- inherit_schema=False, quote=None):
+ inherit_schema=False, quote=None):
if name is not None:
self.name = quoted_name(name, quote)
else:
@@ -941,8 +966,8 @@ class SchemaType(SchemaEventTarget):
event.listen(
table,
"before_create",
- util.portable_instancemethod(
- self._on_table_create)
+ util.portable_instancemethod(
+ self._on_table_create)
)
event.listen(
table,
@@ -974,10 +999,10 @@ class SchemaType(SchemaEventTarget):
# listeners
metadata = kw.pop('metadata', None)
return impltype(name=self.name,
- schema=schema,
- metadata=metadata,
- inherit_schema=self.inherit_schema,
- **kw)
+ schema=schema,
+ metadata=metadata,
+ inherit_schema=self.inherit_schema,
+ **kw)
@property
def bind(self):
@@ -1021,7 +1046,9 @@ class SchemaType(SchemaEventTarget):
if t.__class__ is not self.__class__ and isinstance(t, SchemaType):
t._on_metadata_drop(target, bind, **kw)
+
class Enum(String, SchemaType):
+
"""Generic Enum Type.
The Enum type provides a set of possible string values which the
@@ -1118,12 +1145,12 @@ class Enum(String, SchemaType):
def __repr__(self):
return util.generic_repr(self,
- to_inspect=[Enum, SchemaType],
- )
+ to_inspect=[Enum, SchemaType],
+ )
def _should_create_constraint(self, compiler):
return not self.native_enum or \
- not compiler.dialect.supports_native_enum
+ not compiler.dialect.supports_native_enum
@util.dependencies("sqlalchemy.sql.schema")
def _set_table(self, schema, column, table):
@@ -1131,11 +1158,11 @@ class Enum(String, SchemaType):
SchemaType._set_table(self, column, table)
e = schema.CheckConstraint(
- type_coerce(column, self).in_(self.enums),
- name=_defer_name(self.name),
- _create_rule=util.portable_instancemethod(
- self._should_create_constraint)
- )
+ type_coerce(column, self).in_(self.enums),
+ name=_defer_name(self.name),
+ _create_rule=util.portable_instancemethod(
+ self._should_create_constraint)
+ )
assert e.table is table
def adapt(self, impltype, **kw):
@@ -1143,18 +1170,19 @@ class Enum(String, SchemaType):
metadata = kw.pop('metadata', None)
if issubclass(impltype, Enum):
return impltype(name=self.name,
- schema=schema,
- metadata=metadata,
- convert_unicode=self.convert_unicode,
- native_enum=self.native_enum,
- inherit_schema=self.inherit_schema,
- *self.enums,
- **kw)
+ schema=schema,
+ metadata=metadata,
+ convert_unicode=self.convert_unicode,
+ native_enum=self.native_enum,
+ inherit_schema=self.inherit_schema,
+ *self.enums,
+ **kw)
else:
return super(Enum, self).adapt(impltype, **kw)
class PickleType(TypeDecorator):
+
"""Holds Python objects, which are serialized using pickle.
PickleType builds upon the Binary type to apply Python's
@@ -1170,7 +1198,7 @@ class PickleType(TypeDecorator):
impl = LargeBinary
def __init__(self, protocol=pickle.HIGHEST_PROTOCOL,
- pickler=None, comparator=None):
+ pickler=None, comparator=None):
"""
Construct a PickleType.
@@ -1235,6 +1263,7 @@ class PickleType(TypeDecorator):
class Boolean(TypeEngine, SchemaType):
+
"""A bool datatype.
Boolean typically uses BOOLEAN or SMALLINT on the DDL side, and on
@@ -1267,11 +1296,11 @@ class Boolean(TypeEngine, SchemaType):
return
e = schema.CheckConstraint(
- type_coerce(column, self).in_([0, 1]),
- name=_defer_name(self.name),
- _create_rule=util.portable_instancemethod(
- self._should_create_constraint)
- )
+ type_coerce(column, self).in_([0, 1]),
+ name=_defer_name(self.name),
+ _create_rule=util.portable_instancemethod(
+ self._should_create_constraint)
+ )
assert e.table is table
@property
@@ -1301,6 +1330,7 @@ class Boolean(TypeEngine, SchemaType):
class Interval(_DateAffinity, TypeDecorator):
+
"""A type for ``datetime.timedelta()`` objects.
The Interval type deals with ``datetime.timedelta`` objects. In
@@ -1321,8 +1351,8 @@ class Interval(_DateAffinity, TypeDecorator):
epoch = dt.datetime.utcfromtimestamp(0)
def __init__(self, native=True,
- second_precision=None,
- day_precision=None):
+ second_precision=None,
+ day_precision=None):
"""Construct an Interval object.
:param native: when True, use the actual
@@ -1349,10 +1379,10 @@ class Interval(_DateAffinity, TypeDecorator):
return cls._adapt_from_generic_interval(self, **kw)
else:
return self.__class__(
- native=self.native,
- second_precision=self.second_precision,
- day_precision=self.day_precision,
- **kw)
+ native=self.native,
+ second_precision=self.second_precision,
+ day_precision=self.day_precision,
+ **kw)
@property
def python_type(self):
@@ -1423,30 +1453,35 @@ class Interval(_DateAffinity, TypeDecorator):
class REAL(Float):
+
"""The SQL REAL type."""
__visit_name__ = 'REAL'
class FLOAT(Float):
+
"""The SQL FLOAT type."""
__visit_name__ = 'FLOAT'
class NUMERIC(Numeric):
+
"""The SQL NUMERIC type."""
__visit_name__ = 'NUMERIC'
class DECIMAL(Numeric):
+
"""The SQL DECIMAL type."""
__visit_name__ = 'DECIMAL'
class INTEGER(Integer):
+
"""The SQL INT or INTEGER type."""
__visit_name__ = 'INTEGER'
@@ -1454,18 +1489,21 @@ INT = INTEGER
class SMALLINT(SmallInteger):
+
"""The SQL SMALLINT type."""
__visit_name__ = 'SMALLINT'
class BIGINT(BigInteger):
+
"""The SQL BIGINT type."""
__visit_name__ = 'BIGINT'
class TIMESTAMP(DateTime):
+
"""The SQL TIMESTAMP type."""
__visit_name__ = 'TIMESTAMP'
@@ -1475,30 +1513,35 @@ class TIMESTAMP(DateTime):
class DATETIME(DateTime):
+
"""The SQL DATETIME type."""
__visit_name__ = 'DATETIME'
class DATE(Date):
+
"""The SQL DATE type."""
__visit_name__ = 'DATE'
class TIME(Time):
+
"""The SQL TIME type."""
__visit_name__ = 'TIME'
class TEXT(Text):
+
"""The SQL TEXT type."""
__visit_name__ = 'TEXT'
class CLOB(Text):
+
"""The CLOB type.
This type is found in Oracle and Informix.
@@ -1508,53 +1551,63 @@ class CLOB(Text):
class VARCHAR(String):
+
"""The SQL VARCHAR type."""
__visit_name__ = 'VARCHAR'
class NVARCHAR(Unicode):
+
"""The SQL NVARCHAR type."""
__visit_name__ = 'NVARCHAR'
class CHAR(String):
+
"""The SQL CHAR type."""
__visit_name__ = 'CHAR'
class NCHAR(Unicode):
+
"""The SQL NCHAR type."""
__visit_name__ = 'NCHAR'
class BLOB(LargeBinary):
+
"""The SQL BLOB type."""
__visit_name__ = 'BLOB'
class BINARY(_Binary):
+
"""The SQL BINARY type."""
__visit_name__ = 'BINARY'
class VARBINARY(_Binary):
+
"""The SQL VARBINARY type."""
__visit_name__ = 'VARBINARY'
class BOOLEAN(Boolean):
+
"""The SQL BOOLEAN type."""
__visit_name__ = 'BOOLEAN'
+
class NullType(TypeEngine):
+
"""An unknown type.
:class:`.NullType` is used as a default type for those cases where
@@ -1568,12 +1621,13 @@ class NullType(TypeEngine):
as ``None`` or is not passed at all.
The :class:`.NullType` can be used within SQL expression invocation
- without issue, it just has no behavior either at the expression construction
- level or at the bind-parameter/result processing level. :class:`.NullType`
- will result in a :exc:`.CompileError` if the compiler is asked to render
- the type itself, such as if it is used in a :func:`.cast` operation
- or within a schema creation operation such as that invoked by
- :meth:`.MetaData.create_all` or the :class:`.CreateTable` construct.
+ without issue, it just has no behavior either at the expression
+ construction level or at the bind-parameter/result processing level.
+ :class:`.NullType` will result in a :exc:`.CompileError` if the compiler
+ is asked to render the type itself, such as if it is used in a
+ :func:`.cast` operation or within a schema creation operation such as that
+ invoked by :meth:`.MetaData.create_all` or the :class:`.CreateTable`
+ construct.
"""
__visit_name__ = 'null'
@@ -1586,9 +1640,10 @@ class NullType(TypeEngine):
return process
class Comparator(TypeEngine.Comparator):
+
def _adapt_expression(self, op, other_comparator):
if isinstance(other_comparator, NullType.Comparator) or \
- not operators.is_commutative(op):
+ not operators.is_commutative(op):
return op, self.expr.type
else:
return other_comparator._adapt_expression(op, self)
@@ -1633,11 +1688,14 @@ type_api._type_map = _type_map
# the expression element system, as you might expect. We can use
# importlaters or whatnot, but the typing system just necessarily has
# to have some kind of connection like this. right now we're injecting the
-# _DefaultColumnComparator implementation into the TypeEngine.Comparator interface.
-# Alternatively TypeEngine.Comparator could have an "impl" injected, though
-# just injecting the base is simpler, error free, and more performant.
+# _DefaultColumnComparator implementation into the TypeEngine.Comparator
+# interface. Alternatively TypeEngine.Comparator could have an "impl"
+# injected, though just injecting the base is simpler, error free, and more
+# performant.
+
+
class Comparator(_DefaultColumnComparator):
BOOLEANTYPE = BOOLEANTYPE
-TypeEngine.Comparator.__bases__ = (Comparator, ) + TypeEngine.Comparator.__bases__
-
+TypeEngine.Comparator.__bases__ = (
+ Comparator, ) + TypeEngine.Comparator.__bases__
diff --git a/lib/sqlalchemy/sql/type_api.py b/lib/sqlalchemy/sql/type_api.py
index f9af21baa..77c6e1b1e 100644
--- a/lib/sqlalchemy/sql/type_api.py
+++ b/lib/sqlalchemy/sql/type_api.py
@@ -20,13 +20,15 @@ INTEGERTYPE = None
NULLTYPE = None
STRINGTYPE = None
+
class TypeEngine(Visitable):
"""The ultimate base class for all SQL datatypes.
Common subclasses of :class:`.TypeEngine` include
:class:`.String`, :class:`.Integer`, and :class:`.Boolean`.
- For an overview of the SQLAlchemy typing system, see :ref:`types_toplevel`.
+ For an overview of the SQLAlchemy typing system, see
+ :ref:`types_toplevel`.
.. seealso::
@@ -50,7 +52,6 @@ class TypeEngine(Visitable):
def __reduce__(self):
return _reconstitute_comparator, (self.expr, )
-
hashable = True
"""Flag, if False, means values from this type aren't hashable.
@@ -265,7 +266,6 @@ class TypeEngine(Visitable):
"""
return Variant(self, {dialect_name: to_instance(type_)})
-
@util.memoized_property
def _type_affinity(self):
"""Return a rudimental 'affinity' value expressing the general class
@@ -290,7 +290,6 @@ class TypeEngine(Visitable):
except KeyError:
return self._dialect_info(dialect)['impl']
-
def _cached_literal_processor(self, dialect):
"""Return a dialect-specific literal processor for this type."""
try:
@@ -352,7 +351,6 @@ class TypeEngine(Visitable):
"""
return util.constructor_copy(self, cls, **kw)
-
def coerce_compared_value(self, op, value):
"""Suggest a type for a 'coerced' Python value in an expression.
@@ -374,7 +372,7 @@ class TypeEngine(Visitable):
"""
_coerced_type = _type_map.get(type(value), NULLTYPE)
if _coerced_type is NULLTYPE or _coerced_type._type_affinity \
- is self._type_affinity:
+ is self._type_affinity:
return self
else:
return _coerced_type
@@ -411,13 +409,14 @@ class TypeEngine(Visitable):
def __str__(self):
if util.py2k:
return unicode(self.compile()).\
- encode('ascii', 'backslashreplace')
+ encode('ascii', 'backslashreplace')
else:
return str(self.compile())
def __repr__(self):
return util.generic_repr(self)
+
class UserDefinedType(TypeEngine):
"""Base for user defined types.
@@ -454,16 +453,15 @@ class UserDefinedType(TypeEngine):
"""
__visit_name__ = "user_defined"
-
class Comparator(TypeEngine.Comparator):
def _adapt_expression(self, op, other_comparator):
if hasattr(self.type, 'adapt_operator'):
util.warn_deprecated(
"UserDefinedType.adapt_operator is deprecated. Create "
- "a UserDefinedType.Comparator subclass instead which "
- "generates the desired expression constructs, given a "
- "particular operator."
- )
+ "a UserDefinedType.Comparator subclass instead which "
+ "generates the desired expression constructs, given a "
+ "particular operator."
+ )
return self.type.adapt_operator(op), self.type
else:
return op, self.type
@@ -602,7 +600,8 @@ class TypeDecorator(TypeEngine):
level to "IS <constant>" when compared using ``==`` (and same for
``IS NOT`` in conjunction with ``!=``.
- For most SQLAlchemy types, this includes ``NoneType``, as well as ``bool``.
+ For most SQLAlchemy types, this includes ``NoneType``, as well as
+ ``bool``.
:class:`.TypeDecorator` modifies this list to only include ``NoneType``,
as typedecorator implementations that deal with boolean types are common.
@@ -622,18 +621,18 @@ class TypeDecorator(TypeEngine):
def operate(self, op, *other, **kwargs):
kwargs['_python_is_types'] = self.expr.type.coerce_to_is_types
return super(TypeDecorator.Comparator, self).operate(
- op, *other, **kwargs)
+ op, *other, **kwargs)
def reverse_operate(self, op, other, **kwargs):
kwargs['_python_is_types'] = self.expr.type.coerce_to_is_types
return super(TypeDecorator.Comparator, self).reverse_operate(
- op, other, **kwargs)
+ op, other, **kwargs)
@property
def comparator_factory(self):
return type("TDComparator",
- (TypeDecorator.Comparator, self.impl.comparator_factory),
- {})
+ (TypeDecorator.Comparator, self.impl.comparator_factory),
+ {})
def _gen_dialect_impl(self, dialect):
"""
@@ -651,8 +650,8 @@ class TypeDecorator(TypeEngine):
if not isinstance(tt, self.__class__):
raise AssertionError('Type object %s does not properly '
'implement the copy() method, it must '
- 'return an object of type %s' % (self,
- self.__class__))
+ 'return an object of type %s' %
+ (self, self.__class__))
tt.impl = typedesc
return tt
@@ -676,7 +675,7 @@ class TypeDecorator(TypeEngine):
"""
adapted = dialect.type_descriptor(self)
- if type(adapted) is not type(self):
+ if not isinstance(adapted, type(self)):
return adapted
elif isinstance(self.impl, TypeDecorator):
return self.impl.type_engine(dialect)
@@ -796,16 +795,19 @@ class TypeDecorator(TypeEngine):
"""Provide a literal processing function for the given
:class:`.Dialect`.
- Subclasses here will typically override :meth:`.TypeDecorator.process_literal_param`
- instead of this method directly.
+ Subclasses here will typically override
+ :meth:`.TypeDecorator.process_literal_param` instead of this method
+ directly.
- By default, this method makes use of :meth:`.TypeDecorator.process_bind_param`
- if that method is implemented, where :meth:`.TypeDecorator.process_literal_param`
- is not. The rationale here is that :class:`.TypeDecorator` typically deals
- with Python conversions of data that are above the layer of database
- presentation. With the value converted by :meth:`.TypeDecorator.process_bind_param`,
- the underlying type will then handle whether it needs to be presented to the
- DBAPI as a bound parameter or to the database as an inline SQL value.
+ By default, this method makes use of
+ :meth:`.TypeDecorator.process_bind_param` if that method is
+ implemented, where :meth:`.TypeDecorator.process_literal_param` is
+ not. The rationale here is that :class:`.TypeDecorator` typically
+ deals with Python conversions of data that are above the layer of
+ database presentation. With the value converted by
+ :meth:`.TypeDecorator.process_bind_param`, the underlying type will
+ then handle whether it needs to be presented to the DBAPI as a bound
+ parameter or to the database as an inline SQL value.
.. versionadded:: 0.9.0
@@ -903,7 +905,7 @@ class TypeDecorator(TypeEngine):
if self._has_result_processor:
process_value = self.process_result_value
impl_processor = self.impl.result_processor(dialect,
- coltype)
+ coltype)
if impl_processor:
def process(value):
return process_value(impl_processor(value), dialect)
@@ -1032,6 +1034,7 @@ class Variant(TypeDecorator):
"""express comparison behavior in terms of the base type"""
return self.impl.comparator_factory
+
def _reconstitute_comparator(expression):
return expression.comparator
@@ -1066,5 +1069,3 @@ def adapt_type(typeobj, colspecs):
if (issubclass(typeobj.__class__, impltype)):
return typeobj
return typeobj.adapt(impltype)
-
-
diff --git a/lib/sqlalchemy/sql/util.py b/lib/sqlalchemy/sql/util.py
index b4ed7a5f3..8bbae8b93 100644
--- a/lib/sqlalchemy/sql/util.py
+++ b/lib/sqlalchemy/sql/util.py
@@ -16,13 +16,13 @@ from itertools import chain
from collections import deque
from .elements import BindParameter, ColumnClause, ColumnElement, \
- Null, UnaryExpression, literal_column, Label
+ Null, UnaryExpression, literal_column, Label
from .selectable import ScalarSelect, Join, FromClause, FromGrouping
from .schema import Column
join_condition = util.langhelpers.public_factory(
- Join._join_condition,
- ".sql.util.join_condition")
+ Join._join_condition,
+ ".sql.util.join_condition")
# names that are still being imported from the outside
from .annotation import _shallow_annotate, _deep_annotate, _deep_deannotate
@@ -99,7 +99,7 @@ def visit_binary_product(fn, expr):
# those are just column elements by themselves
yield element
elif element.__visit_name__ == 'binary' and \
- operators.is_comparison(element.operator):
+ operators.is_comparison(element.operator):
stack.insert(0, element)
for l in visit(element.left):
for r in visit(element.right):
@@ -135,7 +135,7 @@ def find_tables(clause, check_columns=False,
if include_crud:
_visitors['insert'] = _visitors['update'] = \
- _visitors['delete'] = lambda ent: tables.append(ent.table)
+ _visitors['delete'] = lambda ent: tables.append(ent.table)
if check_columns:
def visit_column(column):
@@ -148,7 +148,6 @@ def find_tables(clause, check_columns=False,
return tables
-
def unwrap_order_by(clause):
"""Break up an 'order by' expression into individual column-expressions,
without DESC/ASC/NULLS FIRST/NULLS LAST"""
@@ -159,9 +158,9 @@ def unwrap_order_by(clause):
t = stack.popleft()
if isinstance(t, ColumnElement) and \
(
- not isinstance(t, UnaryExpression) or \
+ not isinstance(t, UnaryExpression) or
not operators.is_ordering_modifier(t.modifier)
- ):
+ ):
cols.add(t)
else:
for c in t.get_children():
@@ -184,6 +183,7 @@ def clause_is_present(clause, search):
else:
return False
+
def surface_selectables(clause):
stack = [clause]
while stack:
@@ -194,14 +194,16 @@ def surface_selectables(clause):
elif isinstance(elem, FromGrouping):
stack.append(elem.element)
+
def selectables_overlap(left, right):
"""Return True if left/right have some overlapping selectable"""
return bool(
- set(surface_selectables(left)).intersection(
- surface_selectables(right)
- )
- )
+ set(surface_selectables(left)).intersection(
+ surface_selectables(right)
+ )
+ )
+
def bind_values(clause):
"""Return an ordered list of "bound" values in the given clause.
@@ -237,26 +239,25 @@ class _repr_params(object):
display to the given number of 'multi' parameter sets.
"""
+
def __init__(self, params, batches):
self.params = params
self.batches = batches
def __repr__(self):
if isinstance(self.params, (list, tuple)) and \
- len(self.params) > self.batches and \
- isinstance(self.params[0], (list, dict, tuple)):
+ len(self.params) > self.batches and \
+ isinstance(self.params[0], (list, dict, tuple)):
msg = " ... displaying %i of %i total bound parameter sets ... "
return ' '.join((
- repr(self.params[:self.batches - 2])[0:-1],
- msg % (self.batches, len(self.params)),
- repr(self.params[-2:])[1:]
- ))
+ repr(self.params[:self.batches - 2])[0:-1],
+ msg % (self.batches, len(self.params)),
+ repr(self.params[-2:])[1:]
+ ))
else:
return repr(self.params)
-
-
def adapt_criterion_to_null(crit, nulls):
"""given criterion containing bind params, convert selected elements
to IS NULL.
@@ -265,14 +266,14 @@ def adapt_criterion_to_null(crit, nulls):
def visit_binary(binary):
if isinstance(binary.left, BindParameter) \
- and binary.left._identifying_key in nulls:
+ and binary.left._identifying_key in nulls:
# reverse order if the NULL is on the left side
binary.left = binary.right
binary.right = Null()
binary.operator = operators.is_
binary.negate = operators.isnot
elif isinstance(binary.right, BindParameter) \
- and binary.right._identifying_key in nulls:
+ and binary.right._identifying_key in nulls:
binary.right = Null()
binary.operator = operators.is_
binary.negate = operators.isnot
@@ -320,8 +321,8 @@ def reduce_columns(columns, *clauses, **kw):
\**kw may specify 'ignore_nonexistent_tables' to ignore foreign keys
whose tables are not yet configured, or columns that aren't yet present.
- This function is primarily used to determine the most minimal "primary key"
- from a selectable, by reducing the set of primary key columns present
+ This function is primarily used to determine the most minimal "primary
+ key" from a selectable, by reducing the set of primary key columns present
in the selectable to just those that are not repeated.
"""
@@ -353,21 +354,21 @@ def reduce_columns(columns, *clauses, **kw):
else:
raise
if fk_col.shares_lineage(c) and \
- (not only_synonyms or \
- c.name == col.name):
+ (not only_synonyms or
+ c.name == col.name):
omit.add(col)
break
if clauses:
def visit_binary(binary):
if binary.operator == operators.eq:
- cols = util.column_set(chain(*[c.proxy_set
- for c in columns.difference(omit)]))
+ cols = util.column_set(
+ chain(*[c.proxy_set for c in columns.difference(omit)]))
if binary.left in cols and binary.right in cols:
for c in reversed(columns):
if c.shares_lineage(binary.right) and \
- (not only_synonyms or \
- c.name == binary.left.name):
+ (not only_synonyms or
+ c.name == binary.left.name):
omit.add(c)
break
for clause in clauses:
@@ -378,7 +379,7 @@ def reduce_columns(columns, *clauses, **kw):
def criterion_as_pairs(expression, consider_as_foreign_keys=None,
- consider_as_referenced_keys=None, any_operator=False):
+ consider_as_referenced_keys=None, any_operator=False):
"""traverse an expression and locate binary criterion pairs."""
if consider_as_foreign_keys and consider_as_referenced_keys:
@@ -387,37 +388,37 @@ def criterion_as_pairs(expression, consider_as_foreign_keys=None,
"'consider_as_referenced_keys'")
def col_is(a, b):
- #return a is b
+ # return a is b
return a.compare(b)
def visit_binary(binary):
if not any_operator and binary.operator is not operators.eq:
return
if not isinstance(binary.left, ColumnElement) or \
- not isinstance(binary.right, ColumnElement):
+ not isinstance(binary.right, ColumnElement):
return
if consider_as_foreign_keys:
if binary.left in consider_as_foreign_keys and \
- (col_is(binary.right, binary.left) or
- binary.right not in consider_as_foreign_keys):
+ (col_is(binary.right, binary.left) or
+ binary.right not in consider_as_foreign_keys):
pairs.append((binary.right, binary.left))
elif binary.right in consider_as_foreign_keys and \
- (col_is(binary.left, binary.right) or
- binary.left not in consider_as_foreign_keys):
+ (col_is(binary.left, binary.right) or
+ binary.left not in consider_as_foreign_keys):
pairs.append((binary.left, binary.right))
elif consider_as_referenced_keys:
if binary.left in consider_as_referenced_keys and \
- (col_is(binary.right, binary.left) or
- binary.right not in consider_as_referenced_keys):
+ (col_is(binary.right, binary.left) or
+ binary.right not in consider_as_referenced_keys):
pairs.append((binary.left, binary.right))
elif binary.right in consider_as_referenced_keys and \
- (col_is(binary.left, binary.right) or
- binary.left not in consider_as_referenced_keys):
+ (col_is(binary.left, binary.right) or
+ binary.left not in consider_as_referenced_keys):
pairs.append((binary.right, binary.left))
else:
if isinstance(binary.left, Column) and \
- isinstance(binary.right, Column):
+ isinstance(binary.right, Column):
if binary.left.references(binary.right):
pairs.append((binary.right, binary.left))
elif binary.right.references(binary.left):
@@ -427,7 +428,6 @@ def criterion_as_pairs(expression, consider_as_foreign_keys=None,
return pairs
-
class AliasedRow(object):
"""Wrap a RowProxy with a translation map.
@@ -435,6 +435,7 @@ class AliasedRow(object):
to those present in a RowProxy.
"""
+
def __init__(self, row, map):
# AliasedRow objects don't nest, so un-nest
# if another AliasedRow was passed
@@ -483,10 +484,11 @@ class ClauseAdapter(visitors.ReplacingCloningVisitor):
s.c.col1 == table2.c.col1
"""
+
def __init__(self, selectable, equivalents=None,
- include=None, exclude=None,
- include_fn=None, exclude_fn=None,
- adapt_on_names=False):
+ include=None, exclude=None,
+ include_fn=None, exclude_fn=None,
+ adapt_on_names=False):
self.__traverse_options__ = {'stop_on': [selectable]}
self.selectable = selectable
if include:
@@ -505,13 +507,13 @@ class ClauseAdapter(visitors.ReplacingCloningVisitor):
def _corresponding_column(self, col, require_embedded,
_seen=util.EMPTY_SET):
newcol = self.selectable.corresponding_column(
- col,
- require_embedded=require_embedded)
+ col,
+ require_embedded=require_embedded)
if newcol is None and col in self.equivalents and col not in _seen:
for equiv in self.equivalents[col]:
- newcol = self._corresponding_column(equiv,
- require_embedded=require_embedded,
- _seen=_seen.union([col]))
+ newcol = self._corresponding_column(
+ equiv, require_embedded=require_embedded,
+ _seen=_seen.union([col]))
if newcol is not None:
return newcol
if self.adapt_on_names and newcol is None:
@@ -519,9 +521,10 @@ class ClauseAdapter(visitors.ReplacingCloningVisitor):
return newcol
magic_flag = False
+
def replace(self, col):
if not self.magic_flag and isinstance(col, FromClause) and \
- self.selectable.is_derived_from(col):
+ self.selectable.is_derived_from(col):
return self.selectable
elif not isinstance(col, ColumnElement):
return None
@@ -542,10 +545,12 @@ class ColumnAdapter(ClauseAdapter):
adapted_row() factory.
"""
+
def __init__(self, selectable, equivalents=None,
- chain_to=None, include=None,
- exclude=None, adapt_required=False):
- ClauseAdapter.__init__(self, selectable, equivalents, include, exclude)
+ chain_to=None, include=None,
+ exclude=None, adapt_required=False):
+ ClauseAdapter.__init__(self, selectable, equivalents,
+ include, exclude)
if chain_to:
self.chain(chain_to)
self.columns = util.populate_column_dict(self._locate_col)
@@ -599,4 +604,3 @@ class ColumnAdapter(ClauseAdapter):
def __setstate__(self, state):
self.__dict__.update(state)
self.columns = util.PopulateDict(self._locate_col)
-
diff --git a/lib/sqlalchemy/sql/visitors.py b/lib/sqlalchemy/sql/visitors.py
index ddf469d47..bb525744a 100644
--- a/lib/sqlalchemy/sql/visitors.py
+++ b/lib/sqlalchemy/sql/visitors.py
@@ -30,10 +30,10 @@ import operator
from .. import exc
__all__ = ['VisitableType', 'Visitable', 'ClauseVisitor',
- 'CloningVisitor', 'ReplacingCloningVisitor', 'iterate',
- 'iterate_depthfirst', 'traverse_using', 'traverse',
- 'traverse_depthfirst',
- 'cloned_traverse', 'replacement_traverse']
+ 'CloningVisitor', 'ReplacingCloningVisitor', 'iterate',
+ 'iterate_depthfirst', 'traverse_using', 'traverse',
+ 'traverse_depthfirst',
+ 'cloned_traverse', 'replacement_traverse']
class VisitableType(type):
@@ -92,7 +92,7 @@ def _generate_dispatch(cls):
return meth(self, **kw)
_compiler_dispatch.__doc__ = \
- """Look for an attribute named "visit_" + self.__visit_name__
+ """Look for an attribute named "visit_" + self.__visit_name__
on the visitor, and call it with the same kw params.
"""
cls._compiler_dispatch = _compiler_dispatch
@@ -297,7 +297,7 @@ def replacement_traverse(obj, opts, replace):
def clone(elem, **kw):
if id(elem) in stop_on or \
- 'no_replacement_traverse' in elem._annotations:
+ 'no_replacement_traverse' in elem._annotations:
return elem
else:
newelem = replace(elem)