B 4]X@s 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 *Z+d a,e-Z.e/d!Z0ej12Z3e"j4e#j5Gd"d#d#eZ6d$d%Z7d&d'Z8d(d)Z9d*d+Z:d,d-Z;d.d/ZdS)2a5Logic 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_ATTRIBUTEc@s~eZdZdZdZdZejdddddd d ZdZ dZ e d d Z e ddZ dZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZe e ddddZ!ej"ddZ#ddZ$ddZ%ddZ&ddZ'ddZ(d d!Z)d"d#Z*d$d%Z+e,d&d'Z-d(d)Z.d*d+Z/d,d-Z0dd.d/Z1dZ2e3d0d1Z4e3d2d3Z5e3d4d5Z6d6d7Z7dd8d9Z8d:d;Z9dd?Z;d@dAZdFdGZ?dHdIZ@dJdKZAdLdMZBdNdOZCdPdQZDddRdSZEdTdUZFe dVdWZGdXdYZHdZd[ZIe3d\d]ZJe3d^d_ZKe3d`daZLeKZMe3dbdcZNe3dddeZOe3dfdgZPe3dhdiZQe3djdkZRe3dldmZSe3dndoZTe3dpdqZUe drdsZVddtduZWe3dvdwZXddxdyZYe3dzd{ZZe3d|d}Z[e3d~dZ\e3ddZ]e3ddZ^e3ddZ_ddZ`e3ddZae3ddZbddZcddZdddZeddZfddZgddZhe3ddZiddZjddZke ddZldddZmdddZndddZoddZpeqjrfddZsddZte3ddZue3ddZve3ddZwe3ddZxeqjrfddZyddZzddZ{ddZ|eqjrfddZ}ddZ~ddZddÄZeddšddDŽZe3ddɄZddd˄Ze3dd̈́Ze3ddτZddфZej"ddӄZdS)MapperaDefine the correlation of class attributes to database table columns. The :class:`.Mapper` object is instantiated using the :func:`~sqlalchemy.orm.mapper` function. For information about instantiating new :class:`.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:`.Mapper` which maintains it can be acquired using the :func:`.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.order_by` to determine the ordering of a result set.)z1.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:`.relationship` in 1.3.) extensionorder_by non_primaryNTdcCsbt|td|_d|_t||_||_| dk r>t| |_n| |_| |_ t | t rb| |_ d|_ n| |_ | dkrxd|_n| dkrdd|_n| |_||_d|_||_||_||_||_|pi|_g|_||_||_||_t||_g|_t|_||_ ||_!||_"d|_#d|_$d|_%i|_&||_'d|_(t| p6g|_)||_*|jrZ|jsZd|_+n||_+t |jtj,rzt-.d|/|||_0||_1|dkri|_2n||_2|dk rt3||_4nd|_4|rt3||_5nd|_5d|_6t78zd|j9j:;|||<|=|>|?|@|A|BdtC_D|Ed|FWdt7GXdS) aNReturn a new :class:`~.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:`.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:`.Table` produced as a result of the ``__tablename__`` and :class:`.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.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:`.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:`.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:`.Mapper` of one indicating a superclass to which this :class:`.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:`.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 orphanable 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:`.Mapper` is in addition to the "primary" mapper, that is, the one used for persistence. The :class:`.Mapper` created here may be used for ad-hoc mapping of the class to an alternate selectable, for loading only. :paramref:`.Mapper.non_primary` is not an often used option, but is useful in some specific :func:`.relationship` cases. .. seealso:: :ref:`relationship_non_primary_mapper` :param order_by: A single :class:`.Column` or list of :class:`.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:`.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:`.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:`.Column` object that's present in the mapped :class:`.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:`.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:`.Column` objects present in the mapped :class:`.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:`.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:`.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_NFcSs |pddS)Nrr)xr&r&H/opt/alt/python37/lib64/python3.7/site-packages/sqlalchemy/orm/mapper.pyxz!Mapper.__init__..zWhen 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.TZ constructed)Hr Zassert_arg_typetyper% class_managerto_list_primary_key_argumentr#r"always_refresh isinstancerZversion_id_propversion_id_colversion_id_generatorconcretesingleinherits local_tableinherit_conditioninherit_foreign_keys_init_properties_delete_orphansbatcheager_defaults column_prefixrZ_clause_element_as_exprpolymorphic_onZ_dependency_processorsZ immutabledict validatorspassive_updatespassive_deleteslegacy_is_orphanZ_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_MUTEXacquiredispatchZ_eventsZ_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%r6r primary_keyr#r5r7r8r!r"r/r1r2r>Z_polymorphic_maprPr3with_polymorphicrOrIr;r=rSrTr@rArJr<rBrFr&r&r(__init__ksz          zMapper.__init__cCs|S)zrCr7sql_utilZjoin_conditionrjoinrRr8Zcriterion_as_pairsZonclauserDrP_identity_classr1r2warn descriptionr"rQr;append base_mapperr@rA _all_tablesrO_add_with_polymorphic_subclassset)rdZnprhZfksr&r&r(rYs                                 zMapper._configure_inheritancecCs|dkrd|_nTt|ttfrJt|dtjttfr>||_qd|df|_n|dk r^tdnd|_t|jt j r|t d|jrt|jdt j r|jd|jd f|_|j r|dS)N*)r~Nrz$Invalid setting for with_polymorphiczWhen 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.r)rfr0tuplelistr string_typesrLrqr6rrKrMaliasrUrb)rdrfr&r&r(rNns&  zMapper._set_with_polymorphiccCsP|j}|jdkr||fn.|jddkrL||jd|f|jdfdS)Nrr~r)r%rfrN)rdrhZsubclr&r&r(r|s  z%Mapper._add_with_polymorphic_subclasscCs|js t|jrtt|ts"t||_|jj|j|jj|_x |D]}|jdk rLd|_ qLW|jj |_ x|j D]}|jj |_ qvW|jj ||jj|_|jj|_x@|jD]2\}}||jkr|j||ddds|||dqWdS)zSet the given :class:`.Mapper` as the 'inherits' for this :class:`.Mapper`, assuming this :class:`.Mapper` is concrete and does not already have an inherits.NTF)localcolumn)r3AssertionErrorr5r0r rQupdatersr>rCr;self_and_descendantsrzroryr@r{_propsitems_should_exclude_adapt_inherited_property)rdrhZmpkeypropr&r&r(_set_concrete_bases&         zMapper._set_concrete_basecCs||_|ddS)NT)r>r^)rdr>r&r&r(_set_polymorphic_onszMapper._set_polymorphic_oncCsb|jr4|j|jjttdd|jD}nt}x"|jD]}||krB|||qBWdS)NcSsg|] }|jqSr&)rH).0mr&r&r( sz=Mapper._configure_legacy_instrument_class..)r5rXZ_updater}rrsrHZ_adapt_instrument_class)rdsuper_extensionsextr&r&r(rZs z)Mapper._configure_legacy_instrument_classcCsR|jr$ttdd|jD}nt}x"|jD]}||kr2|||q2WdS)NcSsg|] }|jqSr&)rH)rrr&r&r(rsz/Mapper._configure_listeners..)r5r}rrsrHZ_adapt_listener)rdrrr&r&r(r\s zMapper._configure_listenerscCst|j}|jrH|r|js,td|j||_|jj |_ dt |<dS|dk rv|j|jks`t |jrvt d|jdt |<|j ||j|dkrt|j}||_||_ttj||_|jtdrdStj|dtddtj|dtddxt|jD]\}}|d kr:t|d r:|j}t |t!j"r:|j#}t |t!j$rt|d rn||_%tj|d t&ddnXt|d r|j'}xD|j(D]:}||j)krtd||f|j)*|||fi|_)qWqW||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.FZ first_init)rawinitrg_sa_original_init__sa_reconstructor__load__sa_validators__zJA validation function for mapped attribute %r on mapper %s already exists.)+rmanager_of_classr%r# is_mappedrLrMr,rhrv_mapper_registryrrqrXinstrument_classrZregister_classr partialr Zload_scalar_attributesZdeferred_scalar_loaderinfogetr rZlisten_event_on_first_init_event_on_initZiterate_attributeshasattrrr0types MethodTypeZim_func FunctionTyperG_event_on_load__sa_validation_opts__rr?union)rdmanagerrmethodZvalidation_optsnamer&r&r(r[s^            z'Mapper._configure_class_instrumentationcCs tdS)zAClass-level path to the :func:`.configure_mappers` call. N)configure_mappers)clsr&r&r(_configure_all5szMapper._configure_allcCsNd|_d|_t|dr|`|jsJ|jdk rJ|jjrJ|jj|krJt |j dS)NT_configure_failed) rU_dispose_calledrrr#r,rrhrZunregister_classr%)rdr&r&r(dispose;s   zMapper.disposecs"tj_i_i_ttddj D}tdd|D}t jjg}j |xN|D]F}|j r||j rt|j |j|<t|j|j|<qlWjrxjD]2}|jjkrtj|j<j|j|qWnljjks tjjdkr8tdjjfn0jjkrhtjtjrhtdjjjrj sjsjj _ nxjrtj!fddjDd d }ntj!jjd d }t|dkrtdjjft"|_ #d |t fd dj D_$dS) NcSsg|] }|jqSr&) proxy_set)rcolr&r&r(rRsz)Mapper._configure_pks..css|]}|jr|VqdS)N)re)rcr&r&r( Usz(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&)rjcorresponding_column)rr)rdr&r(rsT)Zignore_nonexistent_tablesz"Identified primary key columns: %sc3s>|]6}j|jkrt|dr,|jjkrj|VqdS)tableN)_columntoproperty_identity_key_propsrr_cols_by_table)rr)rdr&r(rs )%rt find_tablesrjtables _pks_by_tablerr column_setrrr}r{rre issupersetZordered_column_set intersectionrr.rZ OrderedSetaddlenrLrqrxr6r0rZTablerwr5r3Zreduce_columnsrra_readonly_props)rdZall_colspk_colsrtkrer&)rdr(r_Ksf              zMapper._configure_pkscCs&t|_|_t|_t||_|jrPx$|j D]\}}| ||dq6W|j rxB|j j D]2\}}||jkrd|j ||dddsd| ||dqdWx|jjD]z}||jkrq|jpd|j}|j |j||jj||drqx&|D]}||jkr|j|j}qW|j ||dddqWdS)NF)rrT)r setparent)r ZOrderedPropertiescolumnsr OrderedDictr_ColumnMappingrr9r_configure_propertyr5rrrjr=rr6Zcontains_columnrs)rdrrrZ column_keyrhr&r&r(r]s4     zMapper._configure_propertiesc sPd}|jdk rd}t|jtjrZy|j|j|_Wn$tk rXtd|jYnX|j|jkrv|j|j}n t|jt rt|jt j std|j}nt |jstdn|j|j}|dkr"d}d}|j}t|tjr&|jdks|jd|dkr&td|jnd}t|dd}|r`||j|jd|rvtd |jn|d |_}|j}t j ||d }|j|||dd |jd |_|jnpxn|D]b}|jdk r|j|jkr|j|_n|j|j|_|jdk r |j|_|j|_nd|_dSqW|rFfdd}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.zUOnly direct column-mapped property or SQL expression can be passed for polymorphic_onrzkCould not map polymorphic_on column '%s' to the mapped table - polymorphic loads will not function properlyrz6Cannot exclude or override the discriminator column %rZ_sa_polymorphic_on)Z _instrument)rrrcs&|j}||||jjjddS)N)dictZget_implr}rrhrP)statedict_)polymorphic_keyr&r(_set_polymorphic_identityvs  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)rhrr)rr&r(_validate_polymorphic_identitys zLMapper._configure_polymorphic_setter.._validate_polymorphic_identity)r>r0r rrKeyErrorrLrqrrr ColumnPropertyr _is_columnrjrrZColumnrfrMrxgetattrrrZlabelrrrsrr) rdrsetterrrZ instrumentrrhrrr&)rr(r^s                    z$Mapper._configure_polymorphic_settercCs|jdk r|j|jSdSdS)N)r1r)rdr&r&r(_version_id_props  zMapper._version_id_propcCsJt}t|g}x4|rD|}|j|jkr||j||jqW|S)N)r}rpopleftrjrrPextendro)rdZ identitiesstackitemr&r&r(rs   z)Mapper._acceptable_polymorphic_identitiescCst|jS)N) frozensetrvalues)rdr&r&r( _prop_setszMapper._prop_setcCsl|js|j||dddnN||jkrh|j||}||ksRt|tjrh|j|j krh|j|t |dddS)NF)rrT) r3rrr,_get_class_attr_mror0rZInstrumentedAttributeZ _parententityparentr ConcreteInheritedProperty)rdrrrZimplementing_attributer&r&r(rs   z Mapper._adapt_inherited_propertyc Cs|d||jjt|ts(|||}t|tjr|j |j d}|dkr|j r|g}xb|j D]T}|j |j d}|dk rx|D]}|jqW|j |j d}P||qhW|dkr|j d}t|drDt|dr|j|jkrD|j|n>t|drD|j|jkrD||j|jkrD|j|j|t|dsn||jkpj|j d|jk|_||j |<x2|j |jD]"}x|jD]}||j|<qWqW||_|r|||||jkrt|j|ddr|j|j} t d | ||| f||jkrlt|tjslt|j|tjtj!fslt"#d |j|||f|j|} |j$%| d||j|<|j&s|'|x|j(D]} | )|||qW|r|*|+||j,r|-dS) 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).ra __class__rrr0r_property_from_columnr rrjrrr5rsr6_reset_exportedryrrrrrr>rZ _orig_columnsrrrZ set_parentrrrrLrqrr rwrlpopr#rrorrpost_instrument_classrUrb) rdrrrrrpathrZm2ZsynZoldproprhr&r&r(rs~                      zMapper._configure_propertyc Cst|}|d}t|s.td||f|j|d}t|t j r|j rb|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|t jrg}xx|D]p}|j|} | dkrr|j|} | dk rH|j|j|} | dkrrtd|||f|| qWt j |Std|||j|fdS) zUgenerate/update a :class:`.ColumnProprerty` given a :class:`.Column` object. rz4%s=%r is not an instance of MapperProperty or ColumnNzImplicitly 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 r-rrrLrqrrr0r rrDrZshares_lineager1rrwrMcopyinsertrarrjrr6rryr) rdrrrrZ warn_onlymsgZ mapped_columnrZmcr&r&r(r6sZ                    zMapper._property_from_columncCsx|ddd|jD}xD|D]<\}}|d||j|krP|jsP||jr$||q$W|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(rsz5Mapper._post_configure_properties..zinitialize prop %sz%_post_configure_properties() completeTN) rarrrZ_configure_startedrZ_configure_finishedrrU)rdlrrr&r&r(_post_configure_propertiess   z!Mapper._post_configure_propertiescCs&x |D]\}}|||q WdS)z^Add the given dictionary of properties to this mapper, using `add_property`. N)r add_property)rdZdict_of_propertiesrvaluer&r&r(add_propertiesszMapper.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)r9rrU)rdrrr&r&r(rs zMapper.add_propertycCs x|D]}t|q WdS)N)rs_memoized_configured_propertyZexpire_instance)rdrhr&r&r(rbszMapper._expire_memoizationscCs>d|jjd|jdk r |jjp(t|j|jr4dp6ddS)N(|z |non-primaryr))r%rrr6rxstrr#)rdr&r&r( _log_descs zMapper._log_desccGs"|jjd|f|jf|dS)Nz%s )loggerrr)rdrargsr&r&r(rasz Mapper._logcGs"|jjd|f|jf|dS)Nz%s )rdebugr)rdrrr&r&r( _log_debugszMapper._log_debugcCsdt||jjfS)Nz)idr%rr)rdr&r&r(__repr__szMapper.__repr__cCs2d|jj|jrdpd|jdk r&|jjn|jjfS)Nzmapped class %s%s->%sz (non-primary)r)r%rrr#r6rxrj)rdr&r&r(__str__s  zMapper.__str__cCstd}x\|D]P}xJ|jD]@\}}d}t|j|||jd}|jrL|rLdS|js|sdSqWqW|jrl|SdSdS)NFT)Z optimistic)rsr:rr has_parentZ has_identityrB)rdrZorphan_possiblerhrrrr&r&r( _is_orphans    zMapper._is_orphancCs ||jkS)N)r)rdrr&r&r( has_propertyszMapper.has_propertycCsF|rtjrty |j|Stk r@td||fYnXdS)z?return a MapperProperty associated with the given key. z Mapper '%s' has no property '%s'N)r r`rrrrLrM)rdrZ_configure_mappersr&r&r( get_propertys  zMapper.get_propertycCs |j|S)zdGiven a :class:`.Column` object, return the :class:`.MapperProperty` which maps this column.)r)rdrr&r&r(get_property_by_columnszMapper.get_property_by_columncCstjr tt|jS)z1return an iterator of all MapperProperty objects.)r r`riterrr)rdr&r&r(iterate_propertiesszMapper.iterate_propertiescs|dkrt|jn~|rtxXt|D]J}t|}||sRtd||f|dkrj | q* |q*Wfdd|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. r~z%r does not inherit from %rNcsg|]}|kr|qSr&r&)rr)mappersr&r(r%sz-Mapper._mappers_from_spec..T)Zinclude_aliasescsg|]}|jkr|qSr&)r6)rr)rr&r(r-s)rrr}r r-r isarLrMrrsrrtr)rdspec selectablerr&)r rr(_mappers_from_specs&  zMapper._mappers_from_speccCs`|j}xT|D]L}||krq |jr,tdq |js |rH||j|j}q ||j|j}q W|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.) rjr3rLrMr4rur6r7Z outerjoin)rdr  innerjoinZfrom_objrr&r&r(_selectable_from_mappers0s zMapper._selectable_from_mapperscCs@|jr8|jr8|jdk r8|jd|idd|jDSdSdS)NZ parentmappercss|] }|jVqdS)N)rP)rrr&r&r(rOsz1Mapper._single_table_criterion..)r4r5r>Z _annotatein_r)rdr&r&r(_single_table_criterionKszMapper._single_table_criterioncCs"tjr t|jsgS|j|jS)N)r r`rrfr)rdr&r&r(_with_polymorphic_mappersTs z Mapper._with_polymorphic_mapperscCs:|js |jS|j\}}|dk r"|S||||dSdS)NF)rfrjrr)rdr rr&r&r(_with_polymorphic_selectable\s z#Mapper._with_polymorphic_selectablecCstdd|jDS)Ncss(|] \}}|tdd|DfVqdS)css|]}|jjr|VqdS)N)r+should_evaluate_none)rrr&r&r(rusz@Mapper._insert_cols_evaluating_none...N)r)rrrr&r&r(rrsz6Mapper._insert_cols_evaluating_none..)rrr)rdr&r&r(_insert_cols_evaluating_noneosz#Mapper._insert_cols_evaluating_nonecCstdd|jDS)Ncss(|] \}}|tdd|DfVqdS)css.|]&}|js|js|js|jjs|jVqdS)N)reserver_defaultdefaultr+rr)rrr&r&r(rs z8Mapper._insert_cols_as_none...N)r)rrrr&r&r(r~s z.Mapper._insert_cols_as_none..)rrr)rdr&r&r(_insert_cols_as_none{s zMapper._insert_cols_as_nonecstfddjDS)Nc3s,|]$\}}|tfdd|DfVqdS)c3s|]}j|j|fVqdS)N)rr)rr)rdr&r(rsz3Mapper._propkey_to_col...N)r)rrr)rdr&r(rsz)Mapper._propkey_to_col..)rrr)rdr&)rdr(_propkey_to_cols zMapper._propkey_to_colcCstdd|jDS)Ncss(|] \}}|tdd|DfVqdS)cSsg|] }|jqSr&)r)rrr&r&r(rsz6Mapper._pk_keys_by_table...N)r)rrpksr&r&r(rsz+Mapper._pk_keys_by_table..)rrr)rdr&r&r(_pk_keys_by_tableszMapper._pk_keys_by_tablecstfddjDS)Nc3s,|]$\}}|tfdd|DfVqdS)csg|]}j|jqSr&)rr)rr)rdr&r(rsz;Mapper._pk_attr_keys_by_table...N)r)rrr)rdr&r(rsz0Mapper._pk_attr_keys_by_table..)rrr)rdr&)rdr(_pk_attr_keys_by_tables zMapper._pk_attr_keys_by_tablecCstdd|jDS)Ncss(|] \}}|tdd|DfVqdS)cSsg|]}|jdk r|jqS)N)rr)rrr&r&r(rsz9Mapper._server_default_cols...N)r)rrrr&r&r(rs z.Mapper._server_default_cols..)rrr)rdr&r&r(_server_default_colss zMapper._server_default_colscCs`t}xT|jD]F\}}x<|D]4}|jdk s8|jdk r ||jkr ||j|jq WqW|S)N)r}rrrserver_onupdaterrr)rdresultrrrr&r&r(&_server_default_plus_onupdate_propkeyss    z-Mapper._server_default_plus_onupdate_propkeyscCstdd|jDS)Ncss(|] \}}|tdd|DfVqdS)cSsg|]}|jdk r|jqS)N)r r)rrr&r&r(rszBMapper._server_onupdate_default_cols...N)r)rrrr&r&r(rs z7Mapper._server_onupdate_default_cols..)rrr)rdr&r&r(_server_onupdate_default_colss z$Mapper._server_onupdate_default_colscCs|jS)a$The :func:`.select` construct this :class:`.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. )r)rdr&r&r(rs zMapper.selectablecCsd|jr(|s|jd}|dkr4|jd}n |dkr4d}|||}|dk rP||fS||||fSdS)NrFr)rfrr)rdr rrr r&r&r(_with_polymorphic_argss   zMapper._with_polymorphic_argscCst||jS)N)r_iterate_polymorphic_propertiesr)rdr&r&r(_polymorphic_propertiesszMapper._polymorphic_propertiesccs|dkr|j}|s*xl|jD] }|VqWnVxTttdd|g|DD]2}t|ddrv|jdksJ|jd|jk rvqJ|VqJWdS)zUReturn an iterator of MapperProperty objects which will render into a SELECT.NcSsg|]}t|jqSr&)rr )rrhr&r&r(r sz:Mapper._iterate_polymorphic_properties..rFr)rr r Z unique_listrrr>r)rdr rr&r&r(r%s    z&Mapper._iterate_polymorphic_propertiescCstjr tt|jS)a]A 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:`.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:`.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:`.Mapper.all_orm_descriptors` )r r`rr ImmutablePropertiesr)rdr&r&r(attrs s"z Mapper.attrscCstt|jS)a+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. 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:`.Mapper.attrs`. .. warning:: The :attr:`.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:`.Mapper.attrs` )r r'rr,Z_all_sqla_attributes)rdr&r&r(all_orm_descriptors= s+zMapper.all_orm_descriptorscCs |tjS)zReturn a namespace of all :class:`.SynonymProperty` properties maintained by this :class:`.Mapper`. .. seealso:: :attr:`.Mapper.attrs` - namespace of all :class:`.MapperProperty` objects. )_filter_propertiesr ZSynonymProperty)rdr&r&r(synonymsl s zMapper.synonymscCs |tjS)zReturn a namespace of all :class:`.ColumnProperty` properties maintained by this :class:`.Mapper`. .. seealso:: :attr:`.Mapper.attrs` - namespace of all :class:`.MapperProperty` objects. )r*r r)rdr&r&r( column_attrsy s zMapper.column_attrscCs |tjS)a4A namespace of all :class:`.RelationshipProperty` properties maintained by this :class:`.Mapper`. .. warning:: the :attr:`.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:`.Mapper.attrs` - namespace of all :class:`.MapperProperty` objects. )r*r ZRelationshipProperty)rdr&r&r( relationships szMapper.relationshipscCs |tjS)zReturn a namespace of all :class:`.CompositeProperty` properties maintained by this :class:`.Mapper`. .. seealso:: :attr:`.Mapper.attrs` - namespace of all :class:`.MapperProperty` objects. )r*r ZCompositeProperty)rdr&r&r( composites s zMapper.compositescs0tjr tttfdd|jDS)Nc3s$|]\}}t|r||fVqdS)N)r0)rrv)type_r&r(r sz,Mapper._filter_properties..)r r`rr r'rrr)rdr0r&)r0r(r* s zMapper._filter_propertiescCs.dd|jD}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)N)r0)r bindparamr+)rrer&r&r(r sz&Mapper._get_clause..cSsg|]\}}||kqSr&r&)rrr/r&r&r(r s)rerand_r column_dict)rdZparamsr&r&r( _get_clause s zMapper._get_clausecsHtfdd}x.|jjD]"}|jdk rt|jid|iqWS)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<dS)N)operatorreqleftrrightr r)binary)r!r&r( visit_binary s   z0Mapper._equivalent_columns..visit_binaryNr9)r r3rzrr7rZtraverse)rdr:rhr&)r!r(_equivalent_columns s  zMapper._equivalent_columnscCs t|ttjtjfrdSdSdS)NFT)r0rrZ ClassManagerrZ ColumnElement)rdobjr&r&r(_is_userland_descriptor s zMapper._is_userland_descriptorcCs|r0|jj|ddk rT||jj|rTdSn$|j|d}|dk rT||rTdS|jdk r||jkr|dksz||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) r%__dict__rr=r,rrSrarT)rdrZ assigned_namerrattrr&r&r(r s(      zMapper._should_excludecCs |j|jkS)zXReturn true if the given mapper shares a common inherited parent as this mapper.)rz)rdotherr&r&r( common_parent$ szMapper.common_parentcCs4|}|jdk s|r$t||St||kSdS)N)primary_mapperr>rr )rdrZallow_subtypessr&r&r(_canload* szMapper._canloadcCs$|}x|r||k r|j}qWt|S)z>Return True if the this mapper inherits from the given mapper.)r5bool)rdr@rr&r&r(r 1 s z Mapper.isaccs|}x|r|V|j}qWdS)N)r5)rdrr&r&r(rs9 szMapper.iterate_to_rootcCs@g}t|g}x&|r4|}||||jqWt|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. )rrryrror rn)rdZ 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()``. )r r)rdr&r&r(polymorphic_iteratorO s zMapper.polymorphic_iteratorcCs|jjS)zSReturn the primary mapper corresponding to this mapper's class key (class).)r,rh)rdr&r&r(rB\ szMapper.primary_mappercCs |jjjS)N)r,rhrz)rdr&r&r(primary_base_mapperb szMapper.primary_base_mappercs@|j}rfdd|D}x|D]}||s"dSq"WdSdS)Ncsg|]}j|qSr&)r)rr)adapterr&r(ri sz3Mapper._result_has_identity_key..FT)reZ_has_key)rdr!rHrrr&)rHr(_result_has_identity_keyf s  zMapper._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:`.RowProxy` instance. The columns which are mapped by this :class:`.Mapper` should be locatable in the row, preferably via the :class:`.Column` object directly (as is the case when a :func:`.select` construct is executed), or via string names of the form ``_``. csg|]}j|qSr&)r)rr)rHr&r(r} sz0Mapper.identity_key_from_row..c3s|]}|VqdS)Nr&)rr)rowr&r(r sz/Mapper.identity_key_from_row..)rervr)rdrJidentity_tokenrHrr&)rHrJr(identity_key_from_rowp 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. )rvr)rdrerKr&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)rdinstancerr&r&r(identity_key_from_instance s z!Mapper.identity_key_from_instancecs4jj|jtfdd|jDjfS)Ncs"g|]}|jjqSr&)rimplr)rr)rrpassiverr&r(r sz3Mapper._identity_key_from_state..)rrrvrrrK)rdrrTr&)rrrTrr(rO s zMapper._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. r)rrNrOrP)rdrQrZ identity_keyr&r&r(primary_key_from_instance s  z Mapper.primary_key_from_instancecsfddjDS)Ncsg|]}j|qSr&)r)rr)rdr&r(r sz.Mapper._identity_key_props..)re)rdr&)rdr(r szMapper._identity_key_propscCs*t}x|jD]}||j|qW|S)N)r}rrr)rdZ collectionrr&r&r( _all_pk_props s zMapper._all_pk_propscCs$t|j}|jdk r ||j|S)N)r}rer>r)rdcolsr&r&r(_should_undefer_in_wildcard s   z"Mapper._should_undefer_in_wildcardcCsdd|jDS)NcSsh|] }|jqSr&)r)rrr&r&r( sz/Mapper._primary_key_propkeys..)rV)rdr&r&r(_primary_key_propkeys szMapper._primary_key_propkeyscCs$|j|}|j|jjj|||dS)N)rT)rrrrSr)rdrrrrTrr&r&r(_get_state_attr_by_column s z Mapper._get_state_attr_by_columncCs&|j|}|j|jj|||dS)N)rrrrSZset_committed_value)rdrrrrrr&r&r(#_set_committed_state_attr_by_column s z*Mapper._set_committed_state_attr_by_columncCs(|j|}|j|jj|||ddS)N)rrrrSr})rdrrrrrr&r&r(_set_state_attr_by_column s z Mapper._set_state_attr_by_columncCs(t|}t|}|j|||tjdS)N)rT)rrNZ instance_dict#_get_committed_state_attr_by_columnrP)rdr<rrrr&r&r(_get_committed_attr_by_column s  z$Mapper._get_committed_attr_by_columncCs$|j|}|j|jjj|||dS)N)rT)rrrrSZget_committed_value)rdrrrrTrr&r&r(r^ s z*Mapper._get_committed_state_attr_by_columnc sjttfdd|Djjkr0dSGdddtfdd}g}yhd}x^ttD]J}|jkrd }nt |jt j sdS|rn|j sn| t|jid |iqnWWnk rdSXtj|}g}x|D]} || jqWtj||d d S) alassemble a WHERE clause which retrieves a given state by primary key, using a minimized set of tables. Applies to a joined-table inheritance mapper where the requested attribute names are only present on joined tables, not the base table. The WHERE clause attempts to include only those tables to minimize joins. cs*g|]"}|jD]}tj|ddqqS)T)Z check_columns)rrtr)rrr)propsr&r(r sz3Mapper._optimized_get_statement..Nc@s eZdZdS)z.ColumnsNotAvailableN)rr __module__ __qualname__r&r&r&r(ColumnsNotAvailable srccs|j}|j}|dks|dkr dS|jkrhjj|tjd}|tjkrPt j d||jj d|_nF|jkrjj|tjd}|tjkrt j d||jj d|_dS)N)rT)r0) r7r8rr^rrZPASSIVE_NO_INITIALIZEorm_utilZ _none_setrr1r+)r9ZleftcolZrightcolZleftvalZrightval)rcrdrrr&r(r: s0      z5Mapper._optimized_get_statement..visit_binaryFTr9)Z use_labels)rr}rrzr6 Exceptionreversedrrsr0rZ TableClauser4ryrZcloned_traverser7rr2rrZselect) rdrZattribute_namesr:ZallcondsstartrhZcondrWrr&)rcr`rdrrr(_optimized_get_statement s>         zMapper._optimized_get_statementccsL||rH|}x8|D],}|V||k r6||jkr6P|}||krPqWdS)N)r rsr)rdrhprevrr&r&r(_iterate_to_target_viawpolyJ s z"Mapper._iterate_to_target_viawpolycCs|s,|}x||D]}|jdkr|SqWndt|}dd|D}xL||gD]<}|j}x0||D]"}|jdks|||krf|||SqfWqPWdS)NrmcSsi|] }||jqSr&)rh)rer&r&r( a sz0Mapper._should_selectin_load..)rjrOr}rrhr)rdZenabled_via_optZpolymorphic_fromrhrZenabled_via_opt_mappersrir&r&r(_should_selectin_loadW s   zMapper._should_selectin_loadzsqlalchemy.ext.bakedzsqlalchemy.orm.strategy_optionsc sjs tjj}t|gj}|}|}xLjD]B}|jksX||krp| |j ft |j qB| |j fddiqBWt jdkrtjjn jdjrjkst|jfddf} | n|jfddf} | fdd7} | ||fS) zmAssemble a BakedQuery that can load the columns local to this subclass as a SELECT with IN. Z do_nothingTrrcs|jS)N)queryZselect_entity_fromrZ_adapt_all_clauses)session)rir&r(r) s z.Mapper._subclass_load_via_in..cs |S)N)rn)ro)rdr&r(r) r*cs"|tjdddjjS)NZ primary_keysT)Z expanding)filterrrr1r"re)q)in_exprrdr&r(r) s)r5rrr>r}rZLoadr(rZset_generic_strategyrrZ strategy_keyrrerZtuple_Zis_aliased_classrhZ BakedQuery_compiled_cacheZspoil) rdZbakedZstrategy_optionsriZpolymorphic_propZ keep_propsZ disable_optZ enable_optrrqr&)rirrrdr(_subclass_load_via_inm s6         zMapper._subclass_load_via_incCs ||S)N)rt)rdr&r&r(_subclass_load_via_in_mapper sz#Mapper._subclass_load_via_in_mapperccst}tt}}|j|s$ttt|jj|||jfg}x|r|d\}} } } |sh| qF| |kr| } || j krqFt| || | ||} | r| | |ddfqF| |krF| \}}}}||||fV| t|j|||fqFWdS)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. rN)r}objectrhr rrrrrrrZcascadecascade_iteratorry)rdr0rZhalt_onZvisited_statesZprpZmppZ visitablesiteratorZ item_typeZ parent_stateZ parent_dictrZqueuerQZinstance_mapperZcorresponding_stateZcorresponding_dictr&r&r(rw sD  zMapper.cascade_iteratorcCs t|jS)N)r ZLRUCacherF)rdr&r&r(rs szMapper._compiled_cachecsix,|jjD] }x|jD]}||qWqWg}x8D],\}|j}|r@|fdd|jDq@Wfdd}tj||d}t }x|D]}|||<qW|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|kSdS)NF) rrrrr7r}rtZ _find_columnsr)ZfkrZdeprW)table_to_mapperr&r(skip s   z#Mapper._sorted_tables..skip)Zskip_fnextra_dependencies) rzrr setdefaultrr5rrtZ sort_tablesr r)rdrhrr{Zsuper_rzZsorted_Zretr&)rryr(_sorted_tables s&   zMapper._sorted_tablescCs,||jkr|j|S||j|<}|SdS)N)rE)rdrZ callable_rr&r&r(_memo0 s  z Mapper._memoc Csttt}xd|jD]Z}t|j}xJ|D]>}|jr*|t tj dd|jDr*|| ||jfq*WqW|S)zgmemoized map of tables to collections of columns to be synchronized upwards to the base mapper.cSsg|]\}}|jqSr&)r)rrrr&r&r(rD sz,Mapper._table_to_equated..) r defaultdictrr}r}rrsrDrreducerry)rdr!rrWrr&r&r(_table_to_equated7 s    zMapper._table_to_equated)NNNFNNNNFFNNNNNFNNTTNNNTFTFFr$)F)TT)T)NFF)N)N)NN)N)N)rrrarb__doc__r`rr Zdeprecated_paramsrgZ is_mapperZrepresents_outer_joinpropertyrhrir6rjr5rUr3rrer%r,r4r#r>rQrPrzrr?rZ deprecatedrkZmemoized_propertyrlrYrNr|rrrZr\r[ classmethodrrr_r]r^rrrrrrrrrrrrbrrarrrrrrrr rrrrrZwith_polymorphic_mappersrrrrrrr"r#rr$r&r%r(r)r+r,r-r.r*r4r;r=rrArDr rsrrFrBrGrIrLrMrRrZPASSIVE_RETURN_NEVER_SETrOrUrrVrXrZr[r\r]r_r^rhrjrmZ dependenciesrtrurwrsr}r~rr&r&r&r(r EsH!  8           " Y e3 1   oV     "           & /    * (         X :  M  3r c CsVtjs dStz"trdSdaztjs0dSd}tjtxtt D]}d}x*|jj D]}|||j }|t kr`d}Pq`W|t krqNt |ddrtd||jf}|j|_||jsNy$|||j||j WqNtk rtd}t|ds||_YqNXqNW|s*dt_WddaXWdtXtjtdS)aInitialize the inter-mapper relationships of all mappers that have been constructed thus far. This function can be called any number of times, but in most cases is invoked automatically, the first time mappings are used, as well as whenever mappings are used and additional not-yet-configured mappers have been constructed. Points at which this occur include when a mapped class is instantiated into an instance, as well as when the :meth:`.Session.query` method is used. The :func:`.configure_mappers` function provides several event hooks that can be used to augment its functionality. These methods include: * :meth:`.MapperEvents.before_configured` - called once before :func:`.configure_mappers` 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:`.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` is complete; at this stage, all :class:`.Mapper` objects that are known to SQLAlchemy 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. NTFrzOne or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: '%s'. Original exception was: %sr)r r`rVrW_already_compilingrXZ _for_classZbefore_configuredrrZbefore_mapper_configuredr%rrrLrMrrUrrbZmapper_configuredresysexc_inforrcZafter_configured)Zhas_skiprhZ run_configurefnrkrr&r&r(rL sV#        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)r)rr&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)rr)r)rrnamesr&r(wrap s zvalidates..wrap)r)rkwrr&)rrrr( validates s#  rcCs$|jjt}|jr ||dS)N)rrr rGr<)rZctxinstrumenting_mapperr&r&r(r s rcCs |jt}|rtjrtdS)zInitial mapper compilation trigger. instrumentation calls this one when InstanceState is first generated, and is needed for legacy mutable attributes to work. N)rrr r r`r)rrrr&r&r(r s rcCs2|jjt}|r.tjrt|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)rrrr r r`rr)rrkwargsrr&r&r(r s rc@s$eZdZdZdZddZddZdS)rz4Error reporting helper for mapper._columntoproperty.)rhcCs ||_dS)N)rh)rdrhr&r&r(rg& 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...)rhrrorm_excZUnmappedColumnErrorrrr)rdrrr&r&r( __missing__) sz_ColumnMapping.__missing__N)rrrarbr __slots__rgrr&r&r&r(r! sr)?rZ __future__r collectionsr itertoolsrrrweakrefrrrrrr r r rdbaser r rrrZ interfacesrrrrZ path_registryrrrLrrrrrrrtrWeakKeyDictionaryrrZ!group_expirable_memoized_propertyrZsymbolrZ threadingRLockrVZ_self_inspectsZ class_loggerr rrrrrrrrr&r&r&r(s                                 e1