diff options
| author | Mike Bayer <mike_mp@zzzcomputing.com> | 2012-12-01 20:12:23 -0500 |
|---|---|---|
| committer | Mike Bayer <mike_mp@zzzcomputing.com> | 2012-12-01 20:12:23 -0500 |
| commit | b66dad46f31961ad9f2271e6dae377e38fc67979 (patch) | |
| tree | a3925db6a95a12334548916aa01f51f5ea8107ae /lib/sqlalchemy | |
| parent | 65dd01233f757e70aa9c7a8b5f92386ac066a46c (diff) | |
| download | sqlalchemy-b66dad46f31961ad9f2271e6dae377e38fc67979.tar.gz | |
- refactor of pathing mechanics, to address #2614, #2617
- paths now store Mapper + MapperProperty now instead of string key,
so that the parent mapper for the property is known, supports same-named
properties on multiple subclasses
- the Mapper within the path is now always relevant to the property
to the right of it. PathRegistry does the translation now, instead
of having all the outside users of PathRegistry worry about it,
to produce a path that is much more consistent. Paths are now
consistent with mappings in all cases. Special logic to get at
"with_polymorphic" structures and such added also.
- AliasedClass now has two modes, "use_mapper_path" and regular;
"use_mapper_path" is for all those situations where we put an AliasedClass
in for a plain class internally, and want it to "path" with the
plain mapper.
- The AliasedInsp is now the first class "entity" for an AliasedClass,
and is passed around internally and used as attr._parententity
and such. it is the AliasedClass analogue for Mapper.
Diffstat (limited to 'lib/sqlalchemy')
| -rw-r--r-- | lib/sqlalchemy/ext/serializer.py | 8 | ||||
| -rw-r--r-- | lib/sqlalchemy/orm/interfaces.py | 33 | ||||
| -rw-r--r-- | lib/sqlalchemy/orm/loading.py | 15 | ||||
| -rw-r--r-- | lib/sqlalchemy/orm/mapper.py | 6 | ||||
| -rw-r--r-- | lib/sqlalchemy/orm/query.py | 37 | ||||
| -rw-r--r-- | lib/sqlalchemy/orm/strategies.py | 83 | ||||
| -rw-r--r-- | lib/sqlalchemy/orm/util.py | 189 |
7 files changed, 235 insertions, 136 deletions
diff --git a/lib/sqlalchemy/ext/serializer.py b/lib/sqlalchemy/ext/serializer.py index 3ed41f48a..c129b0dcc 100644 --- a/lib/sqlalchemy/ext/serializer.py +++ b/lib/sqlalchemy/ext/serializer.py @@ -54,6 +54,7 @@ needed for: from ..orm import class_mapper from ..orm.session import Session from ..orm.mapper import Mapper +from ..orm.interfaces import MapperProperty from ..orm.attributes import QueryableAttribute from .. import Table, Column from ..engine import Engine @@ -90,6 +91,9 @@ def Serializer(*args, **kw): id = "attribute:" + key + ":" + b64encode(pickle.dumps(cls)) elif isinstance(obj, Mapper) and not obj.non_primary: id = "mapper:" + b64encode(pickle.dumps(obj.class_)) + elif isinstance(obj, MapperProperty) and not obj.parent.non_primary: + id = "mapperprop:" + b64encode(pickle.dumps(obj.parent.class_)) + \ + ":" + obj.key elif isinstance(obj, Table): id = "table:" + str(obj) elif isinstance(obj, Column) and isinstance(obj.table, Table): @@ -134,6 +138,10 @@ def Deserializer(file, metadata=None, scoped_session=None, engine=None): elif type_ == "mapper": cls = pickle.loads(b64decode(args)) return class_mapper(cls) + elif type_ == "mapperprop": + mapper, keyname = args.split(':') + cls = pickle.loads(b64decode(args)) + return class_mapper(cls).attrs[keyname] elif type_ == "table": return metadata.tables[args] elif type_ == "column": diff --git a/lib/sqlalchemy/orm/interfaces.py b/lib/sqlalchemy/orm/interfaces.py index c91746da0..55a980b2e 100644 --- a/lib/sqlalchemy/orm/interfaces.py +++ b/lib/sqlalchemy/orm/interfaces.py @@ -219,6 +219,10 @@ class MapperProperty(_MappedAttribute, _InspectionAttr): return operator(self.comparator, value) + def __repr__(self): + return '<%s at 0x%x; %s>' % ( + self.__class__.__name__, + id(self), self.key) class PropComparator(operators.ColumnOperators): """Defines boolean, comparison, and other operators for @@ -413,21 +417,18 @@ class StrategizedProperty(MapperProperty): return None def _get_context_strategy(self, context, path): - # this is essentially performance inlining. - key = ('loaderstrategy', path.reduced_path + (self.key,)) - cls = None - if key in context.attributes: - cls = context.attributes[key] - else: + strategy_cls = path._inlined_get_for(self, context, 'loaderstrategy') + + if not strategy_cls: wc_key = self._wildcard_path if wc_key and wc_key in context.attributes: - cls = context.attributes[wc_key] + strategy_cls = context.attributes[wc_key] - if cls: + if strategy_cls: try: - return self._strategies[cls] + return self._strategies[strategy_cls] except KeyError: - return self.__init_strategy(cls) + return self.__init_strategy(strategy_cls) return self.strategy def _get_strategy(self, cls): @@ -528,10 +529,8 @@ class PropertyOption(MapperOption): def _find_entity_prop_comparator(self, query, token, mapper, raiseerr): if orm_util._is_aliased_class(mapper): searchfor = mapper - isa = False else: searchfor = orm_util._class_to_mapper(mapper) - isa = True for ent in query._mapper_entities: if ent.corresponds_to(searchfor): return ent @@ -600,7 +599,7 @@ class PropertyOption(MapperOption): # exhaust current_path before # matching tokens to entities if current_path: - if current_path[1] == token: + if current_path[1].key == token: current_path = current_path[2:] continue else: @@ -634,7 +633,7 @@ class PropertyOption(MapperOption): # matching tokens to entities if current_path: if current_path[0:2] == \ - [token._parententity, prop.key]: + [token._parententity, prop]: current_path = current_path[2:] continue else: @@ -648,6 +647,7 @@ class PropertyOption(MapperOption): raiseerr) if not entity: return no_result + path_element = entity.entity_zero mapper = entity.mapper else: @@ -659,7 +659,7 @@ class PropertyOption(MapperOption): raise sa_exc.ArgumentError("Attribute '%s' does not " "link from element '%s'" % (token, path_element)) - path = path[path_element][prop.key] + path = path[path_element][prop] paths.append(path) @@ -670,7 +670,8 @@ class PropertyOption(MapperOption): if not ext_info.is_aliased_class: ac = orm_util.with_polymorphic( ext_info.mapper.base_mapper, - ext_info.mapper, aliased=True) + ext_info.mapper, aliased=True, + _use_mapper_path=True) ext_info = inspect(ac) path.set(query, "path_with_polymorphic", ext_info) else: diff --git a/lib/sqlalchemy/orm/loading.py b/lib/sqlalchemy/orm/loading.py index a5d156a1f..4bd80c388 100644 --- a/lib/sqlalchemy/orm/loading.py +++ b/lib/sqlalchemy/orm/loading.py @@ -271,6 +271,7 @@ def instance_processor(mapper, context, path, adapter, new_populators = [] existing_populators = [] eager_populators = [] + load_path = context.query._current_path + path \ if context.query._current_path.path \ else path @@ -504,9 +505,12 @@ def _populators(mapper, context, path, row, adapter, delayed_populators = [] pops = (new_populators, existing_populators, delayed_populators, eager_populators) + for prop in mapper._props.itervalues(): + for i, pop in enumerate(prop.create_row_processor( - context, path, + context, + path, mapper, row, adapter)): if pop is not None: pops[i].append((prop.key, pop)) @@ -529,17 +533,10 @@ def _configure_subclass_mapper(mapper, context, path, adapter): if sub_mapper is mapper: return None - # replace the tip of the path info with the subclass mapper - # being used, that way accurate "load_path" info is available - # for options invoked during deferred loads, e.g. - # query(Person).options(defer(Engineer.machines, Machine.name)). - # for AliasedClass paths, disregard this step (new in 0.8). return instance_processor( sub_mapper, context, - path.parent[sub_mapper] - if not path.is_aliased_class - else path, + path, adapter, polymorphic_from=mapper) return configure_subclass_mapper diff --git a/lib/sqlalchemy/orm/mapper.py b/lib/sqlalchemy/orm/mapper.py index b89163340..626105b5e 100644 --- a/lib/sqlalchemy/orm/mapper.py +++ b/lib/sqlalchemy/orm/mapper.py @@ -472,7 +472,7 @@ class Mapper(_InspectionAttr): dispatch = event.dispatcher(events.MapperEvents) @util.memoized_property - def _sa_path_registry(self): + def _path_registry(self): return PathRegistry.per_mapper(self) def _configure_inheritance(self): @@ -1403,7 +1403,7 @@ class Mapper(_InspectionAttr): if _new_mappers: configure_mappers() if not self.with_polymorphic: - return [self] + return [] return self._mappers_from_spec(*self.with_polymorphic) @_memoized_configured_property @@ -1458,10 +1458,10 @@ class Mapper(_InspectionAttr): 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 a SELECT.""" - if mappers is None: mappers = self._with_polymorphic_mappers diff --git a/lib/sqlalchemy/orm/query.py b/lib/sqlalchemy/orm/query.py index ca334e273..d6847177f 100644 --- a/lib/sqlalchemy/orm/query.py +++ b/lib/sqlalchemy/orm/query.py @@ -157,7 +157,7 @@ class Query(object): ent.setup_entity(*d[entity]) def _mapper_loads_polymorphically_with(self, mapper, adapter): - for m2 in mapper._with_polymorphic_mappers: + for m2 in mapper._with_polymorphic_mappers or [mapper]: self._polymorphic_adapters[m2] = adapter for m in m2.iterate_to_root(): self._polymorphic_adapters[m.local_table] = adapter @@ -2744,17 +2744,24 @@ class _MapperEntity(_QueryEntity): self._with_polymorphic = ext_info.with_polymorphic_mappers self._polymorphic_discriminator = \ ext_info.polymorphic_on + self.entity_zero = ext_info if ext_info.is_aliased_class: - self.entity_zero = ext_info.entity - self._label_name = self.entity_zero._sa_label_name + self._label_name = self.entity_zero.name else: - self.entity_zero = self.mapper self._label_name = self.mapper.class_.__name__ - self.path = self.entity_zero._sa_path_registry + self.path = self.entity_zero._path_registry def set_with_polymorphic(self, query, cls_or_mappers, selectable, polymorphic_on): + """Receive an update from a call to query.with_polymorphic(). + + Note the newer style of using a free standing with_polymporphic() + construct doesn't make use of this method. + + + """ if self.is_aliased_class: + # TODO: invalidrequest ? raise NotImplementedError( "Can't use with_polymorphic() against " "an Aliased object" @@ -2785,13 +2792,18 @@ class _MapperEntity(_QueryEntity): return self.entity_zero def corresponds_to(self, entity): - entity_info = inspect(entity) - if entity_info.is_aliased_class or self.is_aliased_class: - return entity is self.entity_zero \ - or \ - entity in self._with_polymorphic - else: - return entity.common_parent(self.entity_zero) + if entity.is_aliased_class: + if self.is_aliased_class: + if entity._base_alias is self.entity_zero._base_alias: + return True + return False + elif self.is_aliased_class: + if self.entity_zero._use_mapper_path: + return entity in self._with_polymorphic + else: + return entity is self.entity_zero + + return entity.common_parent(self.entity_zero) def adapt_to_selectable(self, query, sel): query._entities.append(self) @@ -3008,6 +3020,7 @@ class _ColumnEntity(_QueryEntity): if self.entity_zero is None: return False elif _is_aliased_class(entity): + # TODO: polymorphic subclasses ? return entity is self.entity_zero else: return not _is_aliased_class(self.entity_zero) and \ diff --git a/lib/sqlalchemy/orm/strategies.py b/lib/sqlalchemy/orm/strategies.py index 586ec4b4e..05c7ef37b 100644 --- a/lib/sqlalchemy/orm/strategies.py +++ b/lib/sqlalchemy/orm/strategies.py @@ -303,16 +303,6 @@ class AbstractRelationshipLoader(LoaderStrategy): self.uselist = self.parent_property.uselist - def _warn_existing_path(self): - raise sa_exc.InvalidRequestError( - "Eager loading cannot currently function correctly when two or " - "more " - "same-named attributes associated with multiple polymorphic " - "classes " - "of the same base are present. Encountered more than one " - r"eager path for attribute '%s' on mapper '%s'." % - (self.key, self.parent.base_mapper, )) - class NoLoader(AbstractRelationshipLoader): """Provide loading behavior for a :class:`.RelationshipProperty` @@ -564,7 +554,7 @@ class LazyLoader(AbstractRelationshipLoader): q = q.autoflush(False) if state.load_path: - q = q._with_current_path(state.load_path[self.key]) + q = q._with_current_path(state.load_path[self.parent_property]) if state.load_options: q = q._conditional_options(*state.load_options) @@ -694,7 +684,7 @@ class SubqueryLoader(AbstractRelationshipLoader): if not context.query._enable_eagerloads: return - path = path[self.key] + path = path[self.parent_property] # build up a path indicating the path from the leftmost # entity to the thing we're subquery loading. @@ -757,22 +747,20 @@ class SubqueryLoader(AbstractRelationshipLoader): # add new query to attributes to be picked up # by create_row_processor - existing = path.replace(context, "subquery", q) - if existing: - self._warn_existing_path() + path.set(context, "subquery", q) def _get_leftmost(self, subq_path): subq_path = subq_path.path subq_mapper = orm_util._class_to_mapper(subq_path[0]) # determine attributes of the leftmost mapper - if self.parent.isa(subq_mapper) and self.key == subq_path[1]: + if self.parent.isa(subq_mapper) and self.parent_property is subq_path[1]: leftmost_mapper, leftmost_prop = \ self.parent, self.parent_property else: leftmost_mapper, leftmost_prop = \ subq_mapper, \ - subq_mapper._props[subq_path[1]] + subq_path[1] leftmost_cols = leftmost_prop.local_columns @@ -805,23 +793,35 @@ class SubqueryLoader(AbstractRelationshipLoader): # the original query now becomes a subquery # which we'll join onto. embed_q = q.with_labels().subquery() - left_alias = orm_util.AliasedClass(leftmost_mapper, embed_q) + left_alias = orm_util.AliasedClass(leftmost_mapper, embed_q, + use_mapper_path=True) return left_alias def _prep_for_joins(self, left_alias, subq_path): - subq_path = subq_path.path - # figure out what's being joined. a.k.a. the fun part - to_join = [ - (subq_path[i], subq_path[i + 1]) - for i in xrange(0, len(subq_path), 2) - ] + to_join = [] + pairs = list(subq_path.pairs()) + + for i, (mapper, prop) in enumerate(pairs): + if i > 0: + # look at the previous mapper in the chain - + # if it is as or more specific than this prop's + # mapper, use that instead. + # note we have an assumption here that + # the non-first element is always going to be a mapper, + # not an AliasedClass + + prev_mapper = pairs[i - 1][1].mapper + to_append = prev_mapper if prev_mapper.isa(mapper) else mapper + else: + to_append = mapper + + to_join.append((to_append, prop.key)) # determine the immediate parent class we are joining from, # which needs to be aliased. - if len(to_join) > 1: - info = inspect(subq_path[-2]) + info = inspect(to_join[-1][0]) if len(to_join) < 2: # in the case of a one level eager load, this is the @@ -833,11 +833,13 @@ class SubqueryLoader(AbstractRelationshipLoader): # in the vast majority of cases, and [ticket:2014] # illustrates a case where sub_path[-2] is a subclass # of self.parent - parent_alias = orm_util.AliasedClass(subq_path[-2]) + parent_alias = orm_util.AliasedClass(to_join[-1][0], + use_mapper_path=True) else: # if of_type() were used leading to this relationship, # self.parent is more specific than subq_path[-2] - parent_alias = orm_util.AliasedClass(self.parent) + parent_alias = orm_util.AliasedClass(self.parent, + use_mapper_path=True) local_cols = self.parent_property.local_columns @@ -916,9 +918,10 @@ class SubqueryLoader(AbstractRelationshipLoader): "population - eager loading cannot be applied." % self) - path = path[self.key] + path = path[self.parent_property] subq = path.get(context, 'subquery') + if subq is None: return None, None, None @@ -1000,7 +1003,7 @@ class JoinedLoader(AbstractRelationshipLoader): if not context.query._enable_eagerloads: return - path = path[self.key] + path = path[self.parent_property] with_polymorphic = None @@ -1040,6 +1043,7 @@ class JoinedLoader(AbstractRelationshipLoader): with_polymorphic = None path = path[self.mapper] + for value in self.mapper._iterate_polymorphic_properties( mappers=with_polymorphic): value.setup( @@ -1079,7 +1083,8 @@ class JoinedLoader(AbstractRelationshipLoader): if with_poly_info: to_adapt = with_poly_info.entity else: - to_adapt = orm_util.AliasedClass(self.mapper) + to_adapt = orm_util.AliasedClass(self.mapper, + use_mapper_path=True) clauses = orm_util.ORMAdapter( to_adapt, equivalents=self.mapper._equivalent_columns, @@ -1104,9 +1109,8 @@ class JoinedLoader(AbstractRelationshipLoader): ) add_to_collection = context.secondary_columns - existing = path.replace(context, "eager_row_processor", clauses) - if existing: - self._warn_existing_path() + path.set(context, "eager_row_processor", clauses) + return clauses, adapter, add_to_collection, allow_innerjoin def _create_eager_join(self, context, entity, @@ -1154,7 +1158,8 @@ class JoinedLoader(AbstractRelationshipLoader): onclause = getattr( orm_util.AliasedClass( self.parent, - adapter.selectable + adapter.selectable, + use_mapper_path=True ), self.key, self.parent_property ) @@ -1238,7 +1243,7 @@ class JoinedLoader(AbstractRelationshipLoader): "population - eager loading cannot be applied." % self) - our_path = path[self.key] + our_path = path[self.parent_property] eager_adapter = self._create_eager_adapter( context, @@ -1391,15 +1396,13 @@ class LoadEagerFromAliasOption(PropertyOption): def process_query_property(self, query, paths): if self.chained: for path in paths[0:-1]: - (root_mapper, propname) = path.path[-2:] - prop = root_mapper._props[propname] + (root_mapper, prop) = path.path[-2:] adapter = query._polymorphic_adapters.get(prop.mapper, None) path.setdefault(query, "user_defined_eager_row_processor", adapter) - root_mapper, propname = paths[-1].path[-2:] - prop = root_mapper._props[propname] + root_mapper, prop = paths[-1].path[-2:] if self.alias is not None: if isinstance(self.alias, basestring): self.alias = prop.target.alias(self.alias) diff --git a/lib/sqlalchemy/orm/util.py b/lib/sqlalchemy/orm/util.py index e5e725138..04838cb64 100644 --- a/lib/sqlalchemy/orm/util.py +++ b/lib/sqlalchemy/orm/util.py @@ -245,6 +245,8 @@ class ORMAdapter(sql_util.ColumnAdapter): else: return None +def _unreduce_path(path): + return PathRegistry.deserialize(path) class PathRegistry(object): """Represent query load paths and registry functions. @@ -277,19 +279,13 @@ class PathRegistry(object): self.path == other.path def set(self, reg, key, value): - reg._attributes[(key, self.reduced_path)] = value - - def replace(self, reg, key, value): - path_key = (key, self.reduced_path) - existing = reg._attributes.get(path_key, None) - reg._attributes[path_key] = value - return existing + reg._attributes[(key, self.path)] = value def setdefault(self, reg, key, value): - reg._attributes.setdefault((key, self.reduced_path), value) + reg._attributes.setdefault((key, self.path), value) def get(self, reg, key, value=None): - key = (key, self.reduced_path) + key = (key, self.path) if key in reg._attributes: return reg._attributes[key] else: @@ -302,17 +298,25 @@ class PathRegistry(object): def length(self): return len(self.path) + def pairs(self): + path = self.path + for i in xrange(0, len(path), 2): + yield path[i], path[i + 1] + def contains_mapper(self, mapper): return mapper in self.path def contains(self, reg, key): - return (key, self.reduced_path) in reg._attributes + return (key, self.path) in reg._attributes + + def __reduce__(self): + return _unreduce_path, (self.serialize(), ) def serialize(self): path = self.path return zip( [m.class_ for m in [path[i] for i in range(0, len(path), 2)]], - [path[i] for i in range(1, len(path), 2)] + [None] + [path[i].key for i in range(1, len(path), 2)] + [None] ) @classmethod @@ -320,7 +324,10 @@ class PathRegistry(object): if path is None: return None - p = tuple(chain(*[(class_mapper(mcls), key) for mcls, key in path])) + p = tuple(chain(*[(class_mapper(mcls), + class_mapper(mcls).attrs[key] + if key is not None else None) + for mcls, key in path])) if p and p[-1] is None: p = p[0:-1] return cls.coerce(p) @@ -337,7 +344,7 @@ class PathRegistry(object): @classmethod def token(cls, token): - return KeyRegistry(cls.root, token) + return TokenRegistry(cls.root, token) def __add__(self, other): return util.reduce( @@ -354,19 +361,36 @@ class RootRegistry(PathRegistry): """ path = () - reduced_path = () - def __getitem__(self, mapper): - return mapper._sa_path_registry + def __getitem__(self, entity): + return entity._path_registry PathRegistry.root = RootRegistry() +class TokenRegistry(PathRegistry): + def __init__(self, parent, token): + self.token = token + self.parent = parent + self.path = parent.path + (token,) -class KeyRegistry(PathRegistry): - def __init__(self, parent, key): - self.key = key + def __getitem__(self, entity): + raise NotImplementedError() + +class PropRegistry(PathRegistry): + def __init__(self, parent, prop): + # restate this path in terms of the + # given MapperProperty's parent. + insp = inspection.inspect(parent[-1]) + if not insp.is_aliased_class or insp._use_mapper_path: + parent = parent.parent[prop.parent] + elif insp.is_aliased_class and insp.with_polymorphic_mappers: + if prop.parent is not insp.mapper and \ + prop.parent in insp.with_polymorphic_mappers: + subclass_entity = parent[-1]._entity_for_mapper(prop.parent) + parent = parent.parent[subclass_entity] + + self.prop = prop self.parent = parent - self.path = parent.path + (key,) - self.reduced_path = parent.reduced_path + (key,) + self.path = parent.path + (prop,) def __getitem__(self, entity): if isinstance(entity, (int, slice)): @@ -381,15 +405,11 @@ class EntityRegistry(PathRegistry, dict): is_aliased_class = False def __init__(self, parent, entity): - self.key = reduced_key = entity + self.key = entity self.parent = parent - if hasattr(entity, 'base_mapper'): - reduced_key = entity.base_mapper - else: - self.is_aliased_class = True + self.is_aliased_class = entity.is_aliased_class self.path = parent.path + (entity,) - self.reduced_path = parent.reduced_path + (reduced_key,) def __nonzero__(self): return True @@ -400,8 +420,26 @@ class EntityRegistry(PathRegistry, dict): else: return dict.__getitem__(self, entity) + def _inlined_get_for(self, prop, context, key): + """an inlined version of: + + cls = path[mapperproperty].get(context, key) + + Skips the isinstance() check in __getitem__ + and the extra method call for get(). + Used by StrategizedProperty for its + very frequent lookup. + + """ + path = dict.__getitem__(self, prop) + path_key = (key, path.path) + if path_key in context._attributes: + return context._attributes[path_key] + else: + return None + def __missing__(self, key): - self[key] = item = KeyRegistry(self, key) + self[key] = item = PropRegistry(self, key) return item @@ -448,8 +486,11 @@ class AliasedClass(object): def __init__(self, cls, alias=None, name=None, adapt_on_names=False, + # TODO: None for default here? with_polymorphic_mappers=(), - with_polymorphic_discriminator=None): + with_polymorphic_discriminator=None, + base_alias=None, + use_mapper_path=False): mapper = _class_to_mapper(cls) if alias is None: alias = mapper._with_polymorphic_selectable.alias(name=name) @@ -458,11 +499,19 @@ class AliasedClass(object): mapper, alias, name, - with_polymorphic_mappers, + with_polymorphic_mappers + if with_polymorphic_mappers + else mapper.with_polymorphic_mappers, with_polymorphic_discriminator + if with_polymorphic_discriminator is not None + else mapper.polymorphic_on, + base_alias, + use_mapper_path ) + self._setup(self._aliased_insp, adapt_on_names) + def _setup(self, aliased_insp, adapt_on_names): self.__adapt_on_names = adapt_on_names mapper = aliased_insp.mapper @@ -473,18 +522,13 @@ class AliasedClass(object): equivalents=mapper._equivalent_columns, adapt_on_names=self.__adapt_on_names) for poly in aliased_insp.with_polymorphic_mappers: - setattr(self, poly.class_.__name__, - AliasedClass(poly.class_, alias)) + if poly is not mapper: + setattr(self, poly.class_.__name__, + AliasedClass(poly.class_, alias, base_alias=self, + use_mapper_path=self._aliased_insp._use_mapper_path)) - # used to assign a name to the RowTuple object - # returned by Query. - self._sa_label_name = aliased_insp.name self.__name__ = 'AliasedClass_%s' % self.__target.__name__ - @util.memoized_property - def _sa_path_registry(self): - return PathRegistry.per_mapper(self) - def __getstate__(self): return { 'mapper': self._aliased_insp.mapper, @@ -494,7 +538,9 @@ class AliasedClass(object): 'with_polymorphic_mappers': self._aliased_insp.with_polymorphic_mappers, 'with_polymorphic_discriminator': - self._aliased_insp.polymorphic_on + self._aliased_insp.polymorphic_on, + 'base_alias': self._aliased_insp._base_alias.entity, + 'use_mapper_path': self._aliased_insp._use_mapper_path } def __setstate__(self, state): @@ -503,8 +549,10 @@ class AliasedClass(object): state['mapper'], state['alias'], state['name'], - state.get('with_polymorphic_mappers'), - state.get('with_polymorphic_discriminator') + state['with_polymorphic_mappers'], + state['with_polymorphic_discriminator'], + state['base_alias'], + state['use_mapper_path'] ) self._setup(self._aliased_insp, state['adapt_on_names']) @@ -521,7 +569,7 @@ class AliasedClass(object): queryattr = attributes.QueryableAttribute( self, key, impl=existing.impl, - parententity=self, + parententity=self._aliased_insp, comparator=comparator) setattr(self, key, queryattr) return queryattr @@ -558,17 +606,7 @@ class AliasedClass(object): id(self), self.__target.__name__) -AliasedInsp = util.namedtuple("AliasedInsp", [ - "entity", - "mapper", - "selectable", - "name", - "with_polymorphic_mappers", - "polymorphic_on" - ]) - - -class AliasedInsp(_InspectionAttr, AliasedInsp): +class AliasedInsp(_InspectionAttr): """Provide an inspection interface for an :class:`.AliasedClass` object. @@ -604,6 +642,22 @@ class AliasedInsp(_InspectionAttr, AliasedInsp): """ + def __init__(self, entity, mapper, selectable, name, + with_polymorphic_mappers, polymorphic_on, + _base_alias, _use_mapper_path): + self.entity = entity + self.mapper = mapper + self.selectable = selectable + self.name = name + self.with_polymorphic_mappers = with_polymorphic_mappers + self.polymorphic_on = polymorphic_on + + # a little dance to get serialization to work + self._base_alias = _base_alias._aliased_insp if _base_alias \ + and _base_alias is not entity else self + self._use_mapper_path = _use_mapper_path + + is_aliased_class = True "always returns True" @@ -613,8 +667,29 @@ class AliasedInsp(_InspectionAttr, AliasedInsp): :class:`.AliasedInsp`.""" return self.mapper.class_ + @util.memoized_property + def _path_registry(self): + if self._use_mapper_path: + return self.mapper._path_registry + else: + return PathRegistry.per_mapper(self) + + def _entity_for_mapper(self, mapper): + self_poly = self.with_polymorphic_mappers + if mapper in self_poly: + return getattr(self.entity, mapper.class_.__name__)._aliased_insp + elif mapper.isa(self.mapper): + return self + else: + assert False, "mapper %s doesn't correspond to %s" % (mapper, self) + + def __repr__(self): + return '<AliasedInsp at 0x%x; %s>' % ( + id(self), self.class_.__name__) + inspection._inspects(AliasedClass)(lambda target: target._aliased_insp) +inspection._inspects(AliasedInsp)(lambda target: target) def aliased(element, alias=None, name=None, adapt_on_names=False): @@ -699,7 +774,7 @@ def aliased(element, alias=None, name=None, adapt_on_names=False): def with_polymorphic(base, classes, selectable=False, polymorphic_on=None, aliased=False, - innerjoin=False): + innerjoin=False, _use_mapper_path=False): """Produce an :class:`.AliasedClass` construct which specifies columns for descendant mappers of the given base. @@ -758,7 +833,8 @@ def with_polymorphic(base, classes, selectable=False, return AliasedClass(base, selectable, with_polymorphic_mappers=mappers, - with_polymorphic_discriminator=polymorphic_on) + with_polymorphic_discriminator=polymorphic_on, + use_mapper_path=_use_mapper_path) def _orm_annotate(element, exclude=None): @@ -1109,6 +1185,7 @@ def _entity_descriptor(entity, key): description = entity entity = insp.c elif insp.is_aliased_class: + entity = insp.entity description = entity elif hasattr(insp, "mapper"): description = entity = insp.mapper.class_ |
