B 4]@sdZddlmZddlZddlZddlmZddlmZddlmZ ddl m Z dd l m Z dd l mZdd l mZdd l mZdd l mZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddl m!Z!ddl m"Z"ddl m#Z#ddl m$Z$ddl m%Z%dd l m&Z&dd!l m'Z'd"d#Z(d$d%Z)ej*ej+j,d&d'd(Gd)d*d*eZ-d+d,Z.Gd-d.d.e/Z0Gd/d0d0e/Z1dS)1aHeuristics related to join conditions as used in :func:`.relationship`. Provides the :class:`.JoinCondition` object, which encapsulates SQL annotation and aliasing behavior focused on the `primaryjoin` and `secondaryjoin` aspects of :func:`.relationship`. )absolute_importN) attributes) dependency)mapper) state_str) MANYTOMANY) MANYTOONE) ONETOMANY)PropComparator)StrategizedProperty) _orm_annotate)_orm_deannotate)CascadeOptions)exc)log)schema)sql)util)inspect) expression) operators)visitors)_deep_deannotate)_shallow_annotate)adapt_criterion_to_null) ClauseAdapter)join_condition)selectables_overlap)visit_binary_productcCstt|ddiS)aAnnotate 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_clause_element_as_expr)exprr%O/opt/alt/python37/lib64/python3.7/site-packages/sqlalchemy/orm/relationships.pyr!3sr!cCstt|ddiS)aAnnotate 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` foreignT)r"rr#)r$r%r%r&r'Fsr'zsqlalchemy.orm.propertiesT)Z add_to_allc!sLeZdZdZdZdZejdddAfd d Zd d Z Gd dde Z dBddZ dCddZ ddZdDddZddZddZejfddZdEddZdd Zejd!d"Zejd#d$Zfd%d&Zd'd(Zd)d*Zd+d,Zd-d.Zd/d0Ze eeZ!d1d2Z"d3d4Z#d5d6Z$d7d8Z%d9d:Z&ejd;d<Z'ejd=d>Z(dFd?d@Z)Z*S)GRelationshipPropertyzDescribes 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` relationshipN)z0.7z:class:`.AttributeExtension` is deprecated in favor of the :class:`.AttributeEvents` listener interface. The :paramref:`.relationship.extension` parameter will be removed in a future release.) extensionFselectTc""sHtt|||_||_||_||_||_| |_d|_ | |_ ||_ ||_ ||_ ||_||_||_||_||_||_||_||_||_||_||_||_|!|_||_| |_||_||_|ptj|_ | |d|_!t"#|| dk r| |_$d|j ff|_%t&|_'| dk r | nd|_(||_)| |_*|j*r>|r6t+,dd|_-n||_-dS)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:`.relationship`, used in a classical mapping:: mapper(Parent, properties={ 'children': relationship(Child) }) Some arguments accepted by :func:`.relationship` optionally accept a callable function, which when called produces the desired value. The callable is invoked by the parent :class:`.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:`.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:`.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:`.relationship`. :ref:`orm_tutorial_relationship` - ORM tutorial introduction. :param argument: a mapped class, or actual :class:`.Mapper` instance, representing the target of the relationship. :paramref:`~.relationship.argument` 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. .. 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:`.Table`. In less common circumstances, the argument may also be specified as an :class:`.Alias` construct, or even a :class:`.Join` construct. :paramref:`~.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:`.Table` that is present in the :class:`.MetaData` collection associated with the parent-mapped :class:`.Table`. The :paramref:`~.relationship.secondary` keyword argument is typically applied in the case where the intermediary :class:`.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:`~.relationship.viewonly` flag so that this :func:`.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:`orm_tutorial_many_to_many` - ORM tutorial introduction to many-to-many relationships. :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:`~.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:`.relationship` SQL conditions to be used. .. versionadded:: 0.9.2 :paramref:`~.relationship.secondary` works more effectively when referring to a :class:`.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: indicates the string name of a property to be placed on the related mapper's class that will handle this relationship in the other direction. The other property will be created automatically when the mappers are configured. Can also be passed as a :func:`.backref` object to control the configuration of the new relationship. .. seealso:: :ref:`relationships_backref` - Introductory documentation and examples. :paramref:`~.relationship.back_populates` - alternative form of backref specification. :func:`.backref` - allows control over :func:`.relationship` configuration when using :paramref:`~.relationship.backref`. :param back_populates: Takes a string name and has the same meaning as :paramref:`~.relationship.backref`, except the complementing property is **not** created automatically, and instead must be configured explicitly on the other mapper. The complementing property should also indicate :paramref:`~.relationship.back_populates` to this relationship to ensure proper functioning. .. seealso:: :ref:`relationships_backref` - Introductory documentation and examples. :paramref:`~.relationship.backref` - alternative form of backref specification. :param bake_queries=True: Use the :class:`.BakedQuery` cache to cache the construction of SQL used in lazy loads. True by default. Set to False if the join condition of the relationship has unusual features that might not respond well to statement caching. .. versionchanged:: 1.2 "Baked" loading is the default implementation for the "select", a.k.a. "lazy" loading strategy for relationships. .. versionadded:: 1.0.0 .. seealso:: :ref:`baked_toplevel` :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. :ref:`tutorial_delete_cascade` - Tutorial example describing a delete cascade. :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. .. seealso:: :ref:`backref_cascade` - Full discussion and examples on how the :paramref:`~.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:`~.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 extension: an :class:`.AttributeExtension` instance, or list of extensions, which will be prepended to the list of attribute listeners for the resulting descriptor placed on the class. :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:`.relationship` object's :paramref:`~.relationship.primaryjoin` condition. That is, if the :paramref:`~.relationship.primaryjoin` condition of this :func:`.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:`.relationship` is ``b.a_id``. In normal cases, the :paramref:`~.relationship.foreign_keys` parameter is **not required.** :func:`.relationship` will automatically determine which columns in the :paramref:`~.relationship.primaryjoin` condition are to be considered "foreign key" columns based on those :class:`.Column` objects that specify :class:`.ForeignKey`, or are otherwise listed as referencing columns in a :class:`.ForeignKeyConstraint` construct. :paramref:`~.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:`.relationship` to consider just those columns specified here as "foreign". 2. The :class:`.Table` being mapped does not actually have :class:`.ForeignKey` or :class:`.ForeignKeyConstraint` constructs present, often because the table was reflected from a database that does not support foreign key reflection (MySQL MyISAM). 3. The :paramref:`~.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:`.relationship` construct will raise informative error messages that suggest the use of the :paramref:`~.relationship.foreign_keys` parameter when presented with an ambiguous condition. In typical cases, if :func:`.relationship` doesn't raise any exceptions, the :paramref:`~.relationship.foreign_keys` parameter is usually not needed. :paramref:`~.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. .. seealso:: :ref:`relationship_foreign_keys` :ref:`relationship_custom_foreign` :func:`.foreign` - allows direct annotation of the "foreign" columns within a :paramref:`~.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:`.joinedload.innerjoin`. See that flag for details on nested / unnested behaviors. .. seealso:: :paramref:`.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:`~.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` 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:`~.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:`~.relationship.order_by` is expected to refer to one of the :class:`.Column` objects to which the target class is mapped, or the attribute itself bound to the target class which refers to the column. :paramref:`~.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. :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 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:`.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. Currently, it also will issue an UPDATE after the instance was UPDATEd as well, although this technically should be improved. 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:`~.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:`~.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. .. 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:`.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. .. seealso:: :ref:`self_referential` - in-depth explanation of how :paramref:`~.relationship.remote_side` is used to configure self-referential relationships. :func:`.remote` - an annotation function that accomplishes the same purpose as :paramref:`~.relationship.remote_side`, typically when a custom :paramref:`~.relationship.primaryjoin` condition is used. :param query_class: a :class:`.Query` subclass that will be used as the base of the "appender query" 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:`~.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. .. 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:`.relationship` constructs which are many-to-one or many-to-many and also specify the ``delete-orphan`` cascade option. The :func:`.relationship` construct itself will raise an error instructing when this option is required. .. seealso:: :ref:`unitofwork_cascades` - includes detail on when the :paramref:`~.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:`.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:`~.relationship.uselist` to False. The :paramref:`~.relationship.uselist` flag is also available on an existing :func:`.relationship` construct as a read-only attribute, which can be used to determine if this :func:`.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:`~.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:`.relationship` which specifies :paramref:`~.relationship.viewonly` can work with a wider range of SQL operations within the :paramref:`~.relationship.primaryjoin` condition, including operations that feature the use of a variety of comparison operators as well as SQL functions such as :func:`~.sql.expression.cast`. The :paramref:`~.relationship.viewonly` flag is also of general use when defining any kind of :func:`~.relationship` that doesn't represent the full set of related objects, to prevent modifications of the collection from resulting in persistence operations. :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. .. versionadded:: 1.3 NlazyFzsave-update, mergezCbackref and back_populates keyword arguments are mutually exclusive).superr(__init__uselistargument secondary primaryjoin secondaryjoin post_update directionviewonlyr, single_parent_user_defined_foreign_keyscollection_classpassive_deletescascade_backrefspassive_updates remote_sideenable_typechecks query_class innerjoindistinct_target_keydocactive_history join_depth omit_joinlocal_remote_pairsr* bake_queriesload_on_pending Comparatorcomparator_factory comparatorrZset_creation_orderinfoZ strategy_keyset_reverse_propertycascadeorder_byback_populatessa_exc ArgumentErrorbackref)"selfr0r1r2r3 foreign_keysr/rPrTrQr4rOr*r6r,r9r:r<r=r>rDrJr7r@rArBrCr;rHrG_local_remote_pairsr?rLrE) __class__r%r&r.lsd`  zRelationshipProperty.__init__cCs&tj|j|j|||||jddS)N)rK parententityrB)rZregister_descriptorclass_keyrJrB)rUrr%r%r&instrument_classs  z%RelationshipProperty.instrument_classc@seZdZdZdZd%ddZddZejddZ ejd d Z ejd d Z d dZ ddZ ddZddZdZddZd&ddZd'ddZd(ddZddZdd Zd!d"Zejd#d$ZdS))zRelationshipProperty.ComparatoraProduce 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` NcCs ||_||_||_|r||_dS)zConstruction of :class:`.RelationshipProperty.Comparator` is internal to the ORM's attribute mechanics. N)prop _parententity_adapt_to_entity_of_type)rUr] parentmapperadapt_to_entityof_typer%r%r&r.s z(RelationshipProperty.Comparator.__init__cCs|j|j|j||jdS)N)rbrc)rXpropertyr^r`)rUrbr%r%r&rbs z/RelationshipProperty.Comparator.adapt_to_entitycCs|jjS)a#The target entity referred to by this :class:`.RelationshipProperty.Comparator`. This is either a :class:`.Mapper` or :class:`.AliasedInsp` object. This is the "target" or "remote" side of the :func:`.relationship`. )rdentity)rUr%r%r&res z&RelationshipProperty.Comparator.entitycCs|jjS)zThe target :class:`.Mapper` referred to by this :class:`.RelationshipProperty.Comparator`. This is the "target" or "remote" side of the :func:`.relationship`. )rdr)rUr%r%r&rs z&RelationshipProperty.Comparator.mappercCs|jjS)N)rdparent)rUr%r%r&r^sz-RelationshipProperty.Comparator._parententitycCs|jr|jjS|jjjSdS)N)r_ selectablerdrf_with_polymorphic_selectable)rUr%r%r&_source_selectablesz2RelationshipProperty.Comparator._source_selectablec CsV|}|jrt|jj}nd}|jj|d|d\}}}}}}|dk rN||@S|SdS)NT)source_selectablesource_polymorphicof_type_mapper)rir`rrrd _create_joins) rUZ adapt_fromrlpjsjsourcedestr1target_adapterr%r%r&__clause_element__s z2RelationshipProperty.Comparator.__clause_element__cCstj|j|j|j|dS)zRedefine this object in terms of a polymorphic subclass. See :meth:`.PropComparator.of_type` for an example. )rbrc)r(rIrdr^r_)rUclsr%r%r&rcs z'RelationshipProperty.Comparator.of_typecCs tddS)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.N)NotImplementedError)rUotherr%r%r&in_sz#RelationshipProperty.Comparator.in_cCsrt|tjtjfrD|jjttgkr,| St |jj d|j dSn*|jj rXtdnt |jj ||j dSdS)aImplement the ``==`` operator. In a many-to-one context, such as:: MyClass.some_prop == this will typically produce a clause such as:: mytable.related_id == Where ```` 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_sourcez]Can't compare a collection to an object or collection; use contains() to test for membership.) isinstancerNoneTyperNullrdr5r r_criterion_existsr _optimized_compareadapterr/rRInvalidRequestError)rUrvr%r%r&__eq__s% z&RelationshipProperty.Comparator.__eq__cKst|ddrft|j}|j|j|j}}}|jjr@|s@|}|j }|dk rn|dk r`||@}qn|}nd}d}|j r~| }nd}|jj d||d\} } } } } }x:|D]2}t|jjj |||k}|dkr|}q||@}qW| dk rt| | @}nt| |jjd}|dk r"|r"|s"||}|dk r:|ddi}|tj|@}| dk rttjdg|| | gd| | }ntjdg|| d| }|S) Nr`FT)dest_polymorphicdest_selectablerj)Zexcludeno_replacement_traverser)Zfrom_obj)getattrrr`rrgis_aliased_classrd_is_self_referentialalias_single_table_criterionr~rirmrZr r=traverse _annotaterZTrue_Z_ifnoneexistsZcorrelate_except)rU criterionkwargsrLZ target_mapperZ to_selectabler single_critrjrnrorprqr1rrkZcritjZexr%r%r&r|IsX              z1RelationshipProperty.Comparator._criterion_existscKs |jjstd|j|f|S)amProduce 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:`.relationship` that has ``uselist=True``. For scalar references, use :meth:`~.RelationshipProperty.Comparator.has`. z9'any()' not implemented for scalar attributes. Use has().)rdr/rRrr|)rUrrr%r%r&anys)z#RelationshipProperty.Comparator.anycKs |jjrtd|j|f|S)aProduce 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:`.relationship` that has ``uselist=False``. For collection references, use :meth:`~.RelationshipProperty.Comparator.any`. z4'has()' not implemented for collections. Use any().)rdr/rRrr|)rUrrr%r%r&hassz#RelationshipProperty.Comparator.hascKs@|jjstd|jj||jd}|jjdk r<|||_|S)ad 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 == Where ```` 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 = Where ```` 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.outerjoin` as well as :ref:`ormtutorial_joins` for more details on constructing outer joins. z9'contains' not implemented for scalar attributes. Use ==)rxN) rdr/rRrr}r~r3'_Comparator__negated_contains_or_equalsZnegation_clause)rUrvrclauser%r%r&containss8  z(RelationshipProperty.Comparator.containscsjjtkrVt|fddfddjjrVtjfddjjDStjddt jj j jj |D} |S)Nc s(|j}tj|djjj|||dS)NT)uniqueZ callable_)dictr bindparamrd_get_attr_w_warn_on_noner)xstatecoldict_)rUr%r&state_bindparam<s zURelationshipProperty.Comparator.__negated_contains_or_equals..state_bindparamcsjr|S|SdS)N)r~)r)rUr%r&adaptFs zKRelationshipProperty.Comparator.__negated_contains_or_equals..adaptc s8g|]0\}}t|||k|dkqS)N)ror_).0ry)rrrr%r& OszPRelationshipProperty.Comparator.__negated_contains_or_equals..cSsg|]\}}||kqSr%r%)rrrr%r%r&rZs)rdr5r rinstance_state_use_getrand_rFziprZ primary_keyZprimary_key_from_instancer|)rUrvrr%)rrUrrr&Z__negated_contains_or_equals8s   z This will typically produce a clause such as:: mytable.related_id != Where ```` 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. N)rxz]Can't compare a collection to an object or collection; use contains() to test for membership.)ryrrzrr{rdr5r r r}r~r|r/rRrr)rUrvr%r%r&__ne__ds'  z&RelationshipProperty.Comparator.__ne__cCstjjrtj|jS)N) mapperlibMapperZ _new_mappersZ_configure_allr])rUr%r%r&rds z(RelationshipProperty.Comparator.property)NN)N)N)N)__name__ __module__ __qualname____doc__r`r.rbrmemoized_propertyrerr^rirsrcrw__hash__rr|rrrrrrdr%r%r%r&rIs(    : T 1 "H,:rIcCs4d}|dk r"t|}|jr"|jj}|j|d||dS)NT)value_is_parentrxalias_secondary)rrZ_adapterZ adapt_clauser})rUinstancerZ from_entityrxZinspr%r%r& _with_parentsz!RelationshipProperty._with_parentcsdk rt| }dkr.j||dS|sFjjjj}njjjj}|rdjnj t  fdd}j dk r|rt j |}t|id|i}|r||}|S)N)rxcs&|jkr"|j|_dS)N)Z_identifying_keyrcallable)r) bind_to_colrrrUrr%r&visit_bindparams  z@RelationshipProperty._optimized_compare..visit_bindparamr)rr_lazy_none_clause_lazy_strategy _lazywhere _bind_to_col_rev_lazywhere_rev_bind_to_colrrf instance_dictobjr1rrrrcloned_traverse)rUrrrxrreverse_directionrrr%)rrrrUrr&r}s0    z'RelationshipProperty._optimized_comparecs.jfdd}|S)aKCreate 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``. csjj}}|tjk }jjr0tjn tjtjAd}|tj krf|st dt fn*|tj kr|st dt fn|}|dkrtd|S)N)passivezUCan't resolve value for column %s on object %s; no value has been set for this columnz`Can't resolve value for column %s on object %s; 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))Z_last_known_valuesr[rZNO_VALUEZ_get_state_attr_by_columnZ persistent PASSIVE_OFFZPASSIVE_NO_FETCHZINIT_OKZ NEVER_SETrRrrPASSIVE_NO_RESULTrwarn)Z last_knownZ to_returnZexisting_is_availableZ current_value)columnrrr]rr%r&_gos0    z:RelationshipProperty._get_attr_w_warn_on_none.._go)Zget_property_by_columnZ_track_last_known_valuer[)rUrrrrrr%)rrrr]rr&rs+  *z-RelationshipProperty._get_attr_w_warn_on_nonecCsD|s|jj|jj}}n|jj|jj}}t||}|r@||}|S)N)rrrrrr)rUrrxrrr%r%r&rIs  z&RelationshipProperty._lazy_none_clausecCst|jjjd|jS)N.)strrfrZrr[)rUr%r%r&__str__[szRelationshipProperty.__str__c Cs|r$x|jD]} || f|kr dSq Wd|jkr2dS|j|kr@dS|jr(||j||} t| drl| j} |r||j||g} xR| D]J} t | } t | }d|| |f<|j | ||||d}|dk r| |qW|s t |||j}x2| D]}||qWn||jj||| ddnx||j} | dk rrt | } t | }d|| |f<|j | ||||d}nd}|s|||j<n||j|||ddS)Nmerge _sa_adapterT)load _recursive_resolve_conflict_mapF)Z_adapt)rN_cascader[r/Zget_implgethasattrrrrrZ_mergeappendZinit_state_collectionZappend_without_eventrM)rUZsessionZ source_stateZ source_dictZ dest_stateZ dest_dictrrrrZ instancesZ dest_listZcurrentZ current_stateZ current_dictrZcollcr%r%r&r^sf                      zRelationshipProperty.mergecCsl|j|j}|j|||d}|tjks.|dkr2gSt|drXdd|j||||dDSt||fgSdS)zReturn a list of tuples (state, obj) for the given key. returns an empty list if the value is None/empty/PASSIVE_NO_RESULT )rNget_collectioncSsg|]}t||fqSr%)rr)ror%r%r&rsz;RelationshipProperty._value_as_iterable..)managerimplrrrrrr)rUrrr[rrrr%r%r&_value_as_iterables  z'RelationshipProperty._value_as_iterablec cs|dks|jrtj}ntj}|dkr<|j|jj||}n|j|||j|d}|dko`d|j k}x|D]\} } | |krzqh| dkrqht | } |r|| rqh|r| jsqh| jj } | |j j j std|j|jj| jf|| | | | | fVqhWdS)Ndeletez save-update)rzrefresh-expirez delete-orphanz@Attribute '%s' on class '%s' doesn't handle objects of type '%s')r:rZPASSIVE_NO_INITIALIZErrr[rZget_all_pendingrrrrZisaZ class_managerAssertionErrorrfrZrXadd) rUtype_rrZvisited_statesZhalt_onrZtuplesZ skip_pendingrrrZinstance_mapperr%r%r&cascade_iterators2    z%RelationshipProperty.cascade_iteratorcCs|jj|dd}|j||j||j|jsNtd||||jf|jt t fkr~|j|jkr~td|||jfdS)NF)Z_configure_mapperszereverse_property %r on relationship %s references relationship %s, which does not reference mapper %szv%s and back-reference %s are both of the same direction %r. Did you mean to set remote_side on the many-to-one side ?) rZ get_propertyrNr common_parentrfrRrSr5r r )rUr[rvr%r%r&_add_reverse_propertys   z*RelationshipProperty._add_reverse_propertycCst|jr(t|jttjfs(|}n|j}t|trFtj|ddSy t|}Wnt j k rhYnXt |drx|St d|j t|fdS)zReturn the target mapped entity, which is an inspect() of the class or aliased class tha is referred towards. F) configurerzErelationship '%s' expects a class or a mapper argument (received: %s)N)rrr0rytyperr class_mapperrrRZNoInspectionAvailablerrSr[)rUr0rer%r%r&res    zRelationshipProperty.entitycCs|jjS)zReturn the targeted :class:`.Mapper` for this :class:`.RelationshipProperty`. This is a lazy-initializing static attribute. )rer)rUr%r%r&r8szRelationshipProperty.mappercs\|||||j|||jt t | | d|_ dS)N))r,r+)_check_conflicts_process_dependent_arguments_setup_join_conditions_check_cascade_settingsr _post_init_generate_backref_join_condition"_warn_for_conflicting_sync_targetsr-r(do_initZ _get_strategyr)rU)rXr%r&rBs  zRelationshipProperty.do_initc Csx.dD]&}t||}t|rt|||qWx6dD].}t||}|dk r6t||tt||q6W|jdk r|jdk rddt|jD|_t ddt |j D|_ t d dt |j D|_ |j j|_dS) zConvert incoming configuration arguments to their proper form. Callables are resolved, ORM annotations removed. )rPr2r3r1r8r=)r2r3NFcSsg|]}t|dqS)rP)r_only_column_elements)rrr%r%r&rtszERelationshipProperty._process_dependent_arguments..css|]}t|dVqdS)rVN)rr)rrr%r%r& yszDRelationshipProperty._process_dependent_arguments..css|]}t|dVqdS)r=N)rr)rrr%r%r&r~s)rrrsetattrrrrrPZto_list column_setZ to_column_setr8r=repersist_selectabletarget)rUattrZ attr_valuevalr%r%r&rMs.     z1RelationshipProperty._process_dependent_argumentscCst|jj|jj|jj|jj|j|j|j|jj|j j|j |j |j |j ||j |jd|_}|j|_|j|_|j|_|j |_ |j|_ |j|_|j|_|j|_|j|_dS)N)parent_persist_selectablechild_persist_selectableparent_local_selectablechild_local_selectabler2r1r3parent_equivalentschild_equivalentsconsider_as_foreign_keysrFr=self_referentialr] support_synccan_be_synced_fn) JoinConditionrfrre local_tabler2r1r3Z_equivalent_columnsrr8rFr=rr6_columns_are_mappedrr5remote_columns local_columnssynchronize_pairsforeign_key_columnsZ_calculated_foreign_keyssecondary_synchronize_pairs)rUZjcr%r%r&rs4z+RelationshipProperty._setup_join_conditionscCsH|jjrDtj|jjdd|jsDtd|j|jjj |jjj fdS)zOTest that this relationship is legal, warn about inheritance conflicts.F)rzAttempting to assign a new relationship '%s' to a non-primary mapper on class '%s'. New relationships can only be added to the primary mapper, i.e. the very first mapper created for class '%s' N) rf non_primaryrrrZ has_propertyr[rRrSr)rUr%r%r&rs z%RelationshipProperty._check_conflictscCs|jS)z\Return the current cascade setting for this :class:`.RelationshipProperty`. )r)rUr%r%r& _get_cascadesz!RelationshipProperty._get_cascadecCs4t|}d|jkr||||_|jr0||j_dS)Nr)r__dict__rr_dependency_processorrO)rUrOr%r%r& _set_cascades   z!RelationshipProperty._set_cascadecCs|jr.|js.|jtks |jtkr.td||jtkrL|jrLt d||jdkrtd|ksfd|krttd||jr|j j |j|jjfdS)NzOn %s, delete-orphan cascade is not supported on a many-to-many or many-to-one relationship when single_parent is not set. Set single_parent=True on the relationship().zlOn %s, 'passive_deletes' is normally configured on one-to-many, one-to-one, many-to-many relationships only.allrz delete-orphanz^On %s, can't set passive_deletes='all' in conjunction with 'delete' or 'delete-orphan' cascade)Z delete_orphanr7r5rr rRrSr:rrrprimary_mapperZ_delete_orphansrr[rfrZ)rUrOr%r%r&rs$  z,RelationshipProperty._check_cascade_settingscCs|j|jko|j|j|kS)zaReturn True if this property will persist values on behalf of the given mapper. )r[Z relationships)rUrr%r%r& _persists_fors z"RelationshipProperty._persists_forcGsNxH|D]@}|jdk r$|jj|r$q|jjj|s|jj|sdSqWdS)zReturn True if all columns in the given collection are mapped by the tables referenced by this :class:`.Relationship`. NFT)r1rcontains_columnrfrr)rUZcolsrr%r%r&rs   z(RelationshipProperty._columns_are_mappedc Cs~|jjr dS|jdk rf|jsft|jtjr<|ji}}n |j\}}|j}|j st |  |j }x0|D](}||rp|j sptd|||fqpW|jdk r|d|jj}|d|jj}n*|d|jj}|dd}|rtd|d|j}|j} |d|j|d|j|d |j||_t| |j||f||jd |} ||| |jrz| |jdS) zhInterpret the 'backref' instruction to create a :func:`.relationship` complementary to this one.Nz]Error creating backref '%s' on relationship '%s': property of that name exists on mapper '%s'r2r3zOCan't assign 'secondaryjoin' on a backref against a non-secondary relationship.rVr6r4r<)rVrQ)!rfrrTrQryrZ string_typesrrZconcreterMZiterate_to_rootunionZself_and_descendantsr rRrSr1poprsecondaryjoin_minus_localprimaryjoin_minus_localprimaryjoin_reverse_remoterr8 setdefaultr6r4r<r(r[Z_configure_propertyr) rUZ backref_keyrrZcheckmrnrorVrfr)r%r%r&rs^            z&RelationshipProperty._generate_backrefcCs.|jdkr|jtk |_|js*tj||_dS)N)r/r5r r6rZDependencyProcessorZfrom_relationshipr )rUr%r%r&rNs   zRelationshipProperty._post_initcCs |j}|jS)zPmemoize the 'use_get' attribute of this RelationshipLoader's lazyloader.)rZuse_get)rUZstrategyr%r%r&rVszRelationshipProperty._use_getcCs|j|jS)N)rrrf)rUr%r%r&r^sz)RelationshipProperty._is_self_referentialc Cs|dkr|r|jjr|jj}d}|dkr\|jj}|r@|jjr@d}|jr`|dkr`|}d}nd}|ph|j}|j}|pz|dk }|j ||||\} } } } }|dkr|jj }|dkr|jj }| | ||| | fS)NFT) rfZwith_polymorphicrhrergrrrrr join_targetsr) rUrkrjrrrlaliasedZ dest_mapperrr2r3r1rrr%r%r&rmbs6    z"RelationshipProperty._create_joins) NNNNNFNNFFNFr+NFTNTNNFFNNFTFTNNNN)TN)FNT)FN)N)FNFNN)+rrrrZstrategy_wildcard_keyr rZdeprecated_paramsr.r\r rIrr}rrrrrrrrrrrerrrrrr r rdrOrrrrrrrrm __classcell__r%r%)rXr&r(Zs  r   4^ X 7 7   Lr(cs"fdd|dk r|}|S)Ncs*t|tjr|}|jd|S)N)clone)ryr ColumnClausercopyZ_copy_internals)elem) annotationsrr%r&rs  z _annotate_columns..cloner%)elementr r%)r rr&r"sr"c @seZdZdddddddddddddf ddZdd Zd d Zd d ZeddZeddZ e j ddZ ddZ e j ddZe j ddZddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.d/Zd0d1Zd2d3Zd4d5Zd6d7Zd8d9Zd:d;Z dd?Z"e#$Z%d@dAZ&e j dBdCZ'e j dDdEZ(e j dFdGZ)dHdIZ*dJdKZ+dPdLdMZ,dQdNdOZ-dS)RrNFTcGsdS)NTr%)rr%r%r&zJoinCondition.cCs||_||_||_||_||_| |_||_||_||_| |_ | |_ | |_ ||_ | |_ ||_||_|||||||||jd|jdk r||jd|||dS)NTF)rrrrrrr2r3r1rrW _remote_sider]rrr_determine_joins_sanitize_joins _annotate_fks_annotate_remote_annotate_local_annotate_parentmapper _setup_pairs_check_foreign_cols_determine_direction_check_remote_side _log_joins)rUrrrrr2r1r3rrrrFr=rr]rrr%r%r&r.s: zJoinCondition.__init__cCs|jdkrdS|jj}|d|j|j|d|j|j|d|jddd|jD|d|jddd|jpxgD|d |jdd d|jD|d |jdd d|j D|d |jddd|j D|d|j|j dS)Nz%s setup primary join %sz%s setup secondary join %sz%s synchronize pairs [%s],css|]\}}d||fVqdS)z (%s => %s)Nr%)rlrr%r%r&rsz+JoinCondition._log_joins..z#%s secondary synchronize pairs [%s]css|]\}}d||fVqdS)z (%s => %s)Nr%)rr1rr%r%r&rsz%s local/remote pairs [%s]css|]\}}d||fVqdS)z (%s / %s)Nr%)rr1rr%r%r&rsz%s remote columns [%s]css|]}d|VqdS)z%sNr%)rrr%r%r&rsz%s local columns [%s]css|]}d|VqdS)z%sNr%)rrr%r%r&rsz%s relationship direction %s) r]ZloggerrLr2r3joinrrrFrrr5)rUrr%r%r&r/s< zJoinCondition._log_joinscCs.t|jdd|_|jdk r*t|jdd|_dS)abremove 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`. )rY)valuesN)rr2r3)rUr%r%r&r&s  zJoinCondition._sanitize_joinscCs<|jdk r$|jdkr$td|jy|jp.d}|jdk r|jdkr\t|j|j|j|d|_|j dkrt|j |j|j |d|_ n"|j dkrt|j |j|j |d|_ Wntj k r|jdk rt d|j|jfnt d|jYnLtj k r6|jdk r"t d|j|jfnt d|jYnXdS)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)Za_subsetra1Could not determine join condition between parent/child tables on relationship %s - there are no foreign keys linking these tables via secondary table '%s'. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify 'primaryjoin' and 'secondaryjoin' expressions.aCould 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.alCould not determine join condition between parent/child tables on relationship %s - there are multiple foreign key paths linking the tables via secondary table '%s'. 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.)r3r1rRrSr]rrrrr2rrZNoForeignKeysErrorZAmbiguousForeignKeysError)rUrr%r%r&r% sR          zJoinCondition._determine_joinscCst|jddS)N)localr!)r3)rr2)rUr%r%r&ri sz%JoinCondition.primaryjoin_minus_localcCst|jddS)N)r4r!)r3)rr3)rUr%r%r&rm sz'JoinCondition.secondaryjoin_minus_localcCs@|jrdd}t|ji|S|jr2t|jddSt|jSdS)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. cSs\d|jkr,|j}|d=d|d<||Sd|jkrX|j}|d=d|d<||SdS)Nr!Tr4) _annotationsrZ_with_annotations)r!vr%r%r&replace~ s     z9JoinCondition.primaryjoin_reverse_remote..replace)r4r!)r3N)_has_remote_annotationsrreplacement_traverser2_has_foreign_annotationsr)rUr7r%r%r&rq s   z(JoinCondition.primaryjoin_reverse_remotecCs,x&t|iD]}||jkrdSqWdSdS)NTF)riterater5)rUr annotationrr%r%r&_has_annotation s zJoinCondition._has_annotationcCs||jdS)Nr')r=r2)rUr%r%r&r: sz&JoinCondition._has_foreign_annotationscCs||jdS)Nr!)r=r2)rUr%r%r&r8 sz%JoinCondition._has_remote_annotationscCs&|jr dS|jr|n|dS)zAnnotate the primaryjoin and secondaryjoin structures with 'foreign' annotations marking columns considered as foreign. N)r:r_annotate_from_fk_list_annotate_present_fks)rUr%r%r&r' s  zJoinCondition._annotate_fkscs>fdd}tji|_jdk r:tji|_dS)Ncs|jkr|ddiSdS)Nr'T)rr)r)rUr%r&check_fk s z6JoinCondition._annotate_from_fk_list..check_fk)rr9r2r3)rUr@r%)rUr&r> s   z$JoinCondition._annotate_from_fk_listcsr|jdk rt|jjntfddfdd}t|jid|i|_|jdk rnt|jid|i|_dS)Ncsdt|tjr4t|tjr4||r&|S||r4|Sr`|krL|krL|S|kr`|kr`|SdS)N)ryrZColumnZ references)ab) secondarycolsr%r& is_foreign s  z7JoinCondition._annotate_present_fks..is_foreigncst|jtjrt|jtjs dSd|jjkrd|jjkr|j|j}|dk r||jrn|jddi|_n||jr|jddi|_dS)Nr'T)ryleftrZ ColumnElementrightr5comparer)binaryr)rDr%r& visit_binary s     z9JoinCondition._annotate_present_fks..visit_binaryrH) r1rrrrMrrr2r3)rUrIr%)rDrCr&r? s   z#JoinCondition._annotate_present_fkscs>|j|jdgfdd}t|jid|idS)zvReturn True if the join condition contains column comparisons where both columns are in both tables. Fcsb|j|j}}t|tjr^t|tjr^|jr^|jr^|jr^|jr^dd<dS)NTr)rErFryrrZis_derived_fromtable)rHrf)mtptresultr%r&rI s      z;JoinCondition._refers_to_parent_table..visit_binaryrHr)rrrrr2)rUrIr%)rLrMrNr&_refers_to_parent_table s  z%JoinCondition._refers_to_parent_tablecCst|j|jS)z5Return True if parent/child tables have some overlap.)rrr)rUr%r%r&_tables_overlap szJoinCondition._tables_overlapcCsl|jr dS|jdk r|nJ|js*|jr4|n4|rN|dddn|r`| n| dS)zAnnotate the primaryjoin and secondaryjoin structures with 'remote' annotations marking columns considered as part of the 'remote' side. NcSs d|jkS)Nr')r5)rr%r%r&r" r#z0JoinCondition._annotate_remote..F) r8r1_annotate_remote_secondaryrWr$_annotate_remote_from_argsrO_annotate_selfrefrP_annotate_remote_with_overlap%_annotate_remote_distinct_selectables)rUr%r%r&r( s     zJoinCondition._annotate_remotecs4fdd}tji|_tji|_dS)z^annotate 'remote' in primaryjoin, secondaryjoin when 'secondary' is present. cs jj|r|ddiSdS)Nr!T)r1rrr)r!)rUr%r&repl' sz6JoinCondition._annotate_remote_secondary..replN)rr9r2r3)rUrVr%)rUr&rQ! s  z(JoinCondition._annotate_remote_secondarycs*fdd}tjid|i_dS)zxannotate 'remote' in primaryjoin, secondaryjoin when the relationship is detected as self-referential. csx|j|j}t|jtjrht|jtjrh|jrF|jddi|_|jrt|st|jddi|_n stdS)Nr!T)rErGrFryrrr_warn_non_column_elements)rHZequated)fnremote_side_givenrUr%r&rI8 s  z5JoinCondition._annotate_selfref..visit_binaryrHN)rrr2)rUrXrYrIr%)rXrYrUr&rS2 s zJoinCondition._annotate_selfrefcsn|jr(|jrtddd|jDn|j|rL|fdddnfdd}t|ji||_d S) 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.cSsg|] \}}|qSr%r%)rr1rr%r%r&rW sz.cs|kS)Nr%)r)r=r%r&r"\ r#z:JoinCondition._annotate_remote_from_args..Tcs|kr|ddiSdS)Nr!T)r)r!)r=r%r&rV_ sz6JoinCondition._annotate_remote_from_args..replN) rWr$rRrSrOrSrr9r2)rUrVr%)r=r&rRI s z(JoinCondition._annotate_remote_from_argscsNfdd}jdk o$jjjjk fddtjid|i_dS)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. cs0|j|j\|_|_|j|j\|_|_dS)N)rErF)rH)proc_left_rightr%r&rIo szAJoinCondition._annotate_remote_with_overlap..visit_binaryNcst|tjrDt|tjrDjj|rjj|r|ddi}nXrl|j dj j krl|ddi}n0r|j dj j kr|ddi}n ||fS)Nr!Tra) ryrrrrrrrr5rr]rrW)rErF)check_entitiesrUr%r&rZ{ s zDJoinCondition._annotate_remote_with_overlap..proc_left_rightrH)r]rrfrrr2)rUrIr%)r[rZrUr&rTg s  z+JoinCondition._annotate_remote_with_overlapcs"fdd}tji|_dS)z}annotate 'remote' in primaryjoin, secondaryjoin when the parent/child tables are entirely separate. cs<jj|r8jj|r*jj|r8|ddiSdS)Nr!T)rrrrrr)r!)rUr%r&rV szAJoinCondition._annotate_remote_distinct_selectables..replN)rr9r2)rUrVr%)rUr&rU s z3JoinCondition._annotate_remote_distinct_selectablescCstd|jdS)NzNon-simple column elements in primary join condition for property %s - consider using remote() annotations to mark the remote side.)rrr])rUr%r%r&rW sz'JoinCondition._warn_non_column_elementscs`||jdrdS|jr0tdd|jDnt|jjfdd}t|ji||_dS)aCAnnotate 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. r4NcSsg|] \}}|qSr%r%)rr1rr%r%r&r sz1JoinCondition._annotate_local..cs$d|jkr |kr |ddiSdS)Nr!r4T)r5r)r) local_sider%r&locals_ sz.JoinCondition._annotate_local..locals_) r=r2rWrrrrrr9)rUr]r%)r\r&r) s  zJoinCondition._annotate_localcs0jdkrdSfdd}tji|_dS)Ncs<d|jkr|djjiSd|jkr8|djjiSdS)Nr!rar4)r5rr]rrf)r)rUr%r&parentmappers_ s  z.parentmappers_)r]rr9r2)rUr^r%)rUr&r* s   z$JoinCondition._annotate_parentmappercCs|jstd|jfdS)NaRelationship %s 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.)rFrRrSr])rUr%r%r&r. sz JoinCondition._check_remote_sidecCsd}||d}t|}|r(t|j}n t|j}|jr<|sF|jsJ|rJdS|jr|r|sd|rbdpdd||jf}|d7}t|n*d|rdpd||jf}|d 7}t|dS) zHCheck the foreign key columns collected and emit error messages.Fr'NzCould not locate any simple equality expressions involving locally mapped foreign key columns for %s join condition '%s' on relationship %s.primaryr1a 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.z`Could not locate any relevant foreign key columns for %s join condition '%s' on relationship %s.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_annotationboolrrrr]rRrS)rUrr_Zcan_syncZ foreign_colsZ has_foreignerrr%r%r&r, s4        z!JoinCondition._check_foreign_colscCs|jdk rt|_nt|jj}t|jj}||j }||j }|r|r| |j dd}t dd| |j dD}|r|r|j |j}||}||}|r|st|_q|r|st|_qtd|jn(|rt|_n|rt|_ntd|jdS)z[Determine if this relationship is one to many, many to one, many to many. Nr!r'cSsg|]}d|jkr|qS)r!)r5)rrr%r%r&rL sz6JoinCondition._determine_direction..aDCan'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)r3rr5rrrrr intersectionrr`r2rMrr differencer r rRrSr])rUZ parentcolsZ targetcolsZ onetomany_fkZ manytoone_fkZonetomany_localZmanytoone_localZ self_equatedr%r%r&r-) s@         z"JoinCondition._determine_directioncCsdd|DS)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. cSs g|]\}}||fqSr%) _deannotate)rrrr%r%r&r sz3JoinCondition._deannotate_pairs..r%)rU collectionr%r%r&_deannotate_pairs} szJoinCondition._deannotate_pairscs~g}tgg}fdd}x4j|fj|fgD]\}}|dkrHq6|||q6W_|_|_dS)Ncsfdd}t||dS)Ncsd|jkr.d|jkr.|r.||fn,d|jkrZd|jkrZ|rZ||f|jtjkr||rd|jkr||fnd|jkr||fdS)Nr!r')r5rroperatorreqr)rHrErF)rflrprUr%r&rI s        z.go..visit_binary)r )joincondrfrI)rjrU)rfr&go sz&JoinCondition._setup_pairs..go)rZ OrderedSetr2r3rgrFrr)rUZ sync_pairsZsecondary_sync_pairsrlrkrfr%)rjrUr&r+ s   zJoinCondition._setup_pairsc s |js dSxdd|jDdd|jDD]\}tjdkrFq.|jkrht|j|i|j<q.g}|j}x^| D]R\}}|j t j kr|j |js| |jjr||k r||jjkr|||fqW|rtd|j|dfdd|Df||j|j<q.WdS) NcSsg|]\}}||fqSr%r%)rfrom_to_r%r%r&r szDJoinCondition._warn_for_conflicting_sync_targets..cSsg|]\}}||fqSr%r%)rrmrnr%r%r&r srzrelationship '%s' will copy column %s to column %s, which conflicts with relationship(s): %s. Consider applying viewonly=True to read-only relationships, or provide a primaryjoin condition marking writable columns with the foreign() annotation.z, c3s |]\}}d||fVqdS)z'%s' (copies %s to %s)Nr%)rprfr_)rnr%r&r szCJoinCondition._warn_for_conflicting_sync_targets..)rrrlenrV_track_overlapping_sync_targetsweakrefWeakKeyDictionaryr]itemsrrZ_mapper_registryrrfrNrrrr2)rUrmZ other_propsZ prop_to_fromrorpr%)rnr&r s8     z0JoinCondition._warn_for_conflicting_sync_targetscCs |dS)Nr!)_gather_join_annotations)rUr%r%r&r szJoinCondition.remote_columnscCs |dS)Nr4)rv)rUr%r%r&r szJoinCondition.local_columnscCs |dS)Nr')rv)rUr%r%r&r sz!JoinCondition.foreign_key_columnscCs>t||j|}|jdk r0|||j|dd|DS)NcSsh|] }|qSr%)re)rrr%r%r& sz9JoinCondition._gather_join_annotations..)rMr`r2r3update)rUr<sr%r%r&rv s  z&JoinCondition._gather_join_annotationscs&ttfddt|iDS)Ncsg|]}|jr|qSr%)issubsetr5)rr)r<r%r&r szAJoinCondition._gather_columns_with_annotation..)rMrr;)rUrr<r%)r<r&r` s z-JoinCondition._gather_columns_with_annotationc Cs t|ddi}|j|j|j}}}|dk rF|dk r>||@}n||@}|r|dk r|jdd}t|}t||jd|} |dk rt|t||jd}| |}n:t|t d|jd}|dk r|t|t d|jdd} | |}| p|} d| _ nd} |||| |fS) a7Given 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. rTN)Zflat) equivalentsr4) exclude_fnr{r!) rr2r3r1rrrchainrr_ColInAnnotationsr|) rUrjrrrr2r3r1Zprimary_aliasizerZsecondary_aliasizerrrr%r%r&r sT         zJoinCondition.join_targetsc stt}|jdk rXttxl|jD]"\}}|||f|||<q0Wn>szx8|jD]\}}|||<qdWnx|jD]\}}|||<qWfdd}|j}|jdksst |i|}|jdk r|j}rt |i|}t ||}fddD}|||fS)NcsXsd|jks,rTr|ks,sTd|jkrT|krLtjdd|jdd|<|SdS)Nr4r!T)rr)r5rrr)r)binds has_secondarylookuprr%r& col_to_bindy s z5JoinCondition.create_lazy_clause..col_to_bindcsi|]}||jqSr%)r[)rr)rr%r& sz4JoinCondition.create_lazy_clause..) rZ column_dictr3 collections defaultdictlistrFrr2rr9rr) rUrZequated_columnsr1rrZ lazywherer3rr%)rrrrr&create_lazy_clauseg s4       z JoinCondition.create_lazy_clause)N)F).rrrr.r/r&r%rdrrrrrr=r:r8r'r>r?rOrPr(rQrSrRrTrUrWr)r*r.r,r-rgr+rsrtrrrrrrrvr`rrr%r%r%r&rsb ([  # ./ BT +@  Qrc@s eZdZdZddZddZdS)r~zKSeralizable equivalent to: lambda c: "name" in c._annotations cCs ||_dS)N)name)rUrr%r%r&r. sz_ColInAnnotations.__init__cCs |j|jkS)N)rr5)rUrr%r%r&__call__ sz_ColInAnnotations.__call__N)rrrrr.rr%r%r%r&r~ sr~)2rZ __future__rrrsrrrrbaserZ interfacesrr r r r rr rrrrRrrrZ inspectionrrrrZsql.utilrrrrrrr r!r'Z class_loggerZ langhelpersZdependency_forr(r"objectrr~r%r%r%r&s~                              J