summaryrefslogtreecommitdiff
path: root/lib/sqlalchemy/orm/mapper.py
diff options
context:
space:
mode:
Diffstat (limited to 'lib/sqlalchemy/orm/mapper.py')
-rw-r--r--lib/sqlalchemy/orm/mapper.py1029
1 files changed, 595 insertions, 434 deletions
diff --git a/lib/sqlalchemy/orm/mapper.py b/lib/sqlalchemy/orm/mapper.py
index fa731f729..ea8890788 100644
--- a/lib/sqlalchemy/orm/mapper.py
+++ b/lib/sqlalchemy/orm/mapper.py
@@ -26,12 +26,21 @@ from ..sql import expression, visitors, operators, util as sql_util
from . import instrumentation, attributes, exc as orm_exc, loading
from . import properties
from . import util as orm_util
-from .interfaces import MapperProperty, InspectionAttr, _MappedAttribute, \
- EXT_SKIP
-
-
-from .base import _class_to_mapper, _state_mapper, class_mapper, \
- state_str, _INSTRUMENTOR
+from .interfaces import (
+ MapperProperty,
+ InspectionAttr,
+ _MappedAttribute,
+ EXT_SKIP,
+)
+
+
+from .base import (
+ _class_to_mapper,
+ _state_mapper,
+ class_mapper,
+ state_str,
+ _INSTRUMENTOR,
+)
from .path_registry import PathRegistry
import sys
@@ -46,7 +55,7 @@ _memoized_configured_property = util.group_expirable_memoized_property()
# a constant returned by _get_attr_by_column to indicate
# this mapper is not handling an attribute for a particular
# column
-NO_ATTRIBUTE = util.symbol('NO_ATTRIBUTE')
+NO_ATTRIBUTE = util.symbol("NO_ATTRIBUTE")
# lock used to synchronize the "mapper configure" step
_CONFIGURE_MUTEX = util.threading.RLock()
@@ -90,38 +99,39 @@ class Mapper(InspectionAttr):
_new_mappers = False
_dispose_called = False
- def __init__(self,
- class_,
- local_table=None,
- properties=None,
- primary_key=None,
- non_primary=False,
- inherits=None,
- inherit_condition=None,
- inherit_foreign_keys=None,
- extension=None,
- order_by=False,
- always_refresh=False,
- version_id_col=None,
- version_id_generator=None,
- polymorphic_on=None,
- _polymorphic_map=None,
- polymorphic_identity=None,
- concrete=False,
- with_polymorphic=None,
- polymorphic_load=None,
- allow_partial_pks=True,
- batch=True,
- column_prefix=None,
- include_properties=None,
- exclude_properties=None,
- passive_updates=True,
- passive_deletes=False,
- confirm_deleted_rows=True,
- eager_defaults=False,
- legacy_is_orphan=False,
- _compiled_cache_size=100,
- ):
+ def __init__(
+ self,
+ class_,
+ local_table=None,
+ properties=None,
+ primary_key=None,
+ non_primary=False,
+ inherits=None,
+ inherit_condition=None,
+ inherit_foreign_keys=None,
+ extension=None,
+ order_by=False,
+ always_refresh=False,
+ version_id_col=None,
+ version_id_generator=None,
+ polymorphic_on=None,
+ _polymorphic_map=None,
+ polymorphic_identity=None,
+ concrete=False,
+ with_polymorphic=None,
+ polymorphic_load=None,
+ allow_partial_pks=True,
+ batch=True,
+ column_prefix=None,
+ include_properties=None,
+ exclude_properties=None,
+ passive_updates=True,
+ passive_deletes=False,
+ confirm_deleted_rows=True,
+ eager_defaults=False,
+ legacy_is_orphan=False,
+ _compiled_cache_size=100,
+ ):
r"""Return a new :class:`~.Mapper` object.
This function is typically used behind the scenes
@@ -588,7 +598,7 @@ class Mapper(InspectionAttr):
"""
- self.class_ = util.assert_arg_type(class_, type, 'class_')
+ self.class_ = util.assert_arg_type(class_, type, "class_")
self.class_manager = None
@@ -600,7 +610,8 @@ class Mapper(InspectionAttr):
util.warn_deprecated(
"Mapper.order_by is deprecated."
"Use Query.order_by() in order to affect the ordering of ORM "
- "result sets.")
+ "result sets."
+ )
else:
self.order_by = order_by
@@ -631,7 +642,8 @@ class Mapper(InspectionAttr):
self.eager_defaults = eager_defaults
self.column_prefix = column_prefix
self.polymorphic_on = expression._clause_element_as_expr(
- polymorphic_on)
+ polymorphic_on
+ )
self._dependency_processors = []
self.validators = util.immutabledict()
self.passive_updates = passive_updates
@@ -974,14 +986,16 @@ class Mapper(InspectionAttr):
self.inherits = class_mapper(self.inherits, configure=False)
if not issubclass(self.class_, self.inherits.class_):
raise sa_exc.ArgumentError(
- "Class '%s' does not inherit from '%s'" %
- (self.class_.__name__, self.inherits.class_.__name__))
+ "Class '%s' does not inherit from '%s'"
+ % (self.class_.__name__, self.inherits.class_.__name__)
+ )
if self.non_primary != self.inherits.non_primary:
np = not self.non_primary and "primary" or "non-primary"
raise sa_exc.ArgumentError(
"Inheritance of %s mapper for class '%s' is "
- "only allowed from a %s mapper" %
- (np, self.class_.__name__, np))
+ "only allowed from a %s mapper"
+ % (np, self.class_.__name__, np)
+ )
# inherit_condition is optional.
if self.local_table is None:
self.local_table = self.inherits.local_table
@@ -1000,18 +1014,19 @@ class Mapper(InspectionAttr):
# full table which could pull in other stuff we don't
# want (allows test/inheritance.InheritTest4 to pass)
self.inherit_condition = sql_util.join_condition(
- self.inherits.local_table,
- self.local_table)
+ self.inherits.local_table, self.local_table
+ )
self.mapped_table = sql.join(
self.inherits.mapped_table,
self.local_table,
- self.inherit_condition)
+ self.inherit_condition,
+ )
fks = util.to_set(self.inherit_foreign_keys)
- self._inherits_equated_pairs = \
- sql_util.criterion_as_pairs(
- self.mapped_table.onclause,
- consider_as_foreign_keys=fks)
+ self._inherits_equated_pairs = sql_util.criterion_as_pairs(
+ self.mapped_table.onclause,
+ consider_as_foreign_keys=fks,
+ )
else:
self.mapped_table = self.local_table
@@ -1023,21 +1038,27 @@ class Mapper(InspectionAttr):
if self.version_id_col is None:
self.version_id_col = self.inherits.version_id_col
self.version_id_generator = self.inherits.version_id_generator
- elif self.inherits.version_id_col is not None and \
- self.version_id_col is not self.inherits.version_id_col:
+ elif (
+ self.inherits.version_id_col is not None
+ and self.version_id_col is not self.inherits.version_id_col
+ ):
util.warn(
"Inheriting version_id_col '%s' does not match inherited "
"version_id_col '%s' and will not automatically populate "
"the inherited versioning column. "
"version_id_col should only be specified on "
- "the base-most mapper that includes versioning." %
- (self.version_id_col.description,
- self.inherits.version_id_col.description)
+ "the base-most mapper that includes versioning."
+ % (
+ self.version_id_col.description,
+ self.inherits.version_id_col.description,
+ )
)
- if self.order_by is False and \
- not self.concrete and \
- self.inherits.order_by is not False:
+ if (
+ self.order_by is False
+ and not self.concrete
+ and self.inherits.order_by is not False
+ ):
self.order_by = self.inherits.order_by
self.polymorphic_map = self.inherits.polymorphic_map
@@ -1045,8 +1066,9 @@ class Mapper(InspectionAttr):
self.inherits._inheriting_mappers.append(self)
self.base_mapper = self.inherits.base_mapper
self.passive_updates = self.inherits.passive_updates
- self.passive_deletes = self.inherits.passive_deletes or \
- self.passive_deletes
+ self.passive_deletes = (
+ self.inherits.passive_deletes or self.passive_deletes
+ )
self._all_tables = self.inherits._all_tables
if self.polymorphic_identity is not None:
@@ -1054,25 +1076,30 @@ class Mapper(InspectionAttr):
util.warn(
"Reassigning polymorphic association for identity %r "
"from %r to %r: Check for duplicate use of %r as "
- "value for polymorphic_identity." %
- (self.polymorphic_identity,
- self.polymorphic_map[self.polymorphic_identity],
- self, self.polymorphic_identity)
+ "value for polymorphic_identity."
+ % (
+ self.polymorphic_identity,
+ self.polymorphic_map[self.polymorphic_identity],
+ self,
+ self.polymorphic_identity,
+ )
)
self.polymorphic_map[self.polymorphic_identity] = self
if self.polymorphic_load and self.concrete:
raise exc.ArgumentError(
"polymorphic_load is not currently supported "
- "with concrete table inheritance")
- if self.polymorphic_load == 'inline':
+ "with concrete table inheritance"
+ )
+ if self.polymorphic_load == "inline":
self.inherits._add_with_polymorphic_subclass(self)
- elif self.polymorphic_load == 'selectin':
+ elif self.polymorphic_load == "selectin":
pass
elif self.polymorphic_load is not None:
raise sa_exc.ArgumentError(
- "unknown argument for polymorphic_load: %r" %
- self.polymorphic_load)
+ "unknown argument for polymorphic_load: %r"
+ % self.polymorphic_load
+ )
else:
self._all_tables = set()
@@ -1084,15 +1111,16 @@ class Mapper(InspectionAttr):
if self.mapped_table is None:
raise sa_exc.ArgumentError(
- "Mapper '%s' does not have a mapped_table specified."
- % self)
+ "Mapper '%s' does not have a mapped_table specified." % self
+ )
def _set_with_polymorphic(self, with_polymorphic):
- if with_polymorphic == '*':
- self.with_polymorphic = ('*', None)
+ if with_polymorphic == "*":
+ self.with_polymorphic = ("*", None)
elif isinstance(with_polymorphic, (tuple, list)):
if isinstance(
- with_polymorphic[0], util.string_types + (tuple, list)):
+ with_polymorphic[0], util.string_types + (tuple, list)
+ ):
self.with_polymorphic = with_polymorphic
else:
self.with_polymorphic = (with_polymorphic, None)
@@ -1109,11 +1137,13 @@ class Mapper(InspectionAttr):
"SELECT from a subquery that does not have an alias."
)
- if self.with_polymorphic and \
- isinstance(self.with_polymorphic[1],
- expression.SelectBase):
- self.with_polymorphic = (self.with_polymorphic[0],
- self.with_polymorphic[1].alias())
+ if self.with_polymorphic and isinstance(
+ self.with_polymorphic[1], expression.SelectBase
+ ):
+ self.with_polymorphic = (
+ self.with_polymorphic[0],
+ self.with_polymorphic[1].alias(),
+ )
if self.configured:
self._expire_memoizations()
@@ -1122,12 +1152,9 @@ class Mapper(InspectionAttr):
subcl = mapper.class_
if self.with_polymorphic is None:
self._set_with_polymorphic((subcl,))
- elif self.with_polymorphic[0] != '*':
+ elif self.with_polymorphic[0] != "*":
self._set_with_polymorphic(
- (
- self.with_polymorphic[0] + (subcl, ),
- self.with_polymorphic[1]
- )
+ (self.with_polymorphic[0] + (subcl,), self.with_polymorphic[1])
)
def _set_concrete_base(self, mapper):
@@ -1152,9 +1179,9 @@ class Mapper(InspectionAttr):
self._all_tables = self.inherits._all_tables
for key, prop in mapper._props.items():
- if key not in self._props and \
- not self._should_exclude(key, key, local=False,
- column=None):
+ if key not in self._props and not self._should_exclude(
+ key, key, local=False, column=None
+ ):
self._adapt_inherited_property(key, prop, False)
def _set_polymorphic_on(self, polymorphic_on):
@@ -1166,8 +1193,13 @@ class Mapper(InspectionAttr):
if self.inherits:
self.dispatch._update(self.inherits.dispatch)
super_extensions = set(
- chain(*[m._deprecated_extensions
- for m in self.inherits.iterate_to_root()]))
+ chain(
+ *[
+ m._deprecated_extensions
+ for m in self.inherits.iterate_to_root()
+ ]
+ )
+ )
else:
super_extensions = set()
@@ -1178,8 +1210,13 @@ class Mapper(InspectionAttr):
def _configure_listeners(self):
if self.inherits:
super_extensions = set(
- chain(*[m._deprecated_extensions
- for m in self.inherits.iterate_to_root()]))
+ chain(
+ *[
+ m._deprecated_extensions
+ for m in self.inherits.iterate_to_root()
+ ]
+ )
+ )
else:
super_extensions = set()
@@ -1206,7 +1243,8 @@ class Mapper(InspectionAttr):
raise sa_exc.InvalidRequestError(
"Class %s has no primary mapper configured. Configure "
"a primary mapper first before setting up a non primary "
- "Mapper." % self.class_)
+ "Mapper." % self.class_
+ )
self.class_manager = manager
self._identity_class = manager.mapper._identity_class
_mapper_registry[self] = True
@@ -1219,12 +1257,13 @@ class Mapper(InspectionAttr):
"Class '%s' already has a primary mapper defined. "
"Use non_primary=True to "
"create a non primary Mapper. clear_mappers() will "
- "remove *all* current mappers from all classes." %
- self.class_)
+ "remove *all* current mappers from all classes."
+ % self.class_
+ )
# else:
- # a ClassManager may already exist as
- # ClassManager.instrument_attribute() creates
- # new managers for each subclass if they don't yet exist.
+ # a ClassManager may already exist as
+ # ClassManager.instrument_attribute() creates
+ # new managers for each subclass if they don't yet exist.
_mapper_registry[self] = True
@@ -1239,33 +1278,35 @@ class Mapper(InspectionAttr):
manager.mapper = self
manager.deferred_scalar_loader = util.partial(
- loading.load_scalar_attributes, self)
+ loading.load_scalar_attributes, self
+ )
# The remaining members can be added by any mapper,
# e_name None or not.
if manager.info.get(_INSTRUMENTOR, False):
return
- event.listen(manager, 'first_init', _event_on_first_init, raw=True)
- event.listen(manager, 'init', _event_on_init, raw=True)
+ event.listen(manager, "first_init", _event_on_first_init, raw=True)
+ event.listen(manager, "init", _event_on_init, raw=True)
for key, method in util.iterate_attributes(self.class_):
- if key == '__init__' and hasattr(method, '_sa_original_init'):
+ if key == "__init__" and hasattr(method, "_sa_original_init"):
method = method._sa_original_init
if isinstance(method, types.MethodType):
method = method.im_func
if isinstance(method, types.FunctionType):
- if hasattr(method, '__sa_reconstructor__'):
+ if hasattr(method, "__sa_reconstructor__"):
self._reconstructor = method
- event.listen(manager, 'load', _event_on_load, raw=True)
- elif hasattr(method, '__sa_validators__'):
+ event.listen(manager, "load", _event_on_load, raw=True)
+ elif hasattr(method, "__sa_validators__"):
validation_opts = method.__sa_validation_opts__
for name in method.__sa_validators__:
if name in self.validators:
raise sa_exc.InvalidRequestError(
"A validation function for mapped "
- "attribute %r on mapper %s already exists." %
- (name, self))
+ "attribute %r on mapper %s already exists."
+ % (name, self)
+ )
self.validators = self.validators.union(
{name: (method, validation_opts)}
)
@@ -1283,13 +1324,15 @@ class Mapper(InspectionAttr):
self.configured = True
self._dispose_called = True
- if hasattr(self, '_configure_failed'):
+ if hasattr(self, "_configure_failed"):
del self._configure_failed
- if not self.non_primary and \
- self.class_manager is not None and \
- self.class_manager.is_mapped and \
- self.class_manager.mapper is self:
+ if (
+ not self.non_primary
+ and self.class_manager is not None
+ and self.class_manager.is_mapped
+ and self.class_manager.mapper is self
+ ):
instrumentation.unregister_class(self.class_)
def _configure_pks(self):
@@ -1298,9 +1341,9 @@ class Mapper(InspectionAttr):
self._pks_by_table = {}
self._cols_by_table = {}
- all_cols = util.column_set(chain(*[
- col.proxy_set for col in
- self._columntoproperty]))
+ all_cols = util.column_set(
+ chain(*[col.proxy_set for col in self._columntoproperty])
+ )
pk_cols = util.column_set(c for c in all_cols if c.primary_key)
@@ -1311,12 +1354,12 @@ class Mapper(InspectionAttr):
if t.primary_key and pk_cols.issuperset(t.primary_key):
# ordering is important since it determines the ordering of
# mapper.primary_key (and therefore query.get())
- self._pks_by_table[t] = \
- util.ordered_column_set(t.primary_key).\
- intersection(pk_cols)
- self._cols_by_table[t] = \
- util.ordered_column_set(t.c).\
- intersection(all_cols)
+ self._pks_by_table[t] = util.ordered_column_set(
+ t.primary_key
+ ).intersection(pk_cols)
+ self._cols_by_table[t] = util.ordered_column_set(t.c).intersection(
+ all_cols
+ )
# if explicit PK argument sent, add those columns to the
# primary key mappings
@@ -1327,22 +1370,30 @@ class Mapper(InspectionAttr):
self._pks_by_table[k.table].add(k)
# otherwise, see that we got a full PK for the mapped table
- elif self.mapped_table not in self._pks_by_table or \
- len(self._pks_by_table[self.mapped_table]) == 0:
+ elif (
+ self.mapped_table not in self._pks_by_table
+ or len(self._pks_by_table[self.mapped_table]) == 0
+ ):
raise sa_exc.ArgumentError(
"Mapper %s could not assemble any primary "
- "key columns for mapped table '%s'" %
- (self, self.mapped_table.description))
- elif self.local_table not in self._pks_by_table and \
- isinstance(self.local_table, schema.Table):
- util.warn("Could not assemble any primary "
- "keys for locally mapped table '%s' - "
- "no rows will be persisted in this Table."
- % self.local_table.description)
-
- if self.inherits and \
- not self.concrete and \
- not self._primary_key_argument:
+ "key columns for mapped table '%s'"
+ % (self, self.mapped_table.description)
+ )
+ elif self.local_table not in self._pks_by_table and isinstance(
+ self.local_table, schema.Table
+ ):
+ util.warn(
+ "Could not assemble any primary "
+ "keys for locally mapped table '%s' - "
+ "no rows will be persisted in this Table."
+ % self.local_table.description
+ )
+
+ if (
+ self.inherits
+ and not self.concrete
+ and not self._primary_key_argument
+ ):
# if inheriting, the "primary key" for this mapper is
# that of the inheriting (unless concrete or explicit)
self.primary_key = self.inherits.primary_key
@@ -1351,19 +1402,24 @@ class Mapper(InspectionAttr):
# reduce to the minimal set of columns
if self._primary_key_argument:
primary_key = sql_util.reduce_columns(
- [self.mapped_table.corresponding_column(c) for c in
- self._primary_key_argument],
- ignore_nonexistent_tables=True)
+ [
+ self.mapped_table.corresponding_column(c)
+ for c in self._primary_key_argument
+ ],
+ ignore_nonexistent_tables=True,
+ )
else:
primary_key = sql_util.reduce_columns(
self._pks_by_table[self.mapped_table],
- ignore_nonexistent_tables=True)
+ ignore_nonexistent_tables=True,
+ )
if len(primary_key) == 0:
raise sa_exc.ArgumentError(
"Mapper %s could not assemble any primary "
- "key columns for mapped table '%s'" %
- (self, self.mapped_table.description))
+ "key columns for mapped table '%s'"
+ % (self, self.mapped_table.description)
+ )
self.primary_key = tuple(primary_key)
self._log("Identified primary key columns: %s", primary_key)
@@ -1373,9 +1429,12 @@ class Mapper(InspectionAttr):
self._readonly_props = set(
self._columntoproperty[col]
for col in self._columntoproperty
- if self._columntoproperty[col] not in self._identity_key_props and
- (not hasattr(col, 'table') or
- col.table not in self._cols_by_table))
+ if self._columntoproperty[col] not in self._identity_key_props
+ and (
+ not hasattr(col, "table")
+ or col.table not in self._cols_by_table
+ )
+ )
def _configure_properties(self):
# Column and other ClauseElement objects which are mapped
@@ -1397,9 +1456,9 @@ class Mapper(InspectionAttr):
# pull properties from the inherited mapper if any.
if self.inherits:
for key, prop in self.inherits._props.items():
- if key not in self._props and \
- not self._should_exclude(key, key, local=False,
- column=None):
+ if key not in self._props and not self._should_exclude(
+ key, key, local=False, column=None
+ ):
self._adapt_inherited_property(key, prop, False)
# create properties for each column in the mapped table,
@@ -1408,12 +1467,13 @@ class Mapper(InspectionAttr):
if column in self._columntoproperty:
continue
- column_key = (self.column_prefix or '') + column.key
+ column_key = (self.column_prefix or "") + column.key
if self._should_exclude(
- column.key, column_key,
+ column.key,
+ column_key,
local=self.local_table.c.contains_column(column),
- column=column
+ column=column,
):
continue
@@ -1423,10 +1483,9 @@ class Mapper(InspectionAttr):
if column in mapper._columntoproperty:
column_key = mapper._columntoproperty[column].key
- self._configure_property(column_key,
- column,
- init=False,
- setparent=True)
+ self._configure_property(
+ column_key, column, init=False, setparent=True
+ )
def _configure_polymorphic_setter(self, init=False):
"""Configure an attribute on the mapper representing the
@@ -1453,7 +1512,8 @@ class Mapper(InspectionAttr):
raise sa_exc.ArgumentError(
"Can't determine polymorphic_on "
"value '%s' - no attribute is "
- "mapped to this name." % self.polymorphic_on)
+ "mapped to this name." % self.polymorphic_on
+ )
if self.polymorphic_on in self._columntoproperty:
# polymorphic_on is a column that is already mapped
@@ -1462,12 +1522,14 @@ class Mapper(InspectionAttr):
elif isinstance(self.polymorphic_on, MapperProperty):
# polymorphic_on is directly a MapperProperty,
# ensure it's a ColumnProperty
- if not isinstance(self.polymorphic_on,
- properties.ColumnProperty):
+ if not isinstance(
+ self.polymorphic_on, properties.ColumnProperty
+ ):
raise sa_exc.ArgumentError(
"Only direct column-mapped "
"property or SQL expression "
- "can be passed for polymorphic_on")
+ "can be passed for polymorphic_on"
+ )
prop = self.polymorphic_on
elif not expression._is_column(self.polymorphic_on):
# polymorphic_on is not a Column and not a ColumnProperty;
@@ -1484,7 +1546,8 @@ class Mapper(InspectionAttr):
# 2. a totally standalone SQL expression which we'd
# hope is compatible with this mapper's mapped_table
col = self.mapped_table.corresponding_column(
- self.polymorphic_on)
+ self.polymorphic_on
+ )
if col is None:
# polymorphic_on doesn't derive from any
# column/expression isn't present in the mapped
@@ -1500,14 +1563,16 @@ class Mapper(InspectionAttr):
instrument = False
col = self.polymorphic_on
if isinstance(col, schema.Column) and (
- self.with_polymorphic is None or
- self.with_polymorphic[1].
- corresponding_column(col) is None):
+ self.with_polymorphic is None
+ or self.with_polymorphic[1].corresponding_column(col)
+ is None
+ ):
raise sa_exc.InvalidRequestError(
"Could not map polymorphic_on column "
"'%s' to the mapped table - polymorphic "
"loads will not function properly"
- % col.description)
+ % col.description
+ )
else:
# column/expression that polymorphic_on derives from
# is present in our mapped table
@@ -1518,16 +1583,15 @@ class Mapper(InspectionAttr):
# polymorphic_union.
# we'll make a separate ColumnProperty for it.
instrument = True
- key = getattr(col, 'key', None)
+ key = getattr(col, "key", None)
if key:
if self._should_exclude(col.key, col.key, False, col):
raise sa_exc.InvalidRequestError(
"Cannot exclude or override the "
- "discriminator column %r" %
- col.key)
+ "discriminator column %r" % col.key
+ )
else:
- self.polymorphic_on = col = \
- col.label("_sa_polymorphic_on")
+ self.polymorphic_on = col = col.label("_sa_polymorphic_on")
key = col.key
prop = properties.ColumnProperty(col, _instrument=instrument)
@@ -1551,43 +1615,51 @@ class Mapper(InspectionAttr):
if self.mapped_table is mapper.mapped_table:
self.polymorphic_on = mapper.polymorphic_on
else:
- self.polymorphic_on = \
- self.mapped_table.corresponding_column(
- mapper.polymorphic_on)
+ self.polymorphic_on = self.mapped_table.corresponding_column(
+ mapper.polymorphic_on
+ )
# we can use the parent mapper's _set_polymorphic_identity
# directly; it ensures the polymorphic_identity of the
# instance's mapper is used so is portable to subclasses.
if self.polymorphic_on is not None:
- self._set_polymorphic_identity = \
+ self._set_polymorphic_identity = (
mapper._set_polymorphic_identity
- self._validate_polymorphic_identity = \
+ )
+ self._validate_polymorphic_identity = (
mapper._validate_polymorphic_identity
+ )
else:
self._set_polymorphic_identity = None
return
if setter:
+
def _set_polymorphic_identity(state):
dict_ = state.dict
state.get_impl(polymorphic_key).set(
- state, dict_,
+ state,
+ dict_,
state.manager.mapper.polymorphic_identity,
- None)
+ None,
+ )
def _validate_polymorphic_identity(mapper, state, dict_):
- if polymorphic_key in dict_ and \
- dict_[polymorphic_key] not in \
- mapper._acceptable_polymorphic_identities:
+ if (
+ polymorphic_key in dict_
+ and dict_[polymorphic_key]
+ not in mapper._acceptable_polymorphic_identities
+ ):
util.warn_limited(
"Flushing object %s with "
"incompatible polymorphic identity %r; the "
"object may not refresh and/or load correctly",
- (state_str(state), dict_[polymorphic_key])
+ (state_str(state), dict_[polymorphic_key]),
)
self._set_polymorphic_identity = _set_polymorphic_identity
- self._validate_polymorphic_identity = \
+ self._validate_polymorphic_identity = (
_validate_polymorphic_identity
+ )
else:
self._set_polymorphic_identity = None
@@ -1628,16 +1700,20 @@ class Mapper(InspectionAttr):
# mapper and we don't map this. don't trip user-defined
# descriptors that might have side effects when invoked.
implementing_attribute = self.class_manager._get_class_attr_mro(
- key, prop)
- if implementing_attribute is prop or (isinstance(
- implementing_attribute,
- attributes.InstrumentedAttribute) and
- implementing_attribute._parententity is prop.parent
+ key, prop
+ )
+ if implementing_attribute is prop or (
+ isinstance(
+ implementing_attribute, attributes.InstrumentedAttribute
+ )
+ and implementing_attribute._parententity is prop.parent
):
self._configure_property(
key,
properties.ConcreteInheritedProperty(),
- init=init, setparent=True)
+ init=init,
+ setparent=True,
+ )
def _configure_property(self, key, prop, init=True, setparent=True):
self._log("_configure_property(%s, %s)", key, prop.__class__.__name__)
@@ -1659,7 +1735,8 @@ class Mapper(InspectionAttr):
for m2 in path:
m2.mapped_table._reset_exported()
col = self.mapped_table.corresponding_column(
- prop.columns[0])
+ prop.columns[0]
+ )
break
path.append(m)
@@ -1670,26 +1747,30 @@ class Mapper(InspectionAttr):
# column is coming in after _readonly_props was
# initialized; check for 'readonly'
- if hasattr(self, '_readonly_props') and \
- (not hasattr(col, 'table') or
- col.table not in self._cols_by_table):
+ if hasattr(self, "_readonly_props") and (
+ not hasattr(col, "table")
+ or col.table not in self._cols_by_table
+ ):
self._readonly_props.add(prop)
else:
# if column is coming in after _cols_by_table was
# initialized, ensure the col is in the right set
- if hasattr(self, '_cols_by_table') and \
- col.table in self._cols_by_table and \
- col not in self._cols_by_table[col.table]:
+ if (
+ hasattr(self, "_cols_by_table")
+ and col.table in self._cols_by_table
+ and col not in self._cols_by_table[col.table]
+ ):
self._cols_by_table[col.table].add(col)
# if this properties.ColumnProperty represents the "polymorphic
# discriminator" column, mark it. We'll need this when rendering
# columns in SELECT statements.
- if not hasattr(prop, '_is_polymorphic_discriminator'):
- prop._is_polymorphic_discriminator = \
- (col is self.polymorphic_on or
- prop.columns[0] is self.polymorphic_on)
+ if not hasattr(prop, "_is_polymorphic_discriminator"):
+ prop._is_polymorphic_discriminator = (
+ col is self.polymorphic_on
+ or prop.columns[0] is self.polymorphic_on
+ )
self.columns[key] = col
for col in prop.columns + prop._orig_columns:
@@ -1701,8 +1782,9 @@ class Mapper(InspectionAttr):
if setparent:
prop.set_parent(self, init)
- if key in self._props and \
- getattr(self._props[key], '_mapped_by_synonym', False):
+ if key in self._props and getattr(
+ self._props[key], "_mapped_by_synonym", False
+ ):
syn = self._props[key]._mapped_by_synonym
raise sa_exc.ArgumentError(
"Can't call map_column=True for synonym %r=%r, "
@@ -1710,20 +1792,22 @@ class Mapper(InspectionAttr):
"%r for column %r" % (syn, key, key, syn)
)
- if key in self._props and \
- not isinstance(prop, properties.ColumnProperty) and \
- not isinstance(
- self._props[key],
- (
- properties.ColumnProperty,
- properties.ConcreteInheritedProperty)
- ):
- util.warn("Property %s on %s being replaced with new "
- "property %s; the old property will be discarded" % (
- self._props[key],
- self,
- prop,
- ))
+ if (
+ key in self._props
+ and not isinstance(prop, properties.ColumnProperty)
+ and not isinstance(
+ self._props[key],
+ (
+ properties.ColumnProperty,
+ properties.ConcreteInheritedProperty,
+ ),
+ )
+ ):
+ util.warn(
+ "Property %s on %s being replaced with new "
+ "property %s; the old property will be discarded"
+ % (self._props[key], self, prop)
+ )
oldprop = self._props[key]
self._path_registry.pop(oldprop, None)
@@ -1753,23 +1837,29 @@ class Mapper(InspectionAttr):
if not expression._is_column(column):
raise sa_exc.ArgumentError(
"%s=%r is not an instance of MapperProperty or Column"
- % (key, prop))
+ % (key, prop)
+ )
prop = self._props.get(key, None)
if isinstance(prop, properties.ColumnProperty):
if (
- not self._inherits_equated_pairs or
- (prop.columns[0], column) not in self._inherits_equated_pairs
- ) and \
- not prop.columns[0].shares_lineage(column) and \
- prop.columns[0] is not self.version_id_col and \
- column is not self.version_id_col:
+ (
+ not self._inherits_equated_pairs
+ or (prop.columns[0], column)
+ not in self._inherits_equated_pairs
+ )
+ and not prop.columns[0].shares_lineage(column)
+ and prop.columns[0] is not self.version_id_col
+ and column is not self.version_id_col
+ ):
warn_only = prop.parent is not self
- msg = ("Implicitly combining column %s with column "
- "%s under attribute '%s'. Please configure one "
- "or more attributes for these same-named columns "
- "explicitly." % (prop.columns[-1], column, key))
+ msg = (
+ "Implicitly combining column %s with column "
+ "%s under attribute '%s'. Please configure one "
+ "or more attributes for these same-named columns "
+ "explicitly." % (prop.columns[-1], column, key)
+ )
if warn_only:
util.warn(msg)
else:
@@ -1779,11 +1869,14 @@ class Mapper(InspectionAttr):
# mapper. make a copy and append our column to it
prop = prop.copy()
prop.columns.insert(0, column)
- self._log("inserting column to existing list "
- "in properties.ColumnProperty %s" % (key))
+ self._log(
+ "inserting column to existing list "
+ "in properties.ColumnProperty %s" % (key)
+ )
return prop
- elif prop is None or isinstance(prop,
- properties.ConcreteInheritedProperty):
+ elif prop is None or isinstance(
+ prop, properties.ConcreteInheritedProperty
+ ):
mapped_column = []
for c in columns:
mc = self.mapped_table.corresponding_column(c)
@@ -1802,7 +1895,8 @@ class Mapper(InspectionAttr):
"column '%s' is not represented in the mapper's "
"table. Use the `column_property()` function to "
"force this column to be mapped as a read-only "
- "attribute." % (key, self, c))
+ "attribute." % (key, self, c)
+ )
mapped_column.append(mc)
return properties.ColumnProperty(*mapped_column)
else:
@@ -1815,8 +1909,8 @@ class Mapper(InspectionAttr):
"(including its availability as a foreign key), "
"use the 'include_properties' or 'exclude_properties' "
"mapper arguments to control specifically which table "
- "columns get mapped." %
- (key, self, column.key, prop))
+ "columns get mapped." % (key, self, column.key, prop)
+ )
def _post_configure_properties(self):
"""Call the ``init()`` method on all ``MapperProperties``
@@ -1867,34 +1961,35 @@ class Mapper(InspectionAttr):
@property
def _log_desc(self):
- return "(" + self.class_.__name__ + \
- "|" + \
- (self.local_table is not None and
- self.local_table.description or
- str(self.local_table)) +\
- (self.non_primary and
- "|non-primary" or "") + ")"
+ return (
+ "("
+ + self.class_.__name__
+ + "|"
+ + (
+ self.local_table is not None
+ and self.local_table.description
+ or str(self.local_table)
+ )
+ + (self.non_primary and "|non-primary" or "")
+ + ")"
+ )
def _log(self, msg, *args):
- self.logger.info(
- "%s " + msg, *((self._log_desc,) + args)
- )
+ self.logger.info("%s " + msg, *((self._log_desc,) + args))
def _log_debug(self, msg, *args):
- self.logger.debug(
- "%s " + msg, *((self._log_desc,) + args)
- )
+ self.logger.debug("%s " + msg, *((self._log_desc,) + args))
def __repr__(self):
- return '<Mapper at 0x%x; %s>' % (
- id(self), self.class_.__name__)
+ return "<Mapper at 0x%x; %s>" % (id(self), self.class_.__name__)
def __str__(self):
return "Mapper|%s|%s%s" % (
self.class_.__name__,
- self.local_table is not None and
- self.local_table.description or None,
- self.non_primary and "|non-primary" or ""
+ self.local_table is not None
+ and self.local_table.description
+ or None,
+ self.non_primary and "|non-primary" or "",
)
def _is_orphan(self, state):
@@ -1904,7 +1999,8 @@ class Mapper(InspectionAttr):
orphan_possible = True
has_parent = attributes.manager_of_class(cls).has_parent(
- state, key, optimistic=state.has_identity)
+ state, key, optimistic=state.has_identity
+ )
if self.legacy_is_orphan and has_parent:
return False
@@ -1930,7 +2026,8 @@ class Mapper(InspectionAttr):
return self._props[key]
except KeyError:
raise sa_exc.InvalidRequestError(
- "Mapper '%s' has no property '%s'" % (self, key))
+ "Mapper '%s' has no property '%s'" % (self, key)
+ )
def get_property_by_column(self, column):
"""Given a :class:`.Column` object, return the
@@ -1953,7 +2050,7 @@ class Mapper(InspectionAttr):
selectable, if present. This helps some more legacy-ish mappings.
"""
- if spec == '*':
+ if spec == "*":
mappers = list(self.self_and_descendants)
elif spec:
mappers = set()
@@ -1961,8 +2058,8 @@ class Mapper(InspectionAttr):
m = _class_to_mapper(m)
if not m.isa(self):
raise sa_exc.InvalidRequestError(
- "%r does not inherit from %r" %
- (m, self))
+ "%r does not inherit from %r" % (m, self)
+ )
if selectable is None:
mappers.update(m.iterate_to_root())
@@ -1973,8 +2070,9 @@ class Mapper(InspectionAttr):
mappers = []
if selectable is not None:
- tables = set(sql_util.find_tables(selectable,
- include_aliases=True))
+ tables = set(
+ sql_util.find_tables(selectable, include_aliases=True)
+ )
mappers = [m for m in mappers if m.local_table in tables]
return mappers
@@ -1991,25 +2089,26 @@ class Mapper(InspectionAttr):
if m.concrete:
raise sa_exc.InvalidRequestError(
"'with_polymorphic()' requires 'selectable' argument "
- "when concrete-inheriting mappers are used.")
+ "when concrete-inheriting mappers are used."
+ )
elif not m.single:
if innerjoin:
- from_obj = from_obj.join(m.local_table,
- m.inherit_condition)
+ from_obj = from_obj.join(
+ m.local_table, m.inherit_condition
+ )
else:
- from_obj = from_obj.outerjoin(m.local_table,
- m.inherit_condition)
+ from_obj = from_obj.outerjoin(
+ m.local_table, m.inherit_condition
+ )
return from_obj
@_memoized_configured_property
def _single_table_criterion(self):
- if self.single and \
- self.inherits and \
- self.polymorphic_on is not None:
+ if self.single and self.inherits and self.polymorphic_on is not None:
return self.polymorphic_on.in_(
- m.polymorphic_identity
- for m in self.self_and_descendants)
+ m.polymorphic_identity for m in self.self_and_descendants
+ )
else:
return None
@@ -2031,8 +2130,8 @@ class Mapper(InspectionAttr):
return selectable
else:
return self._selectable_from_mappers(
- self._mappers_from_spec(spec, selectable),
- False)
+ self._mappers_from_spec(spec, selectable), False
+ )
with_polymorphic_mappers = _with_polymorphic_mappers
"""The list of :class:`.Mapper` objects included in the
@@ -2046,9 +2145,8 @@ class Mapper(InspectionAttr):
(
table,
frozenset(
- col for col in columns
- if col.type.should_evaluate_none
- )
+ col for col in columns if col.type.should_evaluate_none
+ ),
)
for table, columns in self._cols_by_table.items()
)
@@ -2059,10 +2157,13 @@ class Mapper(InspectionAttr):
(
table,
frozenset(
- col.key for col in columns
- if not col.primary_key and
- not col.server_default and not col.default
- and not col.type.should_evaluate_none)
+ col.key
+ for col in columns
+ if not col.primary_key
+ and not col.server_default
+ and not col.default
+ and not col.type.should_evaluate_none
+ ),
)
for table, columns in self._cols_by_table.items()
)
@@ -2073,9 +2174,8 @@ class Mapper(InspectionAttr):
(
table,
dict(
- (self._columntoproperty[col].key, col)
- for col in columns
- )
+ (self._columntoproperty[col].key, col) for col in columns
+ ),
)
for table, columns in self._cols_by_table.items()
)
@@ -2083,10 +2183,7 @@ class Mapper(InspectionAttr):
@_memoized_configured_property
def _pk_keys_by_table(self):
return dict(
- (
- table,
- frozenset([col.key for col in pks])
- )
+ (table, frozenset([col.key for col in pks]))
for table, pks in self._pks_by_table.items()
)
@@ -2095,7 +2192,7 @@ class Mapper(InspectionAttr):
return dict(
(
table,
- frozenset([self._columntoproperty[col].key for col in pks])
+ frozenset([self._columntoproperty[col].key for col in pks]),
)
for table, pks in self._pks_by_table.items()
)
@@ -2105,9 +2202,13 @@ class Mapper(InspectionAttr):
return dict(
(
table,
- frozenset([
- col.key for col in columns
- if col.server_default is not None])
+ frozenset(
+ [
+ col.key
+ for col in columns
+ if col.server_default is not None
+ ]
+ ),
)
for table, columns in self._cols_by_table.items()
)
@@ -2119,11 +2220,9 @@ class Mapper(InspectionAttr):
for table, columns in self._cols_by_table.items():
for col in columns:
if (
- (
- col.server_default is not None or
- col.server_onupdate is not None
- ) and col in self._columntoproperty
- ):
+ col.server_default is not None
+ or col.server_onupdate is not None
+ ) and col in self._columntoproperty:
result.add(self._columntoproperty[col].key)
return result
@@ -2133,9 +2232,13 @@ class Mapper(InspectionAttr):
return dict(
(
table,
- frozenset([
- col.key for col in columns
- if col.server_onupdate is not None])
+ frozenset(
+ [
+ col.key
+ for col in columns
+ if col.server_onupdate is not None
+ ]
+ ),
)
for table, columns in self._cols_by_table.items()
)
@@ -2152,8 +2255,9 @@ class Mapper(InspectionAttr):
"""
return self._with_polymorphic_selectable
- def _with_polymorphic_args(self, spec=None, selectable=False,
- innerjoin=False):
+ def _with_polymorphic_args(
+ self, spec=None, selectable=False, innerjoin=False
+ ):
if self.with_polymorphic:
if not spec:
spec = self.with_polymorphic[0]
@@ -2165,13 +2269,15 @@ class Mapper(InspectionAttr):
if selectable is not None:
return mappers, selectable
else:
- return mappers, self._selectable_from_mappers(mappers,
- innerjoin)
+ return mappers, self._selectable_from_mappers(mappers, innerjoin)
@_memoized_configured_property
def _polymorphic_properties(self):
- return list(self._iterate_polymorphic_properties(
- self._with_polymorphic_mappers))
+ return list(
+ self._iterate_polymorphic_properties(
+ self._with_polymorphic_mappers
+ )
+ )
def _iterate_polymorphic_properties(self, mappers=None):
"""Return an iterator of MapperProperty objects which will render into
@@ -2187,14 +2293,17 @@ class Mapper(InspectionAttr):
# from other mappers, as these are sometimes dependent on that
# mapper's polymorphic selectable (which we don't want rendered)
for c in util.unique_list(
- chain(*[
- list(mapper.iterate_properties) for mapper in
- [self] + mappers
- ])
+ chain(
+ *[
+ list(mapper.iterate_properties)
+ for mapper in [self] + mappers
+ ]
+ )
):
- if getattr(c, '_is_polymorphic_discriminator', False) and \
- (self.polymorphic_on is None or
- c.columns[0] is not self.polymorphic_on):
+ if getattr(c, "_is_polymorphic_discriminator", False) and (
+ self.polymorphic_on is None
+ or c.columns[0] is not self.polymorphic_on
+ ):
continue
yield c
@@ -2282,7 +2391,8 @@ class Mapper(InspectionAttr):
"""
return util.ImmutableProperties(
- dict(self.class_manager._all_sqla_attributes()))
+ dict(self.class_manager._all_sqla_attributes())
+ )
@_memoized_configured_property
def synonyms(self):
@@ -2351,10 +2461,11 @@ class Mapper(InspectionAttr):
def _filter_properties(self, type_):
if Mapper._new_mappers:
configure_mappers()
- return util.ImmutableProperties(util.OrderedDict(
- (k, v) for k, v in self._props.items()
- if isinstance(v, type_)
- ))
+ return util.ImmutableProperties(
+ util.OrderedDict(
+ (k, v) for k, v in self._props.items() if isinstance(v, type_)
+ )
+ )
@_memoized_configured_property
def _get_clause(self):
@@ -2363,10 +2474,14 @@ class Mapper(InspectionAttr):
by primary key.
"""
- params = [(primary_key, sql.bindparam(None, type_=primary_key.type))
- for primary_key in self.primary_key]
- return sql.and_(*[k == v for (k, v) in params]), \
- util.column_dict(params)
+ params = [
+ (primary_key, sql.bindparam(None, type_=primary_key.type))
+ for primary_key in self.primary_key
+ ]
+ return (
+ sql.and_(*[k == v for (k, v) in params]),
+ util.column_dict(params),
+ )
@_memoized_configured_property
def _equivalent_columns(self):
@@ -2401,18 +2516,24 @@ class Mapper(InspectionAttr):
result[binary.right].add(binary.left)
else:
result[binary.right] = util.column_set((binary.left,))
+
for mapper in self.base_mapper.self_and_descendants:
if mapper.inherit_condition is not None:
visitors.traverse(
- mapper.inherit_condition, {},
- {'binary': visit_binary})
+ mapper.inherit_condition, {}, {"binary": visit_binary}
+ )
return result
def _is_userland_descriptor(self, obj):
- if isinstance(obj, (_MappedAttribute,
- instrumentation.ClassManager,
- expression.ColumnElement)):
+ if isinstance(
+ obj,
+ (
+ _MappedAttribute,
+ instrumentation.ClassManager,
+ expression.ColumnElement,
+ ),
+ ):
return False
else:
return True
@@ -2429,26 +2550,29 @@ class Mapper(InspectionAttr):
# check for class-bound attributes and/or descriptors,
# either local or from an inherited class
if local:
- if self.class_.__dict__.get(assigned_name, None) is not None \
- and self._is_userland_descriptor(
- self.class_.__dict__[assigned_name]):
+ if self.class_.__dict__.get(
+ assigned_name, None
+ ) is not None and self._is_userland_descriptor(
+ self.class_.__dict__[assigned_name]
+ ):
return True
else:
attr = self.class_manager._get_class_attr_mro(assigned_name, None)
if attr is not None and self._is_userland_descriptor(attr):
return True
- if self.include_properties is not None and \
- name not in self.include_properties and \
- (column is None or column not in self.include_properties):
+ if (
+ self.include_properties is not None
+ and name not in self.include_properties
+ and (column is None or column not in self.include_properties)
+ ):
self._log("not including property %s" % (name))
return True
- if self.exclude_properties is not None and \
- (
- name in self.exclude_properties or
- (column is not None and column in self.exclude_properties)
- ):
+ if self.exclude_properties is not None and (
+ name in self.exclude_properties
+ or (column is not None and column in self.exclude_properties)
+ ):
self._log("excluding property %s" % (name))
return True
@@ -2545,8 +2669,11 @@ class Mapper(InspectionAttr):
if adapter:
pk_cols = [adapter.columns[c] for c in pk_cols]
- return self._identity_class, \
- tuple(row[column] for column in pk_cols), identity_token
+ return (
+ self._identity_class,
+ tuple(row[column] for column in pk_cols),
+ identity_token,
+ )
def identity_key_from_primary_key(self, primary_key, identity_token=None):
"""Return an identity-map key for use in storing/retrieving an
@@ -2574,14 +2701,20 @@ class Mapper(InspectionAttr):
return self._identity_key_from_state(state, attributes.PASSIVE_OFF)
def _identity_key_from_state(
- self, state, passive=attributes.PASSIVE_RETURN_NEVER_SET):
+ self, state, passive=attributes.PASSIVE_RETURN_NEVER_SET
+ ):
dict_ = state.dict
manager = state.manager
- return self._identity_class, tuple([
- manager[prop.key].
- impl.get(state, dict_, passive)
- for prop in self._identity_key_props
- ]), state.identity_token
+ return (
+ self._identity_class,
+ tuple(
+ [
+ manager[prop.key].impl.get(state, dict_, passive)
+ for prop in self._identity_key_props
+ ]
+ ),
+ state.identity_token,
+ )
def primary_key_from_instance(self, instance):
"""Return the list of primary key values for the given
@@ -2595,7 +2728,8 @@ class Mapper(InspectionAttr):
"""
state = attributes.instance_state(instance)
identity_key = self._identity_key_from_state(
- state, attributes.PASSIVE_OFF)
+ state, attributes.PASSIVE_OFF
+ )
return identity_key[1]
@_memoized_configured_property
@@ -2621,8 +2755,8 @@ class Mapper(InspectionAttr):
return {prop.key for prop in self._all_pk_props}
def _get_state_attr_by_column(
- self, state, dict_, column,
- passive=attributes.PASSIVE_RETURN_NEVER_SET):
+ self, state, dict_, column, passive=attributes.PASSIVE_RETURN_NEVER_SET
+ ):
prop = self._columntoproperty[column]
return state.manager[prop.key].impl.get(state, dict_, passive=passive)
@@ -2638,15 +2772,17 @@ class Mapper(InspectionAttr):
state = attributes.instance_state(obj)
dict_ = attributes.instance_dict(obj)
return self._get_committed_state_attr_by_column(
- state, dict_, column, passive=attributes.PASSIVE_OFF)
+ state, dict_, column, passive=attributes.PASSIVE_OFF
+ )
def _get_committed_state_attr_by_column(
- self, state, dict_, column,
- passive=attributes.PASSIVE_RETURN_NEVER_SET):
+ self, state, dict_, column, passive=attributes.PASSIVE_RETURN_NEVER_SET
+ ):
prop = self._columntoproperty[column]
- return state.manager[prop.key].impl.\
- get_committed_value(state, dict_, passive=passive)
+ return state.manager[prop.key].impl.get_committed_value(
+ state, dict_, passive=passive
+ )
def _optimized_get_statement(self, state, attribute_names):
"""assemble a WHERE clause which retrieves a given state by primary
@@ -2660,11 +2796,15 @@ class Mapper(InspectionAttr):
"""
props = self._props
- tables = set(chain(
- *[sql_util.find_tables(c, check_columns=True)
- for key in attribute_names
- for c in props[key].columns]
- ))
+ tables = set(
+ chain(
+ *[
+ sql_util.find_tables(c, check_columns=True)
+ for key in attribute_names
+ for c in props[key].columns
+ ]
+ )
+ )
if self.base_mapper.local_table in tables:
return None
@@ -2680,22 +2820,28 @@ class Mapper(InspectionAttr):
if leftcol.table not in tables:
leftval = self._get_committed_state_attr_by_column(
- state, state.dict,
+ state,
+ state.dict,
leftcol,
- passive=attributes.PASSIVE_NO_INITIALIZE)
+ passive=attributes.PASSIVE_NO_INITIALIZE,
+ )
if leftval in orm_util._none_set:
raise ColumnsNotAvailable()
- binary.left = sql.bindparam(None, leftval,
- type_=binary.right.type)
+ binary.left = sql.bindparam(
+ None, leftval, type_=binary.right.type
+ )
elif rightcol.table not in tables:
rightval = self._get_committed_state_attr_by_column(
- state, state.dict,
+ state,
+ state.dict,
rightcol,
- passive=attributes.PASSIVE_NO_INITIALIZE)
+ passive=attributes.PASSIVE_NO_INITIALIZE,
+ )
if rightval in orm_util._none_set:
raise ColumnsNotAvailable()
- binary.right = sql.bindparam(None, rightval,
- type_=binary.right.type)
+ binary.right = sql.bindparam(
+ None, rightval, type_=binary.right.type
+ )
allconds = []
@@ -2704,15 +2850,17 @@ class Mapper(InspectionAttr):
for mapper in reversed(list(self.iterate_to_root())):
if mapper.local_table in tables:
start = True
- elif not isinstance(mapper.local_table,
- expression.TableClause):
+ elif not isinstance(
+ mapper.local_table, expression.TableClause
+ ):
return None
if start and not mapper.single:
- allconds.append(visitors.cloned_traverse(
- mapper.inherit_condition,
- {},
- {'binary': visit_binary}
- )
+ allconds.append(
+ visitors.cloned_traverse(
+ mapper.inherit_condition,
+ {},
+ {"binary": visit_binary},
+ )
)
except ColumnsNotAvailable:
return None
@@ -2730,8 +2878,7 @@ class Mapper(InspectionAttr):
for m in self.iterate_to_root():
yield m
- if m is not prev and prev not in \
- m._with_polymorphic_mappers:
+ if m is not prev and prev not in m._with_polymorphic_mappers:
break
prev = m
@@ -2743,7 +2890,7 @@ class Mapper(InspectionAttr):
# common case, takes place for all polymorphic loads
mapper = polymorphic_from
for m in self._iterate_to_target_viawpoly(mapper):
- if m.polymorphic_load == 'selectin':
+ if m.polymorphic_load == "selectin":
return m
else:
# uncommon case, selectin load options were used
@@ -2752,15 +2899,17 @@ class Mapper(InspectionAttr):
for entity in enabled_via_opt.union([polymorphic_from]):
mapper = entity.mapper
for m in self._iterate_to_target_viawpoly(mapper):
- if m.polymorphic_load == 'selectin' or \
- m in enabled_via_opt_mappers:
+ if (
+ m.polymorphic_load == "selectin"
+ or m in enabled_via_opt_mappers
+ ):
return enabled_via_opt_mappers.get(m, m)
return None
@util.dependencies(
- "sqlalchemy.ext.baked",
- "sqlalchemy.orm.strategy_options")
+ "sqlalchemy.ext.baked", "sqlalchemy.orm.strategy_options"
+ )
def _subclass_load_via_in(self, baked, strategy_options, entity):
"""Assemble a BakedQuery that can load the columns local to
this subclass as a SELECT with IN.
@@ -2768,10 +2917,8 @@ class Mapper(InspectionAttr):
"""
assert self.inherits
- polymorphic_prop = self._columntoproperty[
- self.polymorphic_on]
- keep_props = set(
- [polymorphic_prop] + self._identity_key_props)
+ polymorphic_prop = self._columntoproperty[self.polymorphic_on]
+ keep_props = set([polymorphic_prop] + self._identity_key_props)
disable_opt = strategy_options.Load(entity)
enable_opt = strategy_options.Load(entity)
@@ -2781,16 +2928,14 @@ class Mapper(InspectionAttr):
# "enable" options, to turn on the properties that we want to
# load by default (subject to options from the query)
enable_opt.set_generic_strategy(
- (prop.key, ),
- dict(prop.strategy_key)
+ (prop.key,), dict(prop.strategy_key)
)
else:
# "disable" options, to turn off the properties from the
# superclass that we *don't* want to load, applied after
# the options from the query to override them
disable_opt.set_generic_strategy(
- (prop.key, ),
- {"do_nothing": True}
+ (prop.key,), {"do_nothing": True}
)
if len(self.primary_key) > 1:
@@ -2802,22 +2947,21 @@ class Mapper(InspectionAttr):
assert entity.mapper is self
q = baked.BakedQuery(
self._compiled_cache,
- lambda session: session.query(entity).
- select_entity_from(entity.selectable)._adapt_all_clauses(),
- (self, )
+ lambda session: session.query(entity)
+ .select_entity_from(entity.selectable)
+ ._adapt_all_clauses(),
+ (self,),
)
q.spoil()
else:
q = baked.BakedQuery(
self._compiled_cache,
lambda session: session.query(self),
- (self, )
+ (self,),
)
q += lambda q: q.filter(
- in_expr.in_(
- sql.bindparam('primary_keys', expanding=True)
- )
+ in_expr.in_(sql.bindparam("primary_keys", expanding=True))
).order_by(*self.primary_key)
return q, enable_opt, disable_opt
@@ -2856,8 +3000,9 @@ class Mapper(InspectionAttr):
assert state.mapper.isa(self)
- visitables = deque([(deque(state.mapper._props.values()), prp,
- state, state.dict)])
+ visitables = deque(
+ [(deque(state.mapper._props.values()), prp, state, state.dict)]
+ )
while visitables:
iterator, item_type, parent_state, parent_dict = visitables[-1]
@@ -2869,21 +3014,28 @@ class Mapper(InspectionAttr):
prop = iterator.popleft()
if type_ not in prop.cascade:
continue
- queue = deque(prop.cascade_iterator(
- type_, parent_state, parent_dict,
- visited_states, halt_on))
+ queue = deque(
+ prop.cascade_iterator(
+ type_,
+ parent_state,
+ parent_dict,
+ visited_states,
+ halt_on,
+ )
+ )
if queue:
visitables.append((queue, mpp, None, None))
elif item_type is mpp:
- instance, instance_mapper, corresponding_state, \
- corresponding_dict = iterator.popleft()
- yield instance, instance_mapper, \
- corresponding_state, corresponding_dict
+ instance, instance_mapper, corresponding_state, corresponding_dict = (
+ iterator.popleft()
+ )
+ yield instance, instance_mapper, corresponding_state, corresponding_dict
visitables.append(
(
deque(instance_mapper._props.values()),
- prp, corresponding_state,
- corresponding_dict
+ prp,
+ corresponding_state,
+ corresponding_dict,
)
)
@@ -2903,10 +3055,9 @@ class Mapper(InspectionAttr):
for table, mapper in table_to_mapper.items():
super_ = mapper.inherits
if super_:
- extra_dependencies.extend([
- (super_table, table)
- for super_table in super_.tables
- ])
+ extra_dependencies.extend(
+ [(super_table, table) for super_table in super_.tables]
+ )
def skip(fk):
# attempt to skip dependencies that are not
@@ -2916,22 +3067,27 @@ class Mapper(InspectionAttr):
# not what we mean to sort on here.
parent = table_to_mapper.get(fk.parent.table)
dep = table_to_mapper.get(fk.column.table)
- if parent is not None and \
- dep is not None and \
- dep is not parent and \
- dep.inherit_condition is not None:
+ if (
+ parent is not None
+ and dep is not None
+ and dep is not parent
+ and dep.inherit_condition is not None
+ ):
cols = set(sql_util._find_columns(dep.inherit_condition))
if parent.inherit_condition is not None:
- cols = cols.union(sql_util._find_columns(
- parent.inherit_condition))
+ cols = cols.union(
+ sql_util._find_columns(parent.inherit_condition)
+ )
return fk.parent not in cols and fk.column not in cols
else:
return fk.parent not in cols
return False
- sorted_ = sql_util.sort_tables(table_to_mapper,
- skip_fn=skip,
- extra_dependencies=extra_dependencies)
+ sorted_ = sql_util.sort_tables(
+ table_to_mapper,
+ skip_fn=skip,
+ extra_dependencies=extra_dependencies,
+ )
ret = util.OrderedDict()
for t in sorted_:
@@ -2955,12 +3111,12 @@ class Mapper(InspectionAttr):
for table in self._sorted_tables:
cols = set(table.c)
for m in self.iterate_to_root():
- if m._inherits_equated_pairs and \
- cols.intersection(
- util.reduce(set.union,
- [l.proxy_set for l, r in
- m._inherits_equated_pairs])
- ):
+ if m._inherits_equated_pairs and cols.intersection(
+ util.reduce(
+ set.union,
+ [l.proxy_set for l, r in m._inherits_equated_pairs],
+ )
+ ):
result[table].append((m, m._inherits_equated_pairs))
return result
@@ -3034,13 +3190,14 @@ def configure_mappers():
if run_configure is EXT_SKIP:
continue
- if getattr(mapper, '_configure_failed', False):
+ if getattr(mapper, "_configure_failed", False):
e = sa_exc.InvalidRequestError(
"One or more mappers failed to initialize - "
"can't proceed with initialization of other "
"mappers. Triggering mapper: '%s'. "
"Original exception was: %s"
- % (mapper, mapper._configure_failed))
+ % (mapper, mapper._configure_failed)
+ )
e._configure_failed = mapper._configure_failed
raise e
@@ -3049,10 +3206,11 @@ def configure_mappers():
mapper._post_configure_properties()
mapper._expire_memoizations()
mapper.dispatch.mapper_configured(
- mapper, mapper.class_)
+ mapper, mapper.class_
+ )
except Exception:
exc = sys.exc_info()[1]
- if not hasattr(exc, '_configure_failed'):
+ if not hasattr(exc, "_configure_failed"):
mapper._configure_failed = exc
raise
@@ -3127,16 +3285,17 @@ def validates(*names, **kw):
:ref:`simple_validators` - usage examples for :func:`.validates`
"""
- include_removes = kw.pop('include_removes', False)
- include_backrefs = kw.pop('include_backrefs', True)
+ include_removes = kw.pop("include_removes", False)
+ include_backrefs = kw.pop("include_backrefs", True)
def wrap(fn):
fn.__sa_validators__ = names
fn.__sa_validation_opts__ = {
"include_removes": include_removes,
- "include_backrefs": include_backrefs
+ "include_backrefs": include_backrefs,
}
return fn
+
return wrap
@@ -3180,7 +3339,7 @@ def _event_on_init(state, args, kwargs):
class _ColumnMapping(dict):
"""Error reporting helper for mapper._columntoproperty."""
- __slots__ = 'mapper',
+ __slots__ = ("mapper",)
def __init__(self, mapper):
self.mapper = mapper
@@ -3190,8 +3349,10 @@ class _ColumnMapping(dict):
if prop:
raise orm_exc.UnmappedColumnError(
"Column '%s.%s' is not available, due to "
- "conflicting property '%s':%r" % (
- column.table.name, column.name, column.key, prop))
+ "conflicting property '%s':%r"
+ % (column.table.name, column.name, column.key, prop)
+ )
raise orm_exc.UnmappedColumnError(
- "No column %s is configured on mapper %s..." %
- (column, self.mapper))
+ "No column %s is configured on mapper %s..."
+ % (column, self.mapper)
+ )