U kfP@sUdZddlmZddlmZddlmZddlmZddl Z ddl Z ddl m Z ddl m Z dd l mZdd l mZdd l mZdd l mZdd l mZddl mZddl mZddl mZddl mZddl mZddl mZddl mZddl mZddl mZddl mZddl mZddl mZddl mZddl Z ddl!m"Z"ddl!m#Z$ddl!m%Z%ddl!m&Z&dd l!m'Z'dd!l!m(Z)dd"l*m+Z+dd#l,m-Z-dd$l,m.Z.dd%l,m/Z/dd&l,m0Z0dd'l,m1Z1dd(l2m3Z3dd)l2m4Z4dd*l2m5Z5dd+l2m6Z6dd,l2m7Z7dd-l2m8Z8dd.l2m9Z9dd/l:m;Z;d0d1l!mZ>d0d3l!m?Z?d0d4l!m@Z@d0d5l!mAZAd0d!l!m(Z(d0d6llAmKZKd0d?lLmMZMd0d@lNmOZOd0dAlPmQZQd0dBlPmRZRd0dClSmTZTd0dDl(mUZUd0dEl(mVZVd0dFlWmXZXerddGl*mYZYddHl*mZZZddIl*m[Z[ddJl*m\Z\ddKl]m^Z^ddLl_m`Z`ddMlambZbddNlamcZcddOldmeZeddPl%mfZfddQl:mgZgddRl'mhZhddSlimjZjddTlkmlZlddUl(mmZmd0dVlnmoZod0dWlnmpZpd0dXlqmrZrd0dYlqmsZsd0dZltmuZud0d[lNmvZvd0d\lNmwZwd0d]lSmxZxd0d^l(myZyed_e d`Zzedadbd`Z{edcddd`Z|eeXdeeeeXdeeedfee ffedgfeedfee ffZ}e ~Zdhedi<djdkdldmZdndkdodpZdqae(drZe Ze>je?jGdsdtdte8e7e+eMe5e?je>jdueCee+ ZGdvdwdweZdxdkdydzZd{d|dxd}d~dZe(dd{d|dxd}ddZe(dd{d|dxd}ddZddZdqdddd|d|ddddZddZddZGdddedZdS)a5Logic to map Python classes to and from selectables. Defines the :class:`~sqlalchemy.orm.mapper.Mapper` class, the central configurational unit which associates a class with a database table. This is a semi-private module; the main configurational API of the ORM is available in :class:`~sqlalchemy.orm.`. ) annotations)deque)reduce)chainN)Any)Callable)cast) Collection)Deque)Dict) FrozenSet)Generic)Iterable)Iterator)List)Mapping)Optional)Sequence)Set)Tuple)Type) TYPE_CHECKING)TypeVar)Union) attributes)exc)instrumentation)loading) properties)util)_O)_class_to_mapper)_parse_mapper_argument) _state_mapper) PassiveFlag) state_str)_MappedAttribute)EXT_SKIP)InspectionAttr)MapperProperty)ORMEntityColumnsClauseRole)ORMFromClauseRole)StrategizedProperty) PathRegistry)event) inspection)log)schema)sql) dispatcher) EventTarget)base) coercions) expression) operators)roles) TableClause)visitors)MemoizedHasCacheKey)KeyedColumnElement)Column)Table)LABEL_STYLE_TABLENAME_PLUS_COL) HasMemoized)!HasMemoized_ro_memoized_attribute)Literal)_IdentityKeyType) _InstanceDict)_ORMColumnExprArgument) _RegistryType)registry)DependencyProcessor)CompositeProperty)SynonymProperty) MapperEvents) ClassManager)CachingEntityRegistry)ColumnProperty)RelationshipProperty) InstanceState) ORMAdapter)Row) RowMapping)_ColumnExpressionArgument)_EquivalentColumnMap)ReadOnlyColumnCollection) ColumnClause) ColumnElement) FromClause) OrderedSet_T)bound_MPMapperProperty[Any]_FnzCallable[..., Any]* Mapper[Any]r\z.weakref.WeakKeyDictionary[_RegistryType, bool]_mapper_registriesz Set[registry]returnc Cs$tttW5QRSQRXdSN)_CONFIGURE_MUTEXsetrerkrkE/opt/hc_python/lib64/python3.8/site-packages/sqlalchemy/orm/mapper.py_all_registriessrmIterator[Mapper[Any]]ccstD]}|EdHqdSrh)rm_mappers_to_configure)regrkrkrl_unconfigured_mapperss rqF NO_ATTRIBUTEc @s eZdZUdZded<dZdZded<dZej dddd ddddddddddddddddddddddddddddd d!d"Z d#d$Z d%d&Z d Z dZd'ed(<ed)d*d+d,Zed-d.Zd ed/<d ed0<d1ed2<d3ed4<d5ed6<d7ed8<d9ed:<ded;<ded?<d@edA<dBedC<dDedE<dFedG<dHedI<dJedK<dLedM<dedN<dedO<dPedQ<dRedS<dedT<dUedV<dUedW<dXedY<dZed[<dZded\<ded]<d^ed_<d`eda<dedb<dedc<ddede<dfedg<dedh<diedj<dkedl<dkedm<ejedndodpdqZejdrd*dsdtZdudvZddwdxdydzZd{d|Zd}d~ZddZddZdwd*ddZddddddZdwd*ddZ dwd*ddZ!dddZ"d Z#e$j%ddZ&e$j%ddZ'e$j%ddZ(e)dddZ*e)dd d dddddddddddZ+ddddddZ,dddddddddddZ-e)dddddddZ.ej/0de1j2dwd*ddZ3dwd*ddZ4ddZ5dddwdddZ6dwd*ddZ7edd*ddZ8dddwdddZ9dddwdddZ:dd*ddZ;dd*dd„Zdddddʜdd̄Z?dddϜddфZ@eddӄZAdddd՜ddׄZBdddUdٜddۄZCe$j%dd*dd݄ZDe$j%dd߄ZEe$j%ddZFe$j%ddZGe$j%dd*ddZHe$j%ddZIeJdUd*ddZKeHZLeJddZMe$j%ddZNe$j%ddZOe$j%ddZPe$j%ddZQe$j%dd*ddZRe$j%dd*ddZSe$j%dd*ddZTe$j%dd*ddZUe$j%dd*ddZVe$jWddZXejddZYedUd*ddZZdddddd d d Z[e$j%d d Z\eddZ]dddZ^e$j%dd*ddZ_dddZ`e$j%dd*ddZae$j%dd*ddZbe$j%e)ddd*dd Zce$j%e)dd!d*d"d#Zded$d%Zee$j%d&d*d'd(Zfe$j%e)d)d*d*d+d,Zge$j%e)dd-d*d.d/Zhd0d1d2d3d4Zie$j%d5d6Zje$j%d7d*d8d9Zkdddd:d;d<Zle$j%d=d>Zmd?d@ZndiddAdBdCZodiddAdDdEZpdFdddGdHdIZqdiddAdJdKZrdLd*dMdNZse$j%dd*dOdPZtdLd*dQdRZudid*dSdTZvedid*dUdVZwddWdXZxddYddZd[d\d]d^Zydd_dd[d`dadbZzdcd[dddedfZ{e|j}fdÐdgd[dhdidjZ~dcd_dddkdlZe$j%dmdnZe$j%dodpZe$j%dqdrZe$j%dsdtZe$j%dudvZe|j}fdÐdwdxdgddydzd{Zd|d}Zd~dZddZe|j}fddZddZddZe$j%ddZddZddZe)dddZe$j%ddZdddÐdddddZe$j%ddZe$j%ddZe$j%ddZddddddZejddZd S(MapperaDefines an association between a Python class and a database table or other relational structure, so that ORM operations against the class may proceed. The :class:`_orm.Mapper` object is instantiated using mapping methods present on the :class:`_orm.registry` object. For information about instantiating new :class:`_orm.Mapper` objects, see :ref:`orm_mapping_classes_toplevel`. zdispatcher[Mapper[_O]]dispatchFr_configure_failed)1.3aThe :paramref:`.mapper.non_primary` parameter is deprecated, and will be removed in a future release. The functionality of non primary mappers is now better suited using the :class:`.AliasedClass` construct, which can also be used as the target of a :func:`_orm.relationship` in 1.3.) non_primaryNTautodzType[_O]zOptional[FromClause]z+Optional[Mapping[str, MapperProperty[Any]]]z/Optional[Iterable[_ORMColumnExprArgument[Any]]]boolz'Optional[Union[Mapper[Any], Type[Any]]]z)Optional[_ColumnExpressionArgument[bool]]z/Optional[Sequence[_ORMColumnExprArgument[Any]]]z%Optional[_ORMColumnExprArgument[Any]]z5Optional[Union[Literal[False], Callable[[Any], Any]]]zFOptional[Union[_ORMColumnExprArgument[Any], str, MapperProperty[Any]]]z Optional[Dict[Any, Mapper[Any]]]z Optional[Any]zOptional[_WithPolymorphicArg]z)Optional[Literal[('selectin', 'inline')]]z Optional[str]zOptional[Sequence[str]]zLiteral[(True, False, 'auto')]int)class_ local_tabler primary_keyrwinheritsinherit_conditioninherit_foreign_keysalways_refreshversion_id_colversion_id_generatorpolymorphic_on_polymorphic_mappolymorphic_identityconcretewith_polymorphicpolymorphic_abstractpolymorphic_loadallow_partial_pksbatch column_prefixinclude_propertiesexclude_propertiespassive_updatespassive_deletesconfirm_deleted_rowseager_defaultslegacy_is_orphan_compiled_cache_sizec Cst|td|_d|jj|jjf|_t||_||_ | |_ t | t rV| |_ d|_n | dk rptjtj| ddnd|_| dkrd|_n| dkrdd|_n| |_||_d|_|dk rt||_nd|_|dk rtjtj|d d d |_n.|jr|jj|_d |_ntd |jjd |dk r0ttj||_nd|_||_|rJt|ni|_ g|_!||_"||_#||_$| dk rtjtj| ddnd|_%||_&g|_'tj(|_)||_*||_+||_,d|_-d|_.d|_/i|_0||_1d|_2||_3|jr|jsd|_4n||_4|5|||_6||_7| dkr i|_8n| |_8|dk r>t9||_:nd|_:|rXt9||_;nd|_;tj?@|||A|B|C|D|E|jFG||Hd|IW5QRX|j>J||jdS)aVDirect constructor for a new :class:`_orm.Mapper` object. The :class:`_orm.Mapper` constructor is not called directly, and is normally invoked through the use of the :class:`_orm.registry` object through either the :ref:`Declarative ` or :ref:`Imperative ` mapping styles. .. versionchanged:: 2.0 The public facing ``mapper()`` function is removed; for a classical mapping configuration, use the :meth:`_orm.registry.map_imperatively` method. Parameters documented below may be passed to either the :meth:`_orm.registry.map_imperatively` method, or may be passed in the ``__mapper_args__`` declarative class attribute described at :ref:`orm_declarative_mapper_options`. :param class\_: The class to be mapped. When using Declarative, this argument is automatically passed as the declared class itself. :param local_table: The :class:`_schema.Table` or other :class:`_sql.FromClause` (i.e. selectable) to which the class is mapped. May be ``None`` if this mapper inherits from another mapper using single-table inheritance. When using Declarative, this argument is automatically passed by the extension, based on what is configured via the :attr:`_orm.DeclarativeBase.__table__` attribute or via the :class:`_schema.Table` produced as a result of the :attr:`_orm.DeclarativeBase.__tablename__` attribute being present. :param polymorphic_abstract: Indicates this class will be mapped in a polymorphic hierarchy, but not directly instantiated. The class is mapped normally, except that it has no requirement for a :paramref:`_orm.Mapper.polymorphic_identity` within an inheritance hierarchy. The class however must be part of a polymorphic inheritance scheme which uses :paramref:`_orm.Mapper.polymorphic_on` at the base. .. versionadded:: 2.0 .. seealso:: :ref:`orm_inheritance_abstract_poly` :param always_refresh: If True, all query operations for this mapped class will overwrite all data within object instances that already exist within the session, erasing any in-memory changes with whatever information was loaded from the database. Usage of this flag is highly discouraged; as an alternative, see the method :meth:`_query.Query.populate_existing`. :param allow_partial_pks: Defaults to True. Indicates that a composite primary key with some NULL values should be considered as possibly existing within the database. This affects whether a mapper will assign an incoming row to an existing identity, as well as if :meth:`.Session.merge` will check the database first for a particular primary key value. A "partial primary key" can occur if one has mapped to an OUTER JOIN, for example. :param batch: Defaults to ``True``, indicating that save operations of multiple entities can be batched together for efficiency. Setting to False indicates that an instance will be fully saved before saving the next instance. This is used in the extremely rare case that a :class:`.MapperEvents` listener requires being called in between individual row persistence operations. :param column_prefix: A string which will be prepended to the mapped attribute name when :class:`_schema.Column` objects are automatically assigned as attributes to the mapped class. Does not affect :class:`.Column` objects that are mapped explicitly in the :paramref:`.Mapper.properties` dictionary. This parameter is typically useful with imperative mappings that keep the :class:`.Table` object separate. Below, assuming the ``user_table`` :class:`.Table` object has columns named ``user_id``, ``user_name``, and ``password``:: class User(Base): __table__ = user_table __mapper_args__ = {'column_prefix':'_'} The above mapping will assign the ``user_id``, ``user_name``, and ``password`` columns to attributes named ``_user_id``, ``_user_name``, and ``_password`` on the mapped ``User`` class. The :paramref:`.Mapper.column_prefix` parameter is uncommon in modern use. For dealing with reflected tables, a more flexible approach to automating a naming scheme is to intercept the :class:`.Column` objects as they are reflected; see the section :ref:`mapper_automated_reflection_schemes` for notes on this usage pattern. :param concrete: If True, indicates this mapper should use concrete table inheritance with its parent mapper. See the section :ref:`concrete_inheritance` for an example. :param confirm_deleted_rows: defaults to True; when a DELETE occurs of one more rows based on specific primary keys, a warning is emitted when the number of rows matched does not equal the number of rows expected. This parameter may be set to False to handle the case where database ON DELETE CASCADE rules may be deleting some of those rows automatically. The warning may be changed to an exception in a future release. :param eager_defaults: if True, the ORM will immediately fetch the value of server-generated default values after an INSERT or UPDATE, rather than leaving them as expired to be fetched on next access. This can be used for event schemes where the server-generated values are needed immediately before the flush completes. The fetch of values occurs either by using ``RETURNING`` inline with the ``INSERT`` or ``UPDATE`` statement, or by adding an additional ``SELECT`` statement subsequent to the ``INSERT`` or ``UPDATE``, if the backend does not support ``RETURNING``. The use of ``RETURNING`` is extremely performant in particular for ``INSERT`` statements where SQLAlchemy can take advantage of :ref:`insertmanyvalues `, whereas the use of an additional ``SELECT`` is relatively poor performing, adding additional SQL round trips which would be unnecessary if these new attributes are not to be accessed in any case. For this reason, :paramref:`.Mapper.eager_defaults` defaults to the string value ``"auto"``, which indicates that server defaults for INSERT should be fetched using ``RETURNING`` if the backing database supports it and if the dialect in use supports "insertmanyreturning" for an INSERT statement. If the backing database does not support ``RETURNING`` or "insertmanyreturning" is not available, server defaults will not be fetched. .. versionchanged:: 2.0.0rc1 added the "auto" option for :paramref:`.Mapper.eager_defaults` .. seealso:: :ref:`orm_server_defaults` .. versionchanged:: 2.0.0 RETURNING now works with multiple rows INSERTed at once using the :ref:`insertmanyvalues ` feature, which among other things allows the :paramref:`.Mapper.eager_defaults` feature to be very performant on supporting backends. :param exclude_properties: A list or set of string column names to be excluded from mapping. .. seealso:: :ref:`include_exclude_cols` :param include_properties: An inclusive list or set of string column names to map. .. seealso:: :ref:`include_exclude_cols` :param inherits: A mapped class or the corresponding :class:`_orm.Mapper` of one indicating a superclass to which this :class:`_orm.Mapper` should *inherit* from. The mapped class here must be a subclass of the other mapper's class. When using Declarative, this argument is passed automatically as a result of the natural class hierarchy of the declared classes. .. seealso:: :ref:`inheritance_toplevel` :param inherit_condition: For joined table inheritance, a SQL expression which will define how the two tables are joined; defaults to a natural join between the two tables. :param inherit_foreign_keys: When ``inherit_condition`` is used and the columns present are missing a :class:`_schema.ForeignKey` configuration, this parameter can be used to specify which columns are "foreign". In most cases can be left as ``None``. :param legacy_is_orphan: Boolean, defaults to ``False``. When ``True``, specifies that "legacy" orphan consideration is to be applied to objects mapped by this mapper, which means that a pending (that is, not persistent) object is auto-expunged from an owning :class:`.Session` only when it is de-associated from *all* parents that specify a ``delete-orphan`` cascade towards this mapper. The new default behavior is that the object is auto-expunged when it is de-associated with *any* of its parents that specify ``delete-orphan`` cascade. This behavior is more consistent with that of a persistent object, and allows behavior to be consistent in more scenarios independently of whether or not an orphan object has been flushed yet or not. See the change note and example at :ref:`legacy_is_orphan_addition` for more detail on this change. :param non_primary: Specify that this :class:`_orm.Mapper` is in addition to the "primary" mapper, that is, the one used for persistence. The :class:`_orm.Mapper` created here may be used for ad-hoc mapping of the class to an alternate selectable, for loading only. .. seealso:: :ref:`relationship_aliased_class` - the new pattern that removes the need for the :paramref:`_orm.Mapper.non_primary` flag. :param passive_deletes: Indicates DELETE behavior of foreign key columns when a joined-table inheritance entity is being deleted. Defaults to ``False`` for a base mapper; for an inheriting mapper, defaults to ``False`` unless the value is set to ``True`` on the superclass mapper. When ``True``, it is assumed that ON DELETE CASCADE is configured on the foreign key relationships that link this mapper's table to its superclass table, so that when the unit of work attempts to delete the entity, it need only emit a DELETE statement for the superclass table, and not this table. When ``False``, a DELETE statement is emitted for this mapper's table individually. If the primary key attributes local to this table are unloaded, then a SELECT must be emitted in order to validate these attributes; note that the primary key columns of a joined-table subclass are not part of the "primary key" of the object as a whole. Note that a value of ``True`` is **always** forced onto the subclass mappers; that is, it's not possible for a superclass to specify passive_deletes without this taking effect for all subclass mappers. .. seealso:: :ref:`passive_deletes` - description of similar feature as used with :func:`_orm.relationship` :paramref:`.mapper.passive_updates` - supporting ON UPDATE CASCADE for joined-table inheritance mappers :param passive_updates: Indicates UPDATE behavior of foreign key columns when a primary key column changes on a joined-table inheritance mapping. Defaults to ``True``. When True, it is assumed that ON UPDATE CASCADE is configured on the foreign key in the database, and that the database will handle propagation of an UPDATE from a source column to dependent columns on joined-table rows. When False, it is assumed that the database does not enforce referential integrity and will not be issuing its own CASCADE operation for an update. The unit of work process will emit an UPDATE statement for the dependent columns during a primary key change. .. seealso:: :ref:`passive_updates` - description of a similar feature as used with :func:`_orm.relationship` :paramref:`.mapper.passive_deletes` - supporting ON DELETE CASCADE for joined-table inheritance mappers :param polymorphic_load: Specifies "polymorphic loading" behavior for a subclass in an inheritance hierarchy (joined and single table inheritance only). Valid values are: * "'inline'" - specifies this class should be part of the "with_polymorphic" mappers, e.g. its columns will be included in a SELECT query against the base. * "'selectin'" - specifies that when instances of this class are loaded, an additional SELECT will be emitted to retrieve the columns specific to this subclass. The SELECT uses IN to fetch multiple subclasses at once. .. versionadded:: 1.2 .. seealso:: :ref:`with_polymorphic_mapper_config` :ref:`polymorphic_selectin` :param polymorphic_on: Specifies the column, attribute, or SQL expression used to determine the target class for an incoming row, when inheriting classes are present. May be specified as a string attribute name, or as a SQL expression such as a :class:`_schema.Column` or in a Declarative mapping a :func:`_orm.mapped_column` object. It is typically expected that the SQL expression corresponds to a column in the base-most mapped :class:`.Table`:: class Employee(Base): __tablename__ = 'employee' id: Mapped[int] = mapped_column(primary_key=True) discriminator: Mapped[str] = mapped_column(String(50)) __mapper_args__ = { "polymorphic_on":discriminator, "polymorphic_identity":"employee" } It may also be specified as a SQL expression, as in this example where we use the :func:`.case` construct to provide a conditional approach:: class Employee(Base): __tablename__ = 'employee' id: Mapped[int] = mapped_column(primary_key=True) discriminator: Mapped[str] = mapped_column(String(50)) __mapper_args__ = { "polymorphic_on":case( (discriminator == "EN", "engineer"), (discriminator == "MA", "manager"), else_="employee"), "polymorphic_identity":"employee" } It may also refer to any attribute using its string name, which is of particular use when using annotated column configurations:: class Employee(Base): __tablename__ = 'employee' id: Mapped[int] = mapped_column(primary_key=True) discriminator: Mapped[str] __mapper_args__ = { "polymorphic_on": "discriminator", "polymorphic_identity": "employee" } When setting ``polymorphic_on`` to reference an attribute or expression that's not present in the locally mapped :class:`_schema.Table`, yet the value of the discriminator should be persisted to the database, the value of the discriminator is not automatically set on new instances; this must be handled by the user, either through manual means or via event listeners. A typical approach to establishing such a listener looks like:: from sqlalchemy import event from sqlalchemy.orm import object_mapper @event.listens_for(Employee, "init", propagate=True) def set_identity(instance, *arg, **kw): mapper = object_mapper(instance) instance.discriminator = mapper.polymorphic_identity Where above, we assign the value of ``polymorphic_identity`` for the mapped class to the ``discriminator`` attribute, thus persisting the value to the ``discriminator`` column in the database. .. warning:: Currently, **only one discriminator column may be set**, typically on the base-most class in the hierarchy. "Cascading" polymorphic columns are not yet supported. .. seealso:: :ref:`inheritance_toplevel` :param polymorphic_identity: Specifies the value which identifies this particular class as returned by the column expression referred to by the :paramref:`_orm.Mapper.polymorphic_on` setting. As rows are received, the value corresponding to the :paramref:`_orm.Mapper.polymorphic_on` column expression is compared to this value, indicating which subclass should be used for the newly reconstructed object. .. seealso:: :ref:`inheritance_toplevel` :param properties: A dictionary mapping the string names of object attributes to :class:`.MapperProperty` instances, which define the persistence behavior of that attribute. Note that :class:`_schema.Column` objects present in the mapped :class:`_schema.Table` are automatically placed into ``ColumnProperty`` instances upon mapping, unless overridden. When using Declarative, this argument is passed automatically, based on all those :class:`.MapperProperty` instances declared in the declared class body. .. seealso:: :ref:`orm_mapping_properties` - in the :ref:`orm_mapping_classes_toplevel` :param primary_key: A list of :class:`_schema.Column` objects, or alternatively string names of attribute names which refer to :class:`_schema.Column`, which define the primary key to be used against this mapper's selectable unit. This is normally simply the primary key of the ``local_table``, but can be overridden here. .. versionchanged:: 2.0.2 :paramref:`_orm.Mapper.primary_key` arguments may be indicated as string attribute names as well. .. seealso:: :ref:`mapper_primary_key` - background and example use :param version_id_col: A :class:`_schema.Column` that will be used to keep a running version id of rows in the table. This is used to detect concurrent updates or the presence of stale data in a flush. The methodology is to detect if an UPDATE statement does not match the last known version id, a :class:`~sqlalchemy.orm.exc.StaleDataError` exception is thrown. By default, the column must be of :class:`.Integer` type, unless ``version_id_generator`` specifies an alternative version generator. .. seealso:: :ref:`mapper_version_counter` - discussion of version counting and rationale. :param version_id_generator: Define how new version ids should be generated. Defaults to ``None``, which indicates that a simple integer counting scheme be employed. To provide a custom versioning scheme, provide a callable function of the form:: def generate_version(version): return next_version Alternatively, server-side versioning functions such as triggers, or programmatic versioning schemes outside of the version id generator may be used, by specifying the value ``False``. Please see :ref:`server_side_version_counter` for a discussion of important points when using this option. .. seealso:: :ref:`custom_version_counter` :ref:`server_side_version_counter` :param with_polymorphic: A tuple in the form ``(, )`` indicating the default style of "polymorphic" loading, that is, which tables are queried at once. is any single or list of mappers and/or classes indicating the inherited classes that should be loaded at once. The special value ``'*'`` may be used to indicate all descending classes should be loaded immediately. The second tuple argument indicates a selectable that will be used to query for multiple classes. The :paramref:`_orm.Mapper.polymorphic_load` parameter may be preferable over the use of :paramref:`_orm.Mapper.with_polymorphic` in modern mappings to indicate a per-subclass technique of indicating polymorphic loading styles. .. seealso:: :ref:`with_polymorphic_mapper_config` r|z%s.%sNrargnameFcSs |pddS)Nrrrk)xrkrkrlz!Mapper.__init__..Tr})Zdisable_inspectionrzMapper[zM(None)] has None for a primary table argument and does not specify 'inherits'rrNZ constructed)Kr Zassert_arg_typetyper| __module____name__ _sort_keyto_list_primary_key_argumentrwr isinstancer*Zversion_id_proprr8expectr;ZColumnArgumentOrKeyRolerrsingler#rStrictFromClauseRoler}sa_exc ArgumentErrorZ OnClauseRolerrdict_init_properties_delete_orphansrrrrr_dependency_processors EMPTY_DICT validatorsrrrZ_clause_adapter_requires_row_aliasing_inherits_equated_pairs_memoized_valuesr_reconstructorrr_set_with_polymorphicrrpolymorphic_mapto_setrrrirrtZ_eventsZ_new_mapper_instance_configure_inheritance _configure_class_instrumentation_configure_properties_configure_polymorphic_setter_configure_pksrJZ_flag_new_mapper_log_expire_memoizationsZafter_mapper_constructed)selfr|r}rr~rwrrrrrrrrrrrrrrrrrrrrrrrrrkrkrl__init__s               zMapper.__init__cCs.|jdkr$|jsdS||jko"|jS|jSdS)NrxF)rZimplicit_returning_server_default_col_keysZinsert_executemany_returning)rdialecttablerkrkrl_prefer_eager_defaults\s  zMapper._prefer_eager_defaultscCs|fSrhrk)rZanon_mapZ bindparamsrkrkrl_gen_cache_keyhszMapper._gen_cache_keyrIrJ Mapper[_O]rfcCs|S)ztd|jj|jjjf|j |jj |j |jj kr|j rhdpjd}td||jj|f|j r|jj |_ n|j|jjk r|jr|j|_ |D]}|jdk rd|_qq|jdkrzt|jj|j|_Wntjk rb}zD|jjdk s$t|jdk s4ttd|jjj|jjf|W5d}~XYnftjk r}zD|jjdk st|jdk sttd|jjj|jjf|W5d}~XYnX|jj dk stt|jj |j|j|_ t|j}tj|j j|d |_ n|j|_ |j!dkrf|j|_"|j#s|jj$jdk rt%|d |jj$jd n|jrx|j|_"n |jj"|_"|j&dkr|jj&|_&|jj'|_'n:|jj&dk r|j&|jj&k rt%d |j&j|jj&jf|jj(|_(|jj)|_)|jj*||jj$|_$|jj+|_+|jj,p"|j,|_,|jj-|_-|j!dk rx|j!|j(krlt%d |j!|j(|j!||j!f||j(|j!<|j.r|jrtd|j.dkr|j/|n*|j.dkrn|j.dk rtd|j.nFt0|_-||_$|jdk st|j|_ |j!dk r||j(|j!<|j|_"|j dkr8td|dS)zXConfigure settings related to inheriting and/or inherited mappers being present.z%Class '%s' does not inherit from '%s'primaryz non-primaryzHInheritance of %s mapper for class '%s' is only allowed from a %s mapperNTa7Can't determine the inherit condition between inherited table '%s' and inheriting table '%s'; tables have no foreign key relationships established. Please ensure the inheriting table has a foreign key relationship to the inherited table, or provide an 'on clause' using the 'inherit_condition' mapper argument.zCan't determine the inherit condition between inherited table '%s' and inheriting table '%s'; tables have more than one foreign key relationship established. Please specify the 'on clause' using the 'inherit_condition' mapper argument.)Zconsider_as_foreign_keysz| does not indicate a 'polymorphic_identity', yet is part of an inheritance hierarchy that has a 'polymorphic_on' column of 'a''. If this is an intermediary class that should not be instantiated, the class may either be left unmapped, or may include the 'polymorphic_abstract=True' parameter in its Mapper arguments. To leave the class unmapped when using Declarative, set the '__abstract__ = True' attribute on the class.zInheriting 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.zReassigning polymorphic association for identity %r from %r to %r: Check for duplicate use of %r as value for polymorphic_identity.zKpolymorphic_load is not currently supported with concrete table inheritanceinlineselectinz)unknown argument for polymorphic_load: %rz9Mapper '%s' does not have a persist_selectable specified.)1r WeakSequencerr issubclassr|rrrrt_updaterwrrr}riterate_to_rootrrrsql_utilZjoin_conditionZNoForeignKeysErrorAssertionError descriptionZAmbiguousForeignKeysErrorr4joinrrZcriterion_as_pairsZonclauserrrrrwarnrrrrappendrrrr_add_with_polymorphic_subclassrj)rnprZnfeZafeZfksrkrkrlrs                                    zMapper._configure_inheritanceNone)rrgcCs|dkrd|_n\t|ttfrLt|dtttfr@td||_ql|df|_n |dk rftd|nd|_|jr|jddk r|jdtj t j |jdddf|_|j r| dS) Nrc)rcNrzTuple[ Union[ Literal["*"], Sequence[Union["Mapper[Any]", Type[Any]]], ], Optional["FromClause"], ]z&Invalid setting for with_polymorphic: rTZ allow_select)rrtupleliststrrrrr8rr;rrr)rrrkrkrlr`s0  zMapper._set_with_polymorphiccCsd|j}|jdkr||fnB|jddkr`t|jdts@t||jd|f|jdfdS)Nrrcr)r|rrrrr)rrZsubclrkrkrlrs z%Mapper._add_with_polymorphic_subclasscCs|js t|jrtt|ts"t||_|jj|j|jj|_|D]}|jdk rJd|_ qJ|jj |_ |j D]}|jj |_ qp|jj ||jj|_|jj|_|jD]2\}}||jkr|j||ddds|||dqdS)zSet the given :class:`_orm.Mapper` as the 'inherits' for this :class:`_orm.Mapper`, assuming this :class:`_orm.Mapper` is concrete and does not already have an inherits.NTFlocalcolumn)rrrrrsrupdaterrrrself_and_descendantsrrrrrritems_should_exclude_adapt_inherited_property)rrmpkeyproprkrkrl_set_concrete_bases.          zMapper._set_concrete_basecCs||_|ddS)NT)rr)rrrkrkrl_set_polymorphic_onszMapper._set_polymorphic_oncCst|j}|jrb|r|js,td|j||_|jdk s@t |j|_|j j |_ |j |dS|dksp|jsztd|j ||jtj|j|ttj|dd}||_|jdk st |j|_|j dkrdStj|dtddt|jD]\}}|dkr&t|d r&|j}t|d r&|j}t|rt|d rT||_tj|d tddqt|d r|j}|j D]:}||j!krtd||f|j!"|||fi|_!qjqdS)aIf this mapper is to be a primary mapper (i.e. the non_primary flag is not set), associate this Mapper with the given class and entity name. Subsequent calls to ``class_mapper()`` for the ``class_`` / ``entity`` name combination will return this mapper. Also decorate the `__init__` method on the mapped class to include optional auto-session attachment logic. ztClass %s has no primary mapper configured. Configure a primary mapper first before setting up a non primary Mapper.NzThe _mapper() function and Mapper() constructor may not be invoked directly outside of a declarative registry. Please use the sqlalchemy.orm.registry.map_imperatively() function for a classical mapping.T)rZexpired_attribute_loaderfinalizeinit)rawr_sa_original_init__func____sa_reconstructor__load__sa_validators__zJA validation function for mapped attribute %r on mapper %s already exists.)#rZopt_manager_of_classr|rwZ is_mappedrInvalidRequestErrorrrJrrrZ_add_non_primary_mapperrtinstrument_classrZregister_classr partialrZload_scalar_attributesr0listen_event_on_initZiterate_attributeshasattrrrcallabler_event_on_load__sa_validation_opts__rrunion)rmanagerrmethodZvalidation_optsnamerkrkrlrsn            z'Mapper._configure_class_instrumentationcCs$d|_d|_d|_|jdddS)NTru)r_ready_for_configure_dispose_called__dict__poprrkrkrl_set_dispose_flags szMapper._set_dispose_flagsrz Column[Any])rrrgc Csz|j|}Wn<tk rJ}ztd|d|d|W5d}~XYnXz |j}Wn<tk r}ztd|d|d|W5d}~XYnXt|tstd|d|d|S)NzCan't determine z column 'z(' - no attribute is mapped to this name.z4'; property does not refer to a single mapped Column)rKeyErrorrrr9AttributeErrorrr@)rrrrerrexprZaerkrkrl_str_arg_to_mapped_cols*  zMapper._str_arg_to_mapped_colcsFtj_jddjDi_i_t t ddj D}t dd|D}t j jgD]F}|jr||jrt|j|j|<t|j|j|<qtjrfddddjDD}nd}|r(|D]4}|jjkrtj|j<j|j|qnljjksLtjjdkrdtd jjfn0jjkrtjtjrtd jjj rj!sjsj j_nt|rd dfd d|DD}ntj"jjd d}t|dkrtd jjft#|_$d|fddj D_%dS)Ncss|] }|VqdSrhrk).0trkrkrl .sz(Mapper._configure_pks..cSsg|] }|jqSrk proxy_setrcolrkrkrl 4sz)Mapper._configure_pks..css|]}|jr|VqdSrhr~rrrkrkrlr7scs&g|]}t|trd|n|qSr$)rrrr%rrkrlr#Hscss |]}tjtj|ddVqdS)r~rN)r8rr;ZDDLConstraintColumnRole)rZ coerce_pkrkrkrlrNs rzJMapper %s could not assemble any primary key columns for mapped table '%s'zlCould not assemble any primary keys for locally mapped table '%s' - no rows will be persisted in this Table.cSs g|]\}}|dk r|n|qSrhrk)rccrrkrkrlr#sc3s|]}j||fVqdSrh)rcorresponding_columnr%rrkrlrsT)Zignore_nonexistent_tablesz"Identified primary key columns: %scs<h|]4}j|jkrt|dr.|jjkrj|qSr)r_identity_key_propsr rrr!rrkrl s   z(Mapper._configure_pks..)&r find_tablesrrrrrrr Z column_setrrrjrr~ issupersetZordered_column_set intersectionrrrr]addlenrrrr}rr3rArrrZreduce_columnsrr_readonly_props)rZall_colspk_colsfcZcoerced_pk_argkr~rkrrlr+s              zMapper._configure_pkscCst|_|_t|_t||_i}i}|j r|j D]z\}}t |t s\| ||}n|}d}t |tjr|jD]*}|jj|rvd}|||<||f||<qv|r<|j||ddq<|jrH|jj D]z\}}|j||dddrq||} | r.|j||d| d} | ||<| jD]} || f|| <qq||jkr|||dq|jjD]} | |kr|| \}} |j|| ddqPn| |jkrqP|jpd| j}|j| j||jj| | drƐqP|D]}| |jkr|j| j}q|j|| dddqPdS)NTF)rr) warn_only incoming_propr setparent)sql_baseZColumnCollectionrrr OrderedDictrrrrrrr*_make_prop_from_columnrrQr}Zcontains_column_configure_propertyrrget%_reconcile_prop_with_incoming_columnsrrrrr)rZexplicit_col_props_by_columnZexplicit_col_props_by_keyrprop_argZpossible_col_propZ_map_as_property_nowZ given_colZinherited_propr5new_propZinc_colrrZ column_keyrrkrkrlrs                 zMapper._configure_propertiesc sd}d|jdk rd}t|jtrlz|j|j|_Wn4tk rj}ztd|j|W5d}~XYnX|j|jkr|j|j}nt|jtrt|jt j std|j}n|j |j}|dkr,d}d}|j}t|t jr0|jdks|jddks|jd |dkr0td|jnd}t|dd}|rd|||d|rztd |n|d |_}|j}t j ||d }|j|||dd |jd |_|jn||D]r}|jdk r|j |j kr|j|_n|j |j|_|jdk r|j|_|j|_|j|_n d|_d|_dSq|jrH|jdkrHtd|rzfdd} |_fdd} | |_| |_n d|_d|_dS)aConfigure an attribute on the mapper representing the 'polymorphic_on' column, if applicable, and not already generated by _configure_properties (which is typical). Also create a setter function which will assign this attribute to the value of the 'polymorphic_identity' upon instance construction, also if applicable. This routine will run when an instance is created. FNTzPCan't determine polymorphic_on value '%s' - no attribute is mapped to this name.zUOnly direct column-mapped property or SQL expression can be passed for polymorphic_onrzkCould not map polymorphic_on column '%s' to the mapped table - polymorphic loads will not function properlyrz6Cannot exclude or override the discriminator column %rZ_sa_polymorphic_on)Z _instrumentr7rzThe Mapper.polymorphic_abstract parameter may only be used on a mapper hierarchy which includes the Mapper.polymorphic_on parameter at the base of the hierarchy.csR|j}|jjj}|dkr8|jjjr8td|jjd||||ddS)NzCan't instantiate class for z,; mapper is marked polymorphic_abstract=True) rrrrrrrZget_implrj)statedict_rZpolymorphic_keyrkrlrs  zGMapper._configure_polymorphic_setter.._set_polymorphic_identitycs2|kr.||jkr.tdt||fdS)NznFlushing object %s with incompatible polymorphic identity %r; the object may not refresh and/or load correctly)"_acceptable_polymorphic_identitiesr Z warn_limitedr&)rrArBrCrkrlrszLMapper._configure_polymorphic_setter.._validate_polymorphic_identity)rrrrrrrrr*rrQrr'r3r@rrrgetattrrlabelrr<rrrrrr) rrsetterrrr"Z instrumentrrrrrkrCrlrs                z$Mapper._configure_polymorphic_settercCs|jdk r|j|jSdSdSrh)rrrrkrkrl_version_id_props  zMapper._version_id_propcCsFt}t|g}|rB|}|j|jkr||j||jq|Srh)rjrpopleftrr.rextendr)rZ identitiesstackitemrkrkrlrDs   z)Mapper._acceptable_polymorphic_identitiescCst|jSrh) frozensetrvaluesrrkrkrl _prop_setszMapper._prop_setzsqlalchemy.orm.descriptor_propscCsttjj}|js"|j||dddnN||jkrp|j||}||ksZt|t j rp|j |j krp|j|| |dddS)NFr7T)r preloadedorm_descriptor_propsrr<rr_get_class_attr_mrorrZInstrumentedAttributeZ _parententityparentConcreteInheritedProperty)rrrrdescriptor_propsZimplementing_attributerkrkrlrs,  z Mapper._adapt_inherited_property)rr8warn_for_existingz3Union[KeyedColumnElement[Any], MapperProperty[Any]]ra)rr?rr8rVrgc Cstjj}|d||jjt|ts2|||}n|}t|t j r|j |j d}|dkr|jr|g} |jD]T} | j |j d}|dk r| D]} | j |q|j |j d}q| | qt|dkr|j d}t|drPt|dr|j|jkrP|j|n>t|drP|j|jkrP||j|jkrP|j|j|t|dsz||jkpv|j d|jk|_t|tjr||_|_|j |||j D]}|jD]} ||j| <qqt |d||krt!d|j"jd |jd |d |jd |jd ||_|r&|#||||j$krht |j$|d drh|j$|j%} t&'d| ||| f||j$krt|j$||j(st||j)s|rt*d|j"jd |d|dd|j$|}|j+,|dnf|r@|j"j-.|ddk r@t||j)s@t|j$.|d|j(s@t*d|j"jd |d|dd||j$|<|j/s\|0||j1D]}|2|||qb|r|3|4||j5r|6|S)Nz_configure_property(%s, %s)rr0rr_is_polymorphic_discriminatorrzORM mapped property .z being assigned to attribute z& is already associated with attribute z+. The attribute will be de-associated from _mapped_by_synonymFzpCan't call map_column=True for synonym %r=%r, a ColumnProperty already exists keyed to the name %r for column %rzUser-placed attribute z on z is replacing an existing ORM-mapped attribute. Behavior is not fully defined in this case. This use is deprecated and will raise an error in a future releasez2.0z is replacing an existing class-bound attribute of the same name. Behavior is not fully defined in this case. This use is deprecated and will raise an error in a future release)7r rPrQr __class__rrr*_property_from_columnrrQrr'rrrr}_refresh_for_new_columnrr rrr0r.rrWr9LabelrZ _tq_key_labelr rrErr|Z set_parentrrYrrrTrMZwarn_deprecatedrrrr=rwrrrrpost_instrument_classrr)rrr?rr8rVrUrr"pathmm2Z proxy_colsynZoldproprrkrkrlr<s             ,             zMapper._configure_propertyzAUnion[Sequence[KeyedColumnElement[Any]], KeyedColumnElement[Any]]zColumnProperty[Any])rrrgcCst|}g}|D]j}|j|}|dkrr|j|}|dk rJ|j||j|}|dkrrtd|||f||qt j |S)NzWhen configuring property '%s' on %s, 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.) r rrr'r}r\rrrrrQ)rrrrZ mapped_columnrZmcrkrkrlr;s"      zMapper._make_prop_from_columnzOptional[ColumnProperty[Any]])r existing_propr4r5 single_columnrgc Cs|r|jst|tjs|S|jd}|r6||jkr6|S|dkr^|dk sJt|}|jd|f}n$|dksjt|jd}||jdf}|jr||jkr||s||jk r||jk rd|jd||f} |rt | n t | | } | jd||d|| S)NrzImplicitly combining column %s with column %s under attribute '%s'. Please configure one or more attributes for these same-named columns explicitly.zAinserting column to existing list in properties.ColumnProperty %s)rrrrQrrrZshares_lineagerr rrrcopyinsertr) rrrcr4r5rdZexisting_columnZincoming_columnZequated_pair_keymsgr@rkrkrlr>sV         z,Mapper._reconcile_prop_with_incoming_columnszKeyedColumnElement[Any]cCsttjj}|j|}t|tjr8|j||||j |k dS|dksLt||j rX| ||St d|||j|fdS)zrgenerate/update a :class:`.ColumnProperty` given a :class:`_schema.Column` or other SQL expression object.)rdr4NaWARNING: when configuring property '%s' on %s, column '%s' conflicts with property '%r'. To resolve this, map the column to the class under a different name in the 'properties' dictionary. Or, to remove all awareness of the column entirely (including its availability as a foreign key), use the 'include_properties' or 'exclude_properties' mapper arguments to control specifically which table columns get mapped.)r rPrQrr=rrrQr>rSrTr;rrr)rrrrUrrkrkrlr[' s&      zMapper._property_from_columnzThis warning originated from the `configure_mappers()` process, which was invoked automatically in response to a user-initiated operation.cCs|jjrt|jhdddS)NTcascade)rJ _new_mappers_configure_registriesrrkrkrl_check_configureL szMapper._check_configurecCst|ddd|jD}|D]<\}}|d||j|krN|jsN||jr"||q"|dd|_dS)zCall the ``init()`` method on all ``MapperProperties`` attached to this mapper. This is a deferred configuration step which is intended to execute once all mappers have been constructed. z$_post_configure_properties() startedcSsg|]\}}||fqSrkrk)rrrrkrkrlr#` sz5Mapper._post_configure_properties..zinitialize prop %sz%_post_configure_properties() completeTN) rrrrSZ_configure_startedrZ_configure_finishedr^r)rlrrrkrkrl_post_configure_propertiesV s     z!Mapper._post_configure_propertiescCs"|D]\}}|||qdS)z^Add the given dictionary of properties to this mapper, using `add_property`. N)r add_property)rZdict_of_propertiesrvaluerkrkrladd_propertiesm szMapper.add_propertiesz'Union[Column[Any], MapperProperty[Any]])rrrgcCs0|j|||jdd}t|ts"t||j|<dS)aAAdd an individual MapperProperty to this mapper. If the mapper has not been configured yet, just adds the property to the initial properties dictionary sent to the constructor. If this Mapper has already been configured, then the given MapperProperty is configured immediately. T)rrVN)r<rrr*rr)rrrrkrkrlrpu s zMapper.add_propertycCs|D] }|qdSrh)rZ_reset_memoizationsrrrkrkrlr s zMapper._expire_memoizationscCs>d|jjd|jdk r |jjp(t|j|jr4dp6ddS)N(|z |non-primaryr6))r|rr}rrrwrrkrkrl _log_desc s   zMapper._log_desc)rhargsrgcGs"|jjd|f|jf|dSNz%s )loggerinforwrrhrxrkrkrlr sz Mapper._logcGs"|jjd|f|jf|dSry)rzdebugrwr|rkrkrl _log_debug szMapper._log_debugcCsdt||jjfS)Nz)idr|rrrkrkrl__repr__ szMapper.__repr__cCs2d|jj|jrdpd|jdk r&|jjn|jjfS)NzMapper[%s%s(%s)]z (non-primary)r6)r|rrwr}rrrrkrkrl__str__ s  zMapper.__str__zInstanceState[_O])rArgcCstd}|D]T}|jD]H\}}d}t|j|||jd}|jrL|rLdS|js|sdSqq |jrl|SdSdS)NFT)Z optimistic)rrrZmanager_of_class has_parentZ has_identityr)rrAZorphan_possiblerrclsrrkrkrl _is_orphan s      zMapper._is_orphan)rrgcCs ||jkSrh)rrrrkrkrl has_property szMapper.has_property)r_configure_mappersrgc CsZ|r |z |j|WStk rT}ztd|d|d|W5d}~XYnXdS)z6return a MapperProperty associated with the given key.zMapper 'z' has no property 'zw'. If this property was indicated from other mappers or configure events, ensure registry.configure() has been called.N)rmrrrr)rrrrrkrkrl get_property s zMapper.get_propertyzColumnElement[_T]zMapperProperty[_T])rrgcCs |j|S)zkGiven a :class:`_schema.Column` object, return the :class:`.MapperProperty` which maps this column.r)rrrkrkrlget_property_by_column szMapper.get_property_by_columncCst|jS)z1return an iterator of all MapperProperty objects.)iterrrNrrkrkrliterate_properties szMapper.iterate_propertieszSequence[Mapper[Any]])spec selectablergcs|dkrt|j}nz|rtt|D]J}t|}||sPtd||f|dkrh | q( |q(fdd|jD}ng}|dk rtt j |ddfdd|D}|S) zgiven a with_polymorphic() argument, return the set of mappers it represents. Trims the list of mappers to just those represented within the given selectable, if present. This helps some more legacy-ish mappings. rcz%r does not inherit from %rNcsg|]}|kr|qSrkrkrr`) mapper_setrkrlr# sz-Mapper._mappers_from_spec..T)Zinclude_aliasescsg|]}|jkr|qSrk)r}r)rrkrlr# s )rrrjr rr"isarrrrr.rr+)rrrmappersr`rk)rrrl_mappers_from_spec s*      zMapper._mappers_from_speczIterable[Mapper[Any]])r innerjoinrgcCs\|j}|D]L}||krq |jr*tdq |js |rF||j|j}q ||j|j}q |S)zgiven a list of mappers (assumed to be within this mapper's inheritance hierarchy), construct an outerjoin amongst those mapper's mapped tables. z^'with_polymorphic()' requires 'selectable' argument when concrete-inheriting mappers are used.) rrrrrrr}rZ outerjoin)rrrZfrom_objr`rkrkrl_selectable_from_mappers s&zMapper._selectable_from_mapperscCsL|j}|dkrdSt|ts dS|jdk pF|jdk oF|jj oF|jj SdS)NFT)rrr@server_defaultdefaultZ is_scalar is_callable)rZvid_colrkrkrl!_version_id_has_server_side_value$ s    z(Mapper._version_id_has_server_side_valuecCsB|jr:|jr:|jdk r:|j||ddd|jDSdSdS)N) parententity parentmappercSsg|]}|js|jqSrk)rrrrkrkrlr#< sz2Mapper._single_table_criterion..)rrr _annotatein_rrrkrkrl_single_table_criterion6 s zMapper._single_table_criterioncCs|jot|jdtjS)zreturn True if with_polymorphic[1] is an aliased fromclause, like a subquery. As of #8168, polymorphic adaption with ORMAdapter is used only if this is present. r)rrr9ZAliasedReturnsRowsrrkrkrl#_has_aliased_polymorphic_fromclauseE s z*Mapper._has_aliased_polymorphic_fromclausecCs|jp|jp|jjp|jjS)a;determine if _MapperEntity or _ORMColumnEntity will need to use polymorphic adaption when setting up a SELECT as well as fetching rows for mapped classes and subclasses against this Mapper. moved here from context.py for #8456 to generalize the ruleset for this condition. )rrrrrkrkrl _should_select_with_poly_adapterS s+z'Mapper._should_select_with_poly_adaptercCs||jsgS|j|jSrh)rmrrrrkrkrl_with_polymorphic_mappers sz Mapper._with_polymorphic_mapperscCs |dS)zThis hook is invoked by attribute inspection. E.g. when Query calls: coercions.expect(roles.ColumnsClauseRole, ent, keep_inspect=True) This allows the inspection process run a configure mappers hook. N)rmrrkrkrl _post_inspect s zMapper._post_inspectcCs:|js |jS|j\}}|dk r"|S||||dSdSNF)rrrr)rrrrkrkrl_with_polymorphic_selectable s  z#Mapper._with_polymorphic_selectablecCsdd|jDS)NcSs$i|]\}}|tdd|DqS)css|]}|jjr|VqdSrh)rshould_evaluate_noner!rkrkrlr szAMapper._insert_cols_evaluating_none...rMrrrrkrkrl s z7Mapper._insert_cols_evaluating_none..rrrrkrkrl_insert_cols_evaluating_none sz#Mapper._insert_cols_evaluating_nonecCsdd|jDS)NcSs$i|]\}}|tdd|DqS)css.|]&}|js|js|js|jjs|jVqdSrh)r~rrrrrr!rkrkrlr s z9Mapper._insert_cols_as_none...rrrkrkrlr s  z/Mapper._insert_cols_as_none..rrrkrkrl_insert_cols_as_none s zMapper._insert_cols_as_nonecsfddjDS)Ncs$i|]\}}|fdd|DqS)csi|]}j|j|qSrkrrr!rrkrlr s z5Mapper._propkey_to_col...rkrrrkrlr sz*Mapper._propkey_to_col..rrrkrrl_propkey_to_col s zMapper._propkey_to_colcCsdd|jDS)NcSs$i|]\}}|tdd|DqS)cSsg|] }|jqSrkrr!rkrkrlr# sz7Mapper._pk_keys_by_table...rrrZpksrkrkrlr sz,Mapper._pk_keys_by_table..rrrrkrkrl_pk_keys_by_table szMapper._pk_keys_by_tablecsfddjDS)Ncs(i|] \}}|tfdd|DqS)csg|]}j|jqSrkrr!rrkrlr# sz..rrrrkrlr sz1Mapper._pk_attr_keys_by_table..rrrkrrl_pk_attr_keys_by_table s zMapper._pk_attr_keys_by_tablez+Mapping[FromClause, FrozenSet[Column[Any]]]cCsdd|jDS)NcSs*i|]"\}}|tddtd|DqS)cSs,g|]$}|jdk s$|jdk r|jjr|qSrh)rris_clause_elementr!rkrkrlr# s   z:Mapper._server_default_cols...Iterable[Column[Any]]rMrrrkrkrlr s z/Mapper._server_default_cols..rrrkrkrl_server_default_cols s zMapper._server_default_colscCsdd|jDS)NcSs*i|]"\}}|tddtd|DqS)cSs,g|]$}|jdk s$|jdk r|jjr|qSrh)Zserver_onupdateZonupdaterr!rkrkrlr# s   zCMapper._server_onupdate_default_cols...rrrrkrkrlr s z8Mapper._server_onupdate_default_cols..rrrkrkrl_server_onupdate_default_cols s z$Mapper._server_onupdate_default_colsz#Mapping[FromClause, FrozenSet[str]]cCsdd|jDS)NcSs$i|]\}}|tdd|DqS)css|]}|jdk r|jVqdSrhrr!rkrkrlr s z=Mapper._server_default_col_keys...rrrcolsrkrkrlr sz3Mapper._server_default_col_keys..)rrrrkrkrlr szMapper._server_default_col_keyscCsdd|jDS)NcSs$i|]\}}|tdd|DqS)css|]}|jdk r|jVqdSrhrr!rkrkrlr s zFMapper._server_onupdate_default_col_keys...rrrkrkrlr sz.)rrrrkrkrl!_server_onupdate_default_col_keys sz(Mapper._server_onupdate_default_col_keyszSet[str]cstt}|j|jD]&\}}|fdd|Dq|jD]&\}}|fdd|DqH|S)Nc3s|]}|jVqdSrhrr!Zcol_to_propertyrkrlr sz@Mapper._server_default_plus_onupdate_propkeys..c3s|]}|jVqdSrhrr!rrkrlr s)rjrrrrr-r)rresultrrrkrrl&_server_default_plus_onupdate_propkeys s  z-Mapper._server_default_plus_onupdate_propkeyscCsT|||d}|j|jk r<|j|||dd|d|d<|j|d|dS)N)entity_namespacerrormZcompile_state_pluginZplugin_subjectZ dml_table)rr}r_set_propagate_attrsr)rrrkrkrl__clause_element__ s   zMapper.__clause_element__cCs$t|||ddd|dS)NT)rrridentity_tokenrr)r9nullrrrrkrkrlselect_identity_token7 s zMapper.select_identity_tokencCs|jS)a4The :class:`_schema.FromClause` construct this :class:`_orm.Mapper` selects from by default. Normally, this is equivalent to :attr:`.persist_selectable`, unless the ``with_polymorphic`` feature is in use, in which case the full "polymorphic" selectable is returned. )rrrkrkrlrH s zMapper.selectablez)Union[Literal[(False, None)], FromClause]z(Tuple[Sequence[Mapper[Any]], FromClause])rrrrgcCs~|dkrtjtj|dd}|jrB|s.|jd}|dkrN|jd}n |dkrNd}|||}|dk rj||fS||||fSdS)NrTrrFr)r8rr;rrrr)rrrrrrkrkrl_with_polymorphic_argsT s"   zMapper._with_polymorphic_argscCst||jSrh)r_iterate_polymorphic_propertiesrrrkrkrl_polymorphic_propertiesl s zMapper._polymorphic_propertiescs|j}|jfdd|DS)Ncs<g|]4}t|tjr|jr|jD]}r2j|n|q qSrk)rrrQZ_renders_in_subqueriesr)rrradapterrkrlr#y s  z2Mapper._all_column_expressions..)r_polymorphic_adapter)rpoly_propertiesrkrrl_all_column_expressionst s  zMapper._all_column_expressionsrkcCs$|r||}n|j}dd|DS)NcSs(g|] }t|tjr|j|jdfqS)r)rrrQrrrrrkrkrlr# s z-Mapper._columns_plus_keys..)rr)rZpolymorphic_mappersrrkrkrl_columns_plus_keys szMapper._columns_plus_keyszOptional[orm_util.ORMAdapter]cCs*|jr"tjtjj||j|jddSdSdS)NF)rZ equivalentsZlimit_on_entity)rorm_utilrTZ_TraceAdaptRoleZMAPPER_POLYMORPHIC_ADAPTERr_equivalent_columnsrrkrkrlr szMapper._polymorphic_adapterccs||dkr|j}|s&|jD] }|VqnRttdd|g|DD]2}t|ddrp|jdksD|jd|jk rpqD|VqDdS)zUReturn an iterator of MapperProperty objects which will render into a SELECT.NcSsg|]}t|jqSrk)rr)rrrkrkrlr# sz:Mapper._iterate_polymorphic_properties..rWFr)rrr Z unique_listrrErr)rrrrkrkrlr s&   z&Mapper._iterate_polymorphic_propertiesz,util.ReadOnlyProperties[MapperProperty[Any]]cCs|t|jS)aiA namespace of all :class:`.MapperProperty` objects associated this mapper. This is an object that provides each property based on its key name. For instance, the mapper for a ``User`` class which has ``User.name`` attribute would provide ``mapper.attrs.name``, which would be the :class:`.ColumnProperty` representing the ``name`` column. The namespace object can also be iterated, which would yield each :class:`.MapperProperty`. :class:`_orm.Mapper` has several pre-filtered views of this attribute which limit the types of properties returned, including :attr:`.synonyms`, :attr:`.column_attrs`, :attr:`.relationships`, and :attr:`.composites`. .. warning:: The :attr:`_orm.Mapper.attrs` accessor namespace is an instance of :class:`.OrderedProperties`. This is a dictionary-like object which includes a small number of named methods such as :meth:`.OrderedProperties.items` and :meth:`.OrderedProperties.values`. When accessing attributes dynamically, favor using the dict-access scheme, e.g. ``mapper.attrs[somename]`` over ``getattr(mapper.attrs, somename)`` to avoid name collisions. .. seealso:: :attr:`_orm.Mapper.all_orm_descriptors` )rmr ReadOnlyPropertiesrrrkrkrlattrs s#z Mapper.attrsz'util.ReadOnlyProperties[InspectionAttr]cCstt|jS)ay A namespace of all :class:`.InspectionAttr` attributes associated with the mapped class. These attributes are in all cases Python :term:`descriptors` associated with the mapped class or its superclasses. This namespace includes attributes that are mapped to the class as well as attributes declared by extension modules. It includes any Python descriptor type that inherits from :class:`.InspectionAttr`. This includes :class:`.QueryableAttribute`, as well as extension types such as :class:`.hybrid_property`, :class:`.hybrid_method` and :class:`.AssociationProxy`. To distinguish between mapped attributes and extension attributes, the attribute :attr:`.InspectionAttr.extension_type` will refer to a constant that distinguishes between different extension types. The sorting of the attributes is based on the following rules: 1. Iterate through the class and its superclasses in order from subclass to superclass (i.e. iterate through ``cls.__mro__``) 2. For each class, yield the attributes in the order in which they appear in ``__dict__``, with the exception of those in step 3 below. In Python 3.6 and above this ordering will be the same as that of the class' construction, with the exception of attributes that were added after the fact by the application or the mapper. 3. If a certain attribute key is also in the superclass ``__dict__``, then it's included in the iteration for that class, and not the class in which it first appeared. The above process produces an ordering that is deterministic in terms of the order in which attributes were assigned to the class. .. versionchanged:: 1.3.19 ensured deterministic ordering for :meth:`_orm.Mapper.all_orm_descriptors`. When dealing with a :class:`.QueryableAttribute`, the :attr:`.QueryableAttribute.property` attribute refers to the :class:`.MapperProperty` property, which is what you get when referring to the collection of mapped properties via :attr:`_orm.Mapper.attrs`. .. warning:: The :attr:`_orm.Mapper.all_orm_descriptors` accessor namespace is an instance of :class:`.OrderedProperties`. This is a dictionary-like object which includes a small number of named methods such as :meth:`.OrderedProperties.items` and :meth:`.OrderedProperties.values`. When accessing attributes dynamically, favor using the dict-access scheme, e.g. ``mapper.all_orm_descriptors[somename]`` over ``getattr(mapper.all_orm_descriptors, somename)`` to avoid name collisions. .. seealso:: :attr:`_orm.Mapper.attrs` )r rrrZ_all_sqla_attributesrrkrkrlall_orm_descriptors sB zMapper.all_orm_descriptorszDict[str, str]cs2tjjdd|jDfdd|jDS)z~return a dictionary of {syn_attribute_name: pk_attr_name} for all synonyms that refer to primary key columns cSsh|] }|jqSrkrrrkrkrlr*- sz&Mapper._pk_synonyms..cs0i|](\}}t|jr|jkr|j|jqSrk)rrMrr)rr3rbrUZpk_keysrkrlr/ s   z'Mapper._pk_synonyms..)r rPrQr)rrrrkrrl _pk_synonyms$ s  zMapper._pk_synonymsz-util.ReadOnlyProperties[SynonymProperty[Any]]cCstjj}||jS)zReturn a namespace of all :class:`.Synonym` properties maintained by this :class:`_orm.Mapper`. .. seealso:: :attr:`_orm.Mapper.attrs` - namespace of all :class:`.MapperProperty` objects. )r rPrQ_filter_propertiesrM)rrUrkrkrlsynonyms6 s zMapper.synonymscCs|jSrhrrrkrkrlrG szMapper.entity_namespacez,util.ReadOnlyProperties[ColumnProperty[Any]]cCs |tjS)aReturn a namespace of all :class:`.ColumnProperty` properties maintained by this :class:`_orm.Mapper`. .. seealso:: :attr:`_orm.Mapper.attrs` - namespace of all :class:`.MapperProperty` objects. )rrrQrrkrkrl column_attrsK s zMapper.column_attrszsqlalchemy.orm.relationshipsz2util.ReadOnlyProperties[RelationshipProperty[Any]]cCs|tjjjS)aDA namespace of all :class:`.Relationship` properties maintained by this :class:`_orm.Mapper`. .. warning:: the :attr:`_orm.Mapper.relationships` accessor namespace is an instance of :class:`.OrderedProperties`. This is a dictionary-like object which includes a small number of named methods such as :meth:`.OrderedProperties.items` and :meth:`.OrderedProperties.values`. When accessing attributes dynamically, favor using the dict-access scheme, e.g. ``mapper.relationships[somename]`` over ``getattr(mapper.relationships, somename)`` to avoid name collisions. .. seealso:: :attr:`_orm.Mapper.attrs` - namespace of all :class:`.MapperProperty` objects. )rr rPZorm_relationshipsrRrrkrkrl relationshipsY szMapper.relationshipsz/util.ReadOnlyProperties[CompositeProperty[Any]]cCs|tjjjS)zReturn a namespace of all :class:`.Composite` properties maintained by this :class:`_orm.Mapper`. .. seealso:: :attr:`_orm.Mapper.attrs` - namespace of all :class:`.MapperProperty` objects. )rr rPrQrLrrkrkrl compositesx s zMapper.compositesz Type[_MP]zutil.ReadOnlyProperties[_MP])type_rgcs,|ttfdd|jDS)Nc3s$|]\}}t|r||fVqdSrh)rrr3vrrkrlr s z,Mapper._filter_properties..)rmr rr:rr)rrrkrrlr s zMapper._filter_propertiescCs4ddt|jdD}tjdd|Dt|fS)zcreate a "get clause" based on the primary key. this is used by query.get() and many-to-one lazyloads to load this item by primary key. cSs(g|] \}}|tjd||jdfqS)zpk_%dr)r4 bindparamr)ridxr~rkrkrlr# sz&Mapper._get_clause..rcSsg|]\}}||kqSrkrkrrkrkrlr# s) enumerater~r4and_r Z column_dict)rparamsrkrkrl _get_clause s  zMapper._get_clauserXcs@ifdd}|jjD]"}|jdk rt|jid|iqS)aCreate a map of all equivalent columns, based on the determination of column pairs that are equated to one another based on inherit condition. This is designed to work with the queries that util.polymorphic_union comes up with, which often don't include the columns from the base table directly (including the subclass table columns only). The resulting structure is a dictionary of columns mapped to lists of equivalent columns, e.g.:: { tablea.col1: {tableb.col1, tablec.col1}, tablea.col2: {tabled.col2} } csh|jtjkrd|jkr*|j|jn|jh|j<|jkrV|j|jn|jh|j<dSrh)operatorr:eqleftr.right)binaryrrkrl visit_binary s   z0Mapper._equivalent_columns..visit_binaryNr)rrrr=traverse)rrrrkrrlr s  zMapper._equivalent_columns) assigned_nameobjrgcCs&t|ttjtjfrdS||jkSdSr)rr'rrOr9r[_dataclass_fields)rrrrkrkrl_is_userland_descriptor szMapper._is_userland_descriptorcCsddt|jDS)NcSsg|] }|jqSrk)r)rfrkrkrlr# sz,Mapper._dataclass_fields..)r Zdataclass_fieldsr|rrkrkrlr szMapper._dataclass_fieldscCs|dk rt|rdS|rH|jj|ddk rn|||jj|rndSn&|j|d}|dk rn|||rndS|jdk r||jkr|dks||jkr| d|dS|j dk r||j ks|dk r||j kr| d|dSdS)zdetermine whether a particular property should be implicitly present on the class. This occurs when properties are propagated from an inherited class, or are applied from the columns present in the mapped table. NTznot including property %szexcluding property %sF) r9Z_never_select_columnr|rr=rrrRrrr)rrrrrattrrkrkrlr sR    zMapper._should_exclude)otherrgcCs |j|jkS)zXReturn true if the given mapper shares a common inherited parent as this mapper.)rrrrkrkrl common_parent szMapper.common_parentcCs$|j|jko"|| o"|| S)z{return true if the other mapper is an inheriting sibling to this one. common parent but different branch )rrrrkrkrl is_sibling s    zMapper.is_siblingzInstanceState[Any])rAallow_subtypesrgcCs4|}|jdk s|r$t||St||kSdSrh)primary_mapperrr$r)rrArsrkrkrl_canload szMapper._canloadcCs |}|r||k r|j}qt|S)z>Return True if the this mapper inherits from the given mapper.)rrz)rrr`rkrkrlr) s z Mapper.isarnccs|}|r|V|j}qdSrh)r)rr`rkrkrlr1 szMapper.iterate_to_rootcCs<g}t|g}|r2|}||||jqt|S)zThe collection including this mapper and all descendant mappers. This includes not just the immediately inheriting mappers but all their inheriting mappers as well. )rrIrrJrr r)rZ descendantsrKrLrkrkrlr7 s  zMapper.self_and_descendantscCs t|jS)aCIterate through the collection including this mapper and all descendant mappers. This includes not just the immediately inheriting mappers but all their inheriting mappers as well. To iterate through an entire hierarchy, use ``mapper.base_mapper.polymorphic_iterator()``. )rrrrkrkrlpolymorphic_iteratorG s zMapper.polymorphic_iteratorcCs|jjS)zSReturn the primary mapper corresponding to this mapper's class key (class).)rrrrkrkrlrT szMapper.primary_mappercCs |jjjSrh)rrrrrkrkrlprimary_base_mapperZ szMapper.primary_base_mappercs@|j}rfdd|D}|}|D]}||kr(dSq(dS)Ncsg|]}j|qSrkrr%rrkrlr#a sz3Mapper._result_has_identity_key..FT)r~keys)rrrr1Zrkr"rkrrl_result_has_identity_key^ szMapper._result_has_identity_keyz%Optional[Union[Row[Any], RowMapping]]zOptional[ORMAdapter]z_IdentityKeyType[_O])rowrrrgcsV|j}rfdd|D}t|dr.|jn td||jtfdd|D|fS)aReturn an identity-map key for use in storing/retrieving an item from the identity map. :param row: A :class:`.Row` or :class:`.RowMapping` produced from a result set that selected from the ORM mapped primary key columns. .. versionchanged:: 2.0 :class:`.Row` or :class:`.RowMapping` are accepted for the "row" argument csg|]}j|qSrkrr%rrkrlr#| sz0Mapper.identity_key_from_row.._mappingzMapping[Any, Any]c3s|]}|VqdSrhrk)rr)mappingrkrlr sz/Mapper.identity_key_from_row..)r~r rrrr)rrrrr1rk)rrrlidentity_key_from_rowi s  zMapper.identity_key_from_rowzTuple[Any, ...])r~rrgcCs|jt||fS)zReturn an identity-map key for use in storing/retrieving an item from an identity map. :param primary_key: A list of values indicating the identifier. )rr)rr~rrkrkrlidentity_key_from_primary_key s z$Mapper.identity_key_from_primary_keyr!)instancergcCst|}||tjS)aReturn the identity key for the given instance, based on its primary key attributes. If the instance's state is expired, calling this method will result in a database check to see if the object has been deleted. If the row no longer exists, :class:`~sqlalchemy.orm.exc.ObjectDeletedError` is raised. This value is typically also found on the instance state under the attribute name `key`. rinstance_state_identity_key_from_stater% PASSIVE_OFF)rrrArkrkrlidentity_key_from_instance s z!Mapper.identity_key_from_instancer%)rApassivergcs4jj|jtfdd|jDjfS)Ncs"g|]}|jjqSrk)rimplr=rrBrr rArkrlr# sz3Mapper._identity_key_from_state..)rrrrr)r)rrAr rkrrlr  szMapper._identity_key_from_statecCs t|}||tj}|dS)aGReturn the list of primary key values for the given instance. If the instance's state is expired, calling this method will result in a database check to see if the object has been deleted. If the row no longer exists, :class:`~sqlalchemy.orm.exc.ObjectDeletedError` is raised. rr)rrrAZ identity_keyrkrkrlprimary_key_from_instance s z Mapper.primary_key_from_instancecs:dd|jDtdgr.fdd}ndd}|S)NcSsg|] }|jjqSrk)rZsort_key_functionr!rkrkrlr# sz1Mapper._persistent_sortkey_fn..cstddt|jdDS)Ncss&|]\}}|dk r||n|VqdSrhrk)rZkey_fnvalrkrkrlr sz=Mapper._persistent_sortkey_fn..key..r)rziprrAZkey_fnsrkrlr sz*Mapper._persistent_sortkey_fn..keycSs |jdSNrrrrkrkrlr s)r~rj differencerrkrrl_persistent_sortkey_fn s zMapper._persistent_sortkey_fncsfddjDS)Ncsg|]}j|qSrkrr!rrkrlr# sz.Mapper._identity_key_props..r$rrkrrlr) szMapper._identity_key_propscCs&t}|jD]}||j|q |Srh)rjrrr)rZ collectionrrkrkrl _all_pk_cols s zMapper._all_pk_colscCs$t|j}|jdk r ||j|Srh)rjr~rr.)rrrkrkrl_should_undefer_in_wildcard s   z"Mapper._should_undefer_in_wildcardcsfddjDS)Ncsh|]}j|jqSrkrr!rrkrlr* sz/Mapper._primary_key_propkeys..)rrrkrrl_primary_key_propkeys szMapper._primary_key_propkeysrGColumnElement[Any])rArBrr rgcCs$|j|}|j|jjj|||dSNr )rrrr r=rrArBrr rrkrkrl_get_state_attr_by_column s z Mapper._get_state_attr_by_columncCs&|j|}|j|jj|||dSrh)rrrr Zset_committed_valuerrArBrrqrrkrkrl#_set_committed_state_attr_by_column s z*Mapper._set_committed_state_attr_by_columncCs(|j|}|j|jj|||ddSrh)rrrr rjrrkrkrl_set_state_attr_by_columns z Mapper._set_state_attr_by_columncCs(t|}t|}|j|||tjdSr)rr instance_dict#_get_committed_state_attr_by_columnr%r )rrrrArBrkrkrl_get_committed_attr_by_columns  z$Mapper._get_committed_attr_by_columncCs$|j|}|j|jjj|||dSr)rrrr Zget_committed_valuerrkrkrlr#s  z*Mapper._get_committed_state_attr_by_columnc sXjt|jj}ttfdd|DjjkrFdSfdd}g}d}t t  D]l}|jkrd}nt |jt jsdS|rn|jsn|jst|jrt|jdk st||j|jqnzt|did |i}Wntk rYdSX||d<tj|} g} |D]} | | jq*tj| | t S) alassemble a WHERE clause which retrieves a given state by primary key, using a minimized set of tables. Applies to a joined-table inheritance mapper where the requested attribute names are only present on joined tables, not the base table. The WHERE clause attempts to include only those tables to minimize joins. cs*g|]"}|jD]}tj|ddqqS)T)Z check_columns)rrr+)rrr)propsrkrlr#'s z3Mapper._optimized_get_statement..Ncs|j}|j}|dks|dkr dS|jkrhjj|tjd}|tjkrPt t j d||jj d|_nF|jkrjj|tjd}|tjkrt t j d||jj d|_dS)Nrr) rrrr#rr%ZPASSIVE_NO_INITIALIZErZ _none_set_OptGetColumnsNotAvailabler4rr)rZleftcolZrightcolZleftvalZrightval)rrArrkrlr2s@     z5Mapper._optimized_get_statement..visit_binaryFTrr)!rrjr-rrrrrr}reversedrrrr9r<rrrrrrr.r=Zcloned_traverser&r4rrJrselectwhereset_label_stylerB) rrAZattribute_namesZcol_attribute_namesrZallcondsstartrZ _traversedZcondrrrk)r%rrArrl_optimized_get_statements\           zMapper._optimized_get_statementccsL||rH|}|D]0}|V||k r6||jkr6qH|}||krqHqdSrh)rrr)rrprevr`rkrkrl_iterate_to_target_viawpoly|s  z"Mapper._iterate_to_target_viawpolycCsiSrhrkrrkrkrl&_would_selectinload_combinations_cachesz-Mapper._would_selectinload_combinations_cachecCsn|j}z ||WStk r$YnX||s4t|}||D]}|jdkrB||k}qbqBd}|||<|S)areturn True if this mapper would "selectin" polymorphic load based on the given super mapper, and not from a setting from a subclass. given:: class A: ... class B(A): __mapper_args__ = {"polymorphic_load": "selectin"} class C(B): ... class D(B): __mapper_args__ = {"polymorphic_load": "selectin"} ``inspect(C)._would_selectin_load_only_from_given_mapper(inspect(B))`` returns True, because C does selectin loading because of B's setting. OTOH, ``inspect(D) ._would_selectin_load_only_from_given_mapper(inspect(B))`` returns False, because D does selectin loading because of its own setting; when we are doing a selectin poly load from B, we want to filter out D because it would already have its own selectin poly load set up separately. Added as part of #9373. rF)r/rrrr.r)rZ super_mappercacherr`retvalrkrkrl+_would_selectin_load_only_from_given_mappers  z2Mapper._would_selectin_load_only_from_given_mappercCs|s,|}||D]}|jdkr|Sqndt|}dd|D}||gD]@}|j}||D]*}|jdksx||krb|||SqbqNdS)NrcSsi|] }|j|qSrkr)rerkrkrlrsz0Mapper._should_selectin_load..)r.rrjrrr=)rZenabled_via_optpolymorphic_fromrr`Zenabled_via_opt_mappersrrkrkrl_should_selectin_loads   zMapper._should_selectin_loadzsqlalchemy.orm.strategy_optionscstjj}|jst|jdk r:|j|j}t|g|j}n t|j}| }| }|h}|j} | dk r| |k r| j dkr| | | j} qd|j |j D]t} | j|jkrq| j|ks| |krt| tsq|jtj| jft| jdd}q|jtj| jfddidd}qdd|jD} t| d kr.rrcsg|]}j|qSrk)_adapterr)rr3rrkrlr#.sZ primary_keys)Z expanding)'r rPZorm_strategy_optionsrrrrrjr)Loadrr.rrrrrSrr-Z_set_generic_strategyrErrZ strategy_keyr~r/r4tuple_Zis_aliased_classrr(r*rBr8rr)rrZorder_by)rrr5Zstrategy_optionsZpolymorphic_propZ keep_propsZ disable_optZ enable_optZclasses_to_includer`rr~Zin_exprqrkr9rl_subclass_load_via_insz               zMapper._subclass_load_via_incCs|||jSrh)r=rrrkrkrl_subclass_load_via_in_mapper<sz#Mapper._subclass_load_via_in_mapperz.Optional[Callable[[InstanceState[Any]], bool]]zGIterator[Tuple[object, Mapper[Any], InstanceState[Any], _InstanceDict]])rrAhalt_onrgccst}tt}}|j|s$ttt|jj|||jfg}|r|d\}} } } |sh| qD| |kr| } | j rD|| j krqD| dk st| dk stt| || | ||} | r| | |ddfqD| |krD| \}}}}||||fV| t|j|||fqDdS)a.Iterate each element and its mapper in an object graph, for all relationships that meet the given cascade rule. :param type\_: The name of the cascade rule (i.e. ``"save-update"``, ``"delete"``, etc.). .. note:: the ``"all"`` cascade is not accepted here. For a generic object traversal function, see :ref:`faq_walk_objects`. :param state: The lead InstanceState. child items will be processed per the relationships defined for this object's mapper. :return: the method yields individual object instances. .. seealso:: :ref:`unitofwork_cascades` :ref:`faq_walk_objects` - illustrates a generic function to traverse all objects without relying on cascades. reN)rjobjectrrrrrrNrrrIrjcascade_iteratorr)rrrAr?Zvisited_statesZprpZmppZ visitablesiteratorZ item_typeZ parent_stateZ parent_dictrqueuerZinstance_mapperZcorresponding_stateZcorresponding_dictrkrkrlrAAs^      zMapper.cascade_iteratorcCs t|jSrh)r ZLRUCacherrrkrkrl_compiled_cacheszMapper._compiled_cachecCst|jdkSr)r/rrrkrkrl_multiple_persistence_tablessz#Mapper._multiple_persistence_tablescsi|jjD]}|jD]}||qq g}D],\}|j}|r6|fdd|jDq6fdd}tj||d}t }|D]}|||<q|S)Ncsg|] }|fqSrkrk)rZ super_tabler(rkrlr#sz)Mapper._sorted_tables..cs|jj}|jj}|dk r|dk r||k r|jdk rtt|j}|jdk r~|t|j}|j|ko||j|kS|j|kSdSr) r=rSrrrrjrZ _find_columnsr)ZfkrSdepr)table_to_mapperrkrlskips$   z#Mapper._sorted_tables..skip)Zskip_fnextra_dependencies) rrr setdefaultrrrJrZ sort_tablesr r:)rrrrIZsuper_rHZsorted_retrk)rrGrl_sorted_tabless*   zMapper._sorted_tableszCallable[[], _T]r^)r callable_rgcCs2||jkrtt|j|S||j|<}|SdSrh)rrr^)rrrMrqrkrkrl_memos z Mapper._memocCsptt}dd}|jD]R}t|j}|D]:}|jr.|t |dd|jDr.|| ||jfq.q|S)zgmemoized map of tables to collections of columns to be synchronized upwards to the base mapper.cSs ||Srh)r)ryrkrkrl set_unionsz+Mapper._table_to_equated..set_unioncSsg|]\}}|jqSrkr)rrnrrkrkrlr#sz,Mapper._table_to_equated..) r defaultdictrrLrjrrrr-rr)rrrPrrr`rkrkrl_table_to_equateds      zMapper._table_to_equated)NNNFNNNFNNNNNFNFNTTNNNTFTrxFry)F)NN)F)NFF)rk)N)N)NN)N)N)rr __qualname____doc____annotations__rrurr Zdeprecated_paramsrrrZ is_mapperZrepresents_outer_joinpropertyrrrZnon_memoized_property deprecatedrZmemoized_propertyrrrrrrrrrrrrrrCZmemoized_attributerHrDrOpreload_modulerr<r;r>r[Z langhelpersZtag_method_for_warningsrZ SAWarningrmrorrrprrwrr~rrrrrrrrrrrrrrrrDrZwith_polymorphic_mappersrrrrrrrrrrZmemoized_instancemethodrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr r%ZPASSIVE_RETURN_NO_VALUEr rrr)rrrrr r!r$r#r,r.r/r2r6r=r>rArDrErLrNrSrkrkrkrlrssJ    J            @' ]t G    +$B$  $   0           %E   )  .   "#$    f  7  a a2rsrc@s eZdZdS)r&N)rrrTrkrkrkrlr&sr&rcCsttdddS)a Initialize the inter-mapper relationships of all mappers that have been constructed thus far across all :class:`_orm.registry` collections. The configure step is used to reconcile and initialize the :func:`_orm.relationship` linkages between mapped classes, as well as to invoke configuration events such as the :meth:`_orm.MapperEvents.before_configured` and :meth:`_orm.MapperEvents.after_configured`, which may be used by ORM extensions or user-defined extension hooks. Mapper configuration is normally invoked automatically, the first time mappings from a particular :class:`_orm.registry` are used, as well as whenever mappings are used and additional not-yet-configured mappers have been constructed. The automatic configuration process however is local only to the :class:`_orm.registry` involving the target mapper and any related :class:`_orm.registry` objects which it may depend on; this is equivalent to invoking the :meth:`_orm.registry.configure` method on a particular :class:`_orm.registry`. By contrast, the :func:`_orm.configure_mappers` function will invoke the configuration process on all :class:`_orm.registry` objects that exist in memory, and may be useful for scenarios where many individual :class:`_orm.registry` objects that are nonetheless interrelated are in use. .. versionchanged:: 1.4 As of SQLAlchemy 1.4.0b2, this function works on a per-:class:`_orm.registry` basis, locating all :class:`_orm.registry` objects present and invoking the :meth:`_orm.registry.configure` method on each. The :meth:`_orm.registry.configure` method may be preferred to limit the configuration of mappers to those local to a particular :class:`_orm.registry` and/or declarative base class. Points at which automatic configuration is invoked include when a mapped class is instantiated into an instance, as well as when ORM queries are emitted using :meth:`.Session.query` or :meth:`_orm.Session.execute` with an ORM-enabled statement. The mapper configure process, whether invoked by :func:`_orm.configure_mappers` or from :meth:`_orm.registry.configure`, provides several event hooks that can be used to augment the mapper configuration step. These hooks include: * :meth:`.MapperEvents.before_configured` - called once before :func:`.configure_mappers` or :meth:`_orm.registry.configure` does any work; this can be used to establish additional options, properties, or related mappings before the operation proceeds. * :meth:`.MapperEvents.mapper_configured` - called as each individual :class:`_orm.Mapper` is configured within the process; will include all mapper state except for backrefs set up by other mappers that are still to be configured. * :meth:`.MapperEvents.after_configured` - called once after :func:`.configure_mappers` or :meth:`_orm.registry.configure` is complete; at this stage, all :class:`_orm.Mapper` objects that fall within the scope of the configuration operation will be fully configured. Note that the calling application may still have other mappings that haven't been produced yet, such as if they are in modules as yet unimported, and may also have mappings that are still to be configured, if they are in other :class:`_orm.registry` collections not part of the current scope of configuration. TriN)rlrmrkrkrkrlconfigure_mappers sDrZzSet[_RegistryType]rz) registriesrjrgc Cs|D]}|jrqqdSthtr0W5QRdSdazD|D]}|jr:q\q:W,W5QRdStjtt||W5daXW5QRXtjtdS)NTF) rkri_already_compilingrsrtZ _for_classZbefore_configured_do_configure_registriesZafter_configured)r[rjrprkrkrlrlPs"rlzsqlalchemy.orm.decl_apic Cs"tjjj}t|}||D]}d}|D]}d}|jjD] }|||j }|t kr>d}q`q>|t krjq.t |ddrt d||jf} |j| _| |js.z$|||j||j Wq.tk rtd} t| ds| |_Yq.Xq.|sd|_|s|j|rt dqdS)NFTruzOne or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: '%s'. Original exception was: %srzHconfigure was called with cascade=False but additional registries remain)r rP orm_decl_apirJrjZ_recurse_with_dependenciesrortZbefore_mapper_configuredr|r(rErrrurrorZmapper_configured Exceptionsysexc_infor rk _dependenciesr) r[rjrJorigrpZhas_skiprZ run_configurefnr4rrkrkrlr]rsJ        r]c Cstjjj}t|}||D]}|s:|j|r:t d|j rtz|j \}}Wnt k rfYq:X| |q:|j|j|jD]}|j|q|jd|_qdS)Nz^Registry has dependent registries that are not disposed; pass cascade=True to clear these alsoF)r rPr^rJrjZ_recurse_with_dependentsZ _dependentsrrrZ _managerspopitemrZ_dispose_manager_and_mapperZ_non_primary_mappersclearrbdiscardrk)r[rjrJrcrpr_rFrkrkrl_dispose_registriess&      ricCs d|_|S)aDecorate a method as the 'reconstructor' hook. Designates a single method as the "reconstructor", an ``__init__``-like method that will be called by the ORM after the instance has been loaded from the database or otherwise reconstituted. .. tip:: The :func:`_orm.reconstructor` decorator makes use of the :meth:`_orm.InstanceEvents.load` event hook, which can be used directly. The reconstructor will be invoked with no arguments. Scalar (non-collection) database-mapped attributes of the instance will be available for use within the function. Eagerly-loaded collections are generally not yet available and will usually only contain the first element. ORM state changes made to objects at this stage will not be recorded for the next flush() operation, so the activity within a reconstructor should be conservative. .. seealso:: :meth:`.InstanceEvents.load` T)rrdrkrkrl reconstructorsrkTinclude_removesinclude_backrefsrzCallable[[_Fn], _Fn])namesrmrnrgcsdddfdd }|S)aDecorate a method as a 'validator' for one or more named properties. Designates a method as a validator, a method which receives the name of the attribute as well as a value to be assigned, or in the case of a collection, the value to be added to the collection. The function can then raise validation exceptions to halt the process from continuing (where Python's built-in ``ValueError`` and ``AssertionError`` exceptions are reasonable choices), or can modify or replace the value before proceeding. The function should otherwise return the given value. Note that a validator for a collection **cannot** issue a load of that collection within the validation routine - this usage raises an assertion to avoid recursion overflows. This is a reentrant condition which is not supported. :param \*names: list of attribute names to be validated. :param include_removes: if True, "remove" events will be sent as well - the validation function must accept an additional argument "is_remove" which will be a boolean. :param include_backrefs: defaults to ``True``; if ``False``, the validation function will not emit if the originator is an attribute event related via a backref. This can be used for bi-directional :func:`.validates` usage where only one validator should emit per attribute operation. .. versionchanged:: 2.0.16 This paramter inadvertently defaulted to ``False`` for releases 2.0.0 through 2.0.15. Its correct default of ``True`` is restored in 2.0.16. .. seealso:: :ref:`simple_validators` - usage examples for :func:`.validates` rb)rdrgcs|_d|_|S)Nrl)rr rjrnrmrorkrlwraps zvalidates..wraprk)rmrnrorqrkrprl validatess(rrcCs |jj}|jr||dSrh)rrrr)rActxinstrumenting_mapperrkrkrlr sr cCs(|jj}|r$||jr$||dS)zRun init_instance hooks. This also includes mapper compilation, normally not needed here but helps with some piecemeal configuration scenarios (such as in the ORM tutorial). N)rrrmr)rArxkwargsrtrkrkrlr !s r c@s$eZdZdZdZddZddZdS)rz4Error reporting helper for mapper._columntoproperty.r3cCs ||_dSrhr3rsrkrkrlr6sz_ColumnMapping.__init__cCsH|jj|}|r0td|jj|j|j|ftd||jfdS)NzDColumn '%s.%s' is not available, due to conflicting property '%s':%rz*No column %s is configured on mapper %s...)rrr=orm_excZUnmappedColumnErrorrrr)rrrrkrkrl __missing__:sz_ColumnMapping.__missing__N)rrrTrU __slots__rrwrkrkrkrlr1sr)rra)rU __future__r collectionsr functoolsr itertoolsrr` threadingtypingrrrr r r r r rrrrrrrrrrrrweakrefr6rrrvrrrr rZ_typingr!r7r"r#r$r%r&Z interfacesr'r(r)r*r+r,r-Z path_registryr.r0rr1r2r3r4r5r6r9r8r9r:r;r<rr=Z sql.cache_keyr>Z sql.elementsr?Z sql.schemar@rAZsql.selectablerBrCrDZ util.typingrErFrGrHrIZdecl_apirJ dependencyrKrUrLrMeventsrNrOrPrQrrRrArSrTZenginerUrVZ sql._typingrWrXZsql.baserYrZr[r\r]r^r`rbZ_WithPolymorphicArgWeakKeyDictionaryrerVrmrqr\symbolrrRLockriZ_self_inspectsZ class_loggerZ IdentifiedZ Inspectablersr_r&rZrlrYr]rirkrrr r rrkrkrkrl s\                                                                                                    G"4!3