o znh@sXddlZddlZddlZddlmZddlmZddlmZddlmZddlm Z ddlm Z dd lm Z dd lm Z dd lm Z dd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZedZ GdddeZ!ddZ" dMd!d"Z#d#d$Z$Gd%d&d&ej%Z&Gd'd(d(e'Z(Gd)d*d*e Z)e*e(d+d,e*e)d-d,dNd/d0Z+ . .  . . . dOd1d2Z,dPd3d4Z-d5d6Z.d7d8Z/Gd9d:d:ej0Z1 dQd;d<Z2dRd=d>Z3dPd?d@Z4dAdBZ5dCdDZ6dEdFZ7dGdHZ8dIdJZ9dKdLZ:dS)SN) attributes)_class_to_mapper) _never_set) _none_set) attribute_str) class_mapper)InspectionAttr) instance_str) object_mapper) object_state)state_attribute_str)state_class_str) state_str)MapperProperty)PropComparator) PathRegistry)event)exc) inspection)sql)util) expression)delete delete-orphanallmergeexpunge save-updaterefresh-expirenonec@sJeZdZdZegdZeZgdZdZ ddZ ddZ e d d Z d S) CascadeOptionsz9Keeps track of the options sent to relationship().cascade)rr!r)rrr!r ) save_updaterrefresh_expirerr delete_orphanc Cst|tjs |dur||St|}||jr.tdd ddt ||jDd|vr8| |j d|vr@| |dtt|}d|v|_d|v|_d |v|_d |v|_d |v|_d |v|_|jrt|jsttd |S)NzInvalid cascade option(s): %s, cSsg|]}t|qS)repr.0xr'r'>/usr/local/lib/python3.10/dist-packages/sqlalchemy/orm/util.py Osz*CascadeOptions.__new__..rr!rrr rrrz5The 'delete-orphan' cascade option requires 'delete'.) isinstancer string_types from_stringset difference_allowed_cascadessa_exc ArgumentErrorjoinsortedupdate_add_w_all_cascadescleardiscard frozenset__new__r"r#rr$rrr%warn)cls value_listvaluesselfr'r'r,r=Gs@             zCascadeOptions.__new__cCsddddt|DS)NzCascadeOptions(%r),cSsg|]}|qSr'r'r)r'r'r,r-msz+CascadeOptions.__repr__..)r6r7rBr'r'r,__repr__lszCascadeOptions.__repr__cCs"ddtd|p dD}||S)NcSsg|]}|r|qSr'r')r*cr'r'r,r-qsz.CascadeOptions.from_string..z\s*,\s*)resplit)r?argrAr'r'r,r0oszCascadeOptions.from_stringN)__name__ __module__ __qualname____doc__ all_cascadesr2r9r3_viewonly_cascades __slots__r=rE classmethodr0r'r'r'r,r"4s %r"c ssfdd|r/fdd}fdd}fdd}fd d }nfd d}fd d}fd d}tj|d|dddtj|d|ddtj|d|ddd|rutj|d|ddddSdS)zNRuns a validation method on an attribute value to be set or appended. cs|jj}|j|uSN)managerimpl)state initiatorrU)keyr'r,detect_is_backref|s  z,_validator_events..detect_is_backrefcs0|jtjurs ||s||dS|SNFoprOP_BULK_REPLACEobjrVvaluerWrYinclude_backrefsrX validatorr'r,appends z!_validator_events..appendc<s||s|fdd|D|dd<dSdS)Ncsg|] }|dqS)Fr'r*r`rXr^rcr'r,r-s7_validator_events..bulk_set..r^rVrArWrarir,bulk_sets z#_validator_events..bulk_setcs$s||s||dS|SrZrirVr`oldvaluerWrar'r,set_sz_validator_events..set_cs(s||s||ddSdS)NTrir_rar'r,removesz!_validator_events..removecs.|jtjurs ||s||S|SrSr[r_rar'r,rds cre)Ncsg|]}|qSr'r'rfrgr'r,r-srhrirjrarir,rks"cs"s||s||S|SrSrirlrar'r,rnsrdT)rawretval bulk_replace)rpr1roN)rlisten) descrXrcinclude_removesrbrdrkrnror'rar,_validator_eventsus  rvp_unionTc st}ii|D]1}||ttjr||<i}jD]}||j|||j<|j |j<q#|<q fddg}| D];\} |durr| tj fdd|Dt t| |ggdqJ| tj fdd|DgdqJtj||S)a)Create a ``UNION`` statement used by a polymorphic mapper. See :ref:`concrete_inheritance` for an example of how this is used. :param table_map: mapping of polymorphic identities to :class:`.Table` objects. :param typecolname: string name of a "discriminator" column, which will be derived from the query, producing the polymorphic identity for each row. If ``None``, no polymorphic discriminator is generated. :param aliasname: name of the :func:`~sqlalchemy.sql.expression.alias()` construct generated. :param cast_nulls: if True, non-existent columns, which are represented as labeled NULLs, will be passed into CAST. This is a legacy behavior that is problematic on some backends such as Oracle - in which case it can be set to False. cs^z||WSty.rtt||YStt||YSwrS)KeyErrorrcastnulllabel type_coerce)nametable) cast_nulls colnamemapstypesr'r,cols zpolymorphic_union..colNcg|]}|qSr'r'r*r}rr~r'r,r-z%polymorphic_union..)from_objcrr'r'rrr'r,r-r)r OrderedSetr.rSelectaliasrFaddrXtypeitemsrdselectliteral_columnsql_util_quote_ddl_exprr{ union_all) table_map typecolname aliasnamercolnamesrXmrFresulttype_r')rrrr~rr,polymorphic_unionsH       rc Os|rad}t|}|dkr&|d}z|d}Wnty%|d}Ynw|dvr/|\}}ntd||dd}|rHtd d |t|}|durZ|jt ||d S|j ||d S|d }|rstd d |j t |}| |S) aGenerate "identity key" tuples, as are used as keys in the :attr:`.Session.identity_map` dictionary. This function has several call styles: * ``identity_key(class, ident, identity_token=token)`` This form receives a mapped class and a primary key scalar or tuple as an argument. E.g.:: >>> identity_key(MyClass, (1, 2)) (, (1, 2), None) :param class: mapped class (must be a positional argument) :param ident: primary key, may be a scalar or tuple argument. :param identity_token: optional identity token .. versionadded:: 1.2 added identity_token * ``identity_key(instance=instance)`` This form will produce the identity key for a given instance. The instance need not be persistent, only that its primary key attributes are populated (else the key will contain ``None`` for those missing values). E.g.:: >>> instance = MyClass(1, 2) >>> identity_key(instance=instance) (, (1, 2), None) In this form, the given instance is ultimately run though :meth:`.Mapper.identity_key_from_instance`, which will have the effect of performing a database check for the corresponding row if the object is expired. :param instance: object instance (must be given as a keyword arg) * ``identity_key(class, row=row, identity_token=token)`` This form is similar to the class/tuple form, except is passed a database result row as a :class:`.RowProxy` object. E.g.:: >>> row = engine.execute("select * from table where a=1 and b=2").first() >>> identity_key(MyClass, row=row) (, (1, 2), None) :param class: mapped class (must be a positional argument) :param row: :class:`.RowProxy` row returned by a :class:`.ResultProxy` (must be given as a keyword arg) :param identity_token: optional identity token .. versionadded:: 1.2 added identity_token Nrrrowident)rz1expected up to three positional arguments, got %sidentity_tokenzunknown keyword arguments: %sr&)rinstance)lenpoprxr4r5r6ridentity_key_from_primary_keyrto_listidentity_key_from_rowkeysr identity_key_from_instance) argskwargsrlargsclass_rrmapperrr'r'r, identity_keysF?       rc@s*eZdZdZ    d ddZddZdS) ORMAdapterzaColumnAdapter subclass which excludes adaptation of entities from non-matching mappers. NFTc CsPt|}|j|_|j}|j}|r||_nd|_tjj|||||||j ddS)N)adapt_requiredallow_label_resolveanonymize_labels include_fn) rinspectr selectableis_aliased_class aliased_classr ColumnAdapter__init__ _include_fn) rBentity equivalentsrrrinforrr'r'r,rms  zORMAdapter.__init__cCs |jdd}| p||jS)N parentmapper) _annotationsgetisar)rBelemrr'r'r,rszORMAdapter._include_fn)NFTF)rKrLrMrNrrr'r'r'r,rgs rc@sDeZdZdZ         d ddZddZd d Zd d ZdS) AliasedClassaRepresents an "aliased" form of a mapped class for usage with Query. The ORM equivalent of a :func:`~sqlalchemy.sql.expression.alias` construct, this object mimics the mapped class using a ``__getattr__`` scheme and maintains a reference to a real :class:`~sqlalchemy.sql.expression.Alias` object. A primary purpose of :class:`.AliasedClass` is to serve as an alternate within a SQL statement generated by the ORM, such that an existing mapped entity can be used in multiple contexts. A simple example:: # find all pairs of users with the same name user_alias = aliased(User) session.query(User, user_alias).\ join((user_alias, User.id > user_alias.id)).\ filter(User.name == user_alias.name) :class:`.AliasedClass` is also capable of mapping an existing mapped class to an entirely new selectable, provided this selectable is column- compatible with the existing mapped selectable, and it can also be configured in a mapping as the target of a :func:`.relationship`. See the links below for examples. The :class:`.AliasedClass` object is constructed typically using the :func:`.orm.aliased` function. It also is produced with additional configuration when using the :func:`.orm.with_polymorphic` function. The resulting object is an instance of :class:`.AliasedClass`. This object implements an attribute scheme which produces the same attribute and method interface as the original mapped class, allowing :class:`.AliasedClass` to be compatible with any attribute technique which works on the original class, including hybrid attributes (see :ref:`hybrids_toplevel`). The :class:`.AliasedClass` can be inspected for its underlying :class:`.Mapper`, aliased selectable, and other information using :func:`.inspect`:: from sqlalchemy import inspect my_alias = aliased(MyClass) insp = inspect(my_alias) The resulting inspection object is an instance of :class:`.AliasedInsp`. .. seealso:: :func:`.aliased` :func:`.with_polymorphic` :ref:`relationship_aliased_class` :ref:`relationship_to_window_function` NFr'c Csft|} |dur| jj||d}t|| |||r|n| j|dur!|n| j|| || |_d| jj|_dS)N)r}flatzAliasedClass_%s) r_with_polymorphic_selectabler AliasedInspwith_polymorphic_mapperspolymorphic_on _aliased_insprrK) rBr?rr}radapt_on_namesrwith_polymorphic_discriminator base_aliasuse_mapper_pathrepresents_outer_joinrr'r'r,rs,zAliasedClass.__init__cCsz|jd}Wn tytw|j}t||}t|dr+t|dr+t|j|St|dr6| d|}t|drF| |}t ||||S)Nr__call____self____get__adapt_to_entity) __dict__rxAttributeError_targetgetattrhasattrr MethodType__func__rrsetattr)rBrXrtargetattrr'r'r, __getattr__s       zAliasedClass.__getattr__cCsdt||jjjfS)Nz)idrrrKrDr'r'r,rE szAliasedClass.__repr__cCs t|jSrS)strrrDr'r'r,__str__ zAliasedClass.__str__) NNFFr'NNFF)rKrLrMrNrrrErr'r'r'r,rs= ' rc@seZdZdZddZeddZdZ eddZed d Z d d Z d dZ ddZ ddZ ejddZejddZddZddZddZdS)raProvide an inspection interface for an :class:`.AliasedClass` object. The :class:`.AliasedInsp` object is returned given an :class:`.AliasedClass` using the :func:`.inspect` function:: from sqlalchemy import inspect from sqlalchemy.orm import aliased my_alias = aliased(MyMappedClass) insp = inspect(my_alias) Attributes on :class:`.AliasedInsp` include: * ``entity`` - the :class:`.AliasedClass` represented. * ``mapper`` - the :class:`.Mapper` mapping the underlying class. * ``selectable`` - the :class:`.Alias` construct which ultimately represents an aliased :class:`.Table` or :class:`.Select` construct. * ``name`` - the name of the alias. Also is used as the attribute name when returned in a result tuple from :class:`.Query`. * ``with_polymorphic_mappers`` - collection of :class:`.Mapper` objects indicating all those mappers expressed in the select construct for the :class:`.AliasedClass`. * ``polymorphic_on`` - an alternate column or SQL expression which will be used as the "discriminator" for a polymorphic load. .. seealso:: :ref:`inspection_toplevel` c Cst||_||_||_|_|_||_||_t|p||_ ||_ | |_ |rVd|_ ||_ g|_|j D] } | |urTt| j||| |d} t|j| jj| |j| jq4nd|_ |g|_ tj||j| dd|_| |_|j|_dS)NT)rrrF)rrr)weakrefref _weak_entityrrpersist_selectable local_tabler}r _base_alias_use_mapper_pathr_is_with_polymorphicr_with_polymorphic_entitiesrrrrrKrdrrr_equivalent_columns_adapter_adapt_on_namesr) rBrrrr}rrrrrrpolyentr'r'r,r;sL   zAliasedInsp.__init__cCs|SrS)rrDr'r'r,rrszAliasedInsp.entityTcCs|jjS)zUReturn the mapped class ultimately represented by this :class:`.AliasedInsp`.)rrrDr'r'r,ryszAliasedInsp.class_cCs|jr|jjSt|SrS)rr_path_registryr per_mapperrDr'r'r,rs zAliasedInsp._path_registryc Cs0|j|j|j|j|j|j|j||j|j d S)N) rrrr}rrrrrr) rrrr}rrrrrrrDr'r'r, __getstate__szAliasedInsp.__getstate__c CsH||d|d|d|d|d|d|d|d|d |d  dS) Nrrrr}rrrrrr)r)rBrVr'r'r, __setstate__szAliasedInsp.__setstate__cCs|j|||jdS)N) parententityr)rtraverse _annotater)rBrr'r'r,_adapt_elements  zAliasedInsp._adapt_elementcCsN|j}||vr||jur|St|j|jjjS||jr|SJd||f)NFz"mapper %s doesn't correspond to %s)rrrrrrKrr)rBr self_polyr'r'r,_entity_for_mappers   zAliasedInsp._entity_for_mappercs.jj\}}j|fdd|DfS)Ncsi|] \}}j||qSr')rr)r*rparamrDr'r, s z+AliasedInsp._get_clause..)r _get_clauserrr)rBonclause replacemapr'rDr,rs   zAliasedInsp._get_clausecCsiSrSr'rDr'r'r,_memoized_valuesszAliasedInsp._memoized_valuescOs0||jvr |j|S||i||j|<}|SrS)r)rBrX callable_rkwr`r'r'r,_memos  zAliasedInsp._memocCs<|jrdddd|jD}nd}dt||jj|fS)Nz(%s)r&css|]}|jjVqdSrS)rrKr*mpr'r'r, s z'AliasedInsp.__repr__..rGz)rr6rrrK)rB with_polyr'r'r,rEs  zAliasedInsp.__repr__cs:jrdjjdfddjDfSdjjfS)Nzwith_polymorphic(%s, [%s])r&c3s"|] }|jur|jjVqdSrS)rrrKrrDr'r,rs z&AliasedInsp.__str__..z aliased(%s))rrrKr6rrDr'rDr,rs zAliasedInsp.__str__N)rKrLrMrNrpropertyrrrrrrrrrmemoized_propertyrrrrErr'r'r'r,rs,#7      rcCs|jSrS)rrr'r'r,srcCs|SrSr'rr'r'r,rsFcCs:t|tjr|r td|j||dSt|||||dS)agProduce an alias of the given element, usually an :class:`.AliasedClass` instance. E.g.:: my_alias = aliased(MyClass) session.query(MyClass, my_alias).filter(MyClass.id > my_alias.id) The :func:`.aliased` function is used to create an ad-hoc mapping of a mapped class to a new selectable. By default, a selectable is generated from the normally mapped selectable (typically a :class:`.Table`) using the :meth:`.FromClause.alias` method. However, :func:`.aliased` can also be used to link the class to a new :func:`.select` statement. Also, the :func:`.with_polymorphic` function is a variant of :func:`.aliased` that is intended to specify a so-called "polymorphic selectable", that corresponds to the union of several joined-inheritance subclasses at once. For convenience, the :func:`.aliased` function also accepts plain :class:`.FromClause` constructs, such as a :class:`.Table` or :func:`.select` construct. In those cases, the :meth:`.FromClause.alias` method is called on the object and the new :class:`.Alias` object returned. The returned :class:`.Alias` is not ORM-mapped in this case. :param element: element to be aliased. Is normally a mapped class, but for convenience can also be a :class:`.FromClause` element. :param alias: Optional selectable unit to map the element to. This should normally be a :class:`.Alias` object corresponding to the :class:`.Table` to which the class is mapped, or to a :func:`.select` construct that is compatible with the mapping. By default, a simple anonymous alias of the mapped table is generated. :param name: optional string name to use for the alias, if not specified by the ``alias`` parameter. The name, among other things, forms the attribute name that will be accessible via tuples returned by a :class:`.Query` object. :param flat: Boolean, will be passed through to the :meth:`.FromClause.alias` call so that aliases of :class:`.Join` objects don't include an enclosing SELECT. This can lead to more efficient queries in many circumstances. A JOIN against a nested JOIN will be rewritten as a JOIN against an aliased SELECT subquery on backends that don't support this syntax. .. versionadded:: 0.9.0 .. seealso:: :meth:`.Join.alias` :param adapt_on_names: if True, more liberal "matching" will be used when mapping the mapped columns of the ORM entity to those of the given selectable - a name-based match will be performed if the given selectable doesn't otherwise have a column that corresponds to one on the entity. The use case for this is when associating an entity with some derived selectable such as one that uses aggregate functions:: class UnitPrice(Base): __tablename__ = 'unit_price' ... unit_id = Column(Integer) price = Column(Numeric) aggregated_unit_price = Session.query( func.sum(UnitPrice.price).label('price') ).group_by(UnitPrice.unit_id).subquery() aggregated_unit_price = aliased(UnitPrice, alias=aggregated_unit_price, adapt_on_names=True) Above, functions on ``aggregated_unit_price`` which refer to ``.price`` will return the ``func.sum(UnitPrice.price).label('price')`` column, as it is matched on the name "price". Ordinarily, the "price" function wouldn't have any "column correspondence" to the actual ``UnitPrice.price`` column as it is not a proxy of the original. z+adapt_on_names only applies to ORM elementsr)rrr}r)r.r FromClauser4r5rr)elementrr}rrr'r'r,aliaseds Pr c Cst|} |r'|j| us Jt|}tdd|jD} || kr"|S|| }| j|||d\} }|s5|r;|j|d}t ||| ||| dS)a Produce an :class:`.AliasedClass` construct which specifies columns for descendant mappers of the given base. Using this method will ensure that each descendant mapper's tables are included in the FROM clause, and will allow filter() criterion to be used against those tables. The resulting instances will also have those columns already loaded so that no "post fetch" of those columns will be required. .. seealso:: :ref:`with_polymorphic` - full discussion of :func:`.orm.with_polymorphic`. :param base: Base class to be aliased. :param classes: a single class or mapper, or list of class/mappers, which inherit from the base class. Alternatively, it may also be the string ``'*'``, in which case all descending mapped classes will be added to the FROM clause. :param aliased: when True, the selectable will be wrapped in an alias, that is ``(SELECT * FROM ) AS anon_1``. This can be important when using the with_polymorphic() to create the target of a JOIN on a backend that does not support parenthesized joins, such as SQLite and older versions of MySQL. However if the :paramref:`.with_polymorphic.selectable` parameter is in use with an existing :class:`.Alias` construct, then you should not set this flag. :param flat: Boolean, will be passed through to the :meth:`.FromClause.alias` call so that aliases of :class:`.Join` objects don't include an enclosing SELECT. This can lead to more efficient queries in many circumstances. A JOIN against a nested JOIN will be rewritten as a JOIN against an aliased SELECT subquery on backends that don't support this syntax. Setting ``flat`` to ``True`` implies the ``aliased`` flag is also ``True``. .. versionadded:: 0.9.0 .. seealso:: :meth:`.Join.alias` :param selectable: a table or select() statement that will be used in place of the generated FROM clause. This argument is required if any of the desired classes use concrete table inheritance, since SQLAlchemy currently cannot generate UNIONs among tables automatically. If used, the ``selectable`` argument must represent the full set of tables and columns mapped by every mapped class. Otherwise, the unaccounted mapped columns will result in their table being appended directly to the FROM clause which will usually lead to incorrect results. :param polymorphic_on: a column to be used as the "discriminator" column for the given selectable. If not given, the polymorphic_on attribute of the base classes' mapper will be used, if any. This is useful for mappings that don't have polymorphic loading behavior by default. :param innerjoin: if True, an INNER JOIN will be used. This should only be specified if querying for one specific subtype only cSsg|]}|jqSr')rrr'r'r,r-sz$with_polymorphic..) innerjoinr )rrrr) rrrto_setr1runion_with_polymorphic_argsrr) baseclassesrrrr r r_existing_aliasprimary_mapper new_classesmappersr'r'r,with_polymorphicJs.K    rcCst|ddi|S)zDeep copy the given ClauseElement, annotating each element with the "_orm_adapt" flag. Elements within the exclude collection will be cloned but not annotated. _orm_adaptT)r_deep_annotate)r excluder'r'r, _orm_annotatesrcCstj|ddS)zRemove annotations that link a column to a particular mapping. Note this doesn't affect "remote" and "foreign" annotations passed by the :func:`.orm.foreign` and :func:`.orm.remote` annotators. )rr)rAr_deep_deannotater r'r'r,_orm_deannotates rcCs t|SrSrrr'r'r,_orm_full_deannotaterr c@sPeZdZdZejjZ     d ddZddZ    d dd Z dd d Z dS)_ORMJoinz/Extend Join to support ORM constructs as input.NFcCs|t|}t|d|} t|} | j} | |_||_||_t|tj r(t| j |}t|t j r7|j } |j} nt|trC|} | jj} nd} | rt| |jrQ| }n|j}| j|| dd| jdd\}}}}}}|dur|rvt|||}|}n t||||}|}n|}||_tj||||||| st| ddr| jjr| jj}|dur| jr| j |}|j!|@|_!dSdSdSdSdS)N_joined_from_infoT)source_selectabledest_selectablesource_polymorphicdest_polymorphicof_type_mapperalias_secondaryr)"rrrrr" _left_memo _right_memor.rr/rrQueryableAttribute comparator_source_selectablerrparentrclause_is_present _create_joinsrrr6_target_adapterrJoinrsingle_single_table_criterionrrrr)rBleftrightrisouterfullr)r* left_info left_orm_info right_infoadapt_to on_selectableprop adapt_frompjsjsourcedest secondarytarget_adapter single_critr'r'r,rsr              z_ORMJoin.__init__cCsj|}t|tjr|j}t|tjs|j|usJt|j|j|j|j|j|jd}t||j|j|j|j dS)zlSplice a join into the center. Given join(a, b) and join(b, c), return join(a, b).join(c) )r7r)r*)r7r*) r.rr2r5r6r!rr7r)r*)rBotherleftmostr5r'r'r,_splice_into_center#s(   z_ORMJoin._splice_into_centercCst|||||dS)N)r8r7r!)rBr6rr7r8 join_to_leftr'r'r,r6@sz _ORMJoin.joincCst|||d|dS)NT)r7r8rJ)rBr6rr8rKr'r'r, outerjoinJsz_ORMJoin.outerjoin)NFFNNNFFNNFN) rKrLrMrNrr2__visit_name__rrIr6rLr'r'r'r,r!s  S   r!cCst|||||S)aProduce an inner join between left and right clauses. :func:`.orm.join` is an extension to the core join interface provided by :func:`.sql.expression.join()`, where the left and right selectables may be not only core selectable objects such as :class:`.Table`, but also mapped classes or :class:`.AliasedClass` instances. The "on" clause can be a SQL expression, or an attribute or string name referencing a configured :func:`.relationship`. :func:`.orm.join` is not commonly needed in modern usage, as its functionality is encapsulated within that of the :meth:`.Query.join` method, which features a significant amount of automation beyond :func:`.orm.join` by itself. Explicit usage of :func:`.orm.join` with :class:`.Query` involves usage of the :meth:`.Query.select_from` method, as in:: from sqlalchemy.orm import join session.query(User).\ select_from(join(User, Address, User.addresses)).\ filter(Address.email_address=='foo@bar.com') In modern SQLAlchemy the above join can be written more succinctly as:: session.query(User).\ join(User.addresses).\ filter(Address.email_address=='foo@bar.com') See :meth:`.Query.join` for information on modern usage of ORM level joins. .. deprecated:: 0.8 the ``join_to_left`` parameter is deprecated, and will be removed in a future release. The parameter has no effect. rJ)r5r6rr7r8rKr'r'r,r6Ns*r6cCst|||d|S)aProduce a left outer join between left and right clauses. This is the "outer join" version of the :func:`.orm.join` function, featuring the same behavior except that an OUTER JOIN is generated. See that function's documentation for other usage details. TrJ)r5r6rr8rKr'r'r,rL{srLcCsDt|tjrt|}t|j|j}n t|tjr|j}|j ||dS)aCreate filtering criterion that relates this query's primary entity to the given related instance, using established :func:`.relationship()` configuration. The SQL rendered is the same as that rendered when a lazy loader would fire off from the given parent on that attribute, meaning that the appropriate state is taken from the parent object in Python without the need to render joins to the parent table in the rendered statement. :param instance: An instance which has some :func:`.relationship`. :param property: String property name, or class-bound attribute, which indicates what relationship from the instance should be used to reconcile the parent/child relationship. :param from_entity: Entity in which to consider as the left side. This defaults to the "zero" entity of the :class:`.Query` itself. .. versionadded:: 1.2 ) from_entity) r.rr/r rrrrr+ _with_parent)rr>rPrr'r'r, with_parents  rRcCt|}|jS)zReturn True if the given object has a database identity. This typically corresponds to the object being in either the persistent or detached state. .. seealso:: :func:`.was_deleted` )rinstance_state has_identityobject_rVr'r'r,rUs rUcCrS)zReturn True if the given object was deleted within a session flush. This is regardless of whether or not the object is persistent or detached. .. seealso:: :attr:`.InstanceState.was_deleted` )rrT was_deletedrVr'r'r,rXs rXcCsL|jr|jr||urdSdS|jr!|jr||jvS||uS||S)zdetermine if 'given' corresponds to 'entity', in terms of an entity passed to Query that would match the same entity being referred to elsewhere in the query. TF)rrrr common_parentgivenrr'r'r,_entity_corresponds_tos  r\cCsH|jr|jo|j o||up||jvS|js||jS|jo#||jvS)adetermine if 'given' corresponds to 'entity', in terms of a path of loader options where a mapped attribute is taken to be a member of a parent entity. e.g.:: someoption(A).someoption(A.b) # -> fn(A, A) -> True someoption(A).someoption(C.d) # -> fn(A, C) -> False a1 = aliased(A) someoption(a1).someoption(A.b) # -> fn(a1, A) -> False someoption(a1).someoption(a1.b) # -> fn(a1, a1) -> True wp = with_polymorphic(A, [A1, A2]) someoption(wp).someoption(A1.foo) # -> fn(wp, A1) -> False someoption(wp).someoption(wp.A1.foo) # -> fn(wp, wp.A1) -> True )rrrrYrrrZr'r'r,$_entity_corresponds_to_use_path_impls r]cCs6|jr||jvp |j|S|jr||jvS||S)zedetermine if 'given' "is a" mapper, in terms of the given would load rows of type 'mapper'. )rrrr)r[rr'r'r, _entity_isas  r^cCsRddlm}m}m}m}ddlm}ddlm}||_ |_ |_ |_ |_ dS)aZUse random-ordering sets within the unit of work in order to detect unit of work sorting issues. This is a utility function that can be used to help reproduce inconsistent unit of work sorting issues. For example, if two kinds of objects A and B are being inserted, and B has a foreign key reference to A - the A must be inserted first. However, if there is no relationship between A and B, the unit of work won't know to perform this sorting, and an operation may or may not fail, depending on how the ordering works out. Since Python sets and dictionaries have non-deterministic ordering, such an issue may occur on some runs and not on others, and in practice it tends to have a great dependence on the state of the interpreter. This leads to so-called "heisenbugs" where changing entirely irrelevant aspects of the test program still cause the failure behavior to change. By calling ``randomize_unitofwork()`` when a script first runs, the ordering of a key series of sets within the unit of work implementation are randomized, so that the script can be minimized down to the fundamental mapping and operation that's failing, while still reproducing the issue on at least some runs. This utility is also available when running the test suite via the ``--reversetop`` flag. r) unitofworksessionr dependency) topological) RandomSetN) sqlalchemy.ormr_r`rrasqlalchemy.utilrbsqlalchemy.testing.utilrcr1)r_r`rrarbrcr'r'r,randomize_unitofworks   rg)rwT)NNFF)FFNFFFNrSrMrN);rHrrrGrrrrrrrr r r r r rr interfacesrr path_registryrrrr4rrrrrr<rOr"rvrrrrobjectrr _inspectsr rrrr r2r!r6rLrRrUrXr\r]r^rgr'r'r'r,s                       AC Ig' P c e  - ##