id~dZddlmZddlmZddlmZddlZddlZddl Z ddl m Z ddl m Z dd l mZdd l mZdd l mZdd l mZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddl m Z ddl m Z!ddl m"Z"ddl m#Z#ddl m$Z$ddl m%Z%dd l mZddl%m&Z&ddl%m'Z'dd l%mZ(ddl%m)Z)e j*Z+d a,ej-Z.ej/d!Z0ej12Z3e"j4e#j5Gd"d#eZ6Gd$d%e7Z8d&Z9d'Z:d(Z;d)ZGd,d-e?Z@dS).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.`. )absolute_import)deque)chainN) attributes)exc)instrumentation)loading) properties)util)_class_to_mapper) _INSTRUMENTOR) _state_mapper) class_mapper) state_str)_MappedAttribute)EXT_SKIP)InspectionAttr)MapperProperty) PathRegistry)event) inspection)log)schema)sql) expression) operators)visitorsF NO_ATTRIBUTEceZdZdZdZdZejddd drd ZdZ dZ e d Z e d Z dZ dZ dZ dZ dZ dZ dZ dZ dZ dZ dZ dZ dZ dZ dZ dZ dZ dZ e ej d ddZ!ej"dZ#dZ$dZ%dZ&dZ'dZ(dZ)dZ*dZ+e,dZ-dZ.dZ/dZ0dsdZ1dZ2e3dZ4e3dZ5e3d Z6d!Z7dtd"Z8d#Z9d$Z:d%Z;d&Zd)Z?d*Z@d+ZAd,ZBd-ZCd.ZDdud/ZEd0ZFe d1ZGd2ZHd3ZIe3d4ZJe3d5ZKe3d6ZLeKZM e3d7ZNe3d8ZOe3d9ZPe3d:ZQe3d;ZRe3d<ZSe3d=ZTe3d>ZUe d?ZV dvd@ZWe3dAZXdwdBZYe3dCZZe3dDZ[e3dEZ\e3dFZ]e3dGZ^e3dHZ_dIZ`e3dJZae3dKZbdLZcdMZddNZedOZfdPZgdQZhe3dRZidSZjdTZke dUZldwdVZmdxdWZndwdXZodYZpeqjrfdZZsd[Zte3d\Zue3d]Zve3d^Zwe3d_Zxe3d`ZyeqjrfdaZzdbZ{dcZ|ddZ}eqjrfdeZ~dfZdgZdhZejdidjdkZe3dlZdwdmZe3dnZe3doZdpZej"dqZdS)yMapperaDefine 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)z0.7z:class:`.MapperExtension` is deprecated in favor of the :class:`.MapperEvents` listener interface. The :paramref:`.mapper.extension` parameter will be removed in a future release.)z1.1zThe :paramref:`.mapper.order_by` parameter is deprecated, and will be removed in a future release. Use :meth:`_query.Query.order_by` to determine the ordering of a result set.)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.) extensionorder_by non_primaryNTdcTtj|td|_d|_tj||_||_| durtj| |_n| |_| |_ t| tr| |_ d|_ n| |_ | durd|_n| d|_n| |_||_d|_||_||_||_||_|pi|_g|_||_||_||_t5j||_g|_tj|_||_ ||_!||_"d|_#d|_$d|_%i|_&||_'d|_(tj| pg|_)||_*|jr|jsd|_+n||_+t|jt4j,rt[j.d|/|||_0||_1|i|_2n||_2|tj3||_4nd|_4|rtj3||_5nd|_5d|_6tn8 |j9j:;|||<|=|>|?|@|A|Bdt_D|Ed|FtnGdS#tnGwxYw)aNReturn a new :class:`_orm.Mapper` object. This function is typically used behind the scenes via the Declarative extension. When using Declarative, many of the usual :func:`.mapper` arguments are handled by the Declarative extension itself, including ``class_``, ``local_table``, ``properties``, and ``inherits``. Other options are passed to :func:`.mapper` using the ``__mapper_args__`` class variable:: class MyClass(Base): __tablename__ = 'my_table' id = Column(Integer, primary_key=True) type = Column(String(50)) alt = Column("some_alt", Integer) __mapper_args__ = { 'polymorphic_on' : type } Explicit use of :func:`.mapper` is often referred to as *classical mapping*. The above declarative example is equivalent in classical form to:: my_table = Table("my_table", metadata, Column('id', Integer, primary_key=True), Column('type', String(50)), Column("some_alt", Integer) ) class MyClass(object): pass mapper(MyClass, my_table, polymorphic_on=my_table.c.type, properties={ 'alt':my_table.c.some_alt }) .. seealso:: :ref:`classical_mapping` - discussion of direct usage of :func:`.mapper` :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 extension: A :class:`.MapperExtension` instance or list of :class:`.MapperExtension` instances which will be applied to all operations by this :class:`_orm.Mapper`. :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. :paramref:`_orm.Mapper.non_primary` is not an often used option, but is useful in some specific :func:`_orm.relationship` cases. .. seealso:: :ref:`relationship_non_primary_mapper` :param order_by: A single :class:`_schema.Column` or list of :class:`_schema.Column` objects for which selection operations should use as the default ordering for entities. By default mappers have no pre-defined ordering. :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_NFc|pddzS)Nrr)xs J/opt/cloudlinux/venv/lib/python3.11/site-packages/sqlalchemy/orm/mapper.pyz!Mapper.__init__..s16Q,When mapping against a select() construct, map against an alias() of the construct instead.This because several databases don't allow a SELECT from a subquery that does not have an alias.T constructed)Hr assert_arg_typetyper) class_managerto_list_primary_key_argumentr&r%always_refresh isinstancerversion_id_propversion_id_colversion_id_generatorconcretesingleinherits local_tableinherit_conditioninherit_foreign_keys_init_properties_delete_orphansbatcheager_defaults column_prefixr_clause_element_as_exprpolymorphic_on_dependency_processors immutabledict validatorspassive_updatespassive_deleteslegacy_is_orphan_clause_adapter_requires_row_aliasing_inherits_equated_pairs_memoized_values_compiled_cache_size_reconstructor_deprecated_extensionsallow_partial_pksconfirm_deleted_rows SelectBasesa_excInvalidRequestError_set_with_polymorphicpolymorphic_loadpolymorphic_identitypolymorphic_mapto_setinclude_propertiesexclude_properties configured_CONFIGURE_MUTEXacquiredispatch_events_new_mapper_instance_configure_inheritance"_configure_legacy_instrument_class _configure_class_instrumentation_configure_listeners_configure_properties_configure_polymorphic_setter_configure_pksr" _new_mappers_log_expire_memoizationsrelease)selfr)r?r primary_keyr&r>r@rAr$r%r7r:r;rH_polymorphic_mapr]r<with_polymorphicr\rVrDrFr`rarLrMrWrErNrSs r-__init__zMapper.__init__ks|*64BB !%)\+%>%>"& 5  L22DMM$DM, nn 5 5 1#1D "&D  "0D  5 ( ((-D % % ! )(>(>D % %( > ,F  ""#3444 0 %9!  ##%D #3D  )&*k2D&E&ED # #&*D #  +&*k2D&E&ED # #&*D #   """ ' M ! 6 6vt D D D  ' ' ) ) )  3 3 5 5 5  1 1 3 3 3  % % ' ' '  & & ( ( (  . . 0 0 0    ! ! !"&F  IIm $ $ $  % % ' ' '  $ $ & & & & &  $ $ & & & &s C!N N'c|S)zr8r3r issubclassr)rY ArgumentError__name__r&r?rr=r<iterate_to_rootrHrPr@sql_utiljoin_conditionrjoinr_rAcriterion_as_pairsonclauserQr]_identity_classr:r;warn descriptionr%r^rDappend base_mapperrLrM _all_tablesr\_add_with_polymorphic_subclassset)rsnprzfkss r-rhzMapper._configure_inheritances $(#4#6#6 =~ /$-.. M ,T]e L L L dk4=+?@@ **{+++T]-A-J-J-JL4=#<<<))7iH=**rr4;///5 '#'=#< *.-*J'" !)BBB=.2.>D+"&"6"6"8"8AA!0<<@F9A-5 2:1H M5t7G22./2h 8(.//D+ +d&?@@C3;3N/814444D00 +/*:'(4T]4'+}'D$$'+{$"*&*m&B#,0M,N)) ,8't}/KKK +777 4@@@    && 'M*%77 $ 6 #'=#@D ,DJ M - 4 4T : : :#}8D #'=#@D  -E1E   $}8D (4,0DDDII !555 01JKKK DD 555   CG$T%>?$  *6$00 <?#';D  " *&K  + *r/cp|dkrd|_nzt|ttfrAt|dtjttfzr||_n'|df|_n|t jdd|_t|jtj rt j d|jrVt|jdtj r1|jd|jd f|_|j r|dSdS)N*)rNrz$Invalid setting for with_polymorphicr0r)rvr8tuplelistr string_typesrYrr?rrXrZaliasrbrq)rsrvs r-r[zMapper._set_with_polymorphic~sR s " "$/D ! ! (5$- 8 8 ) #T%6%%F A)9%%)94(@%%  )&'MNN N$(D ! d& (= > > ,F    Z  !! $j&;& &  %a(%a(..00%D ! ? (  % % ' ' ' ' ' ( (r/c|j}|j||fdS|jddkr3||jd|fz|jdfdSdS)Nrrr)r)rvr[)rsrzsubcls r-rz%Mapper._add_with_polymorphic_subclasss   (  & &x 0 0 0 0 0  "1 % , ,  & &&q)UH4d6KA6NO     - ,r/c|jsJ|jrJt|tsJ||_|jj|j|jj|_|D]}|jd|_|jj |_ |j D]}|jj |_ |jj ||jj|_|jj|_|jD]>\}}||jvr0|||dds|||d?dS)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)r<r>r8r"r^updaterrHrPrDself_and_descendantsrrrrLr_propsitems_should_exclude_adapt_inherited_property)rsrzmpkeyprops r-_set_concrete_basezMapper._set_concrete_basesm }=   &&)))))  %,,T-ABBB#}<**,, 5 5F$004-]( + 7 7B!]6BNN )00666#}<=4,,.. A AIC$+%%d.B.BSd/C//%..sD%@@@  A Ar/c>||_|ddS)NT)rHrm)rsrHs r-_set_polymorphic_onzMapper._set_polymorphic_ons$, **400000r/c0|jr\|j|jjtt d|jD}nt}|jD]}||vr|||dS)Ncg|] }|j Sr+rU.0ms r- z=Mapper._configure_legacy_instrument_class..+0r/)r>re_updaterrrrU_adapt_instrument_classrssuper_extensionsexts r-riz)Mapper._configure_legacy_instrument_classs = % M ! !$-"8 9 9 9"!%!>!>!@!@     #uu . 7 7C***++D#666 7 7r/c|jr8ttd|jD}nt}|jD]}||vr|||dS)Ncg|] }|j Sr+rrs r-rz/Mapper._configure_listeners..rr/)r>rrrrU_adapt_listenerrs r-rkzMapper._configure_listenerss = %"!%!>!>!@!@     #uu . / /C***##D#... / /r/c .tj|j}|jrI|r|jst jd|jz||_|jj |_ dt|<dS|3|j|jusJ|jrt j d|jzdt|<|j ||j|tj|j}||_||_t!jt$j||_|jt.drdSt1j|dt4dt1j|dt6dt!j|jD]\}}|d kr8t;|d r(|j}t?|t@j!r|j"}t?|t@j#rt;|d r%||_$t1j|d tJdt;|d rX|j&}|j'D]I}||j(vrt jd|d|d|j()|||fi|_(J||jt.<dS)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.TNzClass '%s' already has a primary mapper defined. Use non_primary=True to create a non primary Mapper. clear_mappers() will remove *all* current mappers from all classes.F first_init)rawinitrw_sa_original_init__sa_reconstructor__load__sa_validators__z+A validation function for mapped attribute z on mapper z already exists.)*rmanager_of_classr)r& is_mappedrYrZr4rzr_mapper_registryrreinstrument_classr register_classr partialr load_scalar_attributesdeferred_scalar_loaderinfogetrrlisten_event_on_first_init_event_on_inititerate_attributeshasattrrr8types MethodTypeim_func FunctionTyperT_event_on_load__sa_validation_opts__rrKunion)rsmanagerrmethodvalidation_optsnames r-rjz'Mapper._configure_class_instrumentations-dk::    '"3 0 $ , ")D #*>#AD %) T " F  >T[0000  *Ek ""& &&tT[999 ?%4T[AAG$)-  *D* * & <  M5 1 1  F Wl,@dKKKK Wfn$????24;??  KCj  WV5H%I%I 1fe&677,#^F&%"455 6#9::*0D'L&.dKKKKKV%899 &,&CO & 8  4?22"("<"<$(44!/## +//*?*?!FO#<=++'+ ]###r/c"tdS)z8Class-level path to the :func:`.configure_mappers` call.N)configure_mappers)clss r-_configure_allzMapper._configure_allEs r/cd|_d|_t|dr|`|js<|j7|jjr-|jj|ur!tj |j dSdSdSdSdS)NT_configure_failed) rb_dispose_calledrrr&r4rrzr unregister_classr)rys r-disposezMapper.disposeJs# 4, - - '&  :".",/")T11  ,T[ 9 9 9 9 9  : :....11r/ctjj_i_i_t jtdj D}t jd|D}tjjgz}j ||D]}|j rN||j r4t j|j |j|<t j|j|j|<jr^jD]U}|jjvr t jj|j<j|j|Vnjjvs#t-jjdkr%t/jddjjdjjvr@t7jt8jr!t jdjjzjr j sjsjj _ njr(tj!fdjDd }n&tj!jjd }t-|dkr%t/jddjjdtE|_ #d |tfd j D_$dS) Ncg|] }|j Sr+ proxy_setrcols r-rz)Mapper._configure_pks..asDDDcCMDDDr/c3(K|] }|j |VdSr~rt)rcs r- z(Mapper._configure_pks..ds)!G!G!G!!G!G!G!G!G!Gr/rzMapper z> could not assemble any primary key columns for mapped table 'rzlCould not assemble any primary keys for locally mapped table '%s' - no rows will be persisted in this Table.cDg|]}j|Sr+)rcorresponding_column)rrrss r-rz)Mapper._configure_pks..s:/DDQGGr/T)ignore_nonexistent_tablesz"Identified primary key columns: %sc3K|]C}j|jvr-t|dr|jjv4j|VDdS)tableN)_columntoproperty_identity_key_propsrr_cols_by_tablerrrss r-rz(Mapper._configure_pks..st# # %c*$2JJJC))K9D$777  "3 ' 8777 # # r/)%r find_tablesrtables _pks_by_tablerr column_setrrrrrrt issupersetordered_column_set intersectionrr6r OrderedSetaddlenrYrrr?r8rTablerr>r<reduce_columnsrrp_readonly_props)rsall_colspk_colsrtkrts` r-rnzMapper._configure_pksZs*4+BCC  ? DDT-CDDD E  /!G!GX!G!G!GGGT[D$;#<<== '''  A} (!3!3AM!B!B ()-(?M)),w''"1%&*%??1DD&&440<<<>   T%7 7 7J  fl= = 7 I;"./    M! IM! I.! I $}8D  ) &5!%!;/3  '5&t'>?.2 ;1$$**ttT4@@@B %[11D  II:K H H H ## # # # -# # #   r/c@tjx|_|_tj|_t ||_|jr6|j D]\}}| ||d|j r]|j j D]>\}}||jvr0| ||dds| ||d?|jjD]}||jvr |jpd|jz}| |j||jj||rY|D]}||jvr|j|j}| ||dddS)NFrTr setparent)r OrderedPropertiescolumnsr OrderedDictr_ColumnMappingrrBr_configure_propertyr>rrrrFrr?contains_columnr)rsrrr column_keyrzs r-rlzMapper._configure_propertiess $ 6 8 88 tv&(( "0!5!5   ;!288:: ; ; T((dE:::: = E!]17799 E E Tdk))$2F2FE$3G33)223eDDD-5  F///,2fj@J## &(88@@ $  ..00 F FV555!'!9&!A!EJ  $ $F$ %    )  r/cR d}|jqd}t|jtjr` |j|j|_nG#t $r:}tjtjd|jz|Yd}~nd}~wwxYw|j|j vr|j |j}nt|jtr._set_polymorphic_identitysL //33M(= r/c|vr;||jvr.tjdt||fdSdSdS)NznFlushing object %s with incompatible polymorphic identity %r; the object may not refresh and/or load correctly)"_acceptable_polymorphic_identitiesr warn_limitedr)rzr*r+r,s r-_validate_polymorphic_identityzLMapper._configure_polymorphic_setter.._validate_polymorphic_identitysz#u,,o.!DEE%G#5))5+AB  -,EEr/)rHr8r rrKeyErrorraise_rYrrrr ColumnPropertyr _is_columnrrrColumnrvrZrgetattrrrlabelrrrr-r1) rsrsettererrrr instrumentrrzr-r1r,s @r-rmz$Mapper._configure_polymorphic_setters   *F$-t/@AA  *.+d6I*JD''K,3595HI ), "d&<<<-d.ABD/@@L O"')B!.; **4+>??@ O*7-BB';#F!&J-C!#v}55 -503HHMM %8?"o."&Jc5$//"++CGSWeSII$868;@ 14 :N0O0OOD'#'C!0*MMM((d(NNN#',q/D "hOO ..00   (4.&2KKK.4.C++!3..v/DEE+ *6"<6#A;;:>6FF'5*  2          .GD *.  / / /.2D * * *sA B 0BB c8|j|j|jSdSr~)r:rrys r-_version_id_propzMapper._version_id_props!   *)$*=> >4r/ct}t|g}|rX|}|j|jur4||j||j|X|Sr~)rrpopleftrrr]extendr)rs identitiesstackitems r-r/z)Mapper._acceptable_polymorphic_identitiesszUU tf  7==??D&$*AAAt8999 T5666  7 r/cNt|jSr~) frozensetrvaluesrys r- _prop_setzMapper._prop_sets++--...r/cJ|js|||dddS||jvrs|j||}||us(t |t jr<|j|j ur0||tj |ddSdSdSdS)NFrT) r<rrr4_get_class_attr_mror8rInstrumentedAttribute _parententityparentr ConcreteInheritedProperty)rsrrrimplementing_attributes r-rz Mapper._adapt_inherited_propertys}   $ $S$Ue $ L L L L L  # #&*%7%K%KT&& "&--*J,L.+8DKGG((8::" )!$ #.-HGr/c |d||jjt|ts|||}t|t jr|j |j d}||j r|g}|j D]}|j |j d}|E|D]}|j|j |j d}n|||V|j d}t!|dr8t!|dr|j|jvr|j|nWt!|drG|j|jvr9||j|jvr%|j|j|t!|ds"||jup|j d|ju|_||j |<|j |jzD]}|jD] }||j|< ||_|r|||||jvrNt;|j|ddr2|j|j} t?j d | d |d |d | ||jvrt|t jst|j|t jt j!fsQtEj#d |j|d|d|d|j|} |j$%| d||j|<|j&s|'||j(D]} | )||||r)|*|+||j,r|-dSdS)Nz_configure_property(%s, %s)rrrr_is_polymorphic_discriminator_mapped_by_synonymFz'Can't call map_column=True for synonym =z4, a ColumnProperty already exists keyed to the name z for column z Property z on z" being replaced with new property z$; the old property will be discarded).rp __class__rr8r_property_from_columnr r4rrrr>rr?_reset_exportedrrrrrrrHrP _orig_columnsrrr set_parentrr7rQrYrrMr rrpopr&rrrrpost_instrument_classrbrq) rsrrrrrpathrm2synoldproprzs r-rzMapper._configure_propertysd /dn6MNNN$// 9--c488D dJ5 6 66 7)>>t|AOOC {t}{v6688 # #A-<|A$*==2 !$DL |d&88 7 7=77C26D*3//7  ( OOD$ ' ' ' $+  ' K 2E# # +c"5C&&'*cc333SS:  4;  tZ%>??  C -8  II;s###TTT4441    k#&G   # #GT 2 2 2 C (  ! !$ ' ' '. > >F  , ,S$ = = = =  - IIKKK  & &t , , , ? (  % % ' ' ' ' ' ( (r/c tj|}|d}tj|st j|d|d|j|d}t|tj r|j r|j d|f|j vr|j d |sh|j d|jurT||jurK|j|u}d|j dd|d|d }|rtj|nt j||}|j d||d |z|S|t|tjrg}|D]}|j|} | o|j|} | |j|j|} | t jd |d |d |d|| tj |St jd|d |d |jd|d )z[generate/update a :class:`.ColumnProprerty` given a :class:`_schema.Column` object.rrRz/ is not an instance of MapperProperty or ColumnNzImplicitly combining column z with column z under attribute 'zT'. Please configure one or more attributes for these same-named columns explicitly.zAinserting column to existing list in properties.ColumnProperty %szWhen configuring property 'z' on z , column 'z' 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.z$WARNING: when configuring property 'z' conflicts with property 'aG'. 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 r5rr5rYrrrr8r r4rQrshares_lineager:rLrrZcopyinsertrprMrrr?rUrr) rsrrrr warn_onlymsg mapped_columnrmcs r-rTzMapper._property_from_columnHs ,t$$$V,, &33  {sD)) dJ5 6 6D 4 : Q0788 Q66v>>8LO4+>>>$"555 Kt3 &*\"%5%5%5vvvsssD :IcNNNN 4S99999;;D L  6 * * * II258:   K \Z *6  \M ) ),AA!DD:)>>qAAB~ /??AAA0EEaHHBz$22 -0CCqqq :$$R((((,m< <&&*-dddFJJJF   r/cj|dd|jD}|D][\}}|d||j|ur|js||jr||\|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() startedcg|] \}}||f Sr+r+)rrrs r-rz5Mapper._post_configure_properties..s > > >YS$c4[ > > >r/zinitialize prop %sz%_post_configure_properties() completeTN) rprrrL_configure_startedr_configure_finishedrYrb)rslrrs r-_post_configure_propertiesz!Mapper._post_configure_propertiess 8999 > >$+*;*;*=*= > > > 1 1IC II*C 0 0 0{d""4+B" ' 1**4000 9:::r/cf|D]\}}|||dS)z^Add the given dictionary of properties to this mapper, using `add_property`. N)r add_property)rsdict_of_propertiesrvalues r-add_propertieszMapper.add_propertiessF -2244 * *JC   c5 ) ) ) ) * *r/cT||j|<||||jdS)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)rBrrb)rsrrs r-rnzMapper.add_propertys4&*c"   d AAAAAr/ch|D]}t|dSr~)r_memoized_configured_propertyexpire_instancersrzs r-rqzMapper._expire_memoizationssB**,, B BF ) 9 9& A A A A B Br/cd|jjzdz|jdur |jjpt |jz|jrdpdzdzS)N(|z |non-primaryr))r)rr?rstrr&rys r- _log_desczMapper._log_descsu k" #  ,1$0)t'((  2N8b :  r/cD|jjd|zg|jf|zRdSNz%s )loggerrr|rsrdargss r-rpz Mapper._logs3 B(9D(@BBBBBBr/cD|jjd|zg|jf|zRdSr~)rdebugr|rs r- _log_debugzMapper._log_debugs3 %#+C$.):T)ACCCCCCr/c>dt||jjfzS)Nz)idr)rrys r-__repr__zMapper.__repr__s%D4;3G(HHHr/cvd|jj|jrdpdd|j |jjn |jjS)Nz mapped class z (non-primary)rz->)r)rr&r?rrrys r-__str__zMapper.__str__sU K   1!1 7R 7 7+   ( ((4 5  r/cd}|D]Z}|jD]P\}}d}tj||||j}|jr|rdS|js|sdSQ[|jr|SdS)NFT) optimistic)rrCrr has_parent has_identityrN)rsr*orphan_possiblerzrrrs r- _is_orphanzMapper._is_orphans**,, F$4 c"&'8==HH35+=I ( Z  555. z 444    " "5r/c||jvSr~)r)rsrs r- has_propertyzMapper.has_propertysdk!!r/c |rtjrt |j|S#t$r:}t jtjd|d|d|Yd}~dSd}~wwxYw)z6return a MapperProperty associated with the given key.zMapper 'z' has no property 'rr#N) r"rorrr2r r3rYrZ)rsr_configure_mappersr:s r- get_propertyzMapper.get_propertys  &"5     ;s# #    K**:>$$D!$            s + A//A**A/c|j|S)zkGiven a :class:`_schema.Column` object, return the :class:`.MapperProperty` which maps this column.r)rsrs r-get_property_by_columnzMapper.get_property_by_columns%f--r/ctjrtt|jS)z1return an iterator of all MapperProperty objects.)r"roriterrrFrys r-iterate_propertieszMapper.iterate_propertiess7      DK&&(()))r/c|dkrt|jn|rttj|D]~}t |}||stj|d||( | i |fd|jDng|1ttj |dfdDS)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 does not inherit from Ncg|]}|v| Sr+r+)rrmapperss r-rz-Mapper._mappers_from_spec..9sLLLQqG||q|||r/T)include_aliasesc&g|] }|jv |Sr+)r?)rrrs r-rz-Mapper._mappers_from_spec..As%EEEQQ]f-D-Dq-D-D-Dr/)rrrr r5r isarYrZrrrrr)rsspec selectablerrrs @@r-_mappers_from_speczMapper._mappers_from_spec"s3 3;;4455GG  eeG\$'' # #$Q''uuT{{ 49:DDA%NN1#4#4#6#67777KKNNNNLLLL$";LLLGGG  !$ZFFFFFEEE'EEEGr/c|j}|D]l}||ur|jrtjd|jsC|r!||j|j}L||j|j}m|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.) rr<rYrZr=rr?r@ outerjoin)rsr innerjoinfrom_objrs r-_selectable_from_mapperszMapper._selectable_from_mappersDs *  ADyyz 0AX '}} q':  HH (11 q':  Hr/c|jrL|jrE|j>|jd|id|jDSdS)N parentmapperc3$K|] }|jV dSr~)r]rs r-rz1Mapper._single_table_criterion..bs>MM+,&MMMMMMr/)r=r>rH _annotatein_rrys r-_single_table_criterionzMapper._single_table_criterion_sv ; 4= T-@-L&00.$1GHHLLMM040IMMM 4r/cftjrt|jsgS|j|jSr~)r"rorrvrrys r-_with_polymorphic_mappersz Mapper._with_polymorphic_mappershs<      $ I&t&(=>>r/c|js|jS|j\}}||S||||dSNF)rvrrr)rsrrs r-_with_polymorphic_selectablez#Mapper._with_polymorphic_selectableps\$ +* *0j  ! 00''j995 r/cbtd|jDS)Nc3RK|]"\}}|td|DfV#dS)c32K|]}|jj|VdSr~)r3should_evaluate_noners r-rz@Mapper._insert_cols_evaluating_none...s@ch.Kr/NrErrrs r-rz6Mapper._insert_cols_evaluating_none..sj  w #*       r/r(rrrys r-_insert_cols_evaluating_nonez#Mapper._insert_cols_evaluating_nonesA  #'"5";";"="=      r/cbtd|jDS)Nc3RK|]"\}}|td|DfV#dS)c3fK|],}|j |j|j|jj#|jV-dSr~)rtserver_defaultdefaultr3rrrs r-rz8Mapper._insert_cols_as_none...sh? .   K   H9 Gr/Nrrs r-rz.Mapper._insert_cols_as_none..sj   w&        r/rrys r-_insert_cols_as_nonezMapper._insert_cols_as_nonesA   #'"5";";"="=      r/chtfdjDS)Nc3XK|]$\}}|tfd|DfV%dS)c3@K|]}j|j|fVdSr~rrrs r-rz3Mapper._propkey_to_col...sD?BT+C04c:r/N)r()rrrrss r-rz)Mapper._propkey_to_col..su  w FM       r/rrys`r-_propkey_to_colzMapper._propkey_to_colsL    #'"5";";"="=      r/cbtd|jDS)Nc3RK|]"\}}|td|DfV#dS)cg|] }|j Sr+rrs r-rz6Mapper._pk_keys_by_table...s6663sw666r/Nr)rrpkss r-rz+Mapper._pk_keys_by_table..sV  sI66#66677 8      r/r(rrrys r-_pk_keys_by_tablezMapper._pk_keys_by_tables?  "06688      r/chtfdjDS)Nc3XK|]$\}}|tfd|DfV%dS)c4g|]}j|jSr+rrs r-rz;Mapper._pk_attr_keys_by_table...s$JJJs41#6:JJJr/Nr)rrrrss r-rz0Mapper._pk_attr_keys_by_table..sb  sJJJJcJJJKK       r/rrys`r-_pk_attr_keys_by_tablezMapper._pk_attr_keys_by_tablesL    #06688       r/cbtd|jDS)Nc3RK|]"\}}|td|DfV#dS)c*g|]}|j |jSr~)rrrs r-rz9Mapper._server_default_cols...s--9999r/Nrrs r-rz.Mapper._server_default_cols..j   w#*        r/rrys r-_server_default_colszMapper._server_default_colsA   #'"5";";"="=      r/ct}|jD]F\}}|D]>}|j|j.||jvr%||j|j?G|Sr~)rrrrserver_onupdaterrr)rsresultrrrs r-&_server_default_plus_onupdate_propkeysz-Mapper._server_default_plus_onupdate_propkeyss"17799 @ @NE7 @ @&2*6T333JJt5c:>???  @ r/cbtd|jDS)Nc3RK|]"\}}|td|DfV#dS)c*g|]}|j |jSr~)rrrs r-rzBMapper._server_onupdate_default_cols...s-.::::r/Nrrs r-rz7Mapper._server_onupdate_default_cols..rr/rrys r-_server_onupdate_default_colsz$Mapper._server_onupdate_default_colsrr/c|jS)a;The :func:`_expression.select` 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. )rrys r-rzMapper.selectables 00r/c|jr!|s |jd}|dur |jd}n|durd}|||}|||fS||||fS)NrFr)rvrr)rsrrrrs r-_with_polymorphic_argszMapper._with_polymorphic_argss    0,Q/U""!215 5 J))$ ;;  !J& &D99'9MMM Mr/cPt||jSr~)r_iterate_polymorphic_propertiesrrys r-_polymorphic_propertieszMapper._polymorphic_properties s-  0 0.     r/c#K||j}|s|jD]}|VdStjt d|g|zDD]3}t |ddr|j|jd|jur/|V4dS)zUReturn an iterator of MapperProperty objects which will render into a SELECT.Nc6g|]}t|jSr+)rr)rrzs r-rz:Mapper._iterate_polymorphic_properties.. s3"V677r/rPFr)rrr unique_listrr7rHr)rsrrs r-rz&Mapper._iterate_polymorphic_properties s ?4G ,     %'+fw&6  1=uEE'/y|4+>>>  r/chtjrttj|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` )r"rorr ImmutablePropertiesrrys r-attrsz Mapper.attrs, s/D      ' 444r/crtjt|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 rr(r4_all_sqla_attributesrys r-all_orm_descriptorszMapper.all_orm_descriptorsR s4D' #88:: ; ;   r/c@|tjS)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. )_filter_propertiesr SynonymPropertyrys r-synonymszMapper.synonyms s&&z'ABBBr/c@|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. )rr r4rys r- column_attrszMapper.column_attrs s&&z'@AAAr/c@|tjS)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. )rr RelationshipPropertyrys r- relationshipszMapper.relationships s0&&z'FGGGr/c@|tjS)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. )rr CompositePropertyrys r- compositeszMapper.composites s&&z'CDDDr/ctjrttjtjfd|jDS)Nc3FK|]\}}t|||fVdSr~)r8)rrvtype_s r-rz,Mapper._filter_properties.. sN1a*Q:N:NAr/)r"rorr rrrr)rsrs `r-rzMapper._filter_properties ss      '  #';#4#4#6#6     r/c|d|jD}tjd|Dtj|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. cHg|]}|tjd|jf S)Nr)r bindparamr3)rrts r-rz&Mapper._get_clause.. s?   #-K4DEEE F   r/c g|] \}}||k Sr+r+)rrrs r-rz&Mapper._get_clause.. s 333&1aqAv333r/)rtrand_r column_dict)rsparamss r- _get_clausezMapper._get_clause sV  #/    H33F333 4  V $ $  r/ctjfd}|jjD]&}|jt j|jid|i'S)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} } c||jtjkr|jvr&|j|jn"t j|jf|j<|jvr'|j|jdSt j|jf|j<dSdSr~)operatorreqleftrrightr r )binaryrs r- visit_binaryz0Mapper._equivalent_columns..visit_binary s),..;&((6;'++FL9999*./6+J+JF6<(((/.r/Nr)r rrrr@rtraverse)rsrrzrs @r-_equivalent_columnszMapper._equivalent_columns s}*!## K K K K K&;  F'3!,b8\2J r/cbt|ttjtjfrdSdS)NFT)r8rr ClassManagerr ColumnElement)rsobjs r-_is_userland_descriptorzMapper._is_userland_descriptor s7   ,(   54r/c|rI|jj|d '||jj|rdSn4|j|d}|||rdS|j.||jvr%| ||jvr|d|zdS|j.||jvs |#||jvr|d|zdSdS)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) r)__dict__rrr4rIr`rpra)rsr assigned_namerrattrs r-rzMapper._should_exclude, s(  {#''t":: $]3 t%99-NNDD$@$@$F$Ft  # /D33361H#H#H II1T: ; ; ;4  " . D+ + +"v1H'H'H II-6 7 7 74ur/c|j|juS)zXReturn true if the given mapper shares a common inherited parent as this mapper.)r)rsothers r- common_parentzMapper.common_parentT s5#444r/c|}|j|r"t||St||uSr~)primary_mapperrHrr)rsr*allow_subtypesss r-_canloadzMapper._canloadZ sP    ! !   *n * ''++A.. . ''1, ,r/cJ|}|r||ur |j}|r||u t|S)z>Return True if the this mapper inherits from the given mapper.)r>bool)rsrrs r-rz Mapper.isaa s=  AUNN A AUNNAwwr/c#0K|}|r|V|j}| dSdSr~)r>)rsrs r-rzMapper.iterate_to_rooti sA  GGG A     r/cg}t|g}|rE|}||||j|Et j|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. )rr?rr@rr r)rs descendantsrBrCs r-rzMapper.self_and_descendantso sq tf  3==??D   t $ $ $ LL1 2 2 2 3 ---r/c*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()``. )rrrys r-polymorphic_iteratorzMapper.polymorphic_iterator sD-...r/c|jjS)zSReturn the primary mapper corresponding to this mapper's class key (class).)r4rzrys r-rzMapper.primary_mapper s!((r/c$|jjjSr~)r4rzrrys r-primary_base_mapperzMapper.primary_base_mapper s!(44r/cp|j}rfd|D}|D]}||sdSdS)Nc*g|]}j|Sr+rrradapters r-rz3Mapper._result_has_identity_key.. ;;;awq);;;r/FT)rt_has_key)rsrr1rrs ` r-_result_has_identity_keyzMapper._result_has_identity_key sb"  <;;;;7;;;G  C??3'' uu 4r/cz|j}rfd|D}|jtfd|D|fS)aReturn an identity-map key for use in storing/retrieving an item from the identity map. :param row: A :class:`.RowProxy` 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 ``_``. c*g|]}j|Sr+r/r0s r-rz0Mapper.identity_key_from_row.. r2r/c3(K|] }|V dSr~r+)rrrows r-rz/Mapper.identity_key_from_row.. s'44&#f+444444r/)rtrr)rsr8identity_tokenr1rs ` ` r-identity_key_from_rowzMapper.identity_key_from_row sd"  <;;;;7;;;G  4444G444 4 4   r/c0|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)rsrtr9s r-identity_key_from_primary_keyz$Mapper.identity_key_from_primary_key s#U;%7%7GGr/cjtj|}||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)rsinstancer*s r-identity_key_from_instancez!Mapper.identity_key_from_instance s-)(33,,UJ4JKKKr/cjj|jtfd|jDjfS)Nc^g|])}|jj*Sr+)rimplr)rrr+rpassiver*s r-rz3Mapper._identity_key_from_state.. sEDH%*..ueWEEr/)r(rrrrr9)rsr*rGr+rs ``@@r-r@zMapper._identity_key_from_state ss -   $ 8      r/cztj|}||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>)rsrBr* identity_keys r-primary_key_from_instancez Mapper.primary_key_from_instance s=)(3344 :)  Ar/cd|jDtdgrfd}nd}|S)Nc&g|]}|jjSr+)r3sort_key_functionrs r-rz1Mapper._persistent_sortkey_fn.. sJJJ#38-JJJr/chtdt|jdDS)Nc3:K|]\}}| ||n|VdSr~r+)rkey_fnvals r-rz=Mapper._persistent_sortkey_fn..key.. sK#$*#5FF3KKK3r/r)rzipr)r*key_fnss r-rz*Mapper._persistent_sortkey_fn..key sA'*7EIaL'A'Ar/c|jdS)Nrr)r*s r-rz*Mapper._persistent_sortkey_fn..key sy|#r/)rtr difference)rsrrSs @r-_persistent_sortkey_fnzMapper._persistent_sortkey_fn skJJ9IJJJ w<< " "D6 * * $       $ $ $ r/c*fdjDS)Nc*g|]}j|Sr+rrs r-rz.Mapper._identity_key_props.. s!HHH&s+HHHr/rrys`r-rzMapper._identity_key_props s HHHHt7GHHHHr/cvt}|jD]"}||j|#|Sr~)rrrr)rs collectionrs r- _all_pk_propszMapper._all_pk_props sAUU [ 9 9E   d07 8 8 8 8r/cpt|j}|j||j|Sr~)rrtrHr)rscolss r-_should_undefer_in_wildcardz"Mapper._should_undefer_in_wildcard s54#$$   * HHT( ) ) ) r/c$d|jDS)Nch|] }|j Sr+r)rrs r- z/Mapper._primary_key_propkeys.. s888T888r/)r[rys r-_primary_key_propkeyszMapper._primary_key_propkeys s88T%78888r/cv|j|}|j|jj|||SNrG)rrrrFrrsr*r+rrGrs r-_get_state_attr_by_columnz Mapper._get_state_attr_by_column s8%f-}TX&+//ug/NNNr/cx|j|}|j|jj|||dSr~)rrrrFset_committed_valuersr*r+rrprs r-#_set_committed_state_attr_by_columnz*Mapper._set_committed_state_attr_by_column s9%f- dh$88uMMMMMr/cz|j|}|j|jj|||ddSr~)rrrrFrrjs r-_set_state_attr_by_columnz Mapper._set_state_attr_by_column# s;%f- dh$((udCCCCCr/ctj|}tj|}||||tjSrd)rr? instance_dict#_get_committed_state_attr_by_columnrA)rsrrr*r+s r-_get_committed_attr_by_columnz$Mapper._get_committed_attr_by_column' sK)#..(--77 5&**@8   r/cv|j|}|j|jj|||Srd)rrrrFget_committed_valuerfs r-rpz*Mapper._get_committed_state_attr_by_column. sB%f-}TX&+?? 5'@   r/c  j tt fd|D jj vrdS fd}g} d}t t D]i}|j vrd}n"t|jtj sdS|r7|j s0| tj|jid|ijn#t $rYdSwxYwt#j|}g}|D]"} | | j#t#j||dS)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. c\g|](}|jD]}tj|d)S)T) check_columns)rrr)rrrpropss r-rz3Mapper._optimized_get_statement..E sW"3Z/($???r/Nc|j}|j}||dS|jvrlj|t j}|tjvrttj d||jj |_dS|jvrlj|t j}|tjvrttj d||jj |_dSdS)Nrer) r r rrpr(rPASSIVE_NO_INITIALIZEorm_util _none_set_OptGetColumnsNotAvailablerrr3)rleftcolrightcolleftvalrightvalrsr*rs r-rz5Mapper._optimized_get_statement..visit_binaryP s$kG|H("2}F**BBJ&< C h0004666!m'): v--CCJ&< D x1114666"}(&,*;    .-r/FTr) use_labels)rrrrr?reversedrrr8r TableClauser=rrcloned_traverser@r|rrr@rselect) rsr*attribute_namesrallcondsstartrzcondr]rrwrs `` @@r-_optimized_get_statementzMapper._optimized_get_statement7 s  .      '6 1 14       > E"4(<(<(>(>#?#?@@  %// EE#& (>  44OO 0"4%|4 *   44 x"" , ,C KKc * + + + +z$6666sAC#(:C## C10C1c#K||r6|}|D]!}|V||ur ||jvrdS|}||urdS dSdSr~)rrr)rsrzprevrs r-_iterate_to_target_viawpolyz"Mapper._iterate_to_target_viawpoly s 88F   D))++  D==T1L%L%LEE;;EE    r/cV|s*|}||D]}|jdkr|cSn|t|}d|D}||gD]J}|j}||D]+}|jdks||vr|||ccS,KdS)Nrci|] }|j| Sr+rz)res r- z0Mapper._should_selectin_load.. s&L&L&Lqqx&L&L&Lr/)rr\rrrzr)rsenabled_via_optpolymorphic_fromrzrenabled_via_opt_mappersr|s r-_should_selectin_loadzMapper._should_selectin_load s A%F55f==  %33HHH4  "/22O&L&LO&L&L&L #)//1A0BCC A A99&AAAAA*j88 7776::1a@@@@@@@8Atr/zsqlalchemy.ext.bakedzsqlalchemy.orm.strategy_optionsc jsJjj}t|gjz}|}|}jD]\}|jus||vr/||j ft|j >||j fddi]tj dkrtjj n j d jr@jusJ|jfdf} | n |jfdf} | fdz } | ||fS)zmAssemble a BakedQuery that can load the columns local to this subclass as a SELECT with IN. do_nothingTrrc|jSr~)queryselect_entity_fromr_adapt_all_clauses)sessionr|s r-r.z.Mapper._subclass_load_via_in.. s3 f 5 5##F$566##%%r/c.|Sr~)r)rrss r-r.z.Mapper._subclass_load_via_in.. s d 3 3r/c |tjddjjS)N primary_keysT) expanding)filterrrrr%rt)qin_exprrss r-r.z.Mapper._subclass_load_via_in.. sEqxx KK nEEE F F  D$&r/)r>rrHrrLoadrrLset_generic_strategyrr( strategy_keyrrtrtuple_is_aliased_classrz BakedQuery_compiled_cachespoil) rsbakedstrategy_optionsr|polymorphic_prop keep_props disable_opt enable_optrrrs ` ` @r-_subclass_load_via_inzMapper._subclass_load_via_in s}1$2EF*+d.FFGG &++F33 %**622 J  D{d""dj&8&8//XKd&7!8!800XK,!5 t 1 $ $j$"23GG&q)G  " =D((((  $&&&& A GGIIII  $3333A &&&&& &*k))r/c,||Sr~)rrys r-_subclass_load_via_in_mapperz#Mapper._subclass_load_via_in_mapper s))$///r/c #Kt}tt}}|j|sJt t |jj|||jfg}|r|d\}} } } |s|&| |ur`| } || j vrHt | || | ||} | r| | |ddfnb| |ur^| \}}}}||||fV| t |j|||f|dSdS)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) robjectrzrrrrFr(rXr?cascadecascade_iteratorr)rsrr*halt_onvisited_statesprpmpp visitablesiterator item_type parent_state parent_dictrqueuerBinstance_mappercorresponding_statecorresponding_dicts r-rzMapper.cascade_iterator s288VXXS|%%%%%EL'..00113uz J K  ) =G^ :Hi{    C'')) ,,))$#& @%%uc4&>???c!! $$&& #'&#'&  !!o4;;==>>+* E) ) ) ) ) r/c4tj|jSr~)r LRUCacherSrys r-rzMapper._compiled_cache; s}T6777r/c i |jjD]"}|jD]} ||#g} D]4\}|j}|r&|fd|jD5 fd}tj ||}tj }|D] } |||<|S)Ncg|]}|fSr+r+)r super_tablers r-rz)Mapper._sorted_tables..L sKKKkk5)KKKr/c|jj}|jj}||||ur{|jtt t j|j}|j>|t j|j}|j|vo|j|vS|j|vSdSr) rrLrrr@rr _find_columnsr)fkrLdepr]table_to_mappers r-skipz#Mapper._sorted_tables..skipO s %((99F!%%bio66C"Ov%%)581#2GHHII+7:: .v/GHHD9D0JRYd5JJ9D005r/)skip_fnextra_dependencies) rrr setdefaultrr>r@r sort_tablesr r) rsrzrrsuper_rsorted_retrrs @@r-_sorted_tableszMapper._sorted_tables? s$&; 6 6F] 6 6**1f5555 6 ,2244  ME6_F "))KKKKV]KKK     0& 1       ( (A$Q'CFF r/cZ||jvr |j|S|x|j|<}|Sr~)rR)rsr callable_rps r-_memoz Mapper._memor s; $' ' '(- -1: . sKKKAKKKr/) r defaultdictrrrrrrQr reducerr)rsrrr]rs r-_table_to_equatedzMapper._table_to_equatedy s !$''( I IEuw<rbr<rrtr)r4r=r&rHr^r]rrrKr deprecatedrmemoized_propertyrrhr[rrrrirkrj classmethodrrrnrlrmr1rtr=r/rGrrrTrlrqrnrqr|rprrrrrrrrrrrrrwith_polymorphic_mappersrrrrrrrrrrrrrrrrrrrrrrrrr"rrrr)rr,r4r:r<rCrPASSIVE_RETURN_NEVER_SETr@rJrVrr[r^rbrgrkrmrqrprrr dependenciesrrrrrrrr+r/r-r"r"Es @LOT   !8!!!! ?T 'T 'T '32T 'rI%! XXK,8HJ HF K.FMFKN O   K G J A4 T_U566''76X' ---KKKZ ( ( (DAAA6111777&///"W+W+W+r[::: c c c J111fq2q2q2q2f&*""#" #  #" #//#"/4m(m(m(m(^TTTl.*** B B BBBB   X  CCCDDDIII   (""" ... **X*   D6##"#??#"?#  #"  9 #   #"  #  #" #   #"  #  #" #  #" #   #"  #  #" #   #"   1 1X 16;NNNN #  #" 8##5#5#"#5J#C C #"C J# C C#" C# B B#" B#HH#"H2# E E#" E   #   #"  #''#"'R   &&&P555 --- # . .#" . / / /))) 55X5    .HHHHLLL"(@     ##"$#II#"I##" ##" #99#"9-7,OOOOO NNNDDD   -7,O    S7S7S7j   ,T A6*6*6*p#00#"0KKKKZ#88#"8#00#"0d r/r"ceZdZdS)r|N)rrrr+r/r-r|r| sDr/r|ctjsdSt tr tdSda tjs datdSd}tjtttD] }d}|jj D] }|||j }|turd}n!|tur> 22 "666#;#; =A+1*BA'G(  99;;;3355599"FM%!lnnQ/&s,?@@;7:F4   ,&+#!&    & & & &   """"  """" Ov&&7799999sOH H G"H9C G"AFG".wrap7 s'$. 0% % ! r/)rX)rkwrrrs` @@r- validatesr s[Fff.66Ovv0$77 Kr/c|jjt}|jr)||dSdSr~)rrrrTr)r*ctxinstrumenting_mappers r-rrB sI =-m<*9++EIIKK8888899r/c|jt}|rtjrt dSdSdS)zInitial mapper compilation trigger. instrumentation calls this one when InstanceState is first generated, and is needed for legacy mutable attributes to work. N)rrrr"ror)rrr s r-rrH sS#<++M::            r/c|jjt}|r8tjrt |jr||dSdSdS)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)rrrrr"rorr-)r*rkwargsr s r-rrV s{!=-11-@@B        9 B : :5 A A A A A BB B Br/c"eZdZdZdZdZdZdS)rz4Error reporting helper for mapper._columntoproperty.rc||_dSr~rrvs r-rwz_ColumnMapping.__init__l s  r/c |jj|}|r4tjd|jjd|jd|jd|tjd|d|jd)NzColumn '.z1' is not available, due to conflicting property 'z':z No column z is configured on mapper z...)rzrrorm_excUnmappedColumnErrorrrr)rsrrs r- __missing__z_ColumnMapping.__missing__o s{!%%f--  --<$$$fkkk6:::ttE  ))vvt{{{ $   r/N)rrrr __slots__rwrr+r/r-rrg s=>>I      r/r)Ar __future__r collectionsr itertoolsrrrweakrefrrrrr r r r rzbaser rrrr interfacesrrrr path_registryrrrYrrrrrrrrWeakKeyDictionaryrr!group_expirable_memoized_propertyrtsymbolr threadingRLockrc_self_inspects class_loggerr"rr|rrrrrrr(rr+r/r-r$s'&&&&& """"""(((((( &&&&&&&&&&&&''''''""""""-7,.. F F H H t{>** >'')) D1D1D1D1D1^D1D1D1Nb        b:b:b:J4...b999    BBB"     T     r/