U a!" @sdZddlmZddlmZddlmZddlZddlZddl m Z ddl m Z dd l m Z dd l mZdd l mZdd l mZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddl m Z ddl m Z!ddl m"Z"ddl m#Z#ddl m$Z$ddl m%Z%dd l mZddl%mZ&ddl%m'Z'dd l%m(Z(dd!l%m)Z)dd"l%m*Z*dd l%mZ+dd#l%m,Z,dd$l-m.Z.dd%lm/Z/e0Z1dZ2d&d'Z3d(d)Z4d*a5e6d+Z7ej89Z:e"j;e#jGd.d/d/e?Z@d0d1ZAd2d3ZBeCd4d5d6ZDeCd4d7d8ZEd9d:ZFd;d<ZGd=d>ZHd?d@ZIGdAdBdBeJZKdS)Ca5Logic 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.`. )absolute_import)deque)chainN) attributes)exc)instrumentation)loading) properties)util)_class_to_mapper) _state_mapper) class_mapper) state_str)_MappedAttribute)EXT_SKIP)InspectionAttr)MapperProperty)ORMEntityColumnsClauseRole)ORMFromClauseRole) PathRegistry)event) inspection)log)schema)sql)base) coercions) expression) operators)roles)visitors)LABEL_STYLE_TABLENAME_PLUS_COL) HasMemoizedc Cs$tttW5QRSQRXdSN)_CONFIGURE_MUTEXset_mapper_registriesr)r)VC:\Users\vtejo\AppData\Local\Temp\pip-unpacked-wheel-nyjtotrf\sqlalchemy\orm\mapper.py_all_registries?sr+ccs$tD]}|D] }|VqqdSr%)r+_mappers_to_configure)regmapperr)r)r*_unconfigured_mappersDs  r/F NO_ATTRIBUTEc@sfeZdZdZdZdZejddddd ZdZ dZ e d d Z d d Z e ddZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZ e e!ddddZ"ej#ddZ$ddZ%ddZ&ddZ'ddZ(ddZ)d d!Z*d"d#Z+d$d%Z,d&d'Z-dd(d)Z.dZ/e0j1d*d+Z2e0j1d,d-Z3e0j1d.d/Z4e5d0d1d2Z6e5d0dd3d4Z7e5d0d5d6Z8d7d8Z9d9d:Z:d;d<Z;d=d>ZdCdDZ?dEdFZ@dGdHZAdIdJZBdKdLZCdMdNZDddOdPZEdQdRZFe dSdTZGdUdVZHdWdXZIe0j1dYdZZJe0j1d[d\ZKe0j1d]d^ZLe0j1d_d`ZMeKZNe0j1dadbZOe0j1dcddZPe0j1dedfZQe0j1dgdhZRe0j1didjZSe0j1dkdlZTe0j1dmdnZUe0j1dodpZVe0jWdqdrZXej#dsdtZYe dudvZZddwdxZ[e0j1dydzZ\e d{d|Z]dd~dZ^e0j1ddZ_dddZ`e0j1ddZae0j1ddZbe0j1e5d0ddZce ddZde0j1ddZee5de0j1ddZfe0j1e5d0ddZgddZhe0j1ddZie0j1ddZjddZke0j1ddZlddZmddZnddZoddZpddZqddZre0j1ddZsddZtddZue ddZvdddZwdddZxdddZyddZze{j|fddZ}ddZ~e0j1ddZe0j1ddZe0j1dd„Ze0j1ddĄZe0j1ddƄZe{j|fddȄZddʄZdd̄Zdd΄Ze{j|fddЄZdd҄ZddԄZddքZe5ddءddڄZe0j1dd܄ZdddބZe0j1ddZe0j1ddZddZej#ddZdS)MapperaDefine the correlation of class attributes to database table columns. The :class:`_orm.Mapper` object is instantiated using the :func:`~sqlalchemy.orm.mapper` function. For information about instantiating new :class:`_orm.Mapper` objects, see that function's documentation. When :func:`.mapper` is used explicitly to link a user defined class with table metadata, this is referred to as *classical mapping*. Modern SQLAlchemy usage tends to favor the :mod:`sqlalchemy.ext.declarative` extension for class configuration, which makes usage of :func:`.mapper` behind the scenes. Given a particular class known to be mapped by the ORM, the :class:`_orm.Mapper` which maintains it can be acquired using the :func:`_sa.inspect` function:: from sqlalchemy import inspect mapper = inspect(MyClass) A class which was mapped by the :mod:`sqlalchemy.ext.declarative` extension will also have its mapper available via the ``__mapper__`` attribute. F)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_primaryNTdc CsFt|td|_d|jj|jjf|_d|_t||_ ||_ | |_ t | t r\| |_d|_n| |_| dkrrd|_n| dkrdd|_n| |_||_d|_||_|dk rttj||_nd|_||_||_|pi|_g|_||_||_||_| dk rtjtj | ddnd|_!g|_"tj#|_$||_%||_&||_'d|_(d|_)d|_*i|_+||_,d|_-||_.|jrp|jspd|_/n||_/|0|||_1||_2| dkri|_3n| |_3|dk rt4||_5nd|_5|rt4||_6nd|_6t7\|j8j9:|||;|<|=|>|?|j@A||Bd |CW5QRXdS) anJDirect constructor for a new :class:`_orm.Mapper` object. The :func:`_orm.mapper` function is normally invoked through the use of the :class:`_orm.registry` object through either the :ref:`Declarative ` or :ref:`Imperative ` mapping styles. .. versionchanged:: 1.4 The :func:`_orm.mapper` function should not be called directly for classical mapping; for a classical mapping configuration, use the :meth:`_orm.registry.map_imperatively` method. The :func:`_orm.mapper` function may become private in a future release. 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 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 ``__table__`` argument or via the :class:`_schema.Table` produced as a result of the ``__tablename__`` and :class:`_schema.Column` arguments present. :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 explicitly specified column-based properties. See the section :ref:`column_prefix` for an example. :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. .. versionadded:: 0.9.4 - added :paramref:`.mapper.confirm_deleted_rows` as well as conditional matched row checking on delete. :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. By default, this scheme will emit an individual ``SELECT`` statement per row inserted or updated, which note can add significant performance overhead. However, if the target database supports :term:`RETURNING`, the default values will be returned inline with the INSERT or UPDATE statement, which can greatly enhance performance for an application that needs frequent access to just-generated server defaults. .. seealso:: :ref:`orm_server_defaults` .. versionchanged:: 0.9.0 The ``eager_defaults`` option can now make use of :term:`RETURNING` for backends which support it. :param exclude_properties: A list or set of string column names to be excluded from mapping. See :ref:`include_exclude_cols` for an example. :param include_properties: An inclusive list or set of string column names to map. See :ref:`include_exclude_cols` for an example. :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. .. versionadded:: 1.1 .. 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. This value is commonly a :class:`_schema.Column` object that's present in the mapped :class:`_schema.Table`:: class Employee(Base): __tablename__ = 'employee' id = Column(Integer, primary_key=True) discriminator = 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 = Column(Integer, primary_key=True) discriminator = 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 configured with :func:`.column_property`, or to the string name of one:: class Employee(Base): __tablename__ = 'employee' id = Column(Integer, primary_key=True) discriminator = Column(String(50)) employee_type = column_property( case([ (discriminator == "EN", "engineer"), (discriminator == "MA", "manager"), ], else_="employee") ) __mapper_args__ = { "polymorphic_on":employee_type, "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 ``polymorphic_on`` setting. As rows are received, the value corresponding to the ``polymorphic_on`` column expression is compared to this value, indicating which subclass should be used for the newly reconstructed object. :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. :param primary_key: A list of :class:`_schema.Column` objects 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. :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. .. versionadded:: 0.9.0 ``version_id_generator`` supports server-side version number generation. .. 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. .. seealso:: :ref:`with_polymorphic` - discussion of polymorphic querying techniques. class_z%s.%sNFcSs |pddS)Nrrr))xr)r)r*[z!Mapper.__init__..polymorphic_on)argnameZ constructed)Dr Zassert_arg_typetyper5 __module____name__ _sort_key class_managerto_list_primary_key_argumentr3always_refresh isinstancerZversion_id_propversion_id_colversion_id_generatorconcretesingleinheritsrexpectr!StrictFromClauseRole local_tableinherit_conditioninherit_foreign_keys_init_properties_delete_orphansbatcheager_defaults column_prefixZColumnArgumentOrKeyRoler9Z_dependency_processors EMPTY_DICT validatorspassive_updatespassive_deleteslegacy_is_orphanZ_clause_adapter_requires_row_aliasing_inherits_equated_pairs_memoized_values_compiled_cache_size_reconstructorallow_partial_pksconfirm_deleted_rows_set_with_polymorphicpolymorphic_loadpolymorphic_identitypolymorphic_mapto_setinclude_propertiesexclude_propertiesr&dispatchZ_eventsZ_new_mapper_instance_configure_inheritance _configure_class_instrumentation_configure_properties_configure_polymorphic_setter_configure_pksregistryZ_flag_new_mapper_log_expire_memoizations)selfr5rKr primary_keyr3rHrLrMrBrDrEr9Z_polymorphic_maprarFwith_polymorphicr`r]rPrRrdrerUrVr^rQrWr[r)r)r*__init__sH          zMapper.__init__cCs|S)z||_qd|df|_n|dk r^tdnd|_|jr|jddk r|jdtj t j |jdddf|_|j r| dS)N*)rNrz$Invalid setting for with_polymorphicrTZ allow_select)rqrCtuplelistr string_typesrrrrIr!rJ configuredrn)rorqr)r)r*r_Us,    zMapper._set_with_polymorphiccCsP|j}|jdkr||fn.|jddkrL||jd|f|jdfdS)Nrrr)r5rqr_)ror.Zsubclr)r)r*rqs 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)rFAssertionErrorrHrCr1rbupdaterr9rXrPself_and_descendantsrr~rrUr_propsitems_should_exclude_adapt_inherited_property)ror.mpkeypropr)r)r*_set_concrete_basezs.          zMapper._set_concrete_basecCs||_|ddS)NT)r9rj)ror9r)r)r*_set_polymorphic_onszMapper._set_polymorphic_oncCst|j}|jrT|r|js,td|j||_|j|_|j j |_ |j |dS|dk r|j|jkslt |jrt d|j|j||jtj|j|ttj|dd}|jstdtdk st t|||_|j|_|j dkrdStj|dtddt|jD]\}}|d krFt|d rF|j}t|d rF|j}t |rt|d rv||_!tj|d t"ddnTt|dr|j#}|j$D]:}||j%krtd||f|j%&|||fi|_%qqdS)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.Nz1Class '%s' already has a primary mapper defined. T)r.Zexpired_attribute_loaderfinalizezCalling the mapper() function directly outside of a declarative registry is deprecated. Please use the sqlalchemy.orm.registry.map_imperatively() function for a classical mapping.init)rawrr_sa_original_init__func____sa_reconstructor__load__sa_validators__zJA validation function for mapped attribute %r on mapper %s already exists.)'rmanager_of_classr5r3Z is_mappedrInvalidRequestErrorr?rlr.rZ_add_non_primary_mapperrrrfinstrument_classrZregister_classr partialr Zload_scalar_attributesZwarn_deprecated_20_legacy_registryZ _add_managerrlisten_event_on_initZiterate_attributeshasattrrrcallabler\_event_on_load__sa_validation_opts__rrTunion)romanagerrmethodZvalidation_optsnamer)r)r*rhs~                z'Mapper._configure_class_instrumentationcCs$d|_d|_d|_|jdddS)NT_configure_failed)r_ready_for_configure_dispose_called__dict__poprsr)r)r*_set_dispose_flagsszMapper._set_dispose_flagscstj_i_i_ttddj D}tdd|D}t jjg}j ||D]F}|j r||j rt|j |j|<t|j|j|<qjjrjD]2}|jjkrtj|j<j|j|qnljjkstjjdkr0tdjjfn0jjkr`tjtjr`tdjjjrj sjsjj _ nxjrtj!fddjDd d }ntj!jjd d }t|dkrtdjjft"|_ #d |t fd dj D_$dS) NcSsg|] }|jqSr) proxy_set.0colr)r)r* sz)Mapper._configure_pks..css|]}|jr|VqdSr%rprcr)r)r* sz(Mapper._configure_pks..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.csg|]}j|qSr))rwcorresponding_columnrrsr)r*rKsT)Zignore_nonexistent_tablesz"Identified primary key columns: %sc3s>|]6}j|jkrt|dr,|jjkrj|VqdS)tableN)_columntoproperty_identity_key_propsrr_cols_by_tablerrsr)r*rcs   )%r find_tablesrwtables _pks_by_tablerr column_setrrr'rrrp issupersetZordered_column_set intersectionrrArZ OrderedSetaddlenrrrrKrCrZTablerrHrFZreduce_columnsrrm_readonly_props)roZall_colspk_colsrtkrpr)rsr*rks               zMapper._configure_pkscCst|_|_t|_t||_|j rL|j D]\}}| ||dq4|j r|j j D]2\}}||jkr^|j ||ddds^|||dq^|jjD]v}||jkrq|jpd|j}|j |j||jj||drq|D]}||jkr|j|j}q|j ||dddqdS)NFrTr setparent)sql_baseZColumnCollectioncolumnsrr OrderedDictr_ColumnMappingrrNr_configure_propertyrHrrrwrRrrKZcontains_columnr)rorrrZ column_keyr.r)r)r*rimsF       zMapper._configure_propertiesc sNd}|jdk rd}t|jtjrrz|j|j|_Wn<tk rp}ztjtd|j|dW5d}~XYnX|j|j kr|j |j}nt|jt rt|jt j std|j}n|j |j}|dkr"d}d}|j}t|tjr&|jdks|jd|dkr&td|jnd}t|d d}|r`||j|jd|rvtd |jn|d |_}|j}t j ||d }|j|||dd |jd|_|jnn|D]d}|jdk r|j |j kr|j|_n|j |j|_|jdk r|j|_|j|_nd|_dSq|rDfdd} fdd} | |_| |_nd|_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.Zreplace_contextzUOnly 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 _instrumentrrcs&|j}||||jjjddSr%)dictZget_implr'rr.ra)statedict_Zpolymorphic_keyr)r*_set_polymorphic_identity2s 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)r.rrrr)r*_validate_polymorphic_identity;szLMapper._configure_polymorphic_setter.._validate_polymorphic_identity)r9rCr rrKeyErrorraise_rrrrr ColumnPropertyrwrrZColumnrqrrgetattrrrlabelrrrrr) rorsettererrrrZ instrumentrr.rrr)rr*rjs             z$Mapper._configure_polymorphic_settercCs|jdk r|j|jSdSdSr%)rDrrsr)r)r*_version_id_propQs  zMapper._version_id_propcCsFt}t|g}|rB|}|j|jkr||j||jq|Sr%)r'rpopleftrwrraextendr~)roZ identitiesstackitemr)r)r*rXs   z)Mapper._acceptable_polymorphic_identitiescCst|jSr%) frozensetrvaluesrsr)r)r* _prop_seteszMapper._prop_setzsqlalchemy.orm.descriptor_propscCsttjj}|js"|j||dddnN||jkrp|j||}||ksZt|t j rp|j |j krp|j|| |dddS)NFrT)r preloadedorm_descriptor_propsrFrrr?_get_class_attr_mrorCrZInstrumentedAttributeZ _parententityparentConcreteInheritedProperty)rorrrdescriptor_propsZimplementing_attributer)r)r*ris,  z Mapper._adapt_inherited_propertyc Cstjj}|d||jjt|ts0|||}t|t j r|j |j d}|dkr|jr|g}|jD]T}|j |j d}|dk r|D]} | j |q|j |j d}q||qn|dkr |j d}t|drHt|dr|j|jkrH|j|n>t|drH|j|jkrH||j|jkrH|j|j|t|dsr||jkpn|j d|jk|_t|tjr||_|_|j |||j |jD]}|jD]}||j |<qq||_|r|!||||j"kr t#|j"|ddr |j"|j$} t%&d | ||| f||j"krt|t j st|j"|t j |j'fst(d |j"|||f|j"|} |j)*| d||j"|<|j+s|,||j-D]} | .|||q|r|/|0||j1r|2dS) Nz_configure_property(%s, %s)rrrr_is_polymorphic_discriminator_mapped_by_synonymFzpCan't call map_column=True for synonym %r=%r, a ColumnProperty already exists keyed to the name %r for column %rzYProperty %s on %s being replaced with new property %s; the old property will be discarded)3r rrrm __class__r=rCr_property_from_columnr rrwrrrHrrK_refresh_for_new_columnrrrrrrr9rrZLabelrZ _tq_key_labelZ _orig_columnsrrZ set_parentrrrrrrrryrr3rr~rrpost_instrument_classrrn) rorrrrrrpathmm2ZsynZoldpropr.r)r)r*rs                      zMapper._configure_propertyc Cstjj}t|}|d}t|tjs*t|j |d}t|t j r|j r^|j d|f|j kr|j d|s|j d|jk r||jk r|j|k }d|j d||f}|rt|n t||}|j d||d||S|dkst||jrg}|D]r} |j| } | dkrn|j| } | dk rD|j| |j| } | dkrntd||| f|| qt j |Std|||j|fdS)zZgenerate/update a :class:`.ColumnProperty` given a :class:`_schema.Column` object.rNzImplicitly 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 %szWhen 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.aWARNING: 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 rrr@rCr ColumnElementrrgetr rrYrZshares_lineagerDrrrrcopyinsertrmrrwrrKrrrr) rorrrrrZ warn_onlymsgZ mapped_columnrZmcr)r)r*rsv                zMapper._property_from_columncCs|jjrt|jhdddS)NTcascade)rl _new_mappers_configure_registriesrsr)r)r*_check_configureOszMapper._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|]\}}||fqSr)r))rrrr)r)r*r]sz5Mapper._post_configure_properties..zinitialize prop %sz%_post_configure_properties() completeTN) rmrrrZ_configure_startedrZ_configure_finishedrr)rolrrr)r)r*_post_configure_propertiesSs     z!Mapper._post_configure_propertiescCs"|D]\}}|||qdS)z^Add the given dictionary of properties to this mapper, using `add_property`. N)r add_property)roZdict_of_propertiesrvaluer)r)r*add_propertiesjszMapper.add_propertiescCs ||j|<|j|||jddS)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. )rN)rNrr)rorrr)r)r*rrs zMapper.add_propertycCs|D] }|qdSr%)rZ_reset_memoizationsror.r)r)r*rn~s zMapper._expire_memoizationscCs>d|jjd|jdk r |jjp(t|j|jr4dp6ddS)N(|z |non-primaryr))r5r=rKrstrr3rsr)r)r* _log_descs   zMapper._log_desccGs"|jjd|f|jf|dSNz%s )loggerinforrorargsr)r)r*rmsz Mapper._logcGs"|jjd|f|jf|dSr)r debugrr"r)r)r* _log_debugszMapper._log_debugcCsdt||jjfS)Nz)idr5r=rsr)r)r*__repr__szMapper.__repr__cCs2d|jj|jrdpd|jdk r&|jjn|jjfS)Nzmapped class %s%s->%sz (non-primary)r)r5r=r3rKrrwrsr)r)r*__str__s  zMapper.__str__cCstd}|D]T}|jD]H\}}d}t|j|||jd}|jrL|rLdS|js|sdSqq |jrl|SdSdS)NFT)Z optimistic)rrOrr has_parentZ has_identityrW)rorZorphan_possibler.rclsr)r)r)r* _is_orphans      zMapper._is_orphancCs ||jkSr%)rrorr)r)r* has_propertyszMapper.has_propertyc Cs\|r |z |j|WStk rV}z tjtd||f|dW5d}~XYnXdS)z6return a MapperProperty associated with the given key.z Mapper '%s' has no property '%s'rN)rrrr rrr)rorZ_configure_mappersrr)r)r* get_propertys  zMapper.get_propertycCs |j|S)zkGiven a :class:`_schema.Column` object, return the :class:`.MapperProperty` which maps this column.r)rorr)r)r*get_property_by_columnszMapper.get_property_by_columncCs|t|jS)z1return an iterator of all MapperProperty objects.)riterrrrsr)r)r*iterate_propertiesszMapper.iterate_propertiescs|dkrt|jnz|rtt|D]J}t|}||sPtd||f|dkrh | q( |q(fdd|jDng|dk rtt j |ddfddDS) 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. rz%r does not inherit from %rNcsg|]}|kr|qSr)r)rr)mappersr)r*rsz-Mapper._mappers_from_spec..T)Zinclude_aliasescsg|]}|jkr|qSr))rKr3)rr)r*rs )rrr'r r@r isarrrrrrr)rospec selectablerr))r4rr*_mappers_from_specs*     zMapper._mappers_from_speccCs\|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.) rwrFrrrGrrKrLZ outerjoin)ror4 innerjoinZfrom_objrr)r)r*_selectable_from_mapperss&zMapper._selectable_from_mapperscCs@|jr8|jr8|jdk r8|jd|idd|jDSdSdS)N parentmappercss|] }|jVqdSr%)rar3r)r)r*rsz1Mapper._single_table_criterion..)rGrHr9 _annotatein_rrsr)r)r*_single_table_criterions zMapper._single_table_criterioncCs||jsgS|j|jSr%)rrqr8rsr)r)r*_with_polymorphic_mapperssz 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)rrsr)r)r* _post_inspect%s zMapper._post_inspectcCs:|js |jS|j\}}|dk r"|S||||dSdSNF)rqrwr:r8)ror6r7r)r)r*_with_polymorphic_selectable2s  z#Mapper._with_polymorphic_selectablecCstdd|jDS)Ncss(|] \}}|tdd|DfVqdS)css|]}|jjr|VqdSr%)r;should_evaluate_nonerr)r)r*rJsz@Mapper._insert_cols_evaluating_none...Nrrrrr)r)r*rGs z6Mapper._insert_cols_evaluating_none..rrrrsr)r)r*_insert_cols_evaluating_noneEsz#Mapper._insert_cols_evaluating_nonecCstdd|jDS)Ncss(|] \}}|tdd|DfVqdS)css.|]&}|js|js|js|jjs|jVqdSr%)rpserver_defaultdefaultr;rCrrr)r)r*rVs z8Mapper._insert_cols_as_none...NrDrEr)r)r*rSs  z.Mapper._insert_cols_as_none..rFrsr)r)r*_insert_cols_as_noneQs zMapper._insert_cols_as_nonecstfddjDS)Nc3s,|]$\}}|tfdd|DfVqdS)c3s|]}j|j|fVqdSr%rrrrsr)r*rgsz3Mapper._propkey_to_col...N)rrErsr)r*rds  z)Mapper._propkey_to_col..rFrsr)rsr*_propkey_to_colbs zMapper._propkey_to_colcCstdd|jDS)Ncss(|] \}}|tdd|DfVqdS)cSsg|] }|jqSr)rrr)r)r*rqsz6Mapper._pk_keys_by_table...NrDrrZpksr)r)r*rpsz+Mapper._pk_keys_by_table..rrrrsr)r)r*_pk_keys_by_tablenszMapper._pk_keys_by_tablecstfddjDS)Nc3s,|]$\}}|tfdd|DfVqdS)csg|]}j|jqSr)rKrrsr)r*rzsz;Mapper._pk_attr_keys_by_table...NrDrNrsr)r*rwsz0Mapper._pk_attr_keys_by_table..rOrsr)rsr*_pk_attr_keys_by_tableus zMapper._pk_attr_keys_by_tablecCstdd|jDS)Ncss(|] \}}|tdd|DfVqdS)cSsg|]}|jdk r|jqSr%)rHrrr)r)r*rs z9Mapper._server_default_cols...NrDrEr)r)r*rs z.Mapper._server_default_cols..rFrsr)r)r*_server_default_colss zMapper._server_default_colscCsXt}|jD]B\}}|D]4}|jdk s4|jdk r||jkr||j|jqq|Sr%)r'rrrHserver_onupdaterrr)roresultrrrr)r)r*&_server_default_plus_onupdate_propkeyssz-Mapper._server_default_plus_onupdate_propkeyscCstdd|jDS)Ncss(|] \}}|tdd|DfVqdS)cSsg|]}|jdk r|jqSr%)rSrrr)r)r*rs zBMapper._server_onupdate_default_cols...NrDrEr)r)r*rs z7Mapper._server_onupdate_default_cols..rFrsr)r)r*_server_onupdate_default_colss z$Mapper._server_onupdate_default_colscCsT|||d}|j|jk r<|j|||dd|d|d<|j|d|dS)N)entity_namespace parententityr;ormZcompile_state_pluginZplugin_subjectZ dml_table)rwrKr<_set_propagate_attrsr7)ro annotationsr)r)r*__clause_element__s   zMapper.__clause_element__cCs$t|||ddd|dS)NT)rWrXr;identity_tokenrYrZ)rnullr<r[rsr)r)r*select_identity_tokens 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. )rBrsr)r)r*r7s zMapper.selectablecCs~|dkrtjtj|dd}|jrB|s.|jd}|dkrN|jd}n |dkrNd}|||}|dk rj||fS||||fSdS)NrATrrFr)rrIr!rJrqr8r:)ror6r7r9r4r)r)r*_with_polymorphic_argss"   zMapper._with_polymorphic_argscCst||jSr%)r_iterate_polymorphic_propertiesr?rsr)r)r*_polymorphic_propertiess zMapper._polymorphic_propertiescs|j}|jfdd|DS)Ncs<g|]4}t|tjr|jrr.j|jdn|jdqSr)rCr rZ_renders_in_subqueriesrrradapterr)r*r s z2Mapper._all_column_expressions..)rc_polymorphic_adapter)ropoly_propertiesr)rfr*_all_column_expressions s  zMapper._all_column_expressionsr)cCs$|r||}n|j}dd|DS)NcSs(g|] }t|tjr|j|jdfqSrd)rCr rrrrer)r)r*r s z-Mapper._columns_plus_keys..)rbrc)roZpolymorphic_mappersrir)r)r*_columns_plus_keys szMapper._columns_plus_keyscCs |jrtj|j|jdSdSdS)N)Z equivalents)rqrZ ColumnAdapterr7_equivalent_columnsrsr)r)r*rh s zMapper._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|jqSr))rr2)rr.r)r)r*r2 sz:Mapper._iterate_polymorphic_properties..rFr)r?r2r Z unique_listrrr9r)ror4rr)r)r*rb# s&   z&Mapper._iterate_polymorphic_propertiescCs|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` )rr ImmutablePropertiesrrsr)r)r*attrs? s#z Mapper.attrscCstt|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 rmrr?Z_all_sqla_attributesrsr)r)r*all_orm_descriptorse sB zMapper.all_orm_descriptorscCstjj}||jS)aReturn a namespace of all :class:`.SynonymProperty` properties maintained by this :class:`_orm.Mapper`. .. seealso:: :attr:`_orm.Mapper.attrs` - namespace of all :class:`.MapperProperty` objects. )r rr_filter_propertiesZSynonymProperty)rorr)r)r*synonyms s zMapper.synonymscCs|jSr%rursr)r)r*rW szMapper.entity_namespacecCs |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. )rpr rrsr)r)r* column_attrs s zMapper.column_attrszsqlalchemy.orm.relationshipscCs|tjjjS)aLA namespace of all :class:`.RelationshipProperty` 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. )rpr rZorm_relationshipsZRelationshipPropertyrsr)r)r* relationships szMapper.relationshipscCs|tjjjS)aReturn a namespace of all :class:`.CompositeProperty` properties maintained by this :class:`_orm.Mapper`. .. seealso:: :attr:`_orm.Mapper.attrs` - namespace of all :class:`.MapperProperty` objects. )rpr rrZCompositePropertyrsr)r)r* composites s zMapper.compositescs,|ttfdd|jDS)Nc3s$|]\}}t|r||fVqdSr%)rCrrvtype_r)r*r s z,Mapper._filter_properties..)rr rmrrr)rorxr)rwr*rp 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_%drw)r bindparamr;)ridxrpr)r)r*r sz&Mapper._get_clause..rcSsg|]\}}||kqSr)r)rur)r)r*r s) enumeraterprand_r column_dict)roparamsr)r)r* _get_clause s  zMapper._get_clausecsDtfdd}|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} } cst|jtjkrp|jkr*|j|jnt|jf|j<|jkr\|j|jnt|jf|j<dSr%)operatorr eqleftrrightr r)binaryrTr)r* visit_binary. s   z0Mapper._equivalent_columns..visit_binaryNr)r r}rrrLr"Ztraverse)rorr.r)rr*rl s  zMapper._equivalent_columnscCs&t|ttjtjfrdS||jkSdSrA)rCrrZ ClassManagerrr _dataclass_fields)ro assigned_nameobjr)r)r*_is_userland_descriptorA szMapper._is_userland_descriptorcCsddt|jDS)NcSsg|] }|jqSr))r)rfr)r)r*rP sz,Mapper._dataclass_fields..)r Zdataclass_fieldsr5rsr)r)r*rN szMapper._dataclass_fieldscCs|r2|jj|ddk rX|||jj|rXdSn&|j|d}|dk rX|||rXdS|jdk r||jkr|dks~||jkr|d|dS|jdk r||jks|dk r||jkr|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) r5rr rr?rrdrmre)rorrrrattrr)r)r*rR sN    zMapper._should_excludecCs |j|jkS)zXReturn true if the given mapper shares a common inherited parent as this mapper.)rrootherr)r)r* 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 )rr5rr)r)r* is_sibling s    zMapper.is_siblingcCs4|}|jdk s|r$t||St||kSdSr%)primary_mapperr9r r5)rorZallow_subtypessr)r)r*_canload szMapper._canloadcCs |}|r||k r|j}qt|S)z>Return True if the this mapper inherits from the given mapper.)rHbool)rorrr)r)r*r5 s z Mapper.isaccs|}|r|V|j}qdSr%)rH)rorr)r)r*r 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. )rrrrr~r r})roZ descendantsrrr)r)r*r 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()``. )r1rrsr)r)r*polymorphic_iterator s zMapper.polymorphic_iteratorcCs|jjS)zSReturn the primary mapper corresponding to this mapper's class key (class).)r?r.rsr)r)r*r szMapper.primary_mappercCs |jjjSr%)r?r.rrsr)r)r*primary_base_mapper szMapper.primary_base_mappercs@|j}rfdd|D}|}|D]}||kr(dSq(dS)Ncsg|]}j|qSr)rrrfr)r*r sz3Mapper._result_has_identity_key..FT)rpkeys)rorTrgrZrkrr)rfr*_result_has_identity_key szMapper._result_has_identity_keycs:|j}rfdd|D}|jtfdd|D|fS)aReturn an identity-map key for use in storing/retrieving an item from the identity map. :param row: A :class:`.Row` instance. The columns which are mapped by this :class:`_orm.Mapper` should be locatable in the row, preferably via the :class:`_schema.Column` object directly (as is the case when a :func:`_expression.select` construct is executed), or via string names of the form ``_``. csg|]}j|qSr)rrrfr)r*r sz0Mapper.identity_key_from_row..c3s|]}|VqdSr%r))rr)rowr)r*r sz/Mapper.identity_key_from_row..)rprr)rorr^rgrr))rgrr*identity_key_from_row s zMapper.identity_key_from_rowcCs|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)rorpr^r)r)r*identity_key_from_primary_key sz$Mapper.identity_key_from_primary_keycCst|}||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_state PASSIVE_OFF)roinstancerr)r)r*identity_key_from_instance s z!Mapper.identity_key_from_instancecs4jj|jtfdd|jDjfS)Ncs"g|]}|jjqSr))rimplr rerrpassiverr)r*r sz3Mapper._identity_key_from_state..)rrrrrr^)rorrr)rr*r 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)rorrZ identity_keyr)r)r*primary_key_from_instance s z Mapper.primary_key_from_instancecs:dd|jDtdgr.fdd}ndd}|S)NcSsg|] }|jjqSr))r;Zsort_key_functionrr)r)r*r& sz1Mapper._persistent_sortkey_fn..cstddt|jdDS)Ncss&|]\}}|dk r||n|VqdSr%r))rZkey_fnvalr)r)r*r+ sz=Mapper._persistent_sortkey_fn..key..r)rziprrZkey_fnsr)r*r* sz*Mapper._persistent_sortkey_fn..keycSs |jdS)NrrMrr)r)r*r2 s)rpr' differencer,r)rr*_persistent_sortkey_fn$ s zMapper._persistent_sortkey_fncsfddjDS)Ncsg|]}j|qSr)r/rrsr)r*r9 sz.Mapper._identity_key_props..rrsr)rsr*r7 szMapper._identity_key_propscCs&t}|jD]}||j|q |Sr%)r'rrr)roZ collectionrr)r)r* _all_pk_cols; s zMapper._all_pk_colscCs$t|j}|jdk r ||j|Sr%)r'rpr9r)rocolsr)r)r*_should_undefer_in_wildcardB s   z"Mapper._should_undefer_in_wildcardcsfddjDS)Ncsh|]}j|jqSr)rKrrsr)r* K sz/Mapper._primary_key_propkeys..)rrsr)rsr*_primary_key_propkeysI szMapper._primary_key_propkeyscCs$|j|}|j|jjj|||dSNr)rrrrr rorrrrrr)r)r*_get_state_attr_by_columnM s z Mapper._get_state_attr_by_columncCs&|j|}|j|jj|||dSr%)rrrrZset_committed_valuerorrrrrr)r)r*#_set_committed_state_attr_by_columnS s z*Mapper._set_committed_state_attr_by_columncCs(|j|}|j|jj|||ddSr%)rrrrr'rr)r)r*_set_state_attr_by_columnW s z Mapper._set_state_attr_by_columncCs(t|}t|}|j|||tjdSr)rr instance_dict#_get_committed_state_attr_by_columnr)rorrrrr)r)r*_get_committed_attr_by_column[ s  z$Mapper._get_committed_attr_by_columncCs$|j|}|j|jjj|||dSr)rrrrZget_committed_valuerr)r)r*rb s  z*Mapper._get_committed_state_attr_by_columnc sjt|jj}ttfdd|DjjkrFdSfdd}g}zhd}t t  D]N}|jkrd}nt |jt jsWdS|rp|jsp|t|jid|iqpWntk rYdSXtj|}g} |D]} | | jqtj| |tS) 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)propsr)r*r| 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)Nrrw) rrrrrrZPASSIVE_NO_INITIALIZEorm_utilZ _none_set_OptGetColumnsNotAvailablerryr;)rZleftcolZrightcolZleftvalZrightval)rorrr)r*r s@     z5Mapper._optimized_get_statement..visit_binaryFTr)rr'rr.rrrrrrKreversedrrrCrZ TableClauserGrr"Zcloned_traverserLrrr|rrselectwhereZset_label_styler#) rorZattribute_namesZcol_attribute_namesrZallcondsstartr.Zcondrrr))rrorrr*_optimized_get_statementk sZ         zMapper._optimized_get_statementccsL||rH|}|D]0}|V||k r6||jkr6qH|}||krqHqdSr%)r5rr?)ror.prevrr)r)r*_iterate_to_target_viawpoly s  z"Mapper._iterate_to_target_viawpolycCs|s,|}||D]}|jdkr|Sqndt|}dd|D}||gD]@}|j}||D]*}|jdksx||krb|||SqbqNdS)Nr|cSsi|] }|j|qSr)r.)rer)r)r* sz0Mapper._should_selectin_load..)rr`r'rr.r )roZenabled_via_optZpolymorphic_fromr.rZenabled_via_opt_mappersrvr)r)r*_should_selectin_load s   zMapper._should_selectin_loadzsqlalchemy.ext.bakedzsqlalchemy.orm.strategy_optionsc s2tjj}tjj}jstjj}t|gj }| }| }j D]B}|j ksf||kr~| |jft|jqP| |jfddiqPddjDtdkrtjndjrjkst|jfddf} | n|jfd df} | fd d7} | ||fS) zmAssemble a BakedQuery that can load the columns local to this subclass as a SELECT with IN. Z do_nothingTcSsg|]}t|ddiqS)Z _orm_adaptT)rZ_deep_annotate)rpkr)r)r*r sz0Mapper._subclass_load_via_in..rrcs|jSr%)queryZselect_entity_fromr7session)rvr)r*r7 s z.Mapper._subclass_load_via_in..cs |Sr%)rrrsr)r*r7$ r8cs |tjdddjS)NZ primary_keysT)Z expanding)filterr=rryZorder_by)q)in_exprrpr)r*r7( s)r rZorm_strategy_optionsZ ext_bakedrHrrr9r'rLoadrnrZset_generic_strategyrrZ strategy_keyrprrtuple_Zis_aliased_classr.Z BakedQuery_compiled_cacheZspoil) rorvZstrategy_optionsZbakedZpolymorphic_propZ keep_propsZ disable_optZ enable_optrrr))rvrrpror*_subclass_load_via_in sL          zMapper._subclass_load_via_incCs ||Sr%)rrsr)r)r*_subclass_load_via_in_mapper. sz#Mapper._subclass_load_via_in_mapperccst}tt}}|j|s$ttt|jj|||jfg}|r|d\}} } } |sf| qD| |kr| } || j krqDt| || | ||} | 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. r N)r'objectr.r5rrrrrrrrcascade_iteratorr)rorxrZhalt_onZvisited_statesZprpZmppZ visitablesiteratorZ item_typeZ parent_stateZ parent_dictrqueuerZinstance_mapperZcorresponding_stateZcorresponding_dictr)r)r*r2 sZ   zMapper.cascade_iteratorcCs t|jSr%)r ZLRUCacher[rsr)r)r*r szMapper._compiled_cachecsi|jjD]}|jD]}||qq g}D],\}|j}|r6|fdd|jDq6fdd}tj||d}t }|D]}|||<q|S)Ncsg|] }|fqSr)r))rZ super_table)rr)r*r 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|kSdSrA) r rrrrLr'rZ _find_columnsr)Zfkrdepr)table_to_mapperr)r*skip s$   z#Mapper._sorted_tables..skip)Zskip_fnextra_dependencies) rrr setdefaultrrHrrZ sort_tablesr r)ror.rrZsuper_rZsorted_retr))rrr*_sorted_tables s*   zMapper._sorted_tablescCs,||jkr|j|S||j|<}|SdSr%)rZ)rorZ callable_rr)r)r*_memo s  z Mapper._memoc Csltt}|jD]V}t|j}|D]>}|jr&|t tj dd|jDr&|| ||jfq&q|S)zgmemoized map of tables to collections of columns to be synchronized upwards to the base mapper.cSsg|]\}}|jqSr)r)rrrr)r)r*r sz,Mapper._table_to_equated..) r defaultdictrrr'rrrYrreducerr)rorTrrrr)r)r*_table_to_equated s     zMapper._table_to_equated)NNNFNNNFNNNNNFNNTTNNNTFTFFr4)F)TT)T)NFF)r))N)N)NN)N)N)r=r< __qualname____doc__rrr Zdeprecated_paramsrrZ is_mapperZrepresents_outer_joinpropertyr.rtrvrKrwrHrrFrrpr5r?rGr3r9rbrarrrTr deprecatedrxZmemoized_propertyryrgr_rrrrhrrkrirjrr$Zmemoized_attributerrrpreload_modulerrrrrrrrnrrmr%r'r(r+r-r.r0r2r8r:r>r?r@rBZwith_polymorphic_mappersrGrJrLrPrQrRrUrVZmemoized_instancemethodr]r`r7rarcrjrkrhrbrnrorqrWrrrsrtrprrlrrrrrrr5rrrrrrrrrrZPASSIVE_RETURN_NO_VALUErrrrrrrrrrrrrrrrrrrrrrr)r)r)r*r1Vs   .                he7 ,     u R     "                    % E       )  +              \  A  M  2r1c@s eZdZdS)rN)r=r<rr)r)r)r*r srcCsttdddS)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. TrN)rr+r)r)r)r*configure_mappers sDrc Cs|D]}|jrqqdSthtr0W5QRdSdazD|D]}|jr:q\q:W,W5QRdStjtt||W5daXW5QRXtjtdS)NTF) rr&_already_compilingr1rfZ _for_classZbefore_configured_do_configure_registriesZafter_configured) registriesrr-r)r)r*r s"rzsqlalchemy.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)NFTrzOne 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 r orm_decl_apirlr'Z_recurse_with_dependenciesr,rfZbefore_mapper_configuredr5rrrrrrrrnZmapper_configured Exceptionsysexc_inforr _dependenciesr) rrrlorigr-Zhas_skipr.Z run_configurefnrrr)r)r*r> sJ        rc 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 rrrlr'Z_recurse_with_dependentsZ _dependentsrrrZ _managerspopitemrZ_dispose_manager_and_mapperZ_non_primary_mappersclearrdiscardr)rrrlrr-r_rr)r)r*_dispose_registriesq s&      rcCs d|_|S)a-Decorate a method as the 'reconstructor' hook. Designates a 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. 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:: :ref:`mapping_constructors` :meth:`.InstanceEvents.load` T)rrr)r)r* reconstructor srcs,|dd|ddfdd}|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. .. versionadded:: 0.9.0 .. seealso:: :ref:`simple_validators` - usage examples for :func:`.validates` include_removesFinclude_backrefsTcs|_d|_|S)N)rr)rrrrrnamesr)r*wrap s zvalidates..wrap)r)rkwrr)rr* validates s#  rcCs |jj}|jr||dSr%)rr.r\r)rctxinstrumenting_mapperr)r)r*r srcCs(|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)rr.rr)rr#kwargsrr)r)r*r s rc@s$eZdZdZdZddZddZdS)rz4Error reporting helper for mapper._columntoproperty.rcCs ||_dSr%rrr)r)r*rr sz_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...)r.rr orm_excZUnmappedColumnErrorrrr)rorrr)r)r* __missing__ sz_ColumnMapping.__missing__N)r=r<rr __slots__rrrr)r)r)r*r sr)Lr __future__r collectionsr itertoolsrrweakrefrrrrrr r r rrr r rrZ interfacesrrrrrrZ path_registryrrrrrrrrrrr r!rr"Zsql.selectabler#r$WeakKeyDictionaryr(rr+r/rsymbolr0 threadingRLockr&Z_self_inspectsZ class_loggerZMemoizedHasCacheKeyr1rrrrrrrrrrrrrr)r)r)r*s                                       G! 2 "1