B 4];@s>ddlZddlZddlmZddlmZddlmZddlmZddlmZddlm Z dd lm Z dd lm Z dd lm Z dd lm Z dd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZedZGdddeZ 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:ej/Z0dQd;d<Z1dRd=d>Z2dSd?d@Z3dAdBZ4dCdDZ5dEdFZ6dGdHZ7dIdJZ8dKdLZ9dS)TN) 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)deletez delete-orphanallmergeexpungez save-updatezrefresh-expirenonec@sDeZdZdZedddgZeZdZddZ dd Z e d d Z d S) CascadeOptionsz9Keeps track of the options sent to relationship().cascaderrz delete-orphan) save_updaterrefresh_expirerr delete_orphanc Cst|tjs|dkr||St|}||jr\tdd ddt ||jDd|krp| |j d|kr| |dtt|}d|k|_d|k|_d |k|_d |k|_d |k|_d |k|_|jr|jstd |S)NzInvalid cascade option(s): %sz, cSsg|] }t|qS)repr).0xr#r#F/opt/alt/python37/lib64/python3.7/site-packages/sqlalchemy/orm/util.py Msz*CascadeOptions.__new__..rrz save-updaterzrefresh-expirerrz delete-orphanz5The 'delete-orphan' cascade option requires 'delete'.) isinstancer string_types from_stringset difference_allowed_cascadessa_exc ArgumentErrorjoinsortedupdate_add_w_all_cascadescleardiscard frozenset__new__rr rr!rrr"warn)clsZ value_listvaluesselfr#r#r'r8Ds4            zCascadeOptions.__new__cCsddddt|DS)NzCascadeOptions(%r),cSsg|]}|qSr#r#)r%r&r#r#r'r(jsz+CascadeOptions.__repr__..)r1r2)r<r#r#r'__repr__iszCascadeOptions.__repr__cCs"ddtd|pdD}||S)NcSsg|] }|r|qSr#r#)r%cr#r#r'r(nsz.CascadeOptions.from_string..z\s*,\s*)resplit)r:argr;r#r#r'r+lszCascadeOptions.from_stringN) __name__ __module__ __qualname____doc__ all_cascadesr-r4r. __slots__r8r> classmethodr+r#r#r#r'r3s %rc ssfdd|r^fdd}fdd}fdd}fd d }n6fd d}fd d}fd d}tj|d|dddtj|d|ddtj|d|ddd|rtj|d|ddddS)zNRuns a validation method on an attribute value to be set or appended. cs|jj}|j|k S)N)Zmanagerimpl)state initiatorrK)keyr#r'detect_is_backrefys z,_validator_events..detect_is_backrefcs4|jtjk r,s||s,||dS|SdS)NF)oprOP_BULK_REPLACEobj)rLvaluerM)rOinclude_backrefsrN validatorr#r'appends z!_validator_events..appendcs8s||s4|fdd|D|dd<dS)Ncsg|]}|dqS)Fr#)r%rS)rNrRrUr#r'r(sz7_validator_events..bulk_set..)rR)rLr;rM)rOrTrNrU)rRr'bulk_setsz#_validator_events..bulk_setcs(s||s ||dS|SdS)NF)rR)rLrSoldvaluerM)rOrTrNrUr#r'set_sz_validator_events..set_cs$s||s ||ddS)NT)rR)rLrSrM)rOrTrNrUr#r'removesz!_validator_events..removecs2|jtjk r*s||s*||S|SdS)N)rPrrQrR)rLrSrM)rOrTrNrUr#r'rVs cs8s||s4|fdd|D|dd<dS)Ncsg|]}|qSr#r#)r%rS)rNrRrUr#r'r(sz7_validator_events..bulk_set..)rR)rLr;rM)rOrTrNrU)rRr'rWscs&s||s||S|SdS)N)rR)rLrSrXrM)rOrTrNrUr#r'rYsrVT)rawZretvalZ bulk_replace)r[r,rZN)rZlisten) ZdescrNrUZinclude_removesrTrVrWrYrZr#)rOrTrNrUr'_validator_eventsrs r\p_unionTc s(t}iixn|D]f}||ttjr>||<i}x0jD]&}||j|||j<|j |j<qJW|<qWfddg}x| D]v\} |dk r| tj fdd|Dt t| |ggdq| tj fdd|DgdqWtj||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^y ||Stk rXr:tt||Stt||SYnXdS)N)KeyErrorrcastZnulllabelZ type_coerce)nametable) cast_nulls colnamemapstypesr#r'cols  zpolymorphic_union..colNcsg|]}|qSr#r#)r%ra)rfrbr#r'r(sz%polymorphic_union..)Zfrom_objcsg|]}|qSr#r#)r%ra)rfrbr#r'r(s)rZ OrderedSetr)rZSelectaliasr?addrNtypeitemsrVZselectZliteral_columnsql_utilZ_quote_ddl_exprr`Z union_all) Z table_mapZ typecolnameZ aliasnamercZcolnamesrNmr?resultZtype_r#)rcrfrdrbrer'polymorphic_unions:        "rnc Os|rd}t|}|dkrP|d}y|d}Wqptk rL|d}YqpXn |dkrb|\}}ntd||dd}|rtd d |t|}|dkr|jt ||d S|j ||d Sn6|d }|rtd d |j t |}| |SdS) 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: %sz, )rrinstance)lenpopr^r/r0r1rZidentity_key_from_primary_keyrZto_listZidentity_key_from_rowkeysr Zidentity_key_from_instance) argskwargsroZlargsclass_rprrmapperrsr#r#r' identity_keys:?     r{c@s"eZdZdZd 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_labelsZ include_fn) rinspectrz selectableis_aliased_classZ aliased_classrk ColumnAdapter__init__ _include_fn) r<entity equivalentsr}r~rinforrr#r#r'rjs zORMAdapter.__init__cCs |jdd}| p||jS)N parentmapper)Z _annotationsgetisarz)r<elemrr#r#r'rszORMAdapter._include_fn)NFTF)rDrErFrGrrr#r#r#r'r|ds  r|c @s2eZdZdZd 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|} |dkr | jj||d}t|| |||r2|n| j|dk rB|n| j|| || |_d| jj|_dS)N)raflatzAliasedClass_%s) rZ_with_polymorphic_selectablerg AliasedInspwith_polymorphic_mapperspolymorphic_on _aliased_inspryrD) r<r:rgraradapt_on_namesrwith_polymorphic_discriminator base_aliasuse_mapper_pathrepresents_outer_joinrzr#r#r'rs$  zAliasedClass.__init__cCsy|jd}Wntk r(tYnX|j}t||}t|dr\t|dr\t|j|St|drr| d|}t|dr| |}t ||||S)Nr__call____self____get__adapt_to_entity) __dict__r^AttributeError_targetgetattrhasattrre MethodType__func__rrsetattr)r<rNrtargetattrr#r#r' __getattr__s       zAliasedClass.__getattr__cCsdt||jjjfS)Nz)idrrrD)r<r#r#r'r> szAliasedClass.__repr__cCs t|jS)N)strr)r<r#r#r'__str__szAliasedClass.__str__) NNFFr#NNFF)rDrErFrGrrr>rr#r#r#r'rs9 rc@seZdZdZddZdZeddZej ddZ d d Z d d Z d dZ ddZej ddZej ddZddZddZddZdS)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 Cs||_||_||_|_|_||_||_|p0||_||_| |_ |rd|_ ||_ g|_ xZ|j D]@} | |k r^t | j||| |d} t|j| jj| |j | jq^Wnd|_ |g|_ tj||j| dd|_| |_|j|_dS)NT)rrrF)rrr)rrzrZpersist_selectableZ local_tablerar _base_alias_use_mapper_pathr_is_with_polymorphicr_with_polymorphic_entitiesrryrrDrVrrkrZ_equivalent_columns_adapter_adapt_on_namesr) r<rrzrrarrrrrrZpolyZentr#r#r'r8s>    zAliasedInsp.__init__TcCs|jjS)zUReturn the mapped class ultimately represented by this :class:`.AliasedInsp`.)rzry)r<r#r#r'ryrszAliasedInsp.class_cCs|jr|jjSt|SdS)N)rrz_path_registryrZ per_mapper)r<r#r#r'rxszAliasedInsp._path_registryc Cs.|j|j|j|j|j|j|j|j|j|j d S)N) rrzrgrarrrrrr) rrzrrarrrrrr)r<r#r#r' __getstate__szAliasedInsp.__getstate__c CsH||d|d|d|d|d|d|d|d|d |d  dS) Nrrzrgrarrrrrr)r)r<rLr#r#r' __setstate__szAliasedInsp.__setstate__cCs|j|||jdS)N) parententityr)rtraverseZ _annotaterz)r<rr#r#r'_adapt_elements zAliasedInsp._adapt_elementcCsD|j}||kr0||jkr|St|j|jjjSn||jr@|SdS)N)rrzrrryrDrr)r<rzZ self_polyr#r#r'_entity_for_mappers  zAliasedInsp._entity_for_mappercs.jj\}}j|fdd|DfS)Ncsi|]\}}|j|qSr#)rr)r%rfZparam)r<r#r' sz+AliasedInsp._get_clause..)rz _get_clauserrrj)r<onclauseZ replacemapr#)r<r'rs   zAliasedInsp._get_clausecCsiS)Nr#)r<r#r#r'_memoized_valuesszAliasedInsp._memoized_valuescOs0||jkr|j|S||||j|<}|SdS)N)r)r<rNZ callable_rwkwrSr#r#r'_memos  zAliasedInsp._memocCs<|jr"dddd|jD}nd}dt||jj|fS)Nz(%s)z, css|]}|jjVqdS)N)ryrD)r%mpr#r#r' sz'AliasedInsp.__repr__..r@z)rr1rryrD)r<Z with_polyr#r#r'r>szAliasedInsp.__repr__cs>jr,djjdfddjDfSdjjfSdS)Nzwith_polymorphic(%s, [%s])z, c3s |]}|jk r|jjVqdS)N)rzryrD)r%r)r<r#r'rsz&AliasedInsp.__str__..z aliased(%s))rrrDr1r)r<r#)r<r'rs zAliasedInsp.__str__N)rDrErFrGrrpropertyryrZmemoized_propertyrrrrrrrrr>rr#r#r#r'rs"7   rcCs|jS)N)r)rr#r#r'rcCs|S)Nr#)rr#r#r'rrFcCs>t|tjr(|rtd|j||dSt|||||dSdS)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 elements)r)rgrrarN)r)rZ FromClauser/r0rgr)elementrgrarrr#r#r'aliasedsP rc Cs~t|} |r@t|}tdd|jD} || kr6|S|| }| j|||d\} }|s\|rh|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#)ry)r%rr#r#r'r(sz$with_polymorphic..) innerjoin)r)rrrr) rrZto_setr,runionZ_with_polymorphic_argsrgr) baseclassesrrrrrrZ_existing_aliasZprimary_mapperZ new_classesZmappersr#r#r'with_polymorphicCs&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)rkZ_deep_annotate)rZexcluder#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)r;)rk_deep_deannotate)rr#r#r'_orm_deannotates rcCs t|S)N)rkr)rr#r#r'_orm_full_deannotatesrc@s>eZdZdZejjZd ddZddZd dd Z dd d Z dS)_ORMJoinz/Extend Join to support ORM constructs as input.NFcCsxt|}t|d|} t|} | j} | |_||_||_t|tj rPt| j |}t|t j rn|j } |j} nt|tr|} | jj} nd} | rt| |jr| }n|j}| j|| dd| jd\}}}}}}|dk r|rt|||}|}nt||||}|}n|}||_tj||||||| stt| ddrt| jjrt| jj}|dk rt| jrh| j |}|j!|@|_!dS)N_joined_from_infoT)Zsource_selectableZdest_selectableZsource_polymorphicZdest_polymorphicZof_type_mapperrz)"rrrrr _left_memo _right_memor)rr*rrQueryableAttributeZ comparatorZ_source_selectablerrparentrkZclause_is_presentZ _create_joinsrzrr1Z_target_adapterrJoinrZsingleZ_single_table_criterionrrrr)r<leftrightrisouterfullrrZ left_infoZ left_orm_infoZ right_infoZadapt_toZ on_selectablepropZ adapt_fromZpjZsjsourcedestZ secondaryZtarget_adapterZ single_critr#r#r'rsV              z_ORMJoin.__init__cCsV|}xt|tjr|j}qWt|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) )rrr)rr) r)rrrrrrrrr)r<otherZleftmostrr#r#r'_splice_into_centers   z_ORMJoin._splice_into_centercCst|||||dS)N)rr)r)r<rrrr join_to_leftr#r#r'r18sz _ORMJoin.joincCst|||d|dS)NT)rr)r)r<rrrrr#r#r' outerjoinBsz_ORMJoin.outerjoin)NFFNN)NFFN)NFN) rDrErFrGrrZ__visit_name__rrr1rr#r#r#r'rs J  rcCst|||||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. )r)rrrrrrr#r#r'r1Fs*r1cCst|||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. T)r)rrrrrr#r#r'rssrcCsDt|tjr$t|}t|j|j}nt|tjr6|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 rryrrrZ _with_parent)rsrrrzr#r#r' with_parent~s   rcCst|}|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_identity)object_rLr#r#r'rs rcCst|}|jS)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` )rr was_deleted)rrLr#r#r'rs rcCsH|jr |jr|j|jkrdSdS|jr>|jr6||jkS||kS||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_parent)givenrr#r#r'_entity_corresponds_tos  rcCsL|jr&|jo$|j o$||kp$||jkS|js8||jS|joF||jkSdS)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 N)rrrrrzr)rrr#r#r'$_entity_corresponds_to_use_path_impls rcCs:|jr||jkp|j|S|jr,||jkS||SdS)zedetermine if 'given' "is a" mapper, in terms of the given would load rows of type 'mapper'. N)rrrzr)rrzr#r#r' _entity_isas  rcCsRddlm}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) unitofworksessionrz dependency) topological) RandomSetN) Zsqlalchemy.ormrrrzrZsqlalchemy.utilrZsqlalchemy.testing.utilrr,)rrrzrrrr#r#r'randomize_unitofworks  r)r]T)NNFF)FFNFFFN)N)NFFN)NFN)N):rArer@rrrrrrrr r r r r rrZ interfacesrrZ path_registryrrrr/rrrrrkr7rHrr\rnr{rr|objectrrZ _inspectsrrrrrrrr1rrrrrrrrr#r#r#r' sv                        ?C Hg' L c \  , ##