
    +h+*             	          d dl Z d dlZd dlZddlmZ ddlmZ ddlmZ ddlmZ ddlm	Z	 ddlm
Z
 dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlm Z  ddl!m"Z" ddlmZ# ddlm$Z$ dd lm%Z% dd!lm&Z& dd"lm'Z' ddlm Z( dd#lm)Z) dd$l*m+Z+ dd%l,m-Z-  e.d&      Z/ G d' d(e.      Z0d) Z1	 dKd*Z2d+ Z3 G d, d-e(jh                        Z5 G d. d/e6      Z7 G d0 d1eee#jp                  e      Z9 G d2 d3e6      Z: G d4 d5e      Z;  ejx                  e7      d6          ejx                  e9      d7        dLd8Z=	 	 	 	 	 	 	 	 dMd9Z>ej~                   G d: d;ee+e#jp                  e             Z@dNd<ZAd= ZBd> ZC G d? d@e%j                        ZE	 dOdAZFdPdBZGdNdCZHdD ZIdE ZJdF ZKdG ZLdH ZMdI ZNdJ ZOy)Q    N   )
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)CriteriaOption)MapperProperty)ORMColumnsClauseRole)ORMEntityColumnsClauseRole)ORMFromClauseRole)PropComparator)PathRegistry   )event)exc)
inspection)sql)utilresult_tuple)base)	coercions)
expression)lambdas)roles)visitors)SupportsCloneAnnotations)ColumnCollection)deletedelete-orphanallmergeexpungesave-updaterefresh-expirenonec                   b    e Zd ZdZej                  g d      ZeZg dZdZ	d Z
d Zed        Zy)	CascadeOptionszHKeeps track of the options sent to
    :paramref:`.relationship.cascade`)r*   r/   r)   )r,   r*   r/   r.   r+   )save_updater(   refresh_expirer+   r,   delete_orphanc                    t        |t        j                        s|| j                  |      S t	        |      }|j                  | j                        r`t        j                  ddj                  t        |j                  | j                              D cg c]  }t        |       c}      z        d|v r|j                  | j                         d|v r|j                          |j                  d       t         j#                  t$        |      }d|v |_        d|v |_        d|v |_        d|v |_        d	|v |_        d
|v |_        |j0                  r!|j(                  st        j2                  d       |S c c}w )NzInvalid cascade option(s): %s, r*   r/   r-   r(   r.   r+   r,   r)   z5The 'delete-orphan' cascade option requires 'delete'.)
isinstancer   string_typesfrom_stringset
difference_allowed_cascadessa_excArgumentErrorjoinsortedreprupdate_add_w_all_cascadescleardiscard	frozenset__new__r1   r2   r(   r3   r+   r,   r4   warn)cls
value_listvaluesxselfs        F/var/www/html/venv/lib/python3.12/site-packages/sqlalchemy/orm/util.pyrG   zCascadeOptions.__new__T   s^   j$"3"34
8J??:..ZS223&&/)) "("--c.C.CD" Q
 
 F?MM#112VLLNu  8(F2&(.&8&
 F*,6dkkIIJ 7s   E7c                 b    ddj                  t        |       D cg c]  }| c}      z  S c c}w )NzCascadeOptions(%r),)r?   r@   )rM   rL   s     rN   __repr__zCascadeOptions.__repr__y   s(    #sxxF4L0Iq0I'JKK0Is   	,
c                 p    t        j                  d|xs d      D cg c]  }|s|	 }} | |      S c c}w )Nz\s*,\s* )resplit)rI   argcrK   s       rN   r9   zCascadeOptions.from_string|   s6    XXj#)<B!BB6{ Cs   33N)__name__
__module____qualname____doc__all_cascadesr;   rC   r<   _viewonly_cascades	__slots__rG   rQ   classmethodr9        rN   r1   r1   @   sR    ) '11( %NI#JL  ra   r1   c                 d  	 sfd	|r!	fd}	fd}	fd}	fd}n	fd}	fd}	fd}t        j                  | d	|d
d
       t        j                  | d|d
       t        j                  | d|d
d
       |rt        j                  | dd
d
       yy)zNRuns a validation method on an attribute value to be set or
    appended.
    c                 R    | j                      j                  }|j                  |uS N)managerimpl)state	initiatorrf   keys      rN   detect_is_backrefz,_validator_events.<locals>.detect_is_backref   s&    ==%**D>>--ra   c                     |j                   t        j                  ur$s	 | |      s | j                         |d      S |S NFopr   OP_BULK_REPLACEobjrg   valuerh   rj   include_backrefsri   	validators      rN   appendz!_validator_events.<locals>.append   s>    ||:#=#== (9%(K c5%@@ra   c           	          s	 | |      s-| j                         }|D cg c]  } ||d       c}|d d  y y c c}w rl   rp   	rg   rK   rh   rp   rr   rj   rs   ri   rt   s	        rN   bulk_setz#_validator_events.<locals>.bulk_set   sJ    '8	'JiikCI:?Ic3u5q	 (Ks   ;c                 P    s	 | |      s | j                         |d      S |S rl   rw   rg   rr   oldvaluerh   rj   rs   ri   rt   s       rN   set_z_validator_events.<locals>.set_   s,    '8	'J c5%@@ra   c                 P    s	 | |      s | j                         |d       y y )NTrw   rq   s      rN   removez!_validator_events.<locals>.remove   s*    '8	'J%))+sE48 (Kra   c                     |j                   t        j                  ur#s	 | |      s | j                         |      S |S rd   rm   rq   s      rN   ru   z!_validator_events.<locals>.append   s<    ||:#=#== (9%(K c599ra   c                 ~    s	 | |      s,| j                         }|D cg c]  } ||       c}|d d  y y c c}w rd   rw   rx   s	        rN   ry   z#_validator_events.<locals>.bulk_set   sA    '8	'JiikEKLEYsC7Lq	 (KLs   :c                 N    s	 | |      s | j                         |      S |S rd   rw   r{   s       rN   r}   z_validator_events.<locals>.set_   s*    '8	'J c599ra   ru   T)rawretvalbulk_replace)r   r:   r   N)r   listen)
descri   rt   include_removesrs   ru   ry   r}   r   rj   s
    `` `    @rN   _validator_eventsr      s    
 	. 				9 	9		M
	 
LLxT$?	LL~xT:	LLudT:T8VdC ra   c                    t        j                         }i i | D ]  }| |   }t        j                  t        j
                  |d      }|| |<   i }|j                  D ]p  }|j                  |k(  rt        j                  d|d|d      |j                  |j                         |||j                  <   |j                  |j                  <   r ||<    fd}	g }
| j                         D ]  \  }}||
j                  t        j                  |D cg c]  } |	||       c}t        j                   t#        j$                  |            j'                  |      gz    j)                  |             |
j                  t        j                  |D cg c]  } |	||       c} j)                  |              t        j*                  |
 j-                  |      S c c}w c c}w )a0  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:`_schema.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.

    T)allow_selectzPolymorphic union can't use 'z3' as the discriminator column due to mapped column zn; please apply the 'typecolname' argument; this is available on ConcreteBase as '_concrete_discriminator_name'c                 $   	 |   |    S # t         $ r{ r<t        j                  t        j                         |          j	                  |       cY S t        j
                  t        j                         |          j	                  |       cY S w xY wrd   )KeyErrorr   castnulllabeltype_coerce)nametable
cast_nullscolnamemapstypess     rN   colzpolymorphic_union.<locals>.col   sy    	Lu%d++ 	Lxx
E$K8>>tDDsxxz5;?EEdKK		Ls    AB:BB)r   
OrderedSetr!   expectr$   StrictFromClauseRolerW   ri   r=   InvalidRequestErroraddtypeitemsru   r   selectliteral_columnsql_util_quote_ddl_exprr   select_from	union_allalias)	table_maptypecolname	aliasnamer   colnamesri   r   mrW   r   resulttype_r   r   r   s      `         @@rN   polymorphic_unionr      s   ,  HKE #  &&D
 	# 	"Auu#00 #A'  LLAaeeH66E!%%L	" E-0L F!) u"MM

6>?dT5)?.. ( 8 8 ?#eK0	 +e$ MM

3;<4c$&<+e$( ==&!''	22 @ =s   G!G&c                     | rd}t        |       }|dk(  r| d   }	 |j                  d      }n"|dv r| \  }}nt        j                  d|z        |j                  dd      }|r't        j                  d	d
j                  |      z        t        |      }|&|j                  t        j                        |      S |j                  ||      S |j                  d      }|r1t        j                  d	d
j                  |j                        z        t        |      }|j                  |      S # t        $ r |j                  d      }Y w xY w)a9  Generate "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))
        (<class '__main__.MyClass'>, (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)
        (<class '__main__.MyClass'>, (1, 2), None)

      In this form, the given instance is ultimately run though
      :meth:`_orm.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:`.Row` object.

      E.g.::

        >>> row = engine.execute(\
            text("select * from table where a=1 and b=2")\
            ).first()
        >>> identity_key(MyClass, row=row)
        (<class '__main__.MyClass'>, (1, 2), None)

      :param class: mapped class (must be a positional argument)
      :param row: :class:`.Row` row returned by a :class:`_engine.CursorResult`
       (must be given as a keyword arg)
      :param identity_token: optional identity token

        .. versionadded:: 1.2 added identity_token

    Nr   r   rowident)r      z1expected up to three positional arguments, got %sidentity_tokenzunknown keyword arguments: %sr6   )r   instance)lenpopr   r=   r>   r?   r	   identity_key_from_primary_keyr   to_listidentity_key_from_rowkeysr   identity_key_from_instance)	argskwargsr   largsclass_r   r   mapperr   s	            rN   identity_keyr     sm   @ D	A:!WF,jj' f_ MFE&&FN   $4d;&&/$))F2CC  f%;77U#N 8   //N 0   ::j)&&/$))FKK2HH  x(00::=  ,

7+,s   D0 0EEc                   &    e Zd ZdZ	 	 	 	 ddZd Zy)
ORMAdapterzaColumnAdapter subclass which excludes adaptation of entities from
    non-matching mappers.

    Nc           	         t        j                  |      }|j                  | _        |j                  }|j                  }|r|| _        nd | _        t        j                  j                  | |||||| j                         y )N)adapt_requiredallow_label_resolveanonymize_labels
include_fn)
r   inspectr   
selectableis_aliased_classaliased_classr   ColumnAdapter__init___include_fn)	rM   entityequivalentsr   r   r   infor   r   s	            rN   r   zORMAdapter.__init__  s{     !!&)kk__
00!'D!%D'') 3-'' 	( 	
ra   c                     |j                   j                  dd       }| xs8 |j                  | j                        xs | j                  j                  |      S )Nparentmapper)_annotationsgetisar   )rM   elemr   s      rN   r   zORMAdapter._include_fn  sF    ""&&~t<zOVZZ4O8OOra   )NFTF)rX   rY   rZ   r[   r   r   r`   ra   rN   r   r   ~  s       
8Pra   r   c                   R    e Zd ZdZ	 	 	 	 	 	 	 	 	 d	dZed        Zd Zd Zd Z	d Z
y)
AliasedClassa  Represents 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:`_orm.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:`_orm.Mapper`, aliased selectable, and other information
    using :func:`_sa.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`


    Nc                    t        j                  |      }|j                  }d}|[|j                  r1|j                  j
                  r|j                  j                         }n,|j                  j                  ||      }n|j                  rd}t        | ||||r|n|j                  ||n|j                  ||	||
|      | _        d|j                  j                  z  | _        y )NFr   flatTAliasedClass_%s)r   r   r   r   r   _is_subqueryr   _with_polymorphic_selectable_anonymous_fromclauseAliasedInspwith_polymorphic_mapperspolymorphic_on_aliased_inspr   rX   )rM   mapped_class_or_acr   r   r   adapt_on_namesr   with_polymorphic_discriminator
base_aliasuse_mapper_pathrepresents_outer_joininspr   nest_adapterss                 rN   r   zAliasedClass.__init__  s     !!"45=$$)E)E--/ 77MM!! N   "" M(' %00-9 +&&!
$ *FMM,B,BBra   c                 6   | j                  |       }d|j                  j                  j                  z  |_        ||_        |j
                  rL|j                  D ]=  }||ust        j                  |      }t        ||j                  j                  |       ? |S )Nr   )
rG   r   r   rX   r   _is_with_polymorphic_with_polymorphic_entitiesr   _reconstitute_from_aliased_inspsetattr)rI   aliased_insprp   sub_aliased_inspents        rN   r   z,AliasedClass._reconstitute_from_aliased_insp  s    kk#(<+>+>+E+E+N+NN(,,$0$K$K H #<7&FF(C C!1!8!8!A!A3GH 
ra   c                    	 | j                   d   }|j                  }t        ||      }t        |d      r,t        |d      r t        j                  |j                  |       S t        |d      r|j                  d |       }t        |d      r|j                  |      }t        | ||       |S # t        $ r t	               w xY w)Nr   __call____self____get__adapt_to_entity)__dict___targetgetattrr   AttributeErrorhasattrr   
MethodType__func__r   r   r   )rM   ri   r   targetattrs        rN   __getattr__zAliasedClass.__getattr__%  s    	( MM/:M #**F63'D
 4$z)B##DMM488 4#<<d+D 4*+''6DD#t$1  	# ""	#s   B+ +B?c                 R   t        ||      }t        |d      r,t        |d      r t        j                  |j                  |       S t        |d      r|j                  d |       }t        |d      r8t        j                  |       |_        |j                  |      }t        | ||       |S )Nr   r   r   r   )r   r   r   r   r   r   weakrefref_weak_entityr   r   )rM   ri   mapped_classr   r  s        rN   _get_from_serializedz!AliasedClass._get_from_serializedB  s     |S)4$z)B##DMM488 4#<<d+D 4*+(/D(9L%''5DD#t$ra   c                 ^    dt        |       | j                  j                  j                  fz  S )Nz<AliasedClass at 0x%x; %s>)idr   r   rX   rM   s    rN   rQ   zAliasedClass.__repr__W  s0    +tH&&///
 
 	
ra   c                 ,    t        | j                        S rd   )strr   r  s    rN   __str__zAliasedClass.__str__]  s    4%%&&ra   )	NNFFr`   NNFF)rX   rY   rZ   r[   r   r_   r   r  r	  rQ   r  r`   ra   rN   r   r     sT    8z !#'+#2Ch  :*
'ra   r   c                   ^   e Zd ZdZdej
                  j                  fdej
                  j                  fdej
                  j                  fdej
                  j                  fdej
                  j                  fdej                  j                  fdej                  j                  fgZd	 Zed
        ZdZ	 ej$                  d        Zed        Zed        Zed        Zd Zd ZddZd Zej6                  d        Zej6                  d        Zej6                  d        Zd Zd Z d Z!y)r   a  Provide an inspection interface for an
    :class:`.AliasedClass` object.

    The :class:`.AliasedInsp` object is returned
    given an :class:`.AliasedClass` using the
    :func:`_sa.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:`_orm.Mapper` mapping the underlying class.
    * ``selectable`` - the :class:`_expression.Alias`
      construct which ultimately
      represents an aliased :class:`_schema.Table` or
      :class:`_expression.Select`
      construct.
    * ``name`` - the name of the alias.  Also is used as the attribute
      name when returned in a result tuple from :class:`_query.Query`.
    * ``with_polymorphic_mappers`` - collection of :class:`_orm.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`

    r   _adapt_on_names_use_mapper_pathr   r   r   r   c           
         |j                   }|j                  }t        j                  |      | _        || _        |x| _        x| _        | _        || _        || _	        t        j                  |xs |       | _
        || _        |
| _        || _        |rd| _        || _        g | _        | j                  D ]q  }||ust#        |j$                  || |	|      }t'        | j                   |j$                  j(                  |       | j                   j+                  |j,                         s nd| _        |g| _        t/        j0                  ||j2                  |	d| j                  D ch c]  }|	s|j
                   c}      | _        |r*|j4                  j7                  | j4                        | _        |	| _        || _        y c c}w )NT)r   r   r   F)r   r   r   adapt_from_selectables)r   r   r  r  r  r   persist_selectablelocal_tabler   r   _base_aliasr  r   _nest_adaptersr   r   r   r   r   r   rX   ru   r   r   r   _equivalent_columns_adapterwrapr  r   )rM   r   	inspectedr   r   r   r   r  r  r   r   r   r   r   polyr   r   s                    rN   r   zAliasedInsp.__init__  s    '--!!#KK/  *	* 	*#	,";;{':d; 0%:"+#(,D%,DD).0D+55 Nv%&"#''5(8C DKK)=)=sC33::3;L;LMN ).D%-3HD) ..22)! 66$% $
 %..33DMMBDM-)$s   "F?c                     | j                         }|/t        j                  |       }t        j                  |      | _         |S rd   )r  r   r   r  r  )rM   r   s     rN   r   zAliasedInsp.entity  s=     !;>>tDC 'C 0D
ra   Tc                 x    | j                   j                  | j                  | | d      j                  d| d      S )N)r   parententityentity_namespaceormcompile_state_pluginplugin_subject)r   	_annotater   _set_propagate_attrsr  s    rN   __clause_element__zAliasedInsp.__clause_element__  s@    (( $ $$(
 
%*dC
	
ra   c                     | j                   S rd   )r   r  s    rN   r!  zAliasedInsp.entity_namespace   s    {{ra   c                 .    | j                   j                  S )zUReturn the mapped class ultimately represented by this
        :class:`.AliasedInsp`.)r   r   r  s    rN   r   zAliasedInsp.class_  s     {{!!!ra   c                 p    | j                   r| j                  j                  S t        j                  |       S rd   )r  r   _path_registryr   
per_mapperr  s    rN   r,  zAliasedInsp._path_registry
  s,      ;;---**400ra   c                    | j                   | j                  | j                  | j                  | j                  | j
                  | j                  | j                         | j                  | j                  | j                  dS )N)r   r   r   r   r   r   r   r   r   r   r   )r   r   r   r   r  r   r   r  r  r   r  r  s    rN   __getstate__zAliasedInsp.__getstate__  sj    kkkk__II"22(,(E(E.2.A.A**,#44%)%?%?!00
 	
ra   c                 |    | j                  |d   |d   |d   |d   |d   |d   |d   |d   |d	   |d
   |d          y )Nr   r   r   r   r   r   r   r   r   r   r   )r   )rM   rg   s     rN   __setstate__zAliasedInsp.__setstate__   sg    (O(O'N&M,-23,#$"#)*/"	
ra   Nc                     | | j                   d}|r||d<   | j                  j                  |      j                  |      j	                  d| d      S )N)r   r   	proxy_keyr"  r#  )r   r  traverser&  r'  )rM   r   ri   ds       rN   _adapt_elementzAliasedInsp._adapt_element/  sT      KK
  AkNMM""4(Yq\!!).$G	
ra   c                     | j                   }||v rD|| j                  u r| S t        | j                  |j                  j
                        j                  S |j                  | j                        r| S J d|d|        )Nzmapper z doesn't correspond to )r   r   r   r   r   rX   r   r   )rM   r   	self_polys      rN   _entity_for_mapperzAliasedInsp._entity_for_mapper>  sq    11	Y$KK!7!7-  ZZ$KO&$OO5ra   c                     | j                   j                  \  }}| j                  j                  |      |j	                         D ci c]!  \  }}| j                  j                  |      |# c}}fS c c}}w rd   )r   _get_clauser  r4  r   )rM   onclause
replacemapr   params        rN   r;  zAliasedInsp._get_clauseL  sp    #{{66*MM""8, #-"2"2"4C &&s+U2
 	
s   &A2c                     i S rd   r`   r  s    rN   _memoized_valueszAliasedInsp._memoized_valuesW  s    	ra   c                 @   | j                   r>| j                  j                  | j                  D cg c]  }|j                   c}      }n| j                  j                         }|D cg c]  \  }}|| j	                  |      f }}}t        |      S c c}w c c}}w rd   )r   r   _columns_plus_keysr   r6  r'   )rM   r   cols_plus_keysri   r   s        rN   _all_column_expressionsz#AliasedInsp._all_column_expressions[  s    $$![[;;'+'F'FGGN "[[;;=N =K
08SS$%%c*+
 
  // H

s   B*Bc                 n    || j                   v r| j                   |   S  ||i |x| j                   |<   }|S rd   )r@  )rM   ri   	callable_r   kwrr   s         rN   _memozAliasedInsp._memoj  sE    $'''((--1:D1GB1GGD!!#&Lra   c                     | j                   r&ddj                  d | j                   D              z  }nd}dt        |       | j                  j                  |fz  S )Nz(%s)r6   c              3   H   K   | ]  }|j                   j                    y wrd   )r   rX   ).0mps     rN   	<genexpr>z'AliasedInsp.__repr__.<locals>.<genexpr>s  s      +')		""+s    "rS   z<AliasedInsp at 0x%x; %s%s>)r   r?   r  r   rX   )rM   	with_polys     rN   rQ   zAliasedInsp.__repr__q  sc    (( +-1-J-J+ " I I,tHKK  0
 
 	
ra   c                       j                   r?d j                  j                  ddj                   fd j                  D              dS d j                  j                  dS )Nzwith_polymorphic(z, [r6   c              3   f   K   | ](  }|j                   ur|j                  j                   * y wrd   )r   r   rX   )rK  rL  rM   s     rN   rM  z&AliasedInsp.__str__.<locals>.<genexpr>  s/      , II&&s   .1z])zaliased())r   r   rX   r?   r   r  s   `rN   r  zAliasedInsp.__str__~  s\    $$%%		 ";;   % %)LL$9$9;;ra   rd   )"rX   rY   rZ   r[   r%   ExtendedInternalTraversal	dp_string
dp_booleandp_inspectabledp_clauseelementInternalTraversaldp_has_cache_key_list_cache_key_traversalr   propertyr   r   r   memoized_instancemethodr(  r!  r   r,  r/  r1  r6  r9  memoized_propertyr;  r@  rD  rH  rQ   r  r`   ra   rN   r   r   a  s   $N 
33==>	H>>IIJ	X??JJK	H66EEF	x99JJK&&&<<	
 
855FFGF*R   	!!	
 "	
   " "
 1 1


P 

 
 
  
0 0
<ra   r   c                   J    e Zd ZdZdZd Z ej                  d      d        Zy)_WrapUserEntitya  A wrapper used within the loader_criteria lambda caller so that
    we can bypass declared_attr descriptors on unmapped mixins, which
    normally emit a warning for such use.

    might also be useful for other per-lambda instrumentations should
    the need arise.

    subjectc                     || _         y rd   r_  )rM   r`  s     rN   r   z_WrapUserEntity.__init__  s	    ra   zsqlalchemy.orm.decl_apic                 ,   t         j                  j                  j                  }t        j                  | d      }||j                  v rAt        |j                  |   |j                        r|j                  |   j                  |      S t        ||      S )Nr`  )r   	preloadedr"  decl_apiobject__getattribute__r   r7   declared_attrfgetr   )rM   r   rd  r`  s       rN   rf  z _WrapUserEntity.__getattribute__  s    >>%%..))$	:7###
T"H$:$:)
 ##D)..w777D))ra   N)	rX   rY   rZ   r[   r^   r   r   preload_modulerf  r`   ra   rN   r^  r^    s5     I T23	* 4	*ra   r^  c                   D   e Zd ZdZdej
                  j                  fdej
                  j                  fdej                  j                  fdej                  j                  fdej                  j                  fgZ	 	 	 	 ddZed        Zd	 Zd
 Zd Zd Zd Zd Zd Zy)LoaderCriteriaOptiona
  Add additional WHERE criteria to the load for all occurrences of
    a particular entity.

    :class:`_orm.LoaderCriteriaOption` is invoked using the
    :func:`_orm.with_loader_criteria` function; see that function for
    details.

    .. versionadded:: 1.4

    root_entityr   where_criteriainclude_aliasespropagate_to_loadersc                 
   t        j                  |d      }||| _        d| _        nd| _        || _        || _        t        |      r~d| _        t        j                  |t        j                  t        | j                  | j                  n| j                  j                        ft        j                  |            | _        n0d| _        t        j                  t        j                  |      | _        || _        || _        y)aV   Add additional WHERE criteria to the load for all occurrences of
        a particular entity.

        .. versionadded:: 1.4

        The :func:`_orm.with_loader_criteria` option is intended to add
        limiting criteria to a particular kind of entity in a query,
        **globally**, meaning it will apply to the entity as it appears
        in the SELECT query as well as within any subqueries, join
        conditions, and relationship loads, including both eager and lazy
        loaders, without the need for it to be specified in any particular
        part of the query.    The rendering logic uses the same system used by
        single table inheritance to ensure a certain discriminator is applied
        to a table.

        E.g., using :term:`2.0-style` queries, we can limit the way the
        ``User.addresses`` collection is loaded, regardless of the kind
        of loading used::

            from sqlalchemy.orm import with_loader_criteria

            stmt = select(User).options(
                selectinload(User.addresses),
                with_loader_criteria(Address, Address.email_address != 'foo'))
            )

        Above, the "selectinload" for ``User.addresses`` will apply the
        given filtering criteria to the WHERE clause.

        Another example, where the filtering will be applied to the
        ON clause of the join, in this example using :term:`1.x style`
        queries::

            q = session.query(User).outerjoin(User.addresses).options(
                with_loader_criteria(Address, Address.email_address != 'foo'))
            )

        The primary purpose of :func:`_orm.with_loader_criteria` is to use
        it in the :meth:`_orm.SessionEvents.do_orm_execute` event handler
        to ensure that all occurrences of a particular entity are filtered
        in a certain way, such as filtering for access control roles.    It
        also can be used to apply criteria to relationship loads.  In the
        example below, we can apply a certain set of rules to all queries
        emitted by a particular :class:`_orm.Session`::

            session = Session(bind=engine)

            @event.listens_for("do_orm_execute", session)
            def _add_filtering_criteria(execute_state):

                if (
                    execute_state.is_select
                    and not execute_state.is_column_load
                    and not execute_state.is_relationship_load
                ):
                    execute_state.statement = execute_state.statement.options(
                        with_loader_criteria(
                            SecurityRole,
                            lambda cls: cls.role.in_(['some_role']),
                            include_aliases=True
                        )
                    )

        In the above example, the :meth:`_orm.SessionEvents.do_orm_execute`
        event will intercept all queries emitted using the
        :class:`_orm.Session`. For those queries which are SELECT statements
        and are not attribute or relationship loads a custom
        :func:`_orm.with_loader_criteria` option is added to the query.    The
        :func:`_orm.with_loader_criteria` option will be used in the given
        statement and will also be automatically propagated to all relationship
        loads that descend from this query.

        The criteria argument given is a ``lambda`` that accepts a ``cls``
        argument.  The given class will expand to include all mapped subclass
        and need not itself be a mapped class.

        .. tip::

           When using :func:`_orm.with_loader_criteria` option in
           conjunction with the :func:`_orm.contains_eager` loader option,
           it's important to note that :func:`_orm.with_loader_criteria` only
           affects the part of the query that determines what SQL is rendered
           in terms of the WHERE and FROM clauses. The
           :func:`_orm.contains_eager` option does not affect the rendering of
           the SELECT statement outside of the columns clause, so does not have
           any interaction with the :func:`_orm.with_loader_criteria` option.
           However, the way things "work" is that :func:`_orm.contains_eager`
           is meant to be used with a query that is already selecting from the
           additional entities in some way, where
           :func:`_orm.with_loader_criteria` can apply it's additional
           criteria.

           In the example below, assuming a mapping relationship as
           ``A -> A.bs -> B``, the given :func:`_orm.with_loader_criteria`
           option will affect the way in which the JOIN is rendered::

                stmt = select(A).join(A.bs).options(
                    contains_eager(A.bs),
                    with_loader_criteria(B, B.flag == 1)
                )

           Above, the given :func:`_orm.with_loader_criteria` option will
           affect the ON clause of the JOIN that is specified by
           ``.join(A.bs)``, so is applied as expected. The
           :func:`_orm.contains_eager` option has the effect that columns from
           ``B`` are added to the columns clause::

                SELECT
                    b.id, b.a_id, b.data, b.flag,
                    a.id AS id_1,
                    a.data AS data_1
                FROM a JOIN b ON a.id = b.a_id AND b.flag = :flag_1


           The use of the :func:`_orm.contains_eager` option within the above
           statement has no effect on the behavior of the
           :func:`_orm.with_loader_criteria` option. If the
           :func:`_orm.contains_eager` option were omitted, the SQL would be
           the same as regards the FROM and WHERE clauses, where
           :func:`_orm.with_loader_criteria` continues to add its criteria to
           the ON clause of the JOIN. The addition of
           :func:`_orm.contains_eager` only affects the columns clause, in that
           additional columns against ``b`` are added which are then consumed
           by the ORM to produce ``B`` instances.

        .. warning:: The use of a lambda inside of the call to
          :func:`_orm.with_loader_criteria` is only invoked **once per unique
          class**. Custom functions should not be invoked within this lambda.
          See :ref:`engine_lambda_caching` for an overview of the "lambda SQL"
          feature, which is for advanced use only.

        :param entity_or_base: a mapped class, or a class that is a super
         class of a particular set of mapped classes, to which the rule
         will apply.

        :param where_criteria: a Core SQL expression that applies limiting
         criteria.   This may also be a "lambda:" or Python function that
         accepts a target class as an argument, when the given class is
         a base with many different mapped subclasses.

         .. note:: To support pickling, use a module-level Python function to
            produce the SQL expression instead of a lambda or a fixed SQL
            expression, which tend to not be picklable.

        :param include_aliases: if True, apply the rule to :func:`_orm.aliased`
         constructs as well.

        :param propagate_to_loaders: defaults to True, apply to relationship
         loaders such as lazy loaders.  This indicates that the
         option object itself including SQL expression is carried along with
         each loaded instance.  Set to ``False`` to prevent the object from
         being assigned to individual instances.

        .. seealso::

            :ref:`examples_session_orm_events` - includes examples of using
            :func:`_orm.with_loader_criteria`.

            :ref:`do_orm_execute_global_criteria` - basic example on how to
            combine :func:`_orm.with_loader_criteria` with the
            :meth:`_orm.SessionEvents.do_orm_execute` event.

        :param track_closure_variables: when False, closure variables inside
         of a lambda expression will not be used as part of
         any cache key.    This allows more complex expressions to be used
         inside of a lambda expression but requires that the lambda ensures
         it returns the identical SQL every time given a particular class.

         .. versionadded:: 1.4.0b2

        FNT)track_closure_variables)lambda_argsopts)r   r   rl  r   _where_crit_origcallabledeferred_where_criteriar#   DeferredLambdaElementr$   WhereHavingRoler^  LambdaOptionsrm  r!   r   rn  ro  )rM   entity_or_baserm  loader_onlyrn  ro  rq  r   s           rN   r   zLoaderCriteriaOption.__init__  s    h ##NE:>-DDK#D DK .N#+/D(")"?"?%%#++7 ((![[// **,C#D ,1D("+"2"2%%~#D  /$8!ra   c                      t        ||||      S )N)rn  ro  )rk  )rI   r   rm  rn  ro  s        rN   	_unreducezLoaderCriteriaOption._unreduce  s     $+!5	
 	
ra   c                     t         j                  | j                  r| j                  j                  n| j                  | j
                  | j                  | j                  ffS rd   )rk  r}  r   r   rl  rt  rn  ro  r  s    rN   
__reduce__zLoaderCriteriaOption.__reduce__  sP     **&*kk""t7G7G%%$$))	
 	
ra   c              #     K   | j                   r*| j                   j                  j                  D ]  }|  y t        | j                  j                               }|rm|j                  d      }t        j                  |d      }|r |j                  j                  D ]  }|  n|j                  |j                                |rly y w)Nr   F)raiseerr)
r   r   self_and_descendantslistrl  __subclasses__r   r   r   extend)rM   r   stacksubclassrL  s        rN   _all_mappersz!LoaderCriteriaOption._all_mappers  s     ;;{{))>> 	 ))88:;E 99Q< ((EB!jj== ! ! LL!8!8!:; s   CC
Cc                 V    |j                   j                  j                  dd       | u ryy)Nfor_loader_criteriaFT)select_statementr   r   rM   compile_states     rN   _should_includez$LoaderCriteriaOption._should_include  s3    **77;;%t 
 ra   c                     | j                   r&| j                  j                  |j                        }n| j                  }t	        j
                  |d| id      S )Nr  T)detect_subquery_cols)rv  rm  _resolve_with_argsr   r   _deep_annotate)rM   ext_infocrits      rN   _resolve_where_criteriaz,LoaderCriteriaOption._resolve_where_criteria  sP    ''&&99(//JD&&D&&($/d
 	
ra   c                 $    | j                  |      S rd   )process_compile_state)rM   r  mapper_entitiess      rN   'process_compile_state_replaced_entitiesz<LoaderCriteriaOption.process_compile_state_replaced_entities  s     ))-88ra   c                     |j                   j                  rt        j                  d       | j	                  |j
                         y)z7Apply a modification to a given :class:`.CompileState`.zThe with_loader_criteria() function may not work correctly with the legacy Query.with_polymorphic() feature.  Please migrate code to use the with_polymorphic() standalone function before using with_loader_criteria().N)compile_options_with_polymorphic_adapt_mapr   rH   get_global_criteriaglobal_attributesr  s     rN   r  z*LoaderCriteriaOption.process_compile_state  s;     ((DDII@ 	  !@!@Ara   c                 z    | j                         D ](  } |j                  d|fg       }|j                  |        * y )Nadditional_entity_criteria)r  
setdefaultru   )rM   r   rL  load_criterias       rN   r  z(LoaderCriteriaOption.get_global_criteria  sF    ##% 	'B1J11-r2BM   &	'ra   N)FFTT)rX   rY   rZ   r[   r%   rR  dp_plain_objdp_has_cache_keyrW  rV  rT  _traverse_internalsr   r_   r}  r  r  r  r  r  r  r  r`   ra   rN   rk  rk    s    	 
::GGH	855FFG	855FFG	H66AAB	!;!;!F!FG ! $T9l 
 
	
< 
9
B'ra   rk  c                     | j                   S rd   )r   r  s    rN   <lambda>r    s    &2F2F ra   c                     | S rd   r`   r  s    rN   r  r    s     ra   c                     t        | t        j                        rR|rt        j                  d      |r| j                  ||      S t        j                  t        j                  | |      S t        | ||||      S )a  Produce 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:`_schema.Table`
    ) using the
    :meth:`_expression.FromClause.alias` method. However, :func:`.aliased`
    can also be
    used to link the class to a new :func:`_expression.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:`_expression.FromClause` constructs, such as a
    :class:`_schema.Table` or
    :func:`_expression.select` construct.   In those cases, the
    :meth:`_expression.FromClause.alias`
    method is called on the object and the new
    :class:`_expression.Alias` object returned.  The returned
    :class:`_expression.Alias` is not
    ORM-mapped in this case.

    .. seealso::

        :ref:`tutorial_orm_entity_aliases` - in the :ref:`unified_tutorial`

        :ref:`orm_queryguide_orm_aliases` - in the :ref:`queryguide_toplevel`

    :param element: element to be aliased.  Is normally a mapped class,
     but for convenience can also be a :class:`_expression.FromClause`
     element.

    :param alias: Optional selectable unit to map the element to.  This is
     usually used to link the object to a subquery, and should be an aliased
     select construct as one would produce from the
     :meth:`_query.Query.subquery` method or
     the :meth:`_expression.Select.subquery` or
     :meth:`_expression.Select.alias` methods of the :func:`_expression.select`
     construct.

    :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.Query` object.  Not supported when creating aliases
     of :class:`_sql.Join` objects.

    :param flat: Boolean, will be passed through to the
     :meth:`_expression.FromClause.alias` call so that aliases of
     :class:`_expression.Join` objects will alias the individual tables
     inside the join, rather than creating a subquery.  This is generally
     supported by all modern databases with regards to right-nested joins
     and generally produces more efficient queries.

    :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   r   )r   r   r   r   )r7   r"   
FromClauser=   r>   r   r!   r   r$   AnonymizedFromClauseRoler   )elementr   r   r   r   s        rN   aliasedr    s    x ':001&&=  ==d=66##..d  )
 	
ra   c
           	         t        |       }
|dvr|rt        j                  d      |	rj|	j                  |
u sJ t	        j
                  |      }t        |	j                  D cg c]  }|j                   c}      }||k(  r|	S |j                  |      }|
j                  |||      \  }}|s|r|j                  |      }t        | ||||||       S c c}w )ab  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 aliased.   For a
        JOIN, this means the JOIN will be SELECTed from inside of a subquery
        unless the :paramref:`_orm.with_polymorphic.flat` flag is set to
        True, which is recommended for simpler use cases.

    :param flat: Boolean, will be passed through to the
     :meth:`_expression.FromClause.alias` call so that aliases of
     :class:`_expression.Join` objects will alias the individual tables
     inside the join, rather than creating a subquery.  This is generally
     supported by all modern databases with regards to right-nested joins
     and generally produces more efficient queries.  Setting this flag is
     recommended as long as the resulting SQL is functional.

    :param selectable: a table or subquery 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.

        When left at its default value of ``False``, the polymorphic
        selectable assigned to the base mapper is used for selecting rows.
        However, it may also be passed as ``None``, which will bypass the
        configured polymorphic selectable and instead construct an ad-hoc
        selectable for the target classes given; for joined table inheritance
        this will be a join that includes all target mappers and their
        subclasses.

    :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

    :param adapt_on_names: Passes through the
      :paramref:`_orm.aliased.adapt_on_names`
      parameter to the aliased object.  This may be useful in situations where
      the given selectable is not directly related to the existing mapped
      selectable.

      .. versionadded:: 1.4.33

    rl   z[the 'flat' and 'selectable' arguments cannot be passed simultaneously to with_polymorphic())	innerjoinr  )r   r   r   r   r   )r   r=   r>   r   r   to_setr:   r   r   union_with_polymorphic_argsr   r   )r    classesr   r   r   r  r   r  r  _existing_aliasprimary_mapperrL  new_classesmapperss                 rN   with_polymorphicr  ]  s    d &d+N&4""3
 	

 %%777++g&!0!I!IJ2RYYJ
 k!""mmK0G(??y @ GZ $5545@
%!('5("+m  Ks   !Cc                       e Zd ZdZdZ	 dZdZdZdZ e	j                         Zd Zd Zed        Zed        Zed        Zd	Z	 d	Z	 d
 Zd Zed        Zd Zd Zy	)BundleaH  A grouping of SQL expressions that are returned by a :class:`.Query`
    under one namespace.

    The :class:`.Bundle` essentially allows nesting of the tuple-based
    results returned by a column-oriented :class:`_query.Query` object.
    It also
    is extensible via simple subclassing, where the primary capability
    to override is that of how the set of expressions should be returned,
    allowing post-processing as well as custom return types, without
    involving ORM identity-mapped classes.

    .. versionadded:: 0.9.0

    .. seealso::

        :ref:`bundles`


    FTc           
      x   |x| _         | _        |D cg c](  }t        j                  t        j
                  ||       * c}x| _        }t        d |D cg c]  }|j                  j                  d|        c}D              x| _
        | _        |j                  d| j                        | _        yc c}w c c}w )aQ  Construct a new :class:`.Bundle`.

        e.g.::

            bn = Bundle("mybundle", MyClass.x, MyClass.y)

            for row in session.query(bn).filter(
                    bn.c.x == 5).filter(bn.c.y == 4):
                print(row.mybundle.x, row.mybundle.y)

        :param name: name of the bundle.
        :param \*exprs: columns or SQL expressions comprising the bundle.
        :param single_entity=False: if True, rows for this :class:`.Bundle`
         can be returned as a "single entity" outside of any enclosing tuple
         in the same manner as a mapped entity.

        )apply_propagate_attrsc              3   N   K   | ]  }t        |d |j                        |f  yw)ri   N)r   _label)rK  r   s     rN   rM  z"Bundle.__init__.<locals>.<genexpr>  s*      1
 S%,c21
s   #%bundlesingle_entityN)r   r  r!   r   r$   ColumnsClauseRoleexprsr'   r   r   rW   columnsr   r  )rM   r   r  rG  expres         rN   r   zBundle.__init__  s    $ #'&	DK
 	
  ''T
 	

U !1 1
AFGA**8Q7G1
 !
 	
  VVOT5G5GH
 Hs   -B2#B7
c           
          | j                   | j                  | j                  ft        | j                  D cg c]  }|j                  ||       c}      z   S c c}w rd   )	__class__r   r  tupler  _gen_cache_key)rM   anon_map
bindparamsr  s       rN   r  zBundle._gen_cache_key  sN    		4+=+=>CG::N4T  :6NB
 
 	
Ns   A
c                 T    | j                   d   j                  j                  dd       S )Nr   r   r  r   r   r  s    rN   r   zBundle.mapper  #    zz!}))--ndCCra   c                 T    | j                   d   j                  j                  dd       S )Nr   r   r  r  s    rN   r   zBundle.entity#  r  ra   c                     | j                   S rd   )rW   r  s    rN   r!  zBundle.entity_namespace'  s    vvra   Nc                     | j                   j                  | j                         }|j                  j                  | j                         |S rd   )r  rG   r   rB   )rM   cloneds     rN   _clonezBundle._cloneG  s5    ''7t}}-ra   c           	         | | d}|j                  | j                         | j                  d   j                  j	                  d| j
                        }t        j                  | j                  D cg c]  }|j                  j	                  d|        c}t        j                  ddj                  |      j                  d|d      S c c}w )	N)r  r!  r   r%  r  F)_literal_as_text_rolegroupr"  r#  )rB   r   r  _propagate_attrsr   r   r"   
ClauseListr$   r  r&  r'  )rM   annotationsr%  r  s       rN   r(  zBundle.__clause_element__L  s    !%4@4,,-A77;;dkk
 !! <@::Fa!..$$Xq1F ',&=&=
 Y{#!! -2&4	
 Gs   1#Cc                 6    | j                         j                  S rd   )r(  clausesr  s    rN   r  zBundle.clausese  s    &&(000ra   c                 4    | j                         }||_        |S )z<Provide a copy of this :class:`.Bundle` passing a new label.)r  r   )rM   r   r  s      rN   r   zBundle.labeli  s     ra   c                 T    t        ||D cg c]  }d c}      fd}|S c c}w )zProduce the "row processing" function for this :class:`.Bundle`.

        May be overridden by subclasses.

        .. seealso::

            :ref:`bundles` - includes an example of subclassing.

        r`   c                 F     D cg c]
  } ||        c}      S c c}w rd   r`   )r   prockeyed_tupleprocss     rN   r  z)Bundle.create_row_processor.<locals>.proc|  s     e<dS	<==<s   r   )rM   queryr  labelslr  r  s     `   @rN   create_row_processorzBundle.create_row_processorp  s.     #6+?1B+?@	>  ,@s   	%
)rX   rY   rZ   r[   r  is_clause_element	is_mapperr   	is_bundler   immutabledictr  r   r  rZ  r   r   r!  r  rW   r  r(  r  r   r  r`   ra   rN   r  r    s    ( M< II)t))+I@

 D D D D   G0 	A/

2 1 1ra   r  c                 4    t        j                  | ddi|      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   r  )r  excludes     rN   _orm_annotater    s     ""7\4,@'JJra   c                 0    t        j                  | d      S )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.

    )r  r   )rK   r   _deep_deannotater  s    rN   _orm_deannotater    s     $$6 ra   c                 ,    t        j                  |       S rd   r  r  s    rN   _orm_full_deannotater    s    $$W--ra   c                   r    e Zd ZdZej
                  j                  ZdZ	 	 	 	 	 	 ddZd Z		 	 	 	 d	dZ
d
dZy)_ORMJoinz/Extend Join to support ORM constructs as input.TNc	                    t        j                  |      }	t        j                  |      }
|
j                  }|| _        || _        t        |d|	      }|
| _        t        |t        j                        rt        |j                  |      }t        |t        j                        r6|j                  j                         }|j                  }||j                   z  }n+t        |t"              r|}|j$                  j                  }nd }|r|	j                  }t'        j(                  |      r|}n|}|j+                  ||d|
d|      \  }}}}}}|7|rt-        j.                  |||      }|}nt-        j.                  ||||      }|}n|}|| _        |	j2                  r|j4                  j7                  dd       }n|	j8                  s|	j:                  r|	}nd }|"| j4                  j=                  d|i      | _        |d u xr |}t>        j@                  jC                  | |||||       |r%| xjD                  t-        jF                  | z  c_"        |szt        |
dd       rl|
jH                  jJ                  rU|
jH                  jL                  }|<|
j:                  r|
jN                  jQ                  |      }| jD                  |z  | _"        y y y y y )N_joined_from_infoT)source_selectabledest_selectablesource_polymorphicof_type_entityalias_secondaryextra_criteriar   r   ))r   r   r   
_left_memo_right_memor   r  r7   r   r8   r   r   QueryableAttribute
comparator_source_selectablerZ  _extra_criteriar   parentr   clause_is_present_create_joinsr   r?   _target_adapteris_selectabler   r   r  r   r  r"   Joinr   r<  and_r   single_single_table_criterionr  r4  )rM   leftrightr<  isouterfullr  r  r  	left_info
right_infoadapt_toleft_orm_infoon_selectablepropleft_selectable
adapt_frompjsjsourcedest	secondarytarget_adapterr   augment_onclausesingle_crits                             rN   r   z_ORMJoin.__init__  s    &&t,	''.
(( %&  &99E!+h 1 12}33X>H h
 = =>$//BBDM$$Dx777O.1D KK22MD'22O))-I*
,
 """, (#') $. #  ~HHYr:E!H88D)RAD!H#1D  &&.;;??"D  $$	(B(B(#'$($5$5$;$;#\2%! $t+?  tUHgtLMMSXX77M 
Hd3!!((
 %++CCK&..","5"5">">{"KK $ ; ' ) 4 ra   c                    |}t        |t        j                        r'|j                  }t        |t        j                        r'| j                  |u sJ t        | j                  |j                  | j                  | j                  | j                  |j                        }t        ||j                  |j                  |j                  |j                        S )zlSplice a join into the center.

        Given join(a, b) and join(b, c), return join(a, b).join(c)

        )r  r  r  )r  r  )
r7   r   r  r  r  r  r<  r  r  r  )rM   otherleftmostr  s       rN   _splice_into_centerz_ORMJoin._splice_into_center  s     388,}}H 388, zzX%%%IIJJMMLL((
 KKNNMM))
 	
ra   c                 "    t        | ||||      S )N)r  r  r  )rM   r  r<  r  r  join_to_lefts         rN   r?   z_ORMJoin.join4  s     eXD'JJra   c                 "    t        | ||d|      S )NT)r  r  r)  )rM   r  r<  r  r*  s        rN   	outerjoinz_ORMJoin.outerjoin>  s    eXt$GGra   )NFFNNr`   NFFNNFN)rX   rY   rZ   r[   r"   r  __visit_name__inherit_cacher   r'  r?   r,  r`   ra   rN   r  r    sT    9__33NM p<d
@ KHra   r  c                      t        | ||||      S )a  Produce an inner join between left and right clauses.

    :func:`_orm.join` is an extension to the core join interface
    provided by :func:`_expression.join()`, where the
    left and right selectables may be not only core selectable
    objects such as :class:`_schema.Table`, but also mapped classes or
    :class:`.AliasedClass` instances.   The "on" clause can
    be a SQL expression or an ORM mapped attribute
    referencing a configured :func:`_orm.relationship`.

    .. deprecated:: 1.4 using a string relationship name for the "onclause"
       is deprecated and will be removed in 2.0; the onclause may be only
       an ORM-mapped relationship attribute or a SQL expression construct.

    :func:`_orm.join` is not commonly needed in modern usage,
    as its functionality is encapsulated within that of the
    :meth:`_sql.Select.join` and :meth:`_query.Query.join`
    methods. which feature a
    significant amount of automation beyond :func:`_orm.join`
    by itself.  Explicit use of :func:`_orm.join`
    with ORM-enabled SELECT statements involves use of the
    :meth:`_sql.Select.select_from` method, as in::

        from sqlalchemy.orm import join
        stmt = select(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::

        stmt = select(User).\
                join(User.addresses).\
                filter(Address.email_address=='foo@bar.com')

    .. warning:: using :func:`_orm.join` directly may not work properly
       with modern ORM options such as :func:`_orm.with_loader_criteria`.
       It is strongly recommended to use the idiomatic join patterns
       provided by methods such as :meth:`.Select.join` and
       :meth:`.Select.join_from` when creating ORM joins.

    .. seealso::

        :ref:`orm_queryguide_joins` - in the :ref:`queryguide_toplevel` for
        background on idiomatic ORM join patterns

    r)  )r  r  r<  r  r  r*  s         rN   r?   r?   B  s    d D%7D99ra   c                      t        | ||d|      S )a  Produce 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.

    Tr)  )r  r  r<  r  r*  s        rN   r,  r,  w  s     D%466ra   c                 Z   t        |t        j                        rAt        j                  d       t	        |       }t        |j                  |      j                  }n>t        |t        j                        r$|j                  r|j                  }|j                  }|j                  | |      S )a  Create filtering criterion that relates this query's primary entity
    to the given related instance, using established
    :func:`_orm.relationship()`
    configuration.

    E.g.::

        stmt = select(Address).where(with_parent(some_user, User.addresses))


    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.

    The given property may also make use of :meth:`_orm.PropComparator.of_type`
    to indicate the left side of the criteria::


        a1 = aliased(Address)
        a2 = aliased(Address)
        stmt = select(a1, a2).where(
            with_parent(u1, User.addresses.of_type(a2))
        )

    The above use is equivalent to using the
    :func:`_orm.with_parent.from_entity` argument::

        a1 = aliased(Address)
        a2 = aliased(Address)
        stmt = select(a1, a2).where(
            with_parent(u1, User.addresses, from_entity=a2)
        )

    :param instance:
      An instance which has some :func:`_orm.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.

      .. deprecated:: 1.4 Using strings is deprecated and will be removed
         in SQLAlchemy 2.0.  Please use the class-bound attribute directly.

    :param from_entity:
      Entity in which to consider as the left side.  This defaults to the
      "zero" entity of the :class:`_query.Query` itself.

      .. versionadded:: 1.2

    zUsing strings to indicate relationship names in the ORM with_parent() function is deprecated and will be removed SQLAlchemy 2.0.  Please use the class-bound attribute directly.)from_entity)r7   r   r8   warn_deprecated_20r   r   r   rZ  r   r  _of_type_with_parent)r   r  r4  r   s       rN   with_parentr8    s    l $))*N	

 x(v}}d+44	D*77	8==--K}}X;??ra   c                 D    t        j                  |       }|j                  S )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`

    )r   instance_statehas_identityobject_rg   s     rN   r;  r;    s      %%g.Era   c                 D    t        j                  |       }|j                  S )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`

    )r   r:  was_deletedr<  s     rN   r?  r?    s      %%g.Era   c                     |j                   r.| j                   r!|j                         | j                         u ryy| j                   r| j                  r|| j                  v S || u S |j	                  |       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)r   r  r  r   common_parentgivenr   s     rN   _entity_corresponds_torD    st     !!!!#u'8'8'::			!!U;;;;U?"&&ra   c                    | j                   r1|j                   xr# |j                   xr | |u xs | |j                  v S |j                   s| j                  |j                        S |j                  xr | |j
                  v S )a  determine 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


    )r   r  r   rA  r   r   rB  s     rN   $_entity_corresponds_to_use_path_implrF    s    ( ## P+++P&NEV-N-N$N	

 $$""6==11 ## 9888	
ra   c                     | j                   r+|| j                  v xs | j                  j                  |      S | j                  r|| j                  v S | j                  |      S )zedetermine if 'given' "is a" mapper, in terms of the given
    would load rows of type 'mapper'.

    )r   r   r   r   )rC  r   s     rN   _entity_isarH     sd    
 777 
5<<;K;K<
 	
 
	'	'7777yy  ra   c                  z    ddl m} m}m}m} ddlm} ddlm} |x|_	        x| _	        x|_	        x|_	        |_	        y)aZ  Use 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   )
unitofworksessionr   
dependency)topological)	RandomSetN)
sqlalchemy.ormrJ  rK  r   rL  sqlalchemy.utilrM  sqlalchemy.testing.utilrN  r:   )rJ  rK  r   rL  rM  rN  s         rN   randomize_unitofworkrR  /  sA    6 GF+1 5>>KO >>>j:>ra   c                    fd}t        |t              rt        j                  |      \  }}}t        |t              rt        |t              r
||z
  dk  rg S t        |t              r|dk  st        |t              r|dk  r |        t        |       |   S | j                  ||      }|t        |      dd|j                     S t        |      S |dk(  r |        t        |       d   S t        | ||dz          d   S )zdcalculate __getitem__ in terms of an iterable query object
    that also has a slice() method.

    c                  J     st        d      t        j                  d       y )Nz@negative indexes are not accepted by SQL index / slice operatorszSupport for negative indexes for SQL index / slice operators will be removed in 2.0; these operators fetch the complete result and do not work efficiently.)
IndexErrorr   r5  )allow_negatives   rN   _no_negative_indexesz&_getitem.<locals>._no_negative_indexesY  s-    * 
 ##/ra   r   Nr   )r7   slicer   decode_sliceintr  step)iterable_queryitemrV  rW  startstopr\  ress     `     rN   _getitemrb  S  s     $ --d3tT tS!5#&u!I$tS!dQh "'--""5$/9TD49945592: "'++tdQh78;;ra   )p_unionT)NNFF)FFNFFFFNrd   r-  r.  )PrT   r   r  rS   r   r    r   r   r   r   r	   r
   r   r   r   r   r   r   
interfacesr   r   r   r   r   r   path_registryr   r   r   r=   r   r   r   engine.resultr   sql_baser!   r"   r#   r$   r   r%   sql.annotationr&   sql.baser'   rF   r\   r1   r   r   r   r   r   re  r   MemoizedHasCacheKeyr   r^  rk  	_inspectsr  r  _self_inspectsr  r  r  r  r  r  r?   r,  r8  r;  r?  rD  rF  rH  rR  rb  r`   ra   rN   <module>rm     s   
    "          % !  & & , 2 ) & '      ( "     "  5 ' 	?Y ?D?DF =AO3de;P%P'' %PPx'6 x'vh<  	h<V	*f *8}'> }'@
 # 
  \ "#F G ! 
  [ !"7 8n
h 	qh m  	m m`K.aHz aHJ IM2:j7C@L "'( 
F!!>H.<ra   