
    +h}2                       d Z ddlmZ ddlZddlZddlZddlmZ ddlm	Z	 ddlm
Z
 ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlm Z  ddlm!Z! ddl"m#Z# ddl"m$Z$ ddl"m%Z% dd l"m&Z& dd!l"m'Z' dd"l"m(Z( dd#l"m)Z) d$ Z*d% Z+ejX                   G d& d'e             Z-d( Z. G d) d*e/      Z0 G d+ d,e/      Z1y)-a
  Heuristics related to join conditions as used in
:func:`_orm.relationship`.

Provides the :class:`.JoinCondition` object, which encapsulates
SQL annotation and aliasing behavior focused on the `primaryjoin`
and `secondaryjoin` aspects of :func:`_orm.relationship`.

    )absolute_importN   )
attributes)_is_mapped_class)PASSIVE_MERGE)	state_str)
MANYTOMANY)	MANYTOONE)	ONETOMANY)PropComparator)StrategizedProperty)_orm_annotate)_orm_deannotate)CascadeOptions   )exc)log)schema)sql)util)inspect)	coercions)
expression)	operators)roles)visitors)_deep_deannotate)_shallow_annotate)adapt_criterion_to_null)ClauseAdapter)join_condition)selectables_overlapvisit_binary_productc                 b    t        t        j                  t        j                  |       ddi      S )a  Annotate a portion of a primaryjoin expression
    with a 'remote' annotation.

    See the section :ref:`relationship_custom_foreign` for a
    description of use.

    .. seealso::

        :ref:`relationship_custom_foreign`

        :func:`.foreign`

    remoteT_annotate_columnsr   expectr   ColumnArgumentRoleexprs    O/var/www/html/venv/lib/python3.12/site-packages/sqlalchemy/orm/relationships.pyr&   r&   6   s.     11488T:J     c                 b    t        t        j                  t        j                  |       ddi      S )a  Annotate a portion of a primaryjoin expression
    with a 'foreign' annotation.

    See the section :ref:`relationship_custom_foreign` for a
    description of use.

    .. seealso::

        :ref:`relationship_custom_foreign`

        :func:`.remote`

    foreignTr'   r+   s    r-   r0   r0   I   s.     11489d:K r.   c            "       Z    e Zd ZdZdZdZdZ eddddd      ZdZ	dddddddddddddded   ed	   ded
   dddddded   ed   ddddddddf" fd	Z
d Zd Z G d de      Zd5dZ	 	 	 d6dZd Zd7dZd Zd Zej,                  fdZ	 d8dZed        Zed        Zd Zej>                   ej@                  d      d               Z!ej>                  d        Z" fd Z#d! Z$d" Z%d# Z&ed$        Z'ed%        Z(ej>                   ej@                  d&      d'               Z) ej@                  d      d(        Z*ed)        Z+e+jX                  d*        Z+d+ Z-d, Z.d- Z/d. Z0d/ Z1 ej@                  d0      d1        Z2ej>                  d2        Z3ej>                  d3        Z4	 	 	 	 	 	 d9d4Z5 xZ6S ):RelationshipPropertyzDescribes an object property that holds a single item or list
    of items that correspond to a related database table.

    Public constructor is the :func:`_orm.relationship` function.

    .. seealso::

        :ref:`relationship_config_toplevel`

    relationshipTFpassive_deletespassive_updatesenable_typechecksactive_historycascade_backrefsNselectr5   r6   r7   r8   r9   c$                 \   t         t        |           || _        || _        || _        || _        || _        || _        d| _	        || _
        |r| j                  |||||       |r|"rt        j                  d      |"| _        || _        || _        || _        || _        || _        || _        || _        || _        || _        || _        || _        || _        || _        || _        |#| _        || _        |!rt?        j@                  d       |!| _!        || _"        || _#        || _$        |xs t        jJ                  | _&        | jM                  | d      | _'        t?        jP                  |        | | | _)        d| j                  ff| _*        tW               | _,        |
r%tW        t[        j\                  d|
            | _/        nd| _/        |dur|| _0        n| j                  rd	| _0        nd
| _0        || _1        |	| _2        | jd                  r|rt        j                  d      d| _3        y|| _3        y)a(  Provide a relationship between two mapped classes.

        This corresponds to a parent-child or associative table relationship.
        The constructed class is an instance of
        :class:`.RelationshipProperty`.

        A typical :func:`_orm.relationship`, used in a classical mapping::

           mapper(Parent, properties={
             'children': relationship(Child)
           })

        Some arguments accepted by :func:`_orm.relationship`
        optionally accept a
        callable function, which when called produces the desired value.
        The callable is invoked by the parent :class:`_orm.Mapper` at "mapper
        initialization" time, which happens only when mappers are first used,
        and is assumed to be after all mappings have been constructed.  This
        can be used to resolve order-of-declaration and other dependency
        issues, such as if ``Child`` is declared below ``Parent`` in the same
        file::

            mapper(Parent, properties={
                "children":relationship(lambda: Child,
                                    order_by=lambda: Child.id)
            })

        When using the :ref:`declarative_toplevel` extension, the Declarative
        initializer allows string arguments to be passed to
        :func:`_orm.relationship`.  These string arguments are converted into
        callables that evaluate the string as Python code, using the
        Declarative class-registry as a namespace.  This allows the lookup of
        related classes to be automatic via their string name, and removes the
        need for related classes to be imported into the local module space
        before the dependent classes have been declared.  It is still required
        that the modules in which these related classes appear are imported
        anywhere in the application at some point before the related mappings
        are actually used, else a lookup error will be raised when the
        :func:`_orm.relationship`
        attempts to resolve the string reference to the
        related class.    An example of a string- resolved class is as
        follows::

            from sqlalchemy.ext.declarative import declarative_base

            Base = declarative_base()

            class Parent(Base):
                __tablename__ = 'parent'
                id = Column(Integer, primary_key=True)
                children = relationship("Child", order_by="Child.id")

        .. seealso::

          :ref:`relationship_config_toplevel` - Full introductory and
          reference documentation for :func:`_orm.relationship`.

          :ref:`tutorial_orm_related_objects` - ORM tutorial introduction.

        :param argument:
          A mapped class, or actual :class:`_orm.Mapper` instance,
          representing
          the target of the relationship.

          :paramref:`_orm.relationship.argument`
          may also be passed as a callable
          function which is evaluated at mapper initialization time, and may
          be passed as a string name when using Declarative.

          .. warning:: Prior to SQLAlchemy 1.3.16, this value is interpreted
             using Python's ``eval()`` function.
             **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**.
             See :ref:`declarative_relationship_eval` for details on
             declarative evaluation of :func:`_orm.relationship` arguments.

          .. versionchanged 1.3.16::

             The string evaluation of the main "argument" no longer accepts an
             open ended Python expression, instead only accepting a string
             class name or dotted package-qualified name.

          .. seealso::

            :ref:`declarative_configuring_relationships` - further detail
            on relationship configuration when using Declarative.

        :param secondary:
          For a many-to-many relationship, specifies the intermediary
          table, and is typically an instance of :class:`_schema.Table`.
          In less common circumstances, the argument may also be specified
          as an :class:`_expression.Alias` construct, or even a
          :class:`_expression.Join` construct.

          :paramref:`_orm.relationship.secondary` may
          also be passed as a callable function which is evaluated at
          mapper initialization time.  When using Declarative, it may also
          be a string argument noting the name of a :class:`_schema.Table`
          that is
          present in the :class:`_schema.MetaData`
          collection associated with the
          parent-mapped :class:`_schema.Table`.

          .. warning:: When passed as a Python-evaluable string, the
             argument is interpreted using Python's ``eval()`` function.
             **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**.
             See :ref:`declarative_relationship_eval` for details on
             declarative evaluation of :func:`_orm.relationship` arguments.

          The :paramref:`_orm.relationship.secondary` keyword argument is
          typically applied in the case where the intermediary
          :class:`_schema.Table`
          is not otherwise expressed in any direct class mapping. If the
          "secondary" table is also explicitly mapped elsewhere (e.g. as in
          :ref:`association_pattern`), one should consider applying the
          :paramref:`_orm.relationship.viewonly` flag so that this
          :func:`_orm.relationship`
          is not used for persistence operations which
          may conflict with those of the association object pattern.

          .. seealso::

              :ref:`relationships_many_to_many` - Reference example of "many
              to many".

              :ref:`self_referential_many_to_many` - Specifics on using
              many-to-many in a self-referential case.

              :ref:`declarative_many_to_many` - Additional options when using
              Declarative.

              :ref:`association_pattern` - an alternative to
              :paramref:`_orm.relationship.secondary`
              when composing association
              table relationships, allowing additional attributes to be
              specified on the association table.

              :ref:`composite_secondary_join` - a lesser-used pattern which
              in some cases can enable complex :func:`_orm.relationship` SQL
              conditions to be used.

          .. versionadded:: 0.9.2 :paramref:`_orm.relationship.secondary`
             works
             more effectively when referring to a :class:`_expression.Join`
             instance.

        :param active_history=False:
          When ``True``, indicates that the "previous" value for a
          many-to-one reference should be loaded when replaced, if
          not already loaded. Normally, history tracking logic for
          simple many-to-ones only needs to be aware of the "new"
          value in order to perform a flush. This flag is available
          for applications that make use of
          :func:`.attributes.get_history` which also need to know
          the "previous" value of the attribute.

        :param backref:
          A reference to a string relationship name, or a :func:`_orm.backref`
          construct, which will be used to automatically generate a new
          :func:`_orm.relationship` on the related class, which then refers to
          this one using a bi-directional
          :paramref:`_orm.relationship.back_populates` configuration.

          In modern Python, explicit use of :func:`_orm.relationship` with
          :paramref:`_orm.relationship.back_populates` should be preferred, as
          it is more robust in terms of mapper configuration as well as more
          conceptually straightforward. It also integrates with new :pep:`484`
          typing features introduced in SQLAlchemy 2.0 which is not possible
          with dynamically generated attributes.

          .. seealso::

              :ref:`relationships_backref` - notes on using
              :paramref:`_orm.relationship.backref`

              :ref:`tutorial_orm_related_objects` - in the
              :ref:`unified_tutorial`, presents an overview of bi-directional
              relationship configuration and behaviors using
              :paramref:`_orm.relationship.back_populates`

              :func:`.backref` - allows control over :func:`_orm.relationship`
              configuration when using :paramref:`_orm.relationship.backref`.


        :param back_populates:
          Indicates the name of a :func:`_orm.relationship` on the related
          class that will be synchronized with this one.   It is usually
          expected that the :func:`_orm.relationship` on the related class
          also refer to this one.  This allows objects on both sides of
          each :func:`_orm.relationship` to synchronize in-Python state
          changes and also provides directives to the :term:`unit of work`
          flush process how changes along these relationships should
          be persisted.

          .. seealso::

              :ref:`tutorial_orm_related_objects` - in the
              :ref:`unified_tutorial`, presents an overview of bi-directional
              relationship configuration and behaviors.

              :ref:`relationship_patterns` - includes many examples of
              :paramref:`_orm.relationship.back_populates`.

        :param overlaps:
           A string name or comma-delimited set of names of other relationships
           on either this mapper, a descendant mapper, or a target mapper with
           which this relationship may write to the same foreign keys upon
           persistence.   The only effect this has is to eliminate the
           warning that this relationship will conflict with another upon
           persistence.   This is used for such relationships that are truly
           capable of conflicting with each other on write, but the application
           will ensure that no such conflicts occur.

           .. versionadded:: 1.4

           .. seealso::

                :ref:`error_qzyx` - usage example

        :param bake_queries=True:
          Legacy parameter, not used.

          .. versionchanged:: 1.4.23 the "lambda caching" system is no longer
             used by loader strategies and the ``bake_queries`` parameter
             has no effect.

        :param cascade:
          A comma-separated list of cascade rules which determines how
          Session operations should be "cascaded" from parent to child.
          This defaults to ``False``, which means the default cascade
          should be used - this default cascade is ``"save-update, merge"``.

          The available cascades are ``save-update``, ``merge``,
          ``expunge``, ``delete``, ``delete-orphan``, and ``refresh-expire``.
          An additional option, ``all`` indicates shorthand for
          ``"save-update, merge, refresh-expire,
          expunge, delete"``, and is often used as in ``"all, delete-orphan"``
          to indicate that related objects should follow along with the
          parent object in all cases, and be deleted when de-associated.

          .. seealso::

            :ref:`unitofwork_cascades` - Full detail on each of the available
            cascade options.

        :param cascade_backrefs=True:
          A boolean value indicating if the ``save-update`` cascade should
          operate along an assignment event intercepted by a backref.
          When set to ``False``, the attribute managed by this relationship
          will not cascade an incoming transient object into the session of a
          persistent parent, if the event is received via backref.

          .. deprecated:: 1.4 The
             :paramref:`_orm.relationship.cascade_backrefs`
             flag will default to False in all cases in SQLAlchemy 2.0.

          .. seealso::

            :ref:`backref_cascade` - Full discussion and examples on how
            the :paramref:`_orm.relationship.cascade_backrefs` option is used.

        :param collection_class:
          A class or callable that returns a new list-holding object. will
          be used in place of a plain list for storing elements.

          .. seealso::

            :ref:`custom_collections` - Introductory documentation and
            examples.

        :param comparator_factory:
          A class which extends :class:`.RelationshipProperty.Comparator`
          which provides custom SQL clause generation for comparison
          operations.

          .. seealso::

            :class:`.PropComparator` - some detail on redefining comparators
            at this level.

            :ref:`custom_comparators` - Brief intro to this feature.


        :param distinct_target_key=None:
          Indicate if a "subquery" eager load should apply the DISTINCT
          keyword to the innermost SELECT statement.  When left as ``None``,
          the DISTINCT keyword will be applied in those cases when the target
          columns do not comprise the full primary key of the target table.
          When set to ``True``, the DISTINCT keyword is applied to the
          innermost SELECT unconditionally.

          It may be desirable to set this flag to False when the DISTINCT is
          reducing performance of the innermost subquery beyond that of what
          duplicate innermost rows may be causing.

          .. versionchanged:: 0.9.0 -
             :paramref:`_orm.relationship.distinct_target_key` now defaults to
             ``None``, so that the feature enables itself automatically for
             those cases where the innermost query targets a non-unique
             key.

          .. seealso::

            :ref:`loading_toplevel` - includes an introduction to subquery
            eager loading.

        :param doc:
          Docstring which will be applied to the resulting descriptor.

        :param foreign_keys:

          A list of columns which are to be used as "foreign key"
          columns, or columns which refer to the value in a remote
          column, within the context of this :func:`_orm.relationship`
          object's :paramref:`_orm.relationship.primaryjoin` condition.
          That is, if the :paramref:`_orm.relationship.primaryjoin`
          condition of this :func:`_orm.relationship` is ``a.id ==
          b.a_id``, and the values in ``b.a_id`` are required to be
          present in ``a.id``, then the "foreign key" column of this
          :func:`_orm.relationship` is ``b.a_id``.

          In normal cases, the :paramref:`_orm.relationship.foreign_keys`
          parameter is **not required.** :func:`_orm.relationship` will
          automatically determine which columns in the
          :paramref:`_orm.relationship.primaryjoin` condition are to be
          considered "foreign key" columns based on those
          :class:`_schema.Column` objects that specify
          :class:`_schema.ForeignKey`,
          or are otherwise listed as referencing columns in a
          :class:`_schema.ForeignKeyConstraint` construct.
          :paramref:`_orm.relationship.foreign_keys` is only needed when:

            1. There is more than one way to construct a join from the local
               table to the remote table, as there are multiple foreign key
               references present.  Setting ``foreign_keys`` will limit the
               :func:`_orm.relationship`
               to consider just those columns specified
               here as "foreign".

            2. The :class:`_schema.Table` being mapped does not actually have
               :class:`_schema.ForeignKey` or
               :class:`_schema.ForeignKeyConstraint`
               constructs present, often because the table
               was reflected from a database that does not support foreign key
               reflection (MySQL MyISAM).

            3. The :paramref:`_orm.relationship.primaryjoin`
               argument is used to
               construct a non-standard join condition, which makes use of
               columns or expressions that do not normally refer to their
               "parent" column, such as a join condition expressed by a
               complex comparison using a SQL function.

          The :func:`_orm.relationship` construct will raise informative
          error messages that suggest the use of the
          :paramref:`_orm.relationship.foreign_keys` parameter when
          presented with an ambiguous condition.   In typical cases,
          if :func:`_orm.relationship` doesn't raise any exceptions, the
          :paramref:`_orm.relationship.foreign_keys` parameter is usually
          not needed.

          :paramref:`_orm.relationship.foreign_keys` may also be passed as a
          callable function which is evaluated at mapper initialization time,
          and may be passed as a Python-evaluable string when using
          Declarative.

          .. warning:: When passed as a Python-evaluable string, the
             argument is interpreted using Python's ``eval()`` function.
             **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**.
             See :ref:`declarative_relationship_eval` for details on
             declarative evaluation of :func:`_orm.relationship` arguments.

          .. seealso::

            :ref:`relationship_foreign_keys`

            :ref:`relationship_custom_foreign`

            :func:`.foreign` - allows direct annotation of the "foreign"
            columns within a :paramref:`_orm.relationship.primaryjoin`
            condition.

        :param info: Optional data dictionary which will be populated into the
            :attr:`.MapperProperty.info` attribute of this object.

        :param innerjoin=False:
          When ``True``, joined eager loads will use an inner join to join
          against related tables instead of an outer join.  The purpose
          of this option is generally one of performance, as inner joins
          generally perform better than outer joins.

          This flag can be set to ``True`` when the relationship references an
          object via many-to-one using local foreign keys that are not
          nullable, or when the reference is one-to-one or a collection that
          is guaranteed to have one or at least one entry.

          The option supports the same "nested" and "unnested" options as
          that of :paramref:`_orm.joinedload.innerjoin`.  See that flag
          for details on nested / unnested behaviors.

          .. seealso::

            :paramref:`_orm.joinedload.innerjoin` - the option as specified by
            loader option, including detail on nesting behavior.

            :ref:`what_kind_of_loading` - Discussion of some details of
            various loader options.


        :param join_depth:
          When non-``None``, an integer value indicating how many levels
          deep "eager" loaders should join on a self-referring or cyclical
          relationship.  The number counts how many times the same Mapper
          shall be present in the loading condition along a particular join
          branch.  When left at its default of ``None``, eager loaders
          will stop chaining when they encounter a the same target mapper
          which is already higher up in the chain.  This option applies
          both to joined- and subquery- eager loaders.

          .. seealso::

            :ref:`self_referential_eager_loading` - Introductory documentation
            and examples.

        :param lazy='select': specifies
          How the related items should be loaded.  Default value is
          ``select``.  Values include:

          * ``select`` - items should be loaded lazily when the property is
            first accessed, using a separate SELECT statement, or identity map
            fetch for simple many-to-one references.

          * ``immediate`` - items should be loaded as the parents are loaded,
            using a separate SELECT statement, or identity map fetch for
            simple many-to-one references.

          * ``joined`` - items should be loaded "eagerly" in the same query as
            that of the parent, using a JOIN or LEFT OUTER JOIN.  Whether
            the join is "outer" or not is determined by the
            :paramref:`_orm.relationship.innerjoin` parameter.

          * ``subquery`` - items should be loaded "eagerly" as the parents are
            loaded, using one additional SQL statement, which issues a JOIN to
            a subquery of the original statement, for each collection
            requested.

          * ``selectin`` - items should be loaded "eagerly" as the parents
            are loaded, using one or more additional SQL statements, which
            issues a JOIN to the immediate parent object, specifying primary
            key identifiers using an IN clause.

            .. versionadded:: 1.2

          * ``noload`` - no loading should occur at any time.  This is to
            support "write-only" attributes, or attributes which are
            populated in some manner specific to the application.

          * ``raise`` - lazy loading is disallowed; accessing
            the attribute, if its value were not already loaded via eager
            loading, will raise an :exc:`~sqlalchemy.exc.InvalidRequestError`.
            This strategy can be used when objects are to be detached from
            their attached :class:`.Session` after they are loaded.

            .. versionadded:: 1.1

          * ``raise_on_sql`` - lazy loading that emits SQL is disallowed;
            accessing the attribute, if its value were not already loaded via
            eager loading, will raise an
            :exc:`~sqlalchemy.exc.InvalidRequestError`, **if the lazy load
            needs to emit SQL**.  If the lazy load can pull the related value
            from the identity map or determine that it should be None, the
            value is loaded.  This strategy can be used when objects will
            remain associated with the attached :class:`.Session`, however
            additional SELECT statements should be blocked.

            .. versionadded:: 1.1

          * ``dynamic`` - the attribute will return a pre-configured
            :class:`_query.Query` object for all read
            operations, onto which further filtering operations can be
            applied before iterating the results.  See
            the section :ref:`dynamic_relationship` for more details.

          * True - a synonym for 'select'

          * False - a synonym for 'joined'

          * None - a synonym for 'noload'

          .. seealso::

            :doc:`/orm/loading_relationships` - Full documentation on
            relationship loader configuration.

            :ref:`dynamic_relationship` - detail on the ``dynamic`` option.

            :ref:`collections_noload_raiseload` - notes on "noload" and "raise"

        :param load_on_pending=False:
          Indicates loading behavior for transient or pending parent objects.

          When set to ``True``, causes the lazy-loader to
          issue a query for a parent object that is not persistent, meaning it
          has never been flushed.  This may take effect for a pending object
          when autoflush is disabled, or for a transient object that has been
          "attached" to a :class:`.Session` but is not part of its pending
          collection.

          The :paramref:`_orm.relationship.load_on_pending`
          flag does not improve
          behavior when the ORM is used normally - object references should be
          constructed at the object level, not at the foreign key level, so
          that they are present in an ordinary way before a flush proceeds.
          This flag is not not intended for general use.

          .. seealso::

              :meth:`.Session.enable_relationship_loading` - this method
              establishes "load on pending" behavior for the whole object, and
              also allows loading on objects that remain transient or
              detached.

        :param order_by:
          Indicates the ordering that should be applied when loading these
          items.  :paramref:`_orm.relationship.order_by`
          is expected to refer to
          one of the :class:`_schema.Column`
          objects to which the target class is
          mapped, or the attribute itself bound to the target class which
          refers to the column.

          :paramref:`_orm.relationship.order_by`
          may also be passed as a callable
          function which is evaluated at mapper initialization time, and may
          be passed as a Python-evaluable string when using Declarative.

          .. warning:: When passed as a Python-evaluable string, the
             argument is interpreted using Python's ``eval()`` function.
             **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**.
             See :ref:`declarative_relationship_eval` for details on
             declarative evaluation of :func:`_orm.relationship` arguments.

        :param passive_deletes=False:
           Indicates loading behavior during delete operations.

           A value of True indicates that unloaded child items should not
           be loaded during a delete operation on the parent.  Normally,
           when a parent item is deleted, all child items are loaded so
           that they can either be marked as deleted, or have their
           foreign key to the parent set to NULL.  Marking this flag as
           True usually implies an ON DELETE <CASCADE|SET NULL> rule is in
           place which will handle updating/deleting child rows on the
           database side.

           Additionally, setting the flag to the string value 'all' will
           disable the "nulling out" of the child foreign keys, when the parent
           object is deleted and there is no delete or delete-orphan cascade
           enabled.  This is typically used when a triggering or error raise
           scenario is in place on the database side.  Note that the foreign
           key attributes on in-session child objects will not be changed after
           a flush occurs so this is a very special use-case setting.
           Additionally, the "nulling out" will still occur if the child
           object is de-associated with the parent.

           .. seealso::

                :ref:`passive_deletes` - Introductory documentation
                and examples.

        :param passive_updates=True:
          Indicates the persistence behavior to take when a referenced
          primary key value changes in place, indicating that the referencing
          foreign key columns will also need their value changed.

          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 rows.  When False, the SQLAlchemy
          :func:`_orm.relationship`
          construct will attempt to emit its own UPDATE statements to
          modify related targets.  However note that SQLAlchemy **cannot**
          emit an UPDATE for more than one level of cascade.  Also,
          setting this flag to False is not compatible in the case where
          the database is in fact enforcing referential integrity, unless
          those constraints are explicitly "deferred", if the target backend
          supports it.

          It is highly advised that an application which is employing
          mutable primary keys keeps ``passive_updates`` set to True,
          and instead uses the referential integrity features of the database
          itself in order to handle the change efficiently and fully.

          .. seealso::

              :ref:`passive_updates` - Introductory documentation and
              examples.

              :paramref:`.mapper.passive_updates` - a similar flag which
              takes effect for joined-table inheritance mappings.

        :param post_update:
          This indicates that the relationship should be handled by a
          second UPDATE statement after an INSERT or before a
          DELETE. This flag is used to handle saving bi-directional
          dependencies between two individual rows (i.e. each row
          references the other), where it would otherwise be impossible to
          INSERT or DELETE both rows fully since one row exists before the
          other. Use this flag when a particular mapping arrangement will
          incur two rows that are dependent on each other, such as a table
          that has a one-to-many relationship to a set of child rows, and
          also has a column that references a single child row within that
          list (i.e. both tables contain a foreign key to each other). If
          a flush operation returns an error that a "cyclical
          dependency" was detected, this is a cue that you might want to
          use :paramref:`_orm.relationship.post_update` to "break" the cycle.

          .. seealso::

              :ref:`post_update` - Introductory documentation and examples.

        :param primaryjoin:
          A SQL expression that will be used as the primary
          join of the child object against the parent object, or in a
          many-to-many relationship the join of the parent object to the
          association table. By default, this value is computed based on the
          foreign key relationships of the parent and child tables (or
          association table).

          :paramref:`_orm.relationship.primaryjoin` may also be passed as a
          callable function which is evaluated at mapper initialization time,
          and may be passed as a Python-evaluable string when using
          Declarative.

          .. warning:: When passed as a Python-evaluable string, the
             argument is interpreted using Python's ``eval()`` function.
             **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**.
             See :ref:`declarative_relationship_eval` for details on
             declarative evaluation of :func:`_orm.relationship` arguments.

          .. seealso::

              :ref:`relationship_primaryjoin`

        :param remote_side:
          Used for self-referential relationships, indicates the column or
          list of columns that form the "remote side" of the relationship.

          :paramref:`_orm.relationship.remote_side` may also be passed as a
          callable function which is evaluated at mapper initialization time,
          and may be passed as a Python-evaluable string when using
          Declarative.

          .. warning:: When passed as a Python-evaluable string, the
             argument is interpreted using Python's ``eval()`` function.
             **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**.
             See :ref:`declarative_relationship_eval` for details on
             declarative evaluation of :func:`_orm.relationship` arguments.

          .. seealso::

            :ref:`self_referential` - in-depth explanation of how
            :paramref:`_orm.relationship.remote_side`
            is used to configure self-referential relationships.

            :func:`.remote` - an annotation function that accomplishes the
            same purpose as :paramref:`_orm.relationship.remote_side`,
            typically
            when a custom :paramref:`_orm.relationship.primaryjoin` condition
            is used.

        :param query_class:
          A :class:`_query.Query`
          subclass that will be used internally by the
          ``AppenderQuery`` returned by a "dynamic" relationship, that
          is, a relationship that specifies ``lazy="dynamic"`` or was
          otherwise constructed using the :func:`_orm.dynamic_loader`
          function.

          .. seealso::

            :ref:`dynamic_relationship` - Introduction to "dynamic"
            relationship loaders.

        :param secondaryjoin:
          A SQL expression that will be used as the join of
          an association table to the child object. By default, this value is
          computed based on the foreign key relationships of the association
          and child tables.

          :paramref:`_orm.relationship.secondaryjoin` may also be passed as a
          callable function which is evaluated at mapper initialization time,
          and may be passed as a Python-evaluable string when using
          Declarative.

          .. warning:: When passed as a Python-evaluable string, the
             argument is interpreted using Python's ``eval()`` function.
             **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**.
             See :ref:`declarative_relationship_eval` for details on
             declarative evaluation of :func:`_orm.relationship` arguments.

          .. seealso::

              :ref:`relationship_primaryjoin`

        :param single_parent:
          When True, installs a validator which will prevent objects
          from being associated with more than one parent at a time.
          This is used for many-to-one or many-to-many relationships that
          should be treated either as one-to-one or one-to-many.  Its usage
          is optional, except for :func:`_orm.relationship` constructs which
          are many-to-one or many-to-many and also
          specify the ``delete-orphan`` cascade option.  The
          :func:`_orm.relationship` construct itself will raise an error
          instructing when this option is required.

          .. seealso::

            :ref:`unitofwork_cascades` - includes detail on when the
            :paramref:`_orm.relationship.single_parent`
            flag may be appropriate.

        :param uselist:
          A boolean that indicates if this property should be loaded as a
          list or a scalar. In most cases, this value is determined
          automatically by :func:`_orm.relationship` at mapper configuration
          time, based on the type and direction
          of the relationship - one to many forms a list, many to one
          forms a scalar, many to many is a list. If a scalar is desired
          where normally a list would be present, such as a bi-directional
          one-to-one relationship, set :paramref:`_orm.relationship.uselist`
          to
          False.

          The :paramref:`_orm.relationship.uselist`
          flag is also available on an
          existing :func:`_orm.relationship`
          construct as a read-only attribute,
          which can be used to determine if this :func:`_orm.relationship`
          deals
          with collections or scalar attributes::

              >>> User.addresses.property.uselist
              True

          .. seealso::

              :ref:`relationships_one_to_one` - Introduction to the "one to
              one" relationship pattern, which is typically when the
              :paramref:`_orm.relationship.uselist` flag is needed.

        :param viewonly=False:
          When set to ``True``, the relationship is used only for loading
          objects, and not for any persistence operation.  A
          :func:`_orm.relationship` which specifies
          :paramref:`_orm.relationship.viewonly` can work
          with a wider range of SQL operations within the
          :paramref:`_orm.relationship.primaryjoin` condition, including
          operations that feature the use of a variety of comparison operators
          as well as SQL functions such as :func:`_expression.cast`.  The
          :paramref:`_orm.relationship.viewonly`
          flag is also of general use when defining any kind of
          :func:`_orm.relationship` that doesn't represent
          the full set of related objects, to prevent modifications of the
          collection from resulting in persistence operations.

          When using the :paramref:`_orm.relationship.viewonly` flag in
          conjunction with backrefs, the originating relationship for a
          particular state change will not produce state changes within the
          viewonly relationship.   This is the behavior implied by
          :paramref:`_orm.relationship.sync_backref` being set to False.

          .. versionchanged:: 1.3.17 - the
             :paramref:`_orm.relationship.sync_backref` flag is set to False
                 when using viewonly in conjunction with backrefs.

          .. seealso::

            :paramref:`_orm.relationship.sync_backref`

        :param sync_backref:
          A boolean that enables the events used to synchronize the in-Python
          attributes when this relationship is target of either
          :paramref:`_orm.relationship.backref` or
          :paramref:`_orm.relationship.back_populates`.

          Defaults to ``None``, which indicates that an automatic value should
          be selected based on the value of the
          :paramref:`_orm.relationship.viewonly` flag.  When left at its
          default, changes in state will be back-populated only if neither
          sides of a relationship is viewonly.

          .. versionadded:: 1.3.17

          .. versionchanged:: 1.4 - A relationship that specifies
             :paramref:`_orm.relationship.viewonly` automatically implies
             that :paramref:`_orm.relationship.sync_backref` is ``False``.

          .. seealso::

            :paramref:`_orm.relationship.viewonly`

        :param omit_join:
          Allows manual control over the "selectin" automatic join
          optimization.  Set to ``False`` to disable the "omit join" feature
          added in SQLAlchemy 1.3; or leave as ``None`` to leave automatic
          optimization in place.

          .. note:: This flag may only be set to ``False``.   It is not
             necessary to set it to ``True`` as the "omit_join" optimization is
             automatically detected; if it is not detected, then the
             optimization is not supported.

             .. versionchanged:: 1.3.11  setting ``omit_join`` to True will now
                emit a warning as this was not the intended use of this flag.

          .. versionadded:: 1.3


        Nr4   z-sync_backref and viewonly cannot both be Truezsetting omit_join to True is not supported; selectin loading of this relationship may not work correctly if this flag is set explicitly.  omit_join optimization is automatically detected for conditions under which it is supported.lazyz\s*,\s* Fmergezsave-update, mergezCbackref and back_populates keyword arguments are mutually exclusive)4superr2   __init__uselistargument	secondaryprimaryjoinsecondaryjoinpost_update	directionviewonly _warn_for_persistence_only_flagssa_excArgumentErrorsync_backrefr<   single_parent_user_defined_foreign_keyscollection_classr5   r9   r6   remote_sider7   query_class	innerjoindistinct_target_keydocr8   _legacy_inactive_history_style
join_depthr   warn	omit_joinlocal_remote_pairsbake_queriesload_on_pending
Comparatorcomparator_factory
comparatorset_creation_orderinfostrategy_keyset_reverse_propertyresplit	_overlapscascadeorder_byback_populatesbackref)%selfrB   rC   rD   rE   foreign_keysrA   rh   rj   ri   overlapsrF   rg   rH   r<   rO   r5   r6   rP   r7   rV   r]   rM   rR   rS   rT   r8   r9   r[   rZ   _local_remote_pairsrQ   r`   rX   rL   rU   	__class__s%                                       r-   r@   zRelationshipProperty.__init__y   s:   p 	"D24 "&*& 11 / /"3-!1 2  &&?  )	**6' 0. 0.&!2&"#6 ,.L+$II #"5(.A"6"A"A 	 11$=%DI$dii02!$ *h!?@DNDN%"DL]]"DL/DL ,**-   DL"DLr.   c                     |j                         D ]1  \  }}|| j                  |   k7  st        j                  d|d       3 y )NzSetting z on relationship() while also setting viewonly=True does not make sense, as a viewonly=True relationship does not perform persistence operations. This configuration may raise an error in a future release.)items_persistence_onlyr   rW   )rk   kwkvs       r-   rI   z5RelationshipProperty._warn_for_persistence_only_flags,  sF    HHJ 	DAqD**1-- 		
 /0	2	r.   c                     t        j                  |j                  | j                  | j	                  | |      || j
                         y )N)r^   parententityrT   )r   register_descriptorclass_keyr]   rT   rk   mappers     r-   instrument_classz%RelationshipProperty.instrument_class>  s8    &&MMHH..tV<	
r.   c                      e Zd ZdZdZdZ	 	 	 ddZd Zej                  d        Z
ej                  d        Zej                  d        Zd	 Zd
 Zd Zd Zd ZdZd ZddZddZddZd Zd Zd Zej                  d        Zy)RelationshipProperty.Comparatora  Produce boolean, comparison, and other operators for
        :class:`.RelationshipProperty` attributes.

        See the documentation for :class:`.PropComparator` for a brief
        overview of ORM level operator definition.

        .. seealso::

            :class:`.PropComparator`

            :class:`.ColumnProperty.Comparator`

            :class:`.ColumnOperators`

            :ref:`types_operators`

            :attr:`.TypeEngine.comparator_factory`

        Nr=   c                 N    || _         || _        || _        |r|| _        || _        y)zConstruction of :class:`.RelationshipProperty.Comparator`
            is internal to the ORM's attribute mechanics.

            N)prop_parententity_adapt_to_entity_of_type_extra_criteria)rk   r   parentmapperadapt_to_entityof_typeextra_criterias         r-   r@   z(RelationshipProperty.Comparator.__init___  s-     DI!-D$3D! '#1D r.   c                 h    | j                  | j                  | j                  || j                        S )N)r   r   )ro   propertyr   r   )rk   r   s     r-   r   z/RelationshipProperty.Comparator.adapt_to_entityr  s2    >>"" /	 "  r.   c                 p    | j                   t        | j                         S | j                  j                  S )a+  The target entity referred to by this
            :class:`.RelationshipProperty.Comparator`.

            This is either a :class:`_orm.Mapper` or :class:`.AliasedInsp`
            object.

            This is the "target" or "remote" side of the
            :func:`_orm.relationship`.

            )r   r   r   entityrk   s    r-   r   z&RelationshipProperty.Comparator.entityz  s-     }}(t}}--}}+++r.   c                 .    | j                   j                  S )zThe target :class:`_orm.Mapper` referred to by this
            :class:`.RelationshipProperty.Comparator`.

            This is the "target" or "remote" side of the
            :func:`_orm.relationship`.

            )r   r|   r   s    r-   r|   z&RelationshipProperty.Comparator.mapper  s     =='''r.   c                 .    | j                   j                  S N)r   parentr   s    r-   r   z-RelationshipProperty.Comparator._parententity  s    =='''r.   c                     | j                   r| j                   j                  S | j                  j                  j                  S r   )r   
selectabler   r   _with_polymorphic_selectabler   s    r-   _source_selectablez2RelationshipProperty.Comparator._source_selectable  s3    $$,,777}}++HHHr.   c                     | j                         }| j                  rt        | j                        }nd }| j                  j	                  |d|d| j
                        \  }}}}}}|||z  S |S )NT)source_selectablesource_polymorphicof_type_entityalias_secondaryr   )r   r   r   r   _create_joinsr   )	rk   
adapt_fromr   pjsjsourcedestrC   target_adapters	            r-   __clause_element__z2RelationshipProperty.Comparator.__clause_element__  s    002J}}!(!7!% ++",#'- $#33 ,  ~Bw	r.   c                     t         j                  | j                  | j                  | j                  || j
                        S )zRedefine this object in terms of a polymorphic subclass.

            See :meth:`.PropComparator.of_type` for an example.


            r   r   r   )r2   r\   r   r   r   r   )rk   clss     r-   r   z'RelationshipProperty.Comparator.of_type  sA     (22"" $ 5 5#33 3  r.   c                     t         j                  | j                  | j                  | j                  | j
                  | j                  |z         S )zAdd AND criteria.

            See :meth:`.PropComparator.and_` for an example.

            .. versionadded:: 1.4

            r   )r2   r\   r   r   r   r   r   rk   others     r-   and_z$RelationshipProperty.Comparator.and_  sJ     (22"" $ 5 5#33e; 3  r.   c                     t        d      )zProduce an IN clause - this is not implemented
            for :func:`_orm.relationship`-based attributes at this time.

            zvin_() not yet supported for relationships.  For a simple many-to-one, use in_() against the set of foreign key values.)NotImplementedErrorr   s     r-   in_z#RelationshipProperty.Comparator.in_  s    
 &1 r.   c                    t        |t        j                  t        j                  f      rc| j
                  j                  t        t        fv r| j                          S t        | j
                  j                  d| j                              S | j
                  j                  rt        j                  d      t        | j
                  j                  || j                              S )a  Implement the ``==`` operator.

            In a many-to-one context, such as::

              MyClass.some_prop == <some object>

            this will typically produce a
            clause such as::

              mytable.related_id == <some id>

            Where ``<some id>`` is the primary key of the given
            object.

            The ``==`` operator provides partial functionality for non-
            many-to-one comparisons:

            * Comparisons against collections are not supported.
              Use :meth:`~.RelationshipProperty.Comparator.contains`.
            * Compared to a scalar one-to-many, will produce a
              clause that compares the target columns in the parent to
              the given target.
            * Compared to a scalar many-to-many, an alias
              of the association table will be rendered as
              well, forming a natural join that is part of the
              main body of the query. This will not work for
              queries that go beyond simple AND conjunctions of
              comparisons, such as those which use OR. Use
              explicit joins, outerjoins, or
              :meth:`~.RelationshipProperty.Comparator.has` for
              more comprehensive non-many-to-one scalar
              membership tests.
            * Comparisons against ``None`` given in a one-to-many
              or many-to-many context produce a NOT EXISTS clause.

            Nadapt_source]Can't compare a collection to an object or collection; use contains() to test for membership.)
isinstancer   NoneTyper   Nullr   rG   r   r	   _criterion_existsr   _optimized_compareadapterrA   rJ   InvalidRequestErrorr   s     r-   __eq__z&RelationshipProperty.Comparator.__eq__  s    J %$--!AB==**y*.EE 22444(88 t|| 9  
 &&00= 
 %MM44DLL 5  r.   c                 8   t        | dd       rzt        | j                        }|j                  |j                  |j
                  }}}| j                  j                  r|s|j                         }|j                  }||||z  }n|}nd}d }| j                  r| j                         }nd }| j                  j                  ||      \  }	}
}}}}|D ]<  }t        | j                  j                  j                  |      ||   k(  }||}8||z  }> |
t        |	      |
z  }n!t        |	| j                  j                        }||r|s|j!                  |      }||j#                  ddi      }|t$        j&                  j)                  |      z  }|Ft%        j*                  d      j-                  |      j/                  ||      j1                  ||      }|S t%        j*                  d      j-                  |      j/                  |      j1                  |      }|S )Nr   F)dest_selectabler   )excludeno_replacement_traverseTr   )getattrr   r   r|   r   is_aliased_classr   _is_self_referential_anonymous_fromclause_single_table_criterionr   r   r   ry   r   rP   traverse	_annotater   True__ifnoneexistswhereselect_fromcorrelate_except)rk   	criterionkwargsr`   target_mapperto_selectabler   single_critr   r   r   r   r   rC   r   rt   critjexs                      r-   r   z1RelationshipProperty.Comparator._criterion_exists$  s'   tZ.t}}-KKOO)) /?}
 ==55>N$1$G$G$IM+CC* ,$/)$;	$/	#(  $||$($;$;$=!$(! ++ -"3 ,   1t}}33::A>&)K$ $I )D 0I1 ~!"%*!"dmm.G.GH %"( +33I>	 $%//.5	 syy((33D$JJqMU4[ [y1%%dI6	  I JJqMU4[ [&%%d+	  Ir.   c                 ~    | j                   j                  st        j                  d       | j                  |fi |S )as  Produce an expression that tests a collection against
            particular criterion, using EXISTS.

            An expression like::

                session.query(MyClass).filter(
                    MyClass.somereference.any(SomeRelated.x==2)
                )


            Will produce a query like::

                SELECT * FROM my_table WHERE
                EXISTS (SELECT 1 FROM related WHERE related.my_id=my_table.id
                AND related.x=2)

            Because :meth:`~.RelationshipProperty.Comparator.any` uses
            a correlated subquery, its performance is not nearly as
            good when compared against large target tables as that of
            using a join.

            :meth:`~.RelationshipProperty.Comparator.any` is particularly
            useful for testing for empty collections::

                session.query(MyClass).filter(
                    ~MyClass.somereference.any()
                )

            will produce::

                SELECT * FROM my_table WHERE
                NOT (EXISTS (SELECT 1 FROM related WHERE
                related.my_id=my_table.id))

            :meth:`~.RelationshipProperty.Comparator.any` is only
            valid for collections, i.e. a :func:`_orm.relationship`
            that has ``uselist=True``.  For scalar references,
            use :meth:`~.RelationshipProperty.Comparator.has`.

            z9'any()' not implemented for scalar attributes. Use has().r   rA   rJ   r   r   rk   r   r   s      r-   anyz#RelationshipProperty.Comparator.any}  sD    R ==((00- 
 *4)))>v>>r.   c                 ~    | j                   j                  rt        j                  d       | j                  |fi |S )a  Produce an expression that tests a scalar reference against
            particular criterion, using EXISTS.

            An expression like::

                session.query(MyClass).filter(
                    MyClass.somereference.has(SomeRelated.x==2)
                )


            Will produce a query like::

                SELECT * FROM my_table WHERE
                EXISTS (SELECT 1 FROM related WHERE
                related.id==my_table.related_id AND related.x=2)

            Because :meth:`~.RelationshipProperty.Comparator.has` uses
            a correlated subquery, its performance is not nearly as
            good when compared against large target tables as that of
            using a join.

            :meth:`~.RelationshipProperty.Comparator.has` is only
            valid for scalar references, i.e. a :func:`_orm.relationship`
            that has ``uselist=False``.  For collection references,
            use :meth:`~.RelationshipProperty.Comparator.any`.

            z4'has()' not implemented for collections.  Use any().r   r   s      r-   hasz#RelationshipProperty.Comparator.has  sA    8 }}$$00M  *4)))>v>>r.   c                    | j                   j                  st        j                  d      | j                   j	                  || j
                        }| j                   j                  | j                  |      |_        |S )a	  Return a simple expression that tests a collection for
            containment of a particular item.

            :meth:`~.RelationshipProperty.Comparator.contains` is
            only valid for a collection, i.e. a
            :func:`_orm.relationship` that implements
            one-to-many or many-to-many with ``uselist=True``.

            When used in a simple one-to-many context, an
            expression like::

                MyClass.contains(other)

            Produces a clause like::

                mytable.id == <some id>

            Where ``<some id>`` is the value of the foreign key
            attribute on ``other`` which refers to the primary
            key of its parent object. From this it follows that
            :meth:`~.RelationshipProperty.Comparator.contains` is
            very useful when used with simple one-to-many
            operations.

            For many-to-many operations, the behavior of
            :meth:`~.RelationshipProperty.Comparator.contains`
            has more caveats. The association table will be
            rendered in the statement, producing an "implicit"
            join, that is, includes multiple tables in the FROM
            clause which are equated in the WHERE clause::

                query(MyClass).filter(MyClass.contains(other))

            Produces a query like::

                SELECT * FROM my_table, my_association_table AS
                my_association_table_1 WHERE
                my_table.id = my_association_table_1.parent_id
                AND my_association_table_1.child_id = <some id>

            Where ``<some id>`` would be the primary key of
            ``other``. From the above, it is clear that
            :meth:`~.RelationshipProperty.Comparator.contains`
            will **not** work with many-to-many collections when
            used in queries that move beyond simple AND
            conjunctions, such as multiple
            :meth:`~.RelationshipProperty.Comparator.contains`
            expressions joined by OR. In such cases subqueries or
            explicit "outer joins" will need to be used instead.
            See :meth:`~.RelationshipProperty.Comparator.any` for
            a less-performant alternative using EXISTS, or refer
            to :meth:`_query.Query.outerjoin`
            as well as :ref:`orm_queryguide_joins`
            for more details on constructing outer joins.

            kwargs may be ignored by this operator but are required for API
            conformance.
            z9'contains' not implemented for scalar attributes.  Use ==r   )	r   rA   rJ   r   r   r   rE   '_Comparator__negated_contains_or_equalsnegation_clause)rk   r   r   clauses       r-   containsz(RelationshipProperty.Comparator.contains  s}    v ==((00*  ]]55DLL 6 F }}**6)-)J)J*& Mr.   c                      j                   j                  t        k(  rt        j                  |      } fd} fd} j                   j
                  rmt        j                   j                   j                  D cg c];  \  }}t        j                   ||       | ||      ||      k7   ||      d k(        = c}} S t        j                  t         j                   j                  j                   j                   j                  j                  |            D cg c]
  \  }}||k(   c}} } j                  |       S c c}}w c c}}w )Nc                     |j                   }t        j                  | j                  | j                  dj
                  j                  j
                  j                  |||            S )NT)type_unique	callable_)dictr   	bindparamrz   typer   _get_attr_w_warn_on_noner|   )	local_colstate
remote_coldict_rk   s       r-   state_bindparamzURelationshipProperty.Comparator.__negated_contains_or_equals.<locals>.state_bindparam  sS    !JJE==!'nn#"&--"H"H MM00%
#	 r.   c                 B    j                   rj                  |       S | S r   )r   colrk   s    r-   adaptzKRelationshipProperty.Comparator.__negated_contains_or_equals.<locals>.adapt*  s    ||#||C00"
r.   )r   rG   r
   r   instance_state_use_getr   r   rY   or_zipr|   primary_keyprimary_key_from_instancer   )rk   r   r   r   r   xyr   s   `       r-   __negated_contains_or_equalsz<RelationshipProperty.Comparator.__negated_contains_or_equals  s)   }}&&)3"11%8	# ==))88 +/--*J*J !'A  GG %a#258UA#F!G %aD 0	 	  #&,,88,,FFuM#A FI **9555)s   <A E
 E
c                    t        |t        j                  t        j                  f      r^| j
                  j                  t        k(  r1t        | j
                  j                  d| j                               S | j                         S | j
                  j                  rt        j                  d      t        | j                  |            S )a"  Implement the ``!=`` operator.

            In a many-to-one context, such as::

              MyClass.some_prop != <some object>

            This will typically produce a clause such as::

              mytable.related_id != <some id>

            Where ``<some id>`` is the primary key of the
            given object.

            The ``!=`` operator provides partial functionality for non-
            many-to-one comparisons:

            * Comparisons against collections are not supported.
              Use
              :meth:`~.RelationshipProperty.Comparator.contains`
              in conjunction with :func:`_expression.not_`.
            * Compared to a scalar one-to-many, will produce a
              clause that compares the target columns in the parent to
              the given target.
            * Compared to a scalar many-to-many, an alias
              of the association table will be rendered as
              well, forming a natural join that is part of the
              main body of the query. This will not work for
              queries that go beyond simple AND conjunctions of
              comparisons, such as those which use OR. Use
              explicit joins, outerjoins, or
              :meth:`~.RelationshipProperty.Comparator.has` in
              conjunction with :func:`_expression.not_` for
              more comprehensive non-many-to-one scalar
              membership tests.
            * Comparisons against ``None`` given in a one-to-many
              or many-to-many context produce an EXISTS clause.

            Nr   r   )r   r   r   r   r   r   rG   r
   r   r   r   r   rA   rJ   r   r   r   s     r-   __ne__z&RelationshipProperty.Comparator.__ne__H  s    N %$--!AB==**i7(99 t|| :     1133&&009  %T%F%Fu%MNNr.   c                 b    | j                   j                  j                          | j                   S r   )r   r   _check_configurer   s    r-   r   z(RelationshipProperty.Comparator.property  s"    II--/99r.   )NNr=   r   )__name__
__module____qualname____doc__r   r   r@   r   r   memoized_propertyr   r|   r   r   r   r   r   r   __hash__r   r   r   r   r   r   r   r   r=   r.   r-   r\   r   G  s    	(  !	2&	 
			, 
 	,& 
			( 
 	( 
			( 
 	(	I	4		 
	 8	tW	r/	?b 	?DI	V+	6Z8	Ot 
			 
 	r.   r\   c                     |J d }|-t        |      }|j                  r|j                  j                  }| j	                  |d||      S )NT)value_is_parentr   r   )r   r   _adapteradapt_clauser   )rk   instancer   from_entityr   insps         r-   _with_parentz!RelationshipProperty._with_parent  s_    ###";'D$$#}}99&& %+	 ' 
 	
r.   c                    	
 3	 t              t        dd      st        j                  d z        | } j                  ||      S |s. j                  j                   j                  j                  c}n- j                  j                   j                  j                  c}|r j                  
n j                  
t        j                  j                               		
 fd} j                   4|r2t#         j                   j%                               j'                  |      }t)        j*                  |i d|i      }|r ||      }|S # t        j                  $ r d Y `w xY w)Nis_instanceFzMapped instance expected for relationship comparison to object.   Classes, queries and other SQL elements are not accepted in this context; for comparison with a subquery, use %s.has(**criteria).r   c                 p    | j                   v r'j                  | j                            | _        y y r   )_identifying_keyr   callable)r   bind_to_colr   r|   rk   r   s    r-   visit_bindparamz@RelationshipProperty._optimized_compare.<locals>.visit_bindparam  s@    ))[8%)%B%B	 : :;	&	" 9r.   r   )r   rJ   NoInspectionAvailabler   rK   _lazy_none_clause_lazy_strategy
_lazywhere_bind_to_col_rev_lazywhere_rev_bind_to_colr|   r   r   instance_dictobjrC   r    r   r   r   cloned_traverse)rk   r   r  r   r   reverse_directionr   r  r  r   r|   s   ``      @@@r-   r   z'RelationshipProperty._optimized_compare  s     }GE=%$H**. 15	5  !0/=))! *   !##..##00 #I{ ##22##44 #I{
 [[F[[F((5	 	 >>%/%446hy!  ,,rK9
	 $Y/Iq // s   E E54E5c                 z    j                        j                  j                         fd}|S )aK  Create the callable that is used in a many-to-one expression.

        E.g.::

            u1 = s.query(User).get(5)

            expr = Address.user == u1

        Above, the SQL should be "address.user_id = 5". The callable
        returned by this method produces the value "5" based on the identity
        of ``u1``.

        c                     j                   j                     x} }| t        j                  u}j	                  j
                  rt        j                  n t        j                  t        j                  z        }|t        j                  u r'|s`t        j                  ddt              d      |t        j                  u r'|s't        j                  ddt              d      |}|t        j                  dz         |S )NpassivezCan't resolve value for column z on object z'; no value has been set for this columnz2; the object is detached and the value was expiredzGot None for value of column %s; this is unsupported for a relationship comparison and will not currently produce an IS comparison (but may in a future release))_last_known_valuesrz   r   NO_VALUE_get_state_attr_by_column
persistentPASSIVE_OFFPASSIVE_NO_FETCHINIT_OK	NEVER_SETrJ   r   r   PASSIVE_NO_RESULTr   rW   )	
last_known	to_returnexisting_is_availablecurrent_valuecolumnr   r|   r   r   s	       r-   _goz:RelationshipProperty._get_attr_w_warn_on_none.<locals>._go  s   %*%=%=dhh%GGJ$.j6I6I$I! #<<## #..00:3E3EE = M 
 4 44, 44 "9U#35 
 *">">>, 44 &,Yu-=?  *	 		4 7== r.   )get_property_by_column_track_last_known_valuerz   )rk   r|   r   r   r.  r/  r   s    ```` @r-   r   z-RelationshipProperty._get_attr_w_warn_on_none  s<    V ,,V4
 	%%dhh/(	 (	T 
r.   c                     |s-| j                   j                  | j                   j                  }}n,| j                   j                  | j                   j                  }}t        ||      }|r ||      }|S r   )r  r  r  r  r  r   )rk   r  r   r   r  s        r-   r  z&RelationshipProperty._lazy_none_clause7  sr     ##..##00 #I ##22##44 #I
 ,I{C	$Y/Ir.   c                 t    t        | j                  j                  j                        dz   | j                  z   S )N.)strr   ry   r   rz   r   s    r-   __str__zRelationshipProperty.__str__I  s+    4;;%%../#5@@r.   c	                 b   |r| j                   D ]
  }	||	f|v s
 y  d| j                  vry | j                  |vry | j                  rO|j	                  | j                        }
|
j                  ||      }|
j                  r|j                  rJ 	 |r1|j	                  | j                        j                  ||t               g }|D ]]  }t        j                  |      }t        j                  |      }d||| f<   |j                  |||||      }|M|j                  |       _ |s:t        j                  ||| j                        }|D ]  }|j!                  |        y |j	                  | j                        j#                  |||dt               y || j                     }|Ht        j                  |      }t        j                  |      }d||| f<   |j                  |||||      }nd }|s||| j                  <   y |j	                  | j                        j#                  |||d        y )Nr>   Tr  )load
_recursive_resolve_conflict_mapF)_adaptr   )rc   _cascaderz   rA   get_implget_collection
collectionemptygetr   r   r   r  _mergeappendinit_state_collectionappend_without_eventrb   )rk   sessionsource_statesource_dict
dest_state	dest_dictr8  r9  r:  rimplinstances_iterable	dest_listcurrentcurrent_statecurrent_dictr  collcs                      r-   r>   zRelationshipProperty.mergeL  sU    ++  !$
2 $--'88;&<<((2D!%!4!4\;!O
 48??)//LL ##DHH-11	= 2  I- * * 9 9' B)77@48
M401nn! )*? %  ?$$S)* !77	488 # 1A--a01 ##DHH-11 ) 2  "$((+G" * 9 9' B)77@48
M401nn! )*? %  &)	$((###DHH-11	3r.   c                 J   |j                   |   j                  }|j                  |||      }|t        j                  u s|g S t        |d      r8|j                  ||||      D cg c]  }t        j                  |      |f c}S t        j                  |      |fgS c c}w )zReturn a list of tuples (state, obj) for the given
        key.

        returns an empty list if the value is None/empty/PASSIVE_NO_RESULT
        r  r>  )managerrL  rA  r   r)  hasattrr>  r   )rk   r   r   rz   r   rL  r   os           r-   _value_as_iterablez'RelationshipProperty._value_as_iterable  s     }}S!&&HHUE7H3
,,,	IT+, ,,UE1g,N **1-q1 
  ..q11566s   'B c           
   #     K   |dk7  s| j                   rt        j                  }nt        j                  }|dk(  r4|j                  | j
                     j                  j                  ||      }n| j                  ||| j
                  |      }|dk(  xr d| j                  v}|D ]  \  }	}
|	|v r|
t        j                  |
      }|r	 ||	      r.|r|	j
                  s=|	j                  j                  }|j                  | j                  j                  j                        s=t        d| j
                  d| j                  j                   d|
j"                  d	      |j%                  |	       |
||	|f  y w)
Ndeletezsave-updater  zrefresh-expiredelete-orphanzAttribute 'z' on class 'z"' doesn't handle objects of type '')r5   r   PASSIVE_NO_INITIALIZEr%  rU  rz   rL  get_all_pendingrX  r<  r  r|   isaclass_managerAssertionErrorr   ry   ro   add)rk   r   r   r   visited_stateshalt_onr   tuplesskip_pendingr   rS  r  instance_mappers                r-   cascade_iteratorz%RelationshipProperty.cascade_iterator  sq     H 4 4 66G ,,GM!]]488,11AA%OF ,,udhh - F
 %%N/*N 	 "( 	DNA/y
 &44Q7M7>2N$6$6,44;;O"&&t{{'@'@'G'GH$ xx!3!3Q[[B  ~._nmCC?	Ds   E=E?c                 8    | j                   ry| j                  duS )NF)rH   rL   r   s    r-   _effective_sync_backrefz,RelationshipProperty._effective_sync_backref  s    ==$$E11r.   c                     | j                   r(|j                  rt        j                  d|d| d      | j                   r$|j                   s|j                  durd|_        y y y y )NRelationship z( cannot specify sync_backref=True since z includes viewonly=True.F)rH   rL   rJ   r   )rel_arel_bs     r-   _check_sync_backrefz(RelationshipProperty._check_sync_backref  sc    >>e00,,-2E; 
 NNNN""%/!&E 0 # r.   c           
         | j                   j                  |d      }t        |t              st	        j
                  d| d|d      | j                  | |       | j                  ||        | j                  j                  |       |j                  j                  |        |j                   j                  | j                        s+t	        j                  d|d| d|d	| j                        | j                  t        t        fv rB| j                  |j                  k(  r(t	        j                  |d
| d| j                  d      y y )NF)_configure_mappersz back_populates on relationship 'z' refers to attribute 'z{' that is not a relationship.  The back_populates parameter should refer to the name of a relationship on the target class.zreverse_property z on relationship z references relationship z", which does not reference mapper z and back-reference z  are both of the same direction z<.  Did you mean to set remote_side on the many-to-one side ?)r|   get_propertyr   r2   rJ   r   ro  rc   rb  common_parentr   rK   rG   r   r
   )rk   rz   r   s      r-   _add_reverse_propertyz*RelationshipProperty._add_reverse_property  s    (((G%!56,, !%)  	  u- 	  -""5)##D)||))$++6&& eT[[2  NNy)44%//1&& $0  2 5r.   zsqlalchemy.orm.mapperc                 z   t         j                  j                  }t        | j                  t         j
                        r! | j                  | j                               }nXt        | j                        r7t        | j                  t        |j                  f      s| j	                         }n| j                  }t        |t              r|j                  |d      S 	 t        |      }t        |d      r|S t        j                  d| j                   dt        |      d      # t        j                  $ r Y Dw xY w)zReturn the target mapped entity, which is an inspect() of the
        class or aliased class that is referred towards.

        F	configurer|   relationship 'z2' expects a class or a mapper argument (received: ))r   	preloaded
orm_mapperr   rB   string_types_clsregistry_resolve_namer  r   Mapperclass_mapperr   rV  rJ   r  rK   rz   )rk   	mapperlibrB   r   s       r-   r   zRelationshipProperty.entity5  s     NN--	dmmT%6%67Dt55dmmDFHdmm$ZMMD)"2"23.
 }}H}}Hh%))(e)DD	X&F vx("" xxh)
 	
 ++ 		s   D$ $D:9D:c                 .    | j                   j                  S )zReturn the targeted :class:`_orm.Mapper` for this
        :class:`.RelationshipProperty`.

        This is a lazy-initializing static attribute.

        )r   r|   r   s    r-   r|   zRelationshipProperty.mapperZ  s     {{!!!r.   c                    | j                          | j                          | j                          | j                          | j	                  | j
                         | j                          | j                          | j                  j                          t        t        | 3          | j                  d      | _        y )N))r<   r:   )_check_conflicts_process_dependent_arguments_setup_registry_dependencies_setup_join_conditions_check_cascade_settingsr<  
_post_init_generate_backref_join_condition"_warn_for_conflicting_sync_targetsr?   r2   do_init_get_strategyr  )rk   ro   s    r-   r  zRelationshipProperty.do_initd  s    ))+))+##%$$T]]3 ??A"D13"001FGr.   c                     | j                   j                  j                  j                  | j                  j                  j                         y r   )r   r|   registry_set_depends_onr   r   s    r-   r  z1RelationshipProperty._setup_registry_dependenciesp  s3    ##33KK''	
r.   c                    dD ]y  }t        | |      }t        |t        j                        r't	        | | | j                  ||dk(                      Pt        |      s\t        |      rht	        | | |              { dD ]K  }t        | |      }|t	        | |t        t        j                  t        j                  ||                   M | j                  ;t        | j                        r&t        j                  d| j                  d| d	      | j                   d
ur@| j                   4t#        d t        j$                  | j                         D              | _        t        j&                  d t        j(                  | j*                        D              | _        t        j&                  d t        j(                  | j,                        D              | _        | j.                  j0                  | _        y)zConvert incoming configuration arguments to their
        proper form.

        Callables are resolved, ORM annotations removed.

        )rh   rD   rE   rC   rN   rP   rC   )favor_tables)rD   rE   Nargnamezsecondary argument z passed to to relationship() z must be a Table object or other FROM clause; can't send a mapped class directly as rows in 'secondary' are persisted independently of a class that is mapped to that same table.Fc              3   h   K   | ]*  }t        j                  t        j                  |d        , yw)rh   r  Nr   r)   r   r*   .0r   s     r-   	<genexpr>zDRelationshipProperty._process_dependent_arguments.<locals>.<genexpr>  s7      "    ,,a "   02c              3   h   K   | ]*  }t        j                  t        j                  |d        , yw)rl   r  Nr  r  s     r-   r  zDRelationshipProperty._process_dependent_arguments.<locals>.<genexpr>  s7      :
  ((!^ :
r  c              3   h   K   | ]*  }t        j                  t        j                  |d        , yw)rP   r  Nr  r  s     r-   r  zDRelationshipProperty._process_dependent_arguments.<locals>.<genexpr>  s7      +
  ((!] +
r  )r   r   r   r|  setattr_clsregistry_resolve_argr  r   r   r   r)   r   r*   rC   rJ   rK   rh   tupleto_list
column_setto_column_setrN   rP   r   persist_selectabletarget)rk   attr
attr_valuevals       r-   r  z1RelationshipProperty._process_dependent_argumentsu  s   
 	2D !t,J*d&7&78D11"1D 2   *%.>z.JdJL1'	2. 3 	D$%C#!((!44c4	 >>%*:4>>*J&&
 *.	?  ==%$--*C! " dmm4	" DM +/// :
 ''(G(GH	:
 +
'  ?? +
 ''(8(89	+
 
 kk44r.   c                 \   t        di d| j                  j                  d| j                  j                  d| j                  j                  d| j                  j                  d| j
                  d| j                  d| j                  d| j                  j                  d	| j                  j                  d
| j                  d| j                  d| j                  d| j                  d| d| j                   d| j                  x| _        }|j
                  | _        |j                  | _        |j"                  | _        |j                  | _        |j$                  | _        |j&                  | _        |j(                  | _        |j*                  | _        |j.                  | _        y )Nparent_persist_selectablechild_persist_selectableparent_local_selectablechild_local_selectablerD   rC   rE   parent_equivalentschild_equivalentsconsider_as_foreign_keysrY   rP   self_referentialr   support_synccan_be_synced_fnr=   )JoinConditionr   r  r   local_tablerD   rC   rE   _equivalent_columnsr|   rN   rY   rP   r   rH   _columns_are_mappedr  rG   remote_columnslocal_columnssynchronize_pairsforeign_key_columns_calculated_foreign_keyssecondary_synchronize_pairs)rk   jcs     r-   r  z+RelationshipProperty._setup_join_conditions  s   $1 %
&*kk&D&D%
%)[[%C%C%
 %)KK$;$;%
 $(;;#:#:	%

 ((%
 nn%
 ,,%
  ${{>>%
 #kk==%
 &*%D%D%
  $66%
 ((%
 "66%
 %
 "]]*%
  "55!%
 	
r$ >>--"$"7"7,,--!#!5!5(*(>(>%+-+I+I(r.   c                      | j                   d   S )Nr   _clsregistry_resolversr   s    r-   r  z-RelationshipProperty._clsregistry_resolve_arg      **1--r.   c                      | j                   d   S )Nr   r  r   s    r-   r}  z.RelationshipProperty._clsregistry_resolve_name  r  r.   zsqlalchemy.orm.clsregistryc                     t         j                  j                  j                  } || j                  j
                  |       S r   )r   rz  orm_clsregistry	_resolverr   ry   )rk   r  s     r-   r  z+RelationshipProperty._clsregistry_resolvers  s0     NN22<<	++T22r.   c           	         t         j                  j                  }| j                  j                  r|j                  | j                  j                  d      j                  | j                        set        j                  d| j                  d| j                  j                  j                  d| j                  j                  j                  d      yy)zOTest that this relationship is legal, warn about
        inheritance conflicts.Frv  z)Attempting to assign a new relationship 'z$' to a non-primary mapper on class 'zm'.  New relationships can only be added to the primary mapper, i.e. the very first mapper created for class 'z' N)r   rz  r{  r   non_primaryr  ry   has_propertyrz   rJ   rK   r   )rk   r  s     r-   r  z%RelationshipProperty._check_conflicts  s     NN--	;;""9+A+AKK% ,B ,

,txx
 ,! && HHKK&&//KK&&//	 ,!"r.   c                     | j                   S )z\Return the current cascade setting for this
        :class:`.RelationshipProperty`.
        )r<  r   s    r-   rg   zRelationshipProperty.cascade	  s    
 }}r.   c                 &    | j                  |       y r   )_set_cascaderk   rg   s     r-   rg   zRelationshipProperty.cascade	  s    '"r.   c                 n   t        |      }| j                  rZt        |      j                  t         j                        }|r0t        j                  ddj                  t        |            z        d| j                  v r| j                  |       || _        | j                  r|| j                  _        y y )NzsCascade settings "%s" apply to persistence operations and should not be combined with a viewonly=True relationship., r|   )r   rH   rb   
difference_viewonly_cascadesrJ   rK   joinsorted__dict__r  r<  _dependency_processorrg   )rk   rg   non_viewonlys      r-   r  z!RelationshipProperty._set_cascade	  s     )==w<2211L **$'+yy1E'FH  t}}$((1%%18D&&. &r.   c                 x   |j                   r| j                  s| j                  t        u s| j                  t        u rot        j                  d| | j                  t        u rdnd| j                  j                  j                  | j                  j                  j                  dz  d      | j                  dk(  r d|v sd	|v rt        j                  d
| z        |j                   rT| j                  j                         j                  j                  | j                  | j                  j                  f       y y )Na  For %(direction)s relationship %(rel)s, delete-orphan cascade is normally configured only on the "one" side of a one-to-many relationship, and not on the "many" side of a many-to-one or many-to-many relationship.  To force this relationship to allow a particular "%(relatedcls)s" object to be referred towards by only a single "%(clsname)s" object at a time via the %(rel)s relationship, which would allow delete-orphan cascade to take place in this direction, set the single_parent=True flag.zmany-to-onezmany-to-many)relrG   clsname
relatedclsbbf0codeallrZ  r[  z^On %s, can't set passive_deletes='all' in conjunction with 'delete' or 'delete-orphan' cascade)delete_orphanrM   rG   r	   r
   rJ   rK   r   ry   r   r|   r5   primary_mapper_delete_orphansrC  rz   r  s     r-   r  z,RelationshipProperty._check_cascade_settings(	  s   !!&&:-91L&&/  ~~2 "/'#{{11::"&++"4"4"="=* - 2 5(?g#=&&;=AB 
   KK&&(88??4;;--. !r.   c                 l    | j                   |j                  v xr |j                  | j                      | u S )zaReturn True if this property will persist values on behalf
        of the given mapper.

        )rz   relationshipsr{   s     r-   _persists_forz"RelationshipProperty._persists_forT	  s7     HH,,, 7$$TXX.$6	
r.   c                 $   |D ]  }| j                   &| j                   j                  j                  |      r5| j                  j                  j                  j                  |      re| j
                  j                  j                  |      r y y)zReturn True if all columns in the given collection are
        mapped by the tables referenced by this :class:`.Relationship`.

        FT)rC   rS  contains_columnr   r  r  )rk   colsrS  s      r-   r  z(RelationshipProperty._columns_are_mapped_	  sw    
  		A*NN$$44Q7;;1133CCkkmm33A6		 r.   c           
         | j                   j                  ry| j                  x| j                  skt	        | j                  t
        j                        r| j                  i }}n| j                  \  }}| j                  j                         }|j                  svt        |j                               j                  |j                        }|D ]?  }|j                  |      s|j                  r"t        j                   d|d| d|d       | j"                  M|j%                  d| j&                  j(                        }|j%                  d| j&                  j*                        }nO|j%                  d| j&                  j,                        }|j%                  dd      }|rt        j.                  d      |j%                  d	| j0                        }| j                   j                         }	|j3                  d
| j4                         |j3                  d| j6                         |j3                  d| j8                         |j3                  d| j:                         || _        t=        |	| j"                  ||f|| j>                  d|}
|jA                  ||
       | j                  r| jC                  | j                         yy)zlInterpret the 'backref' instruction to create a
        :func:`_orm.relationship` complementary to this one.NzError creating backref 'z' on relationship 'z+': property of that name exists on mapper 'r\  rD   rE   zOCan't assign 'secondaryjoin' on a backref against a non-secondary relationship.rl   rH   rF   r6   rL   )rl   ri   )"r   r  rj   ri   r   r   r|  r|   r  concreterb   iterate_to_rootunionself_and_descendantsr  rJ   rK   rC   popr  secondaryjoin_minus_localprimaryjoin_minus_localprimaryjoin_reverse_remoter   rN   
setdefaultrH   rF   r6   rL   r2   rz   _configure_propertyrt  )rk   backref_keyr   r|   checkmr   r   rl   r   r3   s              r-   r  z&RelationshipProperty._generate_backrefp	  sp    ;;""<<#D,?,?$,,(9(9:&*llBV&*ll#V[[//1F??F2245;;//  A~~k21::$22  +D!5  ~~) ZZ!((BB ZZ#((@@
 ZZ!((CC ZZ6 44@ 
 ":: ? ?L [[//1Fj$--8mT-=-=>/1E1EFnd.?.?@"-D/	
 *#xx L &&{LA&&t':':; r.   zsqlalchemy.orm.dependencyc                     t         j                  j                  }| j                  | j                  t
        u| _        | j                  s!|j                  j                  |       | _	        y y r   )
r   rz  orm_dependencyrA   rG   r
   rH   DependencyProcessorfrom_relationshipr  )rk   
dependencys     r-   r  zRelationshipProperty._post_init	  sV    ^^22
<<>>:DL}}..@@0 & r.   c                 2    | j                   }|j                  S )zPmemoize the 'use_get' attribute of this RelationshipLoader's
        lazyloader.)r  use_get)rk   strategys     r-   r   zRelationshipProperty._use_get	  s    
 &&r.   c                 L    | j                   j                  | j                        S r   )r|   rs  r   r   s    r-   r   z)RelationshipProperty._is_self_referential	  s    {{((55r.   c                    d}|r| j                   d}|.|r,| j                  j                  r| j                  j                  }|r|j                  }||j
                  }d}n| j                  }|O| j                  j
                  }| j                  j                  rd}| j                  rE|C|j                         }d}n0|| j                  j                  us| j                  j                  rd}|j                  }	|xs, |d uxr& || j                  j                  uxs |j                  }| j                  j                  ||||	|      \  }
}}}}|| j                  j                  }|| j                  j                  }|
|||||fS )NFT)rC   r   with_polymorphicr   r|   r   r   r   r   r   _is_subqueryr  join_targetsr  )rk   r   r   r   r   r   r   aliaseddest_mapperr   rD   rE   rC   r   s                 r-   r   z"RelationshipProperty._create_joins	  s    t~~9G$!dkk&B&B$(KK$L$L!(//K&"0";";++K""kk44O{{++((->-F"1"G"G"I4;;#K#KK{{++G!99 
T) !{{??@ 2$11 	   --
	
 $ $ 7 7""kk55O
 	
r.   )TN)FNT)FNr   )FNNNFr=   )7r   r   r   r   strategy_wildcard_keyinherit_cache_links_to_entityr   rr   r  r@   rI   r}   r   r\   r
  r   r   r  r6  r>   r   r%  rX  rh  r   rj  staticmethodro  rt  r   r  preload_moduler   r|   r  r  r  r  r  r}  r  r  rg   setterr  r  r  r  r  r  r   r   r   __classcell__)ro   s   @r-   r2   r2   ]   s   	 +M !
 )*;<)*;<+,?@ ()9:*+=> ',Iq#f$
~^ ~@
" BH\|$A\~ *4)?)?7, <@6Dp 2 2 ' ''R 
T01!
 2 !
F 
" "
H

P5dJ: . . . . 
T563 7 3
 T01 2(   ^^# #9**X	
"K<Z T45 6 
    
6 6
 !K
r.   r2   c                 .    fd|  |       } d | S )Nc                     t        | t        j                        r| j                  j	                               } | j                         | S )N)clone)r   r   ColumnClauser   copy_copy_internals)elemannotationsr  s    r-   r  z _annotate_columns.<locals>.clone#
  s@    dJ334>>+"2"2"45D5)r.   r=   )elementr  r  s    `@r-   r(   r(   "
  s#     .ENr.   c                      e Zd Zdddddddddddd fdZd Zd Zd Zed	        Zed
        Z	e
j                  d        Zd Ze
j                  d        Ze
j                  d        Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Z d  Z!d! Z" e#jH                         Z%d" Z&e
j                  d#        Z'e
j                  d$        Z(e
j                  d%        Z)d& Z*d' Z+	 	 d*d(Z,d+d)Z-y),r  NFTc                       y)NTr=   )rS  s    r-   <lambda>zJoinCondition.<lambda>A
  s    r.   c                    || _         || _        || _        || _        || _        |	| _        || _        || _        || _        |
| _	        || _
        || _        || _        || _        || _        || _        | j!                          | j#                          | j%                          | j'                          | j)                          | j+                          | j-                          | j/                  | j                  d       | j                  | j/                  | j                  d       | j1                          | j3                          | j5                          y NTF)r  r  r  r  r  r  rD   rE   rC   r  rn   _remote_sider   r  r  r  _determine_joins_sanitize_joins_annotate_fks_annotate_remote_annotate_local_annotate_parentmapper_setup_pairs_check_foreign_cols_determine_direction_check_remote_side
_log_joins)rk   r  r  r  r  rD   rC   rE   r  r  r  rY   rP   r  r   r  r  s                    r-   r@   zJoinCondition.__init__0
  s1   & *C&'>$(@%&<#"4!2&*"(@%#5 '	 0( 0##%  !1!148)$$T%7%7?!!#!r.   c           	         | j                   y | j                   j                  } |j                  d| j                   | j                          |j                  d| j                   | j                          |j                  d| j                   dj                  d | j                  D                      |j                  d| j                   dj                  d | j                  xs g D                      |j                  d| j                   dj                  d	 | j                  D                      |j                  d
| j                   dj                  d | j                  D                      |j                  d| j                   dj                  d | j                  D                      |j                  d| j                   | j                         y )Nz%s setup primary join %sz%s setup secondary join %sz%s synchronize pairs [%s],c              3   4   K   | ]  \  }}d |d|d  yw(z => ry  Nr=   r  lrK  s      r-   r  z+JoinCondition._log_joins.<locals>.<genexpr>j
  s      *01a1%   z#%s secondary synchronize pairs [%s]c              3   4   K   | ]  \  }}d |d|d  ywr(  r=   r*  s      r-   r  z+JoinCondition._log_joins.<locals>.<genexpr>q
  s!      Q !"1%r,  z%s local/remote pairs [%s]c              3   4   K   | ]  \  }}d |d|d  yw)r)  z / ry  Nr=   r*  s      r-   r  z+JoinCondition._log_joins.<locals>.<genexpr>y
  s      )/!Qq!$r,  z%s remote columns [%s]c              3   &   K   | ]	  }d |z    ywz%sNr=   r  r   s     r-   r  z+JoinCondition._log_joins.<locals>.<genexpr>
  s     ?CTCZ?   z%s local columns [%s]c              3   &   K   | ]	  }d |z    ywr0  r=   r1  s     r-   r  z+JoinCondition._log_joins.<locals>.<genexpr>
  s     >CTCZ>r2  z%s relationship direction %s)r   loggerr`   rD   rE   r  r  r  rY   r  r  rG   )rk   r   s     r-   r$  zJoinCondition._log_joinsa
  s   99ii+TYY8H8HI-tyy$:L:LM'IIHH 484J4J 	
 	1IIHH ">>D" 	
 	(IIHH 373J3J 	
 	$IIHH?4+>+>??	

 	#IIHH>4+=+=>>	

 	/DNNKr.   c                     t        | j                  d      | _        | j                  t        | j                  d      | _        yy)ab  remove the parententity annotation from our join conditions which
        can leak in here based on some declarative patterns and maybe others.

        We'd want to remove "parentmapper" also, but apparently there's
        an exotic use case in _join_fixture_inh_selfref_w_entity
        that relies upon it being present, see :ticket:`3364`.

        )rw   	proxy_keyvaluesN)r   rD   rE   r   s    r-   r  zJoinCondition._sanitize_joins
  sI     ,%B
 )!1""+H"D *r.   c           
         | j                   .| j                  "t        j                  d| j                  z        	 | j
                  xs d}| j                  }| j                   2t        | j                  | j                  | j                  |      | _         | j                  st        | j                  | j                  | j                  |      | _	        y| j                  3t        | j                  | j                  | j                  |      | _	        yyy# t        j                  $ r}| j                  Ft        j                  t        j                  d| j                  d| j                  d      |       n<t        j                  t        j                  d| j                  z        |       Y d}~yY d}~yd}~wt        j                  $ r}| j                  Ft        j                  t        j                  d| j                  d	| j                  d
      |       n<t        j                  t        j                  d| j                  z        |       Y d}~yY d}~yd}~ww xY w)zDetermine the 'primaryjoin' and 'secondaryjoin' attributes,
        if not passed to the constructor already.

        This is based on analysis of the foreign key relationships
        between the parent and target mapped selectables.

        NzMProperty %s specified with secondary join condition but no secondary argument)a_subsetr  zOCould not determine join condition between parent/child tables on relationship zG - there are no foreign keys linking these tables via secondary table 'z'.  Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify 'primaryjoin' and 'secondaryjoin' expressions.)from_a  Could not determine join condition between parent/child tables on relationship %s - there are no foreign keys linking these tables.  Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.zP - there are multiple foreign key paths linking the tables via secondary table 'z'.  Specify the 'foreign_keys' argument, providing a list of those columns which should be counted as containing a foreign key reference from the secondary table to each of the parent and child tables.a'  Could not determine join condition between parent/child tables on relationship %s - there are multiple foreign key paths linking the tables.  Specify the 'foreign_keys' argument, providing a list of those columns which should be counted as containing a foreign key reference to the parent table.)rE   rC   rJ   rK   r   r  r!   r  r  rD   r  r  NoForeignKeysErrorr   raise_AmbiguousForeignKeysError)rk   r  nfeafes       r-   r  zJoinCondition._determine_joins
  s1    )dnn.D&&(*.))4 S	'+'D'D'L$~~)%%-)755!%!<!<1I	*D& ##+'566!%!=!=1I	(D$ ##+'56655!%!=!=1I	(D$ , , (( 	~~)-- +/))T^^E	  --> AE		J  4 // 	~~)44  99dnn	6   44E ))$	  !	s,   BD >D I*)B	F<<I*B	I%%I*c                 0    t        | j                  d      S Nlocalr&   r7  )r   rD   r   s    r-   r  z%JoinCondition.primaryjoin_minus_local  s     0 09LMMr.   c                 0    t        | j                  d      S rB  )r   rE   r   s    r-   r  z'JoinCondition.secondaryjoin_minus_local  s     2 2;NOOr.   c                     | j                   r$d }t        j                  | j                  i |      S | j                  rt        | j                  d      S t        | j                        S )a(  Return the primaryjoin condition suitable for the
        "reverse" direction.

        If the primaryjoin was delivered here with pre-existing
        "remote" annotations, the local/remote annotations
        are reversed.  Otherwise, the local/remote annotations
        are removed.

        c                     d| j                   v r.t        | j                         }|d= d|d<   | j                  |      S d| j                   v r.t        | j                         }|d= d|d<   | j                  |      S y )Nr&   TrD  )_annotationsr   _with_annotations)r  ru   s     r-   replacez9JoinCondition.primaryjoin_reverse_remote.<locals>.replace  s    w333W112A(!%AgJ"44Q77 4 44W112A'
"&AhK"44Q77	 5r.   rC  r7  )_has_remote_annotationsr   replacement_traverserD   _has_foreign_annotationsr   )rk   rJ  s     r-   r  z(JoinCondition.primaryjoin_reverse_remote  sd     ''
8 001A1A2wOO,,'$$-@  ((8(899r.   c                 Z    t        j                  |i       D ]  }||j                  v s y yr  )r   iteraterH  rk   r   
annotationr   s       r-   _has_annotationzJoinCondition._has_annotation/  s4    ##FB/ 	CS---	 r.   c                 :    | j                  | j                  d      S Nr0   rR  rD   r   s    r-   rM  z&JoinCondition._has_foreign_annotations6  s    ##D$4$4i@@r.   c                 :    | j                  | j                  d      S Nr&   rU  r   s    r-   rK  z%JoinCondition._has_remote_annotations:  s    ##D$4$4h??r.   c                 x    | j                   ry| j                  r| j                          y| j                          y)zAnnotate the primaryjoin and secondaryjoin
        structures with 'foreign' annotations marking columns
        considered as foreign.

        N)rM  r  _annotate_from_fk_list_annotate_present_fksr   s    r-   r  zJoinCondition._annotate_fks>  s1     (((('')&&(r.   c                       fd}t        j                   j                  i |       _         j                  't        j                   j                  i |       _        y y )Nc                 H    | j                   v r| j                  ddi      S y Nr0   T)r  r   r   s    r-   check_fkz6JoinCondition._annotate_from_fk_list.<locals>.check_fkM  s*    d333}}i%677 4r.   r   rL  rD   rE   )rk   r^  s   ` r-   rY  z$JoinCondition._annotate_from_fk_listL  s]    	8 $88b(
 )!)!>!>""B"D *r.   c                 V   | j                   *t        j                  | j                   j                        n
t	               fdfd}t        j                  | j                  i d|i      | _        | j                  )t        j                  | j                  i d|i      | _        y y )Nc                     t        | t        j                        r@t        |t        j                        r&| j                  |      r| S |j                  |       r|S r| v r|vr| S |v r| vr|S y y y r   )r   r   Column
references)absecondarycolss     r-   
is_foreignz7JoinCondition._annotate_present_fks.<locals>.is_foreign_  sw    !V]]+
1fmm0L<<?H\\!_H%!=*@H-'A],BH -C' r.   c                 4   t        | j                  t        j                        r$t        | j                  t        j                        sy d| j                  j
                  vrd| j                  j
                  vr | j                  | j                        }|}|j                  | j                        r#| j                  j                  ddi      | _        y |j                  | j                        r#| j                  j                  ddi      | _        y y y y y r]  )r   leftr   ColumnElementrightrH  comparer   )binaryr   rg  s     r-   visit_binaryz9JoinCondition._annotate_present_fks.<locals>.visit_binaryl  s    S..c.?.?@ !9!99V\\%>%>> fll;?{{6;;/&,kk&;&;Y<M&NV\\2'-||'='=&-( 3 # ? :r.   rm  )	rC   r   r  rS  rb   r   r  rD   rE   )rk   rn  rg  rf  s     @@r-   rZ  z#JoinCondition._annotate_present_fksY  s    >>% OODNN,<,<=MEM		& $33b8\":
 )!)!9!9""B<(@"D *r.   c                     | j                   | j                  dgfd}t        j                  | j                  i d|i       d   S )zvReturn True if the join condition contains column
        comparisons where both columns are in both tables.

        Fc                    | j                   | j                  }}t        |t        j                        rt        |t        j                        rvj                  |j                        rZj                  |j                        r>j                  |j                        r"j                  |j                        rdd<   y y y y y y y )NTr   )ri  rk  r   r   r  is_derived_fromtable)rm  rS  fmtptresults      r-   rn  z;JoinCondition._refers_to_parent_table.<locals>.visit_binary  s    ;;qA1j556q*"9"9:&&qww/&&qww/&&qww/&&qww/ q	 0 0 0 0 ; 7r.   rm  r   )r  r  r   r   rD   )rk   rn  rt  ru  rv  s     @@@r-   _refers_to_parent_tablez%JoinCondition._refers_to_parent_table  sP    
 ++**
	! 	$**B<0HIayr.   c                 B    t        | j                  | j                        S )z5Return True if parent/child tables have some overlap.)r"   r  r  r   s    r-   _tables_overlapzJoinCondition._tables_overlap  s"     #**D,I,I
 	
r.   c                 T   | j                   ry| j                  | j                          y| j                  s| j                  r| j                          y| j                         r| j                  d d       y| j                         r| j                          y| j                          y)zAnnotate the primaryjoin and secondaryjoin
        structures with 'remote' annotations marking columns
        considered as part of the 'remote' side.

        Nc                     d| j                   v S rT  )rH  )r   s    r-   r  z0JoinCondition._annotate_remote.<locals>.<lambda>  s    I)9)99 r.   F)rK  rC   _annotate_remote_secondaryrn   r  _annotate_remote_from_argsrw  _annotate_selfrefry  _annotate_remote_with_overlap%_annotate_remote_distinct_selectablesr   s    r-   r  zJoinCondition._annotate_remote  s     ''>>%++-%%):):++-))+""95 !!#..0668r.   c                       fd}t        j                   j                  i |       _        t        j                   j                  i |       _        y)z^annotate 'remote' in primaryjoin, secondaryjoin
        when 'secondary' is present.

        c                 v    j                   j                  j                  |       r| j                  ddi      S y Nr&   T)rC   rS  r  r   r  rk   s    r-   replz6JoinCondition._annotate_remote_secondary.<locals>.repl  s6    ~~//8(((D)9:: 9r.   Nr_  rk   r  s   ` r-   r|  z(JoinCondition._annotate_remote_secondary  sL    	; $88b$
 &::D
r.   c                 h      fd}t        j                   j                  i d|i       _        y)zxannotate 'remote' in primaryjoin, secondaryjoin
        when the relationship is detected as self-referential.

        c                    | j                   j                  | j                        }t        | j                   t        j
                        rt        | j                  t        j
                        rm | j                         r"| j                   j                  ddi      | _          | j                        r&|s#| j                  j                  ddi      | _        y y y sj                          y y r  )ri  rl  rk  r   r   r  r   _warn_non_column_elements)rm  equatedfnremote_side_givenrk   s     r-   rn  z5JoinCondition._annotate_selfref.<locals>.visit_binary  s    kk))&,,7G&++z'>'>?Jj55E fkk?"(++"7"748H"IFKfll#G#)<<#9#98T:J#KFL -4#&..0 'r.   rm  N)r   r  rD   )rk   r  r  rn  s   ``` r-   r~  zJoinCondition._annotate_selfref  s/    	1 $33b8\":
r.   c                 f   | j                   rA| j                  rt        j                  d      | j                   D cg c]  \  }}|	 c}}n| j                  | j	                         r| j                  fdd       yfd}t        j                  | j                  i |      | _        yc c}}w )zannotate 'remote' in primaryjoin, secondaryjoin
        when the 'remote_side' or '_local_remote_pairs'
        arguments are used.

        zTremote_side argument is redundant against more detailed _local_remote_side argument.c                     | v S r   r=   )r   rP   s    r-   r  z:JoinCondition._annotate_remote_from_args.<locals>.<lambda>  s    sk/A r.   Tc                 F    | t              v r| j                  ddi      S y r  )rb   r   )r  rP   s    r-   r  z6JoinCondition._annotate_remote_from_args.<locals>.repl  s-     c+..",,h-=>> /r.   N)	rn   r  rJ   rK   rw  r~  r   rL  rD   )rk   r+  rK  r  rP   s       @r-   r}  z(JoinCondition._annotate_remote_from_args  s     ##  **   ,0+C+CD!Q1DK++K'')""#A4H?  (<<  "d D Es   B-c                      fd} j                   duxr,  j                   j                   j                   j                  u fdt        j                   j
                  i d|i       _        y)zannotate 'remote' in primaryjoin, secondaryjoin
        when the parent/child tables have some set of
        tables in common, though is not a fully self-referential
        relationship.

        c                      | j                   | j                        \  | _         | _         | j                  | j                         \  | _        | _         y r   )ri  rk  )rm  proc_left_rights    r-   rn  zAJoinCondition._annotate_remote_with_overlap.<locals>.visit_binary  sE    (7V\\)%FK )8fkk)%FL&+r.   Nc                 ~   t        | t        j                        r{t        |t        j                        raj                  j                  j                  |      r8j                  j                  j                  |       r|j                  ddi      }| |fS rH|j                  j                  d      j                  j                  u r|j                  ddi      }| |fS rH| j                  j                  d      j                  j                  u r| j                  ddi      } | |fS j                          | |fS )Nr&   Tr   )r   r   r  r  rS  r  r  r   rH  rA  r   r|   r  )ri  rk  check_entitiesrk   s     r-   r  zDJoinCondition._annotate_remote_with_overlap.<locals>.proc_left_right  s#   $
 7 78Zz..> 0022BB4466FFtL!OOXt,<=E ; &&**>:dii>N>NN4(89 ; %%)).9TYY=M=MM~~x&67 ; ..0;r.   rm  )r   r|   r   r   r  rD   )rk   rn  r  r  s   ` @@r-   r  z+JoinCondition._annotate_remote_with_overlap  se    	 IIT!Ndii&6&6dii>N>N&N 		. $33b8\":
r.   c                 \      fd}t        j                   j                  i |       _        y)z}annotate 'remote' in primaryjoin, secondaryjoin
        when the parent/child tables are entirely
        separate.

        c                    j                   j                  j                  |       r^j                  j                  j                  |       r%j                  j                  j                  |       r| j                  ddi      S y y r  )r  rS  r  r  r  r   r  s    r-   r  zAJoinCondition._annotate_remote_distinct_selectables.<locals>.repl:  ss    ,,..>>wG0022BB7K..00@@I(((D)9:: J Hr.   N)r   rL  rD   r  s   ` r-   r  z3JoinCondition._annotate_remote_distinct_selectables3  s*    	; $88b$
r.   c                 H    t        j                  d| j                  z         y )NzNon-simple column elements in primary join condition for property %s - consider using remote() annotations to mark the remote side.)r   rW   r   r   s    r-   r  z'JoinCondition._warn_non_column_elementsE  s     		<>BiiH	
r.   c                 r   | j                  | j                  d      ry| j                  r3t        j                  | j                  D cg c]  \  }}|	 c}}      n)t        j                  | j
                  j                        fd}t        j                  | j                  i |      | _        yc c}}w )aC  Annotate the primaryjoin and secondaryjoin
        structures with 'local' annotations.

        This annotates all column elements found
        simultaneously in the parent table
        and the join condition that don't have a
        'remote' annotation set up from
        _annotate_remote() or user-defined.

        rD  Nc                 R    d| j                   vr| v r| j                  ddi      S y y )Nr&   rD  T)rH  r   )r  
local_sides    r-   locals_z.JoinCondition._annotate_local.<locals>.locals_a  s4    t000TZ5G~~wo66 6H0r.   )	rR  rD   rn   r   r  r  rS  r   rL  )rk   r+  rK  r  r  s       @r-   r  zJoinCondition._annotate_localL  s      0 0':##!%!9!9:v1:J )G)G)I)IJJ	7 $88b'
 ;s   	B3
c                 v      j                   y  fd}t        j                   j                  i |       _        y )Nc                     d| j                   v r'| j                  dj                  j                  i      S d| j                   v r'| j                  dj                  j                  i      S y )Nr&   r   rD  )rH  r   r   r|   r   )r  rk   s    r-   parentmappers_z<JoinCondition._annotate_parentmapper.<locals>.parentmappers_m  s`    4,,,~~~tyy7G7G&HIID---~~~tyy7G7G&HII .r.   )r   r   rL  rD   )rk   r  s   ` r-   r  z$JoinCondition._annotate_parentmapperi  s8    99	J $88b.
r.   c                 ^   | j                   s#t        j                  d| j                  d      t	        j
                  | j                  j                        j                  | j                  j                        }| j                   D ]#  \  }}||v st	        j                  d|d       % y )Nrl  a   could not determine any unambiguous local/remote column pairs based on join condition and remote_side arguments.  Consider using the remote() annotation to accurately mark those elements of the join condition that are on the remote side of the relationship.zExpression z is marked as 'remote', but these column(s) are local to the local side.  The remote() annotation is needed only for a self-referential relationship where both sides of the relationship refer to the same tables.)rY   rJ   rK   r   r   r  r  rS  r  r  rW   )rk   
not_target_rmts       r-   r#  z JoinCondition._check_remote_sidew  s    &&&& (,yy3	 	 ..00j66889  11 	3*$II !	r.   c                    d}| j                  |d      }t        |      }|rt        | j                        }nt        | j                        }| j                  r|s| j                  s|ry| j                  r<|r:|s8d|xr dxs dd|d| j
                  d	}|d
z  }t        j                  |      d|xr dxs dd|d| j
                  d	}|dz  }t        j                  |      )zHCheck the foreign key columns collected and emit error
        messages.Fr0   NzbCould not locate any simple equality expressions involving locally mapped foreign key columns for primaryrC   z join condition 'z' on relationship r4  a    Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or are annotated in the join condition with the foreign() annotation. To allow comparison operators other than '==', the relationship can be marked as viewonly=True.z6Could not locate any relevant foreign key columns for z  Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or are annotated in the join condition with the foreign() annotation.)_gather_columns_with_annotationboolr  r  r  r   rJ   rK   )rk   r!   r  can_syncforeign_colshas_foreignerrs          r-   r!  z!JoinCondition._check_foreign_cols  s    ;;I
 <(D223HD<<=H %%+
 X )	8[8"II  IC &&s++ )	8[8"II  C &&s++r.   c                    | j                   t        | _        yt        j                  | j
                  j                        }t        j                  | j                  j                        }|j                  | j                        }|j                  | j                        }|r|r| j                  | j                  dd      }t        | j                  | j                  d      D cg c]  }d|j                  vr| c}      }|rI|rG| j                  j                  | j                        }|j!                  |      }|j!                  |      }|r|st"        | _        y|r|st$        | _        yt'        j(                  d| j*                  z        |rt"        | _        y|rt$        | _        yt'        j(                  d| j*                  z        c c}w )z[Determine if this relationship is one to many, many to one,
        many to many.

        Nr&   r0   aD  Can't determine relationship direction for relationship '%s' - foreign key columns within the join condition are present in both the parent and the child's mapped tables.  Ensure that only those columns referring to a parent column are marked as foreign, either via the foreign() annotation or via the foreign_keys argument.zCan't determine relationship direction for relationship '%s' - foreign key columns are present in neither the parent nor the child's mapped tables)rE   r	   rG   r   r  r  rS  r  intersectionr  r  rD   rb   rH  r  r  r  r   r
   rJ   rK   r   )	rk   
parentcols
targetcolsonetomany_fkmanytoone_fkonetomany_localrS  manytoone_localself_equateds	            r-   r"  z"JoinCondition._determine_direction  s   
 )'DN)G)G)I)IJJ)F)F)H)HIJ &2243K3KLL &2243K3KLL #'"F"F$$h	# #& "&!E!E ,,i" $1>>9	 # ##'#6#6#C#C**$L '6&@&@&NO&5&@&@&NO #?%.DN$_%.DN ..9 <@99E	 	 !*!***4 7;ii@ Ws   %Gc                 t    |D cg c]%  \  }}|j                         |j                         f' c}}S c c}}w )zprovide deannotation for the various lists of
        pairs, so that using them in hashes doesn't incur
        high-overhead __eq__() comparisons against
        original columns mapped.

        )_deannotate)rk   r?  r   r   s       r-   _deannotate_pairszJoinCondition._deannotate_pairs*  s/     @JJtq!!--/2JJJs   *4c                 *    g }t        j                  g       g } fd} j                  |f j                  |ffD ]  \  }}|	 |||         j	                         _         j	                  |       _         j	                  |       _        y )Nc                 .    fd}t        ||        y )Nc                    d|j                   v r3d|j                   vr%j                  |      rj                  ||f       n@d|j                   v r2d|j                   vr$j                  |      rj                  ||f       | j                  t        j
                  u rXj                  ||      rEd|j                   v rj                  ||f       y d|j                   v rj                  ||f       y y y y )Nr&   r0   )rH  r  rb  operatorr   eqrC  )rm  ri  rk  r?  lrprk   s      r-   rn  z<JoinCondition._setup_pairs.<locals>.go.<locals>.visit_binary9  s     2 22 (9(99--d3GGT5M* 1 11 (:(::--e4GGUDM*??ill2t7L7L%8 !E$6$66"))4-8"d&7&77"))5$-8 882r.   r#   )joincondr?  rn  r  rk   s    ` r-   goz&JoinCondition._setup_pairs.<locals>.go8  s    9* !x8r.   )r   
OrderedSetrD   rE   r  rY   r  r  )rk   
sync_pairssecondary_sync_pairsr  r  r?  r  s   `     @r-   r   zJoinCondition._setup_pairs3  s    
oob!!	92 z*!56%
 	% Hj x$	% #'"8"8"=!%!7!7
!C+/+A+A ,
(r.   c                 j   | j                   sy | j                  D cg c]	  \  }}||f c}}| j                  D cg c]	  \  }}||f c}}z   D ]  \  }| j                  vr/t	        j
                  | j                  |i      | j                  <   Dg }| j                     }|j                         D ]  \  }}|j                  j                  r|| j                  j                  vs7|j                  | j                  j                  vsZ| j                  j                  |j                  vs}d| j                  j                  vsd|j                  vs| j                  j                  j                  |j                        r| j                  j                  j                  |j                        r| j                  j                  j                  |j                        r7| j                  j                  j                  |j                        rh| j                  j                  |j                  k7  s1| j                  j                  j                  |j                        r|j!                  ||f        |r~t#        j$                  d| j                  d|dddj'                  t)        fd|D                    dd	j'                  t)        d
 |D                    d| j                  dd       || j                     | j                  <    y c c}}w c c}}w )Nz__*rx  z' will copy column z to column z(, which conflicts with relationship(s): r  c              3   <   K   | ]  \  }}d |d|dd  yw)r\  z
' (copies z to ry  Nr=   )r  prfr_to_s      r-   r  zCJoinCondition._warn_for_conflicting_sync_targets.<locals>.<genexpr>  s&      '"(1S ACC$M'"s   a  . If this is not the intention, consider if these relationships should be linked with back_populates, or if viewonly=True should be applied to one or more if they are read-only. For the less common case that foreign key constraints are partially overlapping, the orm.foreign() annotation can be used to isolate the columns that should be written towards.   To silence this warning, add the parameter 'overlaps="r&  c              3   :   K   | ]  \  }}|j                     y wr   )rz   )r  r  frs      r-   r  zCJoinCondition._warn_for_conflicting_sync_targets.<locals>.<genexpr>  s     +Mvr2BFF+Ms   z"' to the 'z' relationship.qzyxr  )r  r  r  _track_overlapping_sync_targetsweakrefWeakKeyDictionaryr   rq   r|   _dispose_calledrc   rz   rf   r   
is_siblingrs  rC  r   rW   r  r  )rk   r;  r  other_propsprop_to_fromr  r  s     `    r-   r  z0JoinCondition._warn_for_conflicting_sync_targets`  s      .2-C-C
)eSUCL
 .2-M-M
)eSUCL

 L	MJE3 $>>> --tyy%.@A 44 !#CCCH+113 6GBII55dii&A&AAFF$))*=*== IIMM= ")<)<<!5 $		 0 0 ; ;BII F $		 0 0 ; ;BII F $		 0 0 ; ;BII F $		 0 0 ; ;BII F IIMMRVV3#'99#3#3#A#A"))#L $**B95164 II !II! II & '"5@'" !"  HHV+M+M%MN II14 $7: HM44S9$))DYL	M 

s
   L)L/c                 $    | j                  d      S rW  _gather_join_annotationsr   s    r-   r  zJoinCondition.remote_columns  s    ,,X66r.   c                 $    | j                  d      S )NrD  r  r   s    r-   r  zJoinCondition.local_columns  s    ,,W55r.   c                 $    | j                  d      S rT  r  r   s    r-   r  z!JoinCondition.foreign_key_columns  s    ,,Y77r.   c                     t        | j                  | j                  |            }| j                  +|j	                  | j                  | j                  |             |D ch c]  }|j                          c}S c c}w r   )rb   r  rD   rE   updater  )rk   rQ  sr   s       r-   r  z&JoinCondition._gather_join_annotations  sq    001A1A:N
 )HH44&&

 *++A+++s   !A;c                     t        |      }t        t        j                  |i       D cg c]  }|j                  |j                        r|! c}      S c c}w r   )rb   r   rO  issubsetrH  rP  s       r-   r  z-JoinCondition._gather_columns_with_annotation  sV    _
 $++FB7&&s'7'78 
 	
s   $Ac                    t        |ddi      }| j                  | j                  | j                  }}}||||z  }n||z  }|r-||t	        j
                  | z  }n|t	        j
                  | z  }|r||j                  d      }t        |t        d            }	t        || j                        j                  |	      }
|:t        |t        d            j                  t        || j                              }	|
j                  |      }nUt        |t        d      | j                        }	|0|	j                  t        |t        d	      | j                               d}
|	j                  |      }|
xs |	}d|_        nd}|||||fS )
a7  Given a source and destination selectable, create a
        join between them.

        This takes into account aliasing the join clause
        to reference the appropriate corresponding columns
        in the target objects, as well as the extra child
        criterion, equivalent column sets, etc.

        r   TN)flatrD  )
exclude_fn)equivalents)r  r  r&   )r   rD   rE   rC   r   r   r   r    _ColInAnnotationsr  chainr  r   r  )rk   r   r   r  r   r   rD   rE   rC   primary_aliasizersecondary_aliasizerr   s               r-   r  zJoinCondition.join_targets  s   * ,7>

 NN %.] "( - ;)K7( -.0I I)CHHn,EE$%;;;F	$1*;G*D%! '4#1G1G'%)* $ %0(5!.?.H)e%-(,(?(? & !4 < <] K$1#09 $ 6 6%!
 %0%++%-'8'B(,(?(? '+#+44[AK0E4EN(,N%!N
 	
r.   c                   
 t        j                         
t        j                         }| j                  d urIt        j                  t
              | j                  D ]   \  }}|   j                  ||f       |||<   " n5s| j                  D ]
  \  }}|||<    n| j                  D ]
  \  }}|||<    
fd}| j                  }| j                  st        j                  |i |      }| j                  ;| j                  }rt        j                  |i |      }t        j                  ||      }
D ci c]  }
|   j                  | }	}||	|fS c c}w )Nc                     sd| j                   v srEr| v ss=d| j                   v r/| vr&t        j                  d d | j                  d      | <   |    S y )NrD  r&   T)r   r   )rH  r   r   r   )r   bindshas_secondarylookupr  s    r-   col_to_bindz5JoinCondition.create_lazy_clause.<locals>.col_to_bindL  si     '7c6F6F+F$"sf})h#:J:J.J e#!$d#((4"E#J Sz!r.   )r   column_dictrE   collectionsdefaultdictlistrY   rC  rD   r   rL  r   r   rz   )rk   r  equated_columnsr+  rK  r  	lazywhererE   r   r  r  r  r  s    `        @@@r-   create_lazy_clausez JoinCondition.create_lazy_clause:  sw     "**,**$6 ,,T2F// '1q	  !Q(%&"' #// '1%&"' // '1%&"'	" $$	%-> 552{I ) ..M  ( = =!2{! M:I6;<suSz~~s*<<+66 =s   ?E)Nr=   )F).r   r   r   r@   r$  r  r  r   r  r  r   r  r  rR  rM  rK  r  rY  rZ  rw  ry  r  r|  r~  r}  r  r  r  r  r  r#  r!  r"  r  r   r  r  r  r  r  r  r  r  r  r  r  r=   r.   r-   r  r  /
  s    !%(#/b&LP$gR N N P P 
 :  :D 
A A 
@ @),\0
9,
"
.@-
^
$

:
:@,DRhK)
V '@g&?&?&A#UMn 
7 7 
6 6 
8 8
,
 _
B37r.   r  c                        e Zd ZdZdZd Zd Zy)r  z<Serializable object that tests for a name in c._annotations.namec                     || _         y r   r  )rk   r  s     r-   r@   z_ColInAnnotations.__init__u  s	    	r.   c                 2    | j                   |j                  v S r   )r  rH  )rk   rS  s     r-   __call__z_ColInAnnotations.__call__x  s    yyANN**r.   N)r   r   r   r   	__slots__r@   r  r=   r.   r-   r  r  p  s    FI+r.   r  )2r   
__future__r   r  rd   r   r   baser   r   r   
interfacesr	   r
   r   r   r   r   r   r   r   r   rJ   r   r   r   
inspectionr   r   r   r   r   r   sql.utilr   r   r   r    r!   r"   r$   r&   r0   class_loggerr2   r(   objectr  r  r=   r.   r-   <module>r     s    '  	   "   " ! ! & +  !               ' ( . $ % * +&( A'
. A'
 A'
HN
~7F ~7B"	+ 	+r.   