o
    g;                    @  s  d dl mZ d dlZd dlZd dlZd dlZd dlZd dlmZ d dlmZ d dlm	Z	 d dlm
Z
 d dlmZ d dlmZ d d	lmZ d d
lmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dl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"m0Z0 dd*l"m1Z1 dd+l"m2Z2 dd,l"m3Z3 dd-l"m4Z4 dd.l"m5Z5 dd/l6m7Z7 dd0l6m8Z8 dd1l6m9Z9 dd2l6m:Z: dd3l6m;Z; dd4l<m=Z= d5d6lm>Z> d5dlmZ? d5d7lm@Z@ d5d8lmAZA d5d9lmBZB d5d:lCmDZD d5d;lAmEZE d5d<lAmFZF d5d=lAmGZG d5d>lAmHZH d5d9lAmBZI d5d?lAmJZJ d5d@lKmLZL d5dAlMmNZN d5dBlOmPZP d5dClQmRZR d5dDlQmSZS d5dElTmUZU d5dFlTmVZV d5dGlWmXZX d5dHlYmZZZ d5dIl[m\Z] d5dJl[m^Z_ d5dKl[m`Z` d5dLl[maZa d5dMl[mbZb d5dNl[mcZc d5dOl[mdZd ejrddPlmeZe ddQlmfZf ddRlmgZg ddSlmhZh ddTlimjZj ddUlimkZk ddVllmmZm ddWl<mnZn ddXlompZp ddYlqmrZr d5dZlsmtZt d5d[lsmuZu d5d\lKmvZv d5d]lKmwZw d5d^lKmxZx d5d_lKmyZy d5d`lKmzZz d5dalKm{Z{ d5dblMm|Z| d5dclOm}Z} d5ddlTm~Z~ d5delWmZ d5dflWmZ d5dglWmZ d5dhlmZ d5dil[mZ edjedkZedlZejejeBe-e5e*dmdnZG dodp dpedZe
eee]Z\G dqdr dredZe
eee_Z^G dsdt dtee Zdudv Z	xddydzZ		ddddd{dddZG dd dejZG dd deIjZG dd deIjZG dd de@jd e9e Ze@jG dd de:e e;eRe+eZe@jd ee 	ZG dd dZG dd de7Ze@edd  e@edddZeee Ze@edddZe@jG dd de9e eNeSe@jd e+ZddddZdddZdddZG dd deFjZ	ddddZdddZdddZdddZdddÄZdddǄZddd̈́ZdddԄZG ddք deZdddۄZ	x	xddddZdddZdS )    )annotationsN)AbstractSet)Any)Callable)cast)Dict)	FrozenSet)Generic)Iterable)Iterator)List)Match)Optional)Sequence)Tuple)Type)TYPE_CHECKING)TypeVar)Union   )
attributes)exc)_O)insp_is_aliased_class)insp_is_mapper)prop_is_relationship)_class_to_mapper)_MappedAnnotationBase)
_never_set)_none_only_set)	_none_set)attribute_str)class_mapper)DynamicMapped)InspectionAttr)instance_str)Mapped)object_mapper)object_state)opt_manager_of_class)ORMDescriptor)state_attribute_str)state_class_str)	state_str)WriteOnlyMapped)CriteriaOption)MapperProperty)ORMColumnsClauseRole)ORMEntityColumnsClauseRole)ORMFromClauseRole)PathRegistry   )event)
inspection)sql)utilresult_tuple)	coercions)
expression)lambdas)roles)visitors)is_selectable)SupportsCloneAnnotations)ColumnCollection)HasCacheKey)MemoizedHasCacheKey)ColumnElement)KeyedColumnElement)
FromClause)MemoizedSlots)de_stringify_annotation)eval_name_only)fixup_container_fwd_refs)
get_origin)is_origin_of_cls)Literal)Protocol)_EntityType)_IdentityKeyType)_InternalEntityType)_ORMCOLEXPR)_MapperEntity)ORMCompileState)Mapper)AbstractEntityRegistry)Query)RelationshipProperty)Row)
RowMapping)_CE)_ColumnExpressionArgument)_EquivalentColumnMap)_FromClauseArgument)_OnClauseArgument)_PropagateAttrsType)_SA)ReadOnlyColumnCollection)BindParameter)_ColumnsClauseElement)Select)
Selectable)anon_map)_AnnotationScanType_T)bound)deletedelete-orphanallmergeexpungesave-updaterefresh-expirenone)r&   r.   r#   )locals_c                   @  s   e Zd ZddddddZdS )_DeStringifyAnnotationNF)str_cleanup_fninclude_genericcls	Type[Any]
annotationrj   originating_modulestrrw   #Optional[Callable[[str, str], str]]rx   boolreturnc                C     d S N )selfry   r{   r|   rw   rx   r   r   U/var/www/html/ecg_monitoring/venv/lib/python3.10/site-packages/sqlalchemy/orm/util.py__call__   s   z_DeStringifyAnnotation.__call__)ry   rz   r{   rj   r|   r}   rw   r~   rx   r   r   rz   __name__
__module____qualname__r   r   r   r   r   rv      s    rv   c                   @  s   e Zd Zd	ddZdS )
_EvalNameOnlynamer}   module_namer   r   c                 C  r   r   r   )r   r   r   r   r   r   r      s    z_EvalNameOnly.__call__N)r   r}   r   r}   r   r   r   r   r   r   r   r      s    r   c                      s   e Zd ZU dZeg dZeZg dZdZ	de
d< de
d< de
d< de
d	< de
d
< de
d< d fddZdd Zedd Z  ZS )CascadeOptionszHKeeps track of the options sent to
    :paramref:`.relationship.cascade`)ro   rt   rn   )rq   ro   rt   rs   rp   )save_updaterm   refresh_expirerp   rq   delete_orphanr   r   rm   r   rp   rq   r   
value_list#Optional[Union[Iterable[str], str]]r   c              
     s   t |ts	|d u r| |S t|}|| jr-tdddd t	|| jD  d|v r7|
| j d|v r?|  |d t | |}d|v |_d|v |_d	|v |_d
|v |_d|v |_d|v |_|jrt|jsttd |S )NzInvalid cascade option(s): %s, c                 S  s   g | ]}t |qS r   )repr.0xr   r   r   
<listcomp>   s    z*CascadeOptions.__new__.<locals>.<listcomp>ro   rt   rr   rm   rs   rp   rq   rn   z5The 'delete-orphan' cascade option requires 'delete'.)
isinstancer}   from_stringset
difference_allowed_cascadessa_excArgumentErrorjoinsortedupdate_add_w_all_cascadescleardiscardsuper__new__r   rm   r   rp   rq   r   r9   warn)ry   r   valuesr   	__class__r   r   r      s<   









zCascadeOptions.__new__c                 C  s   dd dd t| D  S )NzCascadeOptions(%r),c                 S  s   g | ]}|qS r   r   r   r   r   r   r          z+CascadeOptions.__repr__.<locals>.<listcomp>)r   r   r   r   r   r   __repr__   s   zCascadeOptions.__repr__c                 C  s"   dd t d|p	dD }| |S )Nc                 S  s   g | ]}|r|qS r   r   )r   cr   r   r   r          z.CascadeOptions.from_string.<locals>.<listcomp>z\s*,\s* )resplit)ry   argr   r   r   r   r      s   zCascadeOptions.from_string)r   r   r   r   )r   r   r   __doc__all_cascadesr   r   r   _viewonly_cascades	__slots____annotations__r   r   classmethodr   __classcell__r   r   r   r   r      s$   
 	%r   c           	        s   sfdd |r/ fdd} fdd} fdd} fd	d
}n fdd} fdd} fdd}t j| d|ddd t j| d|dd t j| d|ddd |rut j| d|ddd dS dS )zNRuns a validation method on an attribute value to be set or
    appended.
    c                   s   | j   j}|j|uS r   )managerimpl)state	initiatorr   )keyr   r   detect_is_backref  s   
z,_validator_events.<locals>.detect_is_backrefc                   s0   |j tjurs | |s|  |dS |S NFopr   OP_BULK_REPLACEobjr   valuer   r   include_backrefsr   	validatorr   r   append  s   z!_validator_events.<locals>.appendc                   <   s| |s|     fdd|D |d d < d S d S )Nc                   s   g | ]	} |d qS )Fr   r   r   r   r   r   r   r   r     s    7_validator_events.<locals>.bulk_set.<locals>.<listcomp>r   r   r   r   r   r   r   bulk_set  s   z#_validator_events.<locals>.bulk_setc                   s$   s | |s|   |dS |S r   r   r   r   oldvaluer   r   r   r   set_  s   z_validator_events.<locals>.set_c                   s(   s | |s|   |d d S d S )NTr   r   r   r   r   remove  s   z!_validator_events.<locals>.removec                   s.   |j tjurs | |s|  |S |S r   r   r   r   r   r   r   #  s   c                   r   )Nc                   s   g | ]} |qS r   r   r   r   r   r   r   .      r   r   r   r   r   r   r   +  s   "c                   s"   s | |s|   |S |S r   r   r   r   r   r   r   0  s   r   T)rawretvalbulk_replace)r   r   r   N)r6   listen)	descr   r   include_removesr   r   r   r   r   r   r   r   _validator_events   s    r   p_unionTc           
   
     s6  t  }i i | D ]>}| | tjtjdd| |< i }jD ]!}|j|kr2t	d||f |
|j |||j< |j|j< q"|< q
 fddg }|  D ];\}	|dur|tjfdd|D tt|	|g   qW|tjfd	d|D   qWtj| |S )
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_selectzPolymorphic union can't use '%s' as the discriminator column due to mapped column %r; please apply the 'typecolname' argument; this is available on ConcreteBase as '_concrete_discriminator_name'c                   s^   z| |  W S  t y.    rtt |  |  Y S tt |  |  Y S w r   )KeyErrorr8   r   nulllabeltype_coerce)r   table)
cast_nullscolnamemapstypesr   r   coln  s   zpolymorphic_union.<locals>.colNc                      g | ]} |qS r   r   r   r   r   r   r   r   r   }      z%polymorphic_union.<locals>.<listcomp>c                   r   r   r   r   r   r   r   r     r   )r9   
OrderedSetr<   expectr?   StrictFromClauseRoler   r   r   InvalidRequestErroraddtypeitemsr   r8   selectliteral_columnsql_util_quote_ddl_exprr   select_from	union_allalias)
	table_maptypecolname	aliasnamer   colnamesr   mr   resulttype_r   )r   r   r   r   r   r   polymorphic_union=  sX   



		r  )instancerowidentity_tokenclass_Optional[Type[_T]]identUnion[Any, Tuple[Any, ...]]r  Optional[_T]r  %Optional[Union[Row[Any], RowMapping]]r	  Optional[Any]r   _IdentityKeyType[_T]c                C  st   | dur(t | }|du r!|du rtd|jtt||dS |j||dS |dur5t|}|	|S td)a5  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` or :class:`.RowMapping` 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

    Nzident or row is required)r	  zclass or instance is required)
r"   r   r   identity_key_from_primary_keytupler9   to_listidentity_key_from_rowr'   identity_key_from_instance)r
  r  r  r  r	  mapperr   r   r   identity_key  s   E


r  c                   @  sh   e Zd ZdZe Ze Ze Ze Z	e Z
e Ze Ze Ze Ze Ze ZdS )_TraceAdaptRolea  Enumeration of all the use cases for ORMAdapter.

    ORMAdapter remains one of the most complicated aspects of the ORM, as it is
    used for in-place adaption of column expressions to be applied to a SELECT,
    replacing :class:`.Table` and other objects that are mapped to classes with
    aliases of those tables in the case of joined eager loading, or in the case
    of polymorphic loading as used with concrete mappings or other custom "with
    polymorphic" parameters, with whole user-defined subqueries. The
    enumerations provide an overview of all the use cases used by ORMAdapter, a
    layer of formality as to the introduction of new ORMAdapter use cases (of
    which none are anticipated), as well as a means to trace the origins of a
    particular ORMAdapter within runtime debugging.

    SQLAlchemy 2.0 has greatly scaled back ORM features which relied heavily on
    open-ended statement adaption, including the ``Query.with_polymorphic()``
    method and the ``Query.select_from_entity()`` methods, favoring
    user-explicit aliasing schemes using the ``aliased()`` and
    ``with_polymorphic()`` standalone constructs; these still use adaption,
    however the adaption is applied in a narrower scope.

    N)r   r   r   r   enumautoALIASED_INSPJOINEDLOAD_USER_DEFINED_ALIAS JOINEDLOAD_PATH_WITH_POLYMORPHICJOINEDLOAD_MEMOIZED_ADAPTERMAPPER_POLYMORPHIC_ADAPTERWITH_POLYMORPHIC_ADAPTER#WITH_POLYMORPHIC_ADAPTER_RIGHT_JOIN DEPRECATED_JOIN_ADAPT_RIGHT_SIDEADAPT_FROM_STATEMENTCOMPOUND_EAGER_STATEMENTLEGACY_SELECT_FROM_ALIASr   r   r   r   r    s    r  c                      s6   e Zd ZdZdZdddddddd fddZ  ZS )ORMStatementAdapterz.ColumnAdapter which includes a role attribute.)roleNFTequivalentsadapt_requiredallow_label_resolveanonymize_labelsadapt_on_namesadapt_from_selectablesr(  r  
selectablerh   r*  Optional[_EquivalentColumnMap]r+  r   r,  r-  r.  r/  !Optional[AbstractSet[FromClause]]c          	   	     s$   || _ t j|||||||d d S )Nr)  )r(  r   __init__)	r   r(  r0  r*  r+  r,  r-  r.  r/  r   r   r   r3  (  s   
zORMStatementAdapter.__init__)r(  r  r0  rh   r*  r1  r+  r   r,  r   r-  r   r.  r   r/  r2  )r   r   r   r   r   r3  r   r   r   r   r   r'  #  s    r'  c                	      sT   e Zd ZU dZdZded< ded< ddd	ddd	ddd
d fddZdd Z  ZS )
ORMAdapterzaColumnAdapter subclass which excludes adaptation of entities from
    non-matching mappers.

    )r(  r  is_aliased_classaliased_inspr   r5  Optional[AliasedInsp[Any]]r6  NFT)r*  r+  r,  r-  r0  limit_on_entityr.  r/  r(  r  entity_InternalEntityType[Any]r*  r1  r+  r,  r-  r0  Optional[Selectable]r8  r.  r/  r2  c             
     sh   || _ |j| _|d u r|j}t|rd| _|| _nd| _d | _t j||||||r,| jnd |	|
d d S )NTF)r+  r,  r-  
include_fnr.  r/  )	r(  r  r0  r   r5  r6  r   r3  _include_fn)r   r(  r9  r*  r+  r,  r-  r0  r8  r.  r/  r   r   r   r3  K  s&   
zORMAdapter.__init__c                 C  s,   |j dd }| p|| jp| j|S )Nparentmapper)_annotationsgetisar  )r   elemr9  r   r   r   r=  o  s   zORMAdapter._include_fn)r(  r  r9  r:  r*  r1  r+  r   r,  r   r-  r   r0  r;  r8  r   r.  r   r/  r2  )	r   r   r   r   r   r   r3  r=  r   r   r   r   r   r4  @  s   
 $r4  c                   @  sn   e Zd ZU dZded< 									d+d,ddZed-ddZd.d!d"Zd/d%d&Z	d0d'd(Z
d0d)d*ZdS )1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`


    r}   r   NFmapped_class_or_ac_EntityType[_O]r   Optional[FromClause]r   Optional[str]flatr   r.  with_polymorphic_mappersOptional[Sequence[Mapper[Any]]]with_polymorphic_discriminatorOptional[ColumnElement[Any]]
base_aliasr7  use_mapper_pathrepresents_outer_joinc                 C  s   t dt|}|j}d}|d u r'|jr|jjr|j }n|jj	||d}n|jr,d}|d us2J t
| ||||r;|n|j|d urC|n|j||	||
|| _d|jj d| _d S )N_InternalEntityType[_O]Fr   rH  Taliased())r   r7   inspectr  r5  r0  _is_subqueryr   _with_polymorphic_selectable_anonymous_fromclauseAliasedInsprI  polymorphic_on_aliased_inspr
  r   )r   rD  r   r   rH  r.  rI  rK  rM  rN  rO  inspr  nest_adaptersr   r   r   r3    sD   
zAliasedClass.__init__r6  AliasedInsp[_O]r   AliasedClass[_O]c                 C  s\   |  | }d|jjj d|_||_|jr,|jD ]}||ur+t|}t	||jj| q|S )NrR  rS  )
r   r  r
  r   rZ  _is_with_polymorphic_with_polymorphic_entitiesrC  _reconstitute_from_aliased_inspsetattr)ry   r6  r   sub_aliased_inspentr   r   r   ra    s   

z,AliasedClass._reconstitute_from_aliased_inspr   r   c                 C  s   z| j d }W n
 ty   t w |j}t||}t|dr+t|dr+t|j| S t|dr6|	d | }t|drF|
|}t| || |S )NrZ  r   __self____get__adapt_to_entity)__dict__r   AttributeError_targetgetattrhasattrr   
MethodType__func__rf  rg  rb  )r   r   rZ  targetattrr   r   r   __getattr__  s   



zAliasedClass.__getattr__mapped_classr   c                 C  sr   t ||}t|drt|drt|j| S t|dr!|d | }t|dr7t| |_|	|}t
| || |S )Nr   re  rf  rg  )rk  rl  r   rm  rn  rf  weakrefref_weak_entityrg  rb  )r   r   rr  r6  rp  r   r   r   _get_from_serialized  s   



z!AliasedClass._get_from_serializedc                 C  s   dt | | jjjf S )Nz<AliasedClass at 0x%x; %s>)idrZ  rj  r   r   r   r   r   r   5  s   zAliasedClass.__repr__c                 C  s
   t | jS r   )r}   rZ  r   r   r   r   __str__;     
zAliasedClass.__str__)	NNFFNNNFF)rD  rE  r   rF  r   rG  rH  r   r.  r   rI  rJ  rK  rL  rM  r7  rN  r   rO  r   )r6  r]  r   r^  )r   r}   r   r   )r   r}   rr  r   r6  r]  r   r   )r   r}   )r   r   r   r   r   r3  r   ra  rq  rv  r   rx  r   r   r   r   rC  u  s&   
 ;:


rC  r]  c                   @  s  e Zd ZU 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
ed< ded< ded< ded< ded< ded< 	 ded< 	 dgd"d#Ze	$	$	%	%dhdid-d.Ze	%	%	$	%	%	%	$	%djdkd6d7Zedld8d9Zd:Z	 dmd;d<Zedld=d>Zednd@dAZedodCdDZdpdFdGZdqdJdKZdrdNdOZ	$dsdtdSdTZer	$dsdudWdXZneZdYdZ Z d[d\ Z!d]d^ Z"d_d` Z#dadb Z$dcdd Z%dedf Z&d$S )vrX  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`

    )__weakref__ru  r  r0  r   _adapt_on_namesrI  rY  _use_mapper_path_base_aliasrO  persist_selectablelocal_tabler_  r`  _adapterrj  __clause_element___memoized_values_all_column_expressions_nest_adaptersr   r{  r|  rj  r0  rI  rY  z
Mapper[_O]r  rH   r4  r  zSequence[Mapper[Any]]zSequence[AliasedInsp[Any]]r`  zweakref.ref[AliasedClass[_O]]ru  z!Union[Type[_O], AliasedClass[_O]]r9  r^  	inspectedrP  rG  rJ  rL  r}  r7  r   r.  rO  r\  c              
     s,  |j }|j}t|| _|| _| | _ | _| _|| _|| _	t|p#| | _
|| _|
| _|| _|r_d| _|| _g | _| jD ] }||ur]t|j||  |d}t| j |jj| | j|j q=nd| _|g| _ttj|||j d fdd| jD dd| _|rt|tsJ |j| j| _ | _|| _ d S )NT)rM  r.  rN  Fc                   s   h | ]} s|j qS r   )r0  )r   r  r.  r   r   	<setcomp>  s    z'AliasedInsp.__init__.<locals>.<setcomp>)r0  r*  r.  r-  r/  r8  )!r9  r  rs  rt  ru  r0  r~  r  r   rY  r}  r|  rO  r  r_  rI  r`  rC  r
  rb  r   r   rZ  r4  r  r  _equivalent_columnsr  r   rX  wrapr{  rj  )r   r9  r  r0  r   rI  rY  r}  r|  r.  rO  r\  rD  r  polyrd  r   r  r   r3    s`   


zAliasedInsp.__init__NFelement"Union[_EntityType[_O], FromClause]r   rF  rH  r   #Union[AliasedClass[_O], FromClause]c                 C  sN   t |tr|rtd|r|j||dS tjtj||dS t	|||||dS )Nz+adapt_on_names only applies to ORM elementsrQ  rH  )r   rH  r   r.  )
r   rH   r   r   r   r<   r   r?   AnonymizedFromClauseRolerC  )ry   r  r   r   rH  r.  r   r   r   _alias_factory  s"   
	zAliasedInsp._alias_factorybaseUnion[Type[_O], Mapper[_O]]classes/Union[Literal['*'], Iterable[_EntityType[Any]]]'Union[Literal[False, None], FromClause]aliased	innerjoinc              
   C  sl   t |}|dvr|rtd|j|||d\}}|s|r)|d us#J |j|d}t|||	||||
| dS )Nr   z[the 'flat' and 'selectable' arguments cannot be passed simultaneously to with_polymorphic()r  r  )r   rI  r.  rK  rN  rO  )r   r   r   _with_polymorphic_argsrW  rC  )ry   r  r  r0  rH  rY  r  r  r.  r   r|  primary_mappermappersr   r   r   _with_polymorphic_factory  s*   
z%AliasedInsp._with_polymorphic_factoryc                 C  s*   |   }|d u rt| }t|| _ |S r   )ru  rC  ra  rs  rt  )r   rd  r   r   r   r9  6  s
   
zAliasedInsp.entityTc                 C  s"   | j | j| | dd| dS )N)r>  parententityentity_namespaceormcompile_state_pluginplugin_subject)r0  	_annotater  _set_propagate_attrsr   r   r   r   #_memoized_method___clause_element__G  s   z/AliasedInsp._memoized_method___clause_element__c                 C     | j S r   )r9  r   r   r   r   r  R  s   zAliasedInsp.entity_namespaceType[_O]c                 C  s   | j jS )zUReturn the mapped class ultimately represented by this
        :class:`.AliasedInsp`.)r  r
  r   r   r   r   r
  V  s   zAliasedInsp.class_rX   c                 C  s   | j r| jjS t| S r   )r|  r  _path_registryr4   
per_mapperr   r   r   r   r  \  s   
zAliasedInsp._path_registryDict[str, Any]c                 C  s4   | j | j| j| j| j| j| j|  | j| j	| j
dS )N)r9  r  r   r   r.  rI  rK  rM  rN  rO  r\  )r9  r  r0  r   r{  rI  rY  r}  r|  rO  r  r   r   r   r   __getstate__c  s   zAliasedInsp.__getstate__r   Nonec                 C  sN   |  |d |d |d |d |d |d |d |d |d	 |d
 |d  d S )Nr9  r  r   r   rI  rK  rM  rN  r.  rO  r\  )r3  )r   r   r   r   r   __setstate__r  s   zAliasedInsp.__setstate__otherr]  c                 C  s   |j }| j |u s
J tdd | jD }dd |jD }||kr#|S ||}|j|d |j d\}}|jdd}t||||j	|j
|jdjS )	Nc                 s  s    | ]}|j V  qd S r   r
  r   mpr   r   r   	<genexpr>  s    
z*AliasedInsp._merge_with.<locals>.<genexpr>c                 S  s   h | ]}|j qS r   r  r  r   r   r   r        z*AliasedInsp._merge_with.<locals>.<setcomp>r  Tr  )rI  rK  rN  rO  )r  r9   to_setrI  unionr  rO  rW  rC  rY  r|  rZ  )r   r  r  our_classesnew_classesr  r  r0  r   r   r   _merge_with  s.   



zAliasedInsp._merge_withexprrT   r   c                 C  sD   t |tsJ | | jd}|r||d< | j||d| dS )N)r  r>  	proxy_keyr  r  )r   rF   r  r  traverser  r  )r   r  r   dr   r   r   _adapt_element  s   
zAliasedInsp._adapt_elementr   r]   c                 C  r   r   r   )r   r   r   r   r   r   _orm_adapt_element  s   zAliasedInsp._orm_adapt_elementc                 C  sN   | j }||v r|| ju r| S t| j|jjjS || jr| S J d|| f )NFz"mapper %s doesn't correspond to %s)rI  r  rk  r9  r
  r   rZ  rA  )r   r  	self_polyr   r   r   _entity_for_mapper  s   

zAliasedInsp._entity_for_mapperc                   s.    j j\}} j| fdd| D fS )Nc                   s   i | ]\}} j ||qS r   )r  r  )r   r   paramr   r   r   
<dictcomp>  s    z:AliasedInsp._memoized_attr__get_clause.<locals>.<dictcomp>)r  _get_clauser  r  r   )r   onclause
replacemapr   r   r   _memoized_attr__get_clause  s   

z&AliasedInsp._memoized_attr__get_clausec                 C  s   i S r   r   r   r   r   r   _memoized_attr__memoized_values  s   z+AliasedInsp._memoized_attr__memoized_valuesc                   sD    j r jdd  jD }n j } fdd|D }t|S )Nc                 S  s   g | ]}|j qS r   )r  )r   rd  r   r   r   r     r  zFAliasedInsp._memoized_attr__all_column_expressions.<locals>.<listcomp>c                   s   g | ]\}}|  |fqS r   )r  )r   r   r   r   r   r   r     s    )r_  r  _columns_plus_keysr`  rC   )r   cols_plus_keysr   r   r   &_memoized_attr__all_column_expressions  s   

z2AliasedInsp._memoized_attr__all_column_expressionsc                 O  s0   || j v r
| j | S ||i | | j |< }|S r   )r  )r   r   	callable_argskwr   r   r   r   _memo  s   

zAliasedInsp._memoc                 C  s<   | j rdddd | j D  }nd}dt| | jj|f S )Nz(%s)r   c                 s  s    | ]}|j jV  qd S r   )r
  r   r  r   r   r   r    s    
z'AliasedInsp.__repr__.<locals>.<genexpr>r   z<AliasedInsp at 0x%x; %s%s>)rI  r   rw  r
  r   )r   	with_polyr   r   r   r     s   zAliasedInsp.__repr__c                   s:    j rd jjd fdd jD f S d jjf S )Nzwith_polymorphic(%s, [%s])r   c                 3  s"    | ]}| j ur|jjV  qd S r   )r  r
  r   r  r   r   r   r    s    
z&AliasedInsp.__str__.<locals>.<genexpr>zaliased(%s))r_  rj  r   r   rI  r   r   r   r   rx    s   	zAliasedInsp.__str__)r9  r^  r  rP  r0  rH   r   rG  rI  rJ  rY  rL  r}  r7  r|  r   r.  r   rO  r   r\  r   )NNFF)r  r  r   rF  r   rG  rH  r   r.  r   r   r  )FFNFFFNF)r  r  r  r  r0  r  rH  r   rY  rL  r  r   r  r   r.  r   r   rG  r|  r   r   r^  )r   r^  )r   rH   )r   r  )r   rX   )r   r  )r   r  r   r  )r  r]  r   r]  r   )r  rT   r   rG  r   rT   )r   r]   r   rG  r   r]   )'r   r   r   r   r   r@   ExtendedInternalTraversal	dp_string
dp_booleandp_inspectabledp_clauseelementInternalTraversaldp_has_cache_key_list_cache_key_traversalr   r3  r   r  r  propertyr9  r5  r  r  r
  r  r  r  r  r  r   r  r  r  r  r  r  r   rx  r   r   r   r   rX  ?  s   
 
&






L'




rX  c                   @  s.   e Zd ZdZdZdd Zeddd ZdS )	_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                 C  s
   || _ d S r   r  )r   r  r   r   r   r3    ry  z_WrapUserEntity.__init__zsqlalchemy.orm.decl_apic                 C  sL   t jjj}t| d}||jv r!t|j| |jr!|j| 	|S t
||S )Nr  )r9   	preloadedr  decl_apiobject__getattribute__rh  r   declared_attrfgetrk  )r   r   r  r  r   r   r   r    s   

z _WrapUserEntity.__getattribute__N)	r   r   r   r   r   r3  r9   preload_moduler  r   r   r   r   r    s    	r  c                   @  s   e Zd ZU 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ed< d	ed< d
ed< ded< ded< ded< ded< 				d5d6ddZedd Zdd Zd7ddZd8d"d#Zd9d'd(Zd:d,d-Zd;d.d/Zd<d2d3Zd4S )=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_entityr9  deferred_where_criteriawhere_criteria_where_crit_originclude_aliasespropagate_to_loadersr  r9  r  r  r  zOptional[Type[Any]]"Optional[_InternalEntityType[Any]]z9Union[ColumnElement[bool], lambdas.DeferredLambdaElement]r   r  r   r  FTentity_or_base_EntityType[Any]XUnion[_ColumnExpressionArgument[bool], Callable[[Any], _ColumnExpressionArgument[bool]]]loader_onlytrack_closure_variablesc           	      C  s   t dt|d}|d u rt d|| _d | _nd | _|| _|| _t|rL| jd ur-| j}n	|d us3J |j}d| _tj	|t
jt|ftj|dd| _nd| _tt
j|| _|| _|| _d S )Nr:  Frz   T)r  )lambda_argsopts)r   r7   rT  r  r9  r  callabler  r>   DeferredLambdaElementr?   WhereHavingRoler  LambdaOptionsr  r<   r   r  r  )	r   r  r  r  r  r  r  r9  wrap_entityr   r   r   r3  O  s<   


	
zLoaderCriteriaOption.__init__c                 C  s   t ||||dS )N)r  r  )r  )ry   r9  r  r  r  r   r   r   	_unreduce  s   zLoaderCriteriaOption._unreducec                 C  s(   t j| jr	| jjn| j| j| j| jffS r   )r  r  r9  r
  r  r  r  r  r   r   r   r   
__reduce__  s   zLoaderCriteriaOption.__reduce__r   Iterator[Mapper[Any]]c                 c  s    | j r| j jjE d H  d S | jsJ t| j }|r@|d}tdtj	|dd}|r5|jjE d H  n|
|  |sd S d S )Nr   r:  F)raiseerr)r9  r  self_and_descendantsr  list__subclasses__popr   r7   rT  extend)r   stacksubclassrd  r   r   r   _all_mappers  s   

z!LoaderCriteriaOption._all_mapperscompile_staterV   c                 C  s   |j jdd | u rdS dS )Nfor_loader_criteriaFT)select_statementr?  r@  r   r  r   r   r   _should_include  s   z$LoaderCriteriaOption._should_includeext_infor:  ColumnElement[bool]c                 C  sF   | j rtd| j|j}n| j}t|tsJ tj|d| idddS )Nr	  r  T)detect_subquery_colsind_cols_on_fromclause)	r  r   r  _resolve_with_argsr9  r   rF   r   _deep_annotate)r   r  critr   r   r   _resolve_where_criteria  s   z,LoaderCriteriaOption._resolve_where_criteriamapper_entitiesIterable[_MapperEntity]r  c                 C  s   |  | d S r   )process_compile_state)r   r  r  r   r   r   'process_compile_state_replaced_entities  s   z<LoaderCriteriaOption.process_compile_state_replaced_entitiesc                 C  s   |  |j dS )z7Apply a modification to a given :class:`.CompileState`.N)get_global_criteriaglobal_attributesr  r   r   r   r    s   z*LoaderCriteriaOption.process_compile_stater   Dict[Any, Any]c                 C  s,   |   D ]}|d|fg }||  qd S )Nadditional_entity_criteria)r  
setdefaultr   )r   r   r  load_criteriar   r   r   r    s   z(LoaderCriteriaOption.get_global_criteriaN)FFTT)r  r  r  r  r  r   r  r   r  r   r  r   )r   r  )r  rV   r   r   )r  r:  r   r	  )r  rV   r  r  r   r  )r  rV   r   r  )r   r  r   r  )r   r   r   r   r   r@   r  dp_plain_objdp_has_cache_keyr  r  r  _traverse_internalsr   r3  r   r  r  r  r  r  r  r  r  r   r   r   r   r  (  s<   
 




	1







r  c                 C  r  r   )rZ  )ro  r   r   r   <lambda>  s    r  r  Optional[Mapper[_O]]c                 C  s@   zt | }|d u s|jsW d S |j}W |S  tjy   Y d S w r   )r)   	is_mappedr  r   NO_STATE)r
  class_managerr  r   r   r   _inspect_mc  s   r"  c                 C  s   t dt| }t|S )Nr  )r   rM   r"  )r
  originr   r   r   _inspect_generic_alias  s   r$  c                   @  s   e Zd ZU dZdZ	 dZdZdZdZe	
 Zded< e	jZded< d3ddZd4ddZed5ddZed6ddZed7ddZded< 	 ded < 	 d!d" Zd#d$ Zed%d& Zd'd( Zd8d0d1Zd2S )9Bundlea+  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.

    .. seealso::

        :ref:`bundles`


    FTrb   _propagate_attrszList[_ColumnsClauseElement]exprsr   r}   _ColumnExpressionArgument[Any]r  r   c                   s`   |  _  _ fdd|D }| _tdd dd |D D    _ _|d j _dS )a<  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.

        c                   s   g | ]}t jtj| d qS ))apply_propagate_attrs)r<   r   r?   ColumnsClauseRoler   r  r   r   r   r   8  s    z#Bundle.__init__.<locals>.<listcomp>c                 s  s"    | ]}t |d |j|fV  qdS )r   N)rk  _label)r   r   r   r   r   r  @  s
    
z"Bundle.__init__.<locals>.<genexpr>c                 S     g | ]	}|j d |qS bundler?  r@  r   er   r   r   r   B      single_entityN)	r   r,  r'  rC   as_readonlyr   columnsr  r4  )r   r   r'  r  coerced_exprsr   r   r   r3  $  s   

zBundle.__init__ri   
bindparamsList[BindParameter[Any]]r   Tuple[Any, ...]c                   s*   | j | j| jft fdd| jD  S )Nc                   s   g | ]}|  qS r   )_gen_cache_keyr+  ri   r8  r   r   r   J  r   z)Bundle._gen_cache_key.<locals>.<listcomp>)r   r   r4  r  r'  )r   ri   r8  r   r<  r   r;  F  s   zBundle._gen_cache_keyOptional[Mapper[Any]]c                 C     | j d jdd }|S )Nr   r>  r'  r?  r@  )r   r  r   r   r   r  M  s   zBundle.mapperr  c                 C  r>  )Nr   r  r?  )r   ier   r   r   r9  T  s   
zBundle.entity6ReadOnlyColumnCollection[str, KeyedColumnElement[Any]]c                 C  r  r   )r   r   r   r   r   r  [  s   zBundle.entity_namespacer6  r   c                 K  s    | j | j }|j| j |S r   )r   r   rh  r   )r   r  clonedr   r   r   _clone~  s   zBundle._clonec                 C  s^   | | d}| | j | jd jd| j}tjdd | jD tj	dd
|d|d	S )
N)r/  r  r   r  c                 S  r-  r.  r0  r1  r   r   r   r     r3  z-Bundle.__clause_element__.<locals>.<listcomp>F)_literal_as_text_rolegroupr  r  )r   r?  r'  r&  r@  r9  r=   
ClauseListr?   r*  r  r  )r   r   r  r   r   r   r    s"   
zBundle.__clause_element__c                 C  s
   |   jS r   )r  clausesr   r   r   r   rG    s   
zBundle.clausesc                 C  s   |   }||_|S )z<Provide a copy of this :class:`.Bundle` passing a new label.)rC  r   )r   r   rB  r   r   r   r     s   zBundle.labelquerySelect[Any]procs#Sequence[Callable[[Row[Any]], Any]]labelsSequence[str]Callable[[Row[Any]], Any]c                   s(   t |dd |D  d
 fdd}|S )a  Produce the "row processing" function for this :class:`.Bundle`.

        May be overridden by subclasses to provide custom behaviors when
        results are fetched. The method is passed the statement object and a
        set of "row processor" functions at query execution time; these
        processor functions when given a result row will return the individual
        attribute value, which can then be adapted into any kind of return data
        structure.

        The example below illustrates replacing the usual :class:`.Row`
        return structure with a straight Python dictionary::

            from sqlalchemy.orm import Bundle


            class DictBundle(Bundle):
                def create_row_processor(self, query, procs, labels):
                    "Override create_row_processor to return values as dictionaries"

                    def proc(row):
                        return dict(zip(labels, (proc(row) for proc in procs)))

                    return proc

        A result from the above :class:`_orm.Bundle` will return dictionary
        values::

            bn = DictBundle("mybundle", MyClass.data1, MyClass.data2)
            for row in session.execute(select(bn)).where(bn.c.data1 == "d1"):
                print(row.mybundle["data1"], row.mybundle["data2"])

        c                 S  s   g | ]}d qS )r   r   )r   lr   r   r   r     r   z/Bundle.create_row_processor.<locals>.<listcomp>r  Row[Any]r   r   c                   s    fddD S )Nc                   s   g | ]}| qS r   r   )r   procr  r   r   r     r   z=Bundle.create_row_processor.<locals>.proc.<locals>.<listcomp>r   rR  keyed_tuplerJ  rR  r   rQ    s   z)Bundle.create_row_processor.<locals>.procN)r  rP  r   r   r:   )r   rH  rJ  rL  rQ  r   rS  r   create_row_processor  s   &zBundle.create_row_processorN)r   r}   r'  r(  r  r   )ri   ri   r8  r9  r   r:  )r   r=  )r   r  )r   rA  )rH  rI  rJ  rK  rL  rM  r   rN  )r   r   r   r   r4  is_clause_element	is_mapperr5  	is_bundler9   immutabledictr&  r   	EMPTY_SET	proxy_setr3  r;  r  r  r9  r  rC  r  rG  r   rU  r   r   r   r   r%    s:   
 

"
r%  z
Bundle[_T]r  rc   excludec                 C  s   t | 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  r\  r   r   r   _orm_annotate     r^  c                 C  s   t j| d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  )r   r   _deep_deannotater  r   r   r   _orm_deannotate  s   	rc  c                 C  s
   t | S r   r`  rb  r   r   r   _orm_full_deannotate  ry  rd  c                   @  s^   e Zd ZdZejjZdZ						ddddZdd Z				ddddZ
		d d!ddZdS )"_ORMJoinz/Extend Join to support ORM constructs as input.TNFr   leftr`   rightr  Optional[_OnClauseArgument]isouterr   full
_left_memor  _right_memo_extra_criteriaTuple[ColumnElement[bool], ...]c	                 C  s&  t dt|}	t dt|}
|
j}|| _|| _t|tjr8t	r*t|j
tjs*J |j
 }|j}||j7 }nt|trD|}|jj}nd }d }|	j}|rt||rV|}n	t|ts]J |}|j||d|
d|d\}}}}}}|d ur|rt|||}|}nt||||}|}n|}|| _t|	r|jdd }nt|	st|	r|	}nd }|d ur| jd|i| _t|o| }t j!"| ||||| | j#d usJ |r|  j#tj$| M  _#|st%|
dd r|
j&j'rt d|
}
|
j&j(}|d urt|
r|
j)*|}| j#|@ | _#d S d S d S d S d S )Nz+Union[FromClause, _InternalEntityType[Any]]T)source_selectabledest_selectablesource_polymorphicof_type_entityalias_secondaryextra_criteriar  r  r:  )+r   r7   rT  r0  rk  rl  r   r   QueryableAttributer   
comparatorrZ   
Comparator_source_selectabler  rm  r0   parentr   clause_is_presentrH   _create_joinsr8   r   _target_adapterrA   r?  r@  r   r   r  r   r=   Joinr3  r  and_rk  r  single_single_table_criterionr  r  )r   rf  rg  r  ri  rj  rk  rl  rm  	left_info
right_infoadapt_toon_selectablepropleft_selectable
adapt_frompjsjsourcedest	secondarytarget_adapterr  augment_onclausesingle_critr   r   r   r3    s   


	





z_ORMJoin.__init__c                 C  sl   |}t |tjr|j}t |tjs| j|u sJ t| j|j| j| j| j|jj	d}t||j|j|j|j
dS )zlSplice a join into the center.

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

        )ri  rk  rl  )ri  rl  )r   r8   r}  rf  rg  re  r  ri  rk  r  rl  )r   r  leftmostrf  r   r   r   _splice_into_centerq  s(   	z_ORMJoin._splice_into_centerr   c                 C  s   t | ||||dS )N)rj  ri  re  )r   rg  r  ri  rj  r   r   r   r     r_  z_ORMJoin.joinc                 C  s   t | ||d|dS )NT)ri  rj  r  )r   rg  r  rj  r   r   r   	outerjoin  s   z_ORMJoin.outerjoin)NFFNNr   )rf  r`   rg  r`   r  rh  ri  r   rj  r   rk  r  rl  r  rm  rn  )NFF)
rg  r`   r  rh  ri  r   rj  r   r   re  r   )rg  r`   r  rh  rj  r   r   re  )r   r   r   r   r=   r}  __visit_name__inherit_cacher3  r  r   r  r   r   r   r   re    s&    y re  r  r  "attributes.QueryableAttribute[Any]from_entityOptional[_EntityType[Any]]r	  c                 C  sj   t |tr
tdt |tjr,|jr|j}|j}|du s!t|s)td| |}n|}|j	| |d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:
      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.Query` itself.

      .. versionadded:: 1.2

    z@with_parent() accepts class-bound mapped attributes, not stringsNz6Expected relationship property for with_parent(), got )r  )
r   r}   r   r   r   ru  _of_typer  r   _with_parent)r  r  r  mapper_propertyprop_tr   r   r   with_parent  s&   
6
r  object_r   c                 C     t | }|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r  r   r   r   r   r    s   
r  c                 C  r  )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  r   r   r   r    s   
r  givenr:  r9  c                 C  s^   t |rt | r| |  u rdS dS t | r$| jr || jv S || u S t| 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|  rI  r   common_parentr  r9  r   r   r   _entity_corresponds_to  s   

r  c                 C  sN   t | rt |o|j o| |u p|| jv S t |s| |jS |jo&| |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  rI  r  r   r   r   $_entity_corresponds_to_use_path_impl$  s   r  r  Mapper[Any]c                 C  s@   | j r|| jv p| j|S | jr|| jv p| |S | |S )zedetermine if 'given' "is a" mapper, in terms of the given
    would load rows of type 'mapper'.

    )r5  rI  r  rA  )r  r  r   r   r   _entity_isaH  s   
r  iterable_query
Query[Any]itemr   c                 C  s   dd }t |trPt|\}}}t |tr#t |tr#|| dkr#g S t |tr,|dk s5t |tr8|dk r8|  | ||}|durLt|dd|j S t|S |dkrY|  dS t| ||d  d S )zdcalculate __getitem__ in terms of an iterable query object
    that also has a slice() method.

    c                   S  s   t d)Nz@negative indexes are not accepted by SQL index / slice operators)
IndexErrorr   r   r   r   _no_negative_indexes]  s   z&_getitem.<locals>._no_negative_indexesr   Nr   )r   slicer9   decode_sliceintr  step)r  r  r  startstopr  resr   r   r   _getitemW  s*   

r  raw_annotationrj   ry   rz   originating_clsc                 C  s2   z	t || |j}W n
 ty   Y dS w t|tS r   )rJ   r   	NameErrorrN   r   )r  ry   r  	annotatedr   r   r   _is_mapped_annotation~  s   
	r  c                   @  s   e Zd ZdS )_CleanupErrorN)r   r   r   r   r   r   r   r    s    r  r{   r}   r|   c           	   
     s^  t d| }|s
| S z
t|d|}W n ty/ } ztd|  d|d d|d }~ww |tju r8d}nzt|t	rB|j
}n| W S W n tyQ   |  Y S w g }|}	 |||u r_|n|d |d}t d|}|d u rz|| nqWt d	|d
 st d|d
 sd d fdd|d
 dD |d
< d|dt|d   } | S )Nz^([^ \|]+?)\[(.+)\]$r   zFor annotation "z%", could not resolve container type "z[".  Please ensure this type is imported at the module level outside of TYPE_CHECKING blocksClassVarTr5   z^["'].*["']$r  z[\[\]]z"' r   c                 3  s"    | ]}d |   d V  qdS )"N)strip)r   rB  
stripcharsr   r   r    s    
z1_cleanup_mapped_str_annotation.<locals>.<genexpr>r   [])r   matchrK   rE  r  r  typingr  
issubclassr   r   	TypeErrorr   searchr   r   len)	r{   r|   mmr   nereal_symbolr   innerg2r   r  r   _cleanup_mapped_str_annotation  sZ   





r  Optional[_AnnotationScanType]r   r   attr_clsrequiredis_dataclass_fieldexpect_mappedr  @Optional[Tuple[Union[_AnnotationScanType, str], Optional[type]]]c	              
   C  sj  | du r|rt d|j d| d|j ddS z
t|| |td}	W n9 ty9 }
 z
t d|  d|
d}
~
w ty\ } z|rPd	| v rPt d|  d|| }	W Y d}~nd}~ww |rc|	dfS t|	d
rmt|	t	s|r|ssdS t
|	d
d}|tju rdS t|trt|trdS t jd|j d| ddd|	dfS t|	jdkrt dt|	jd |	jfS )zgiven an annotation, figure out if it's ``Mapped[something]`` and if
    so, return the ``something`` part.

    Includes error raise scenarios and other options.

    Nz4Python typing annotation is required for attribute ".z " when primary argument(s) for "z#" construct are None or not present)rw   zCould not interpret annotation zt.  Check that it uses names that are correctly imported at the module level. See chained stack trace for more hints.zMapped[
__origin__zType annotation for "a  " can't be correctly interpreted for Annotated Declarative Table form.  ORM annotations should normally make use of the ``Mapped[]`` generic type, or other ORM-compatible generic type, as a container for the actual type, which indicates the intent that the attribute is mapped. Class variables that are not intended to be mapped by the ORM should use ClassVar[].  To allow Annotated Declarative to disregard legacy annotations which don't use Mapped[] to pass, set "__allow_unmapped__ = True" on the class or a superclass this class.zlpr)coder   z)Expected sub-type for Mapped[] annotationr   )r   r   r   rJ   r  r  r  rl  rN   r   rk  r  r  r   r   r  r*   r  __args__rL   r  )r  ry   r|   r   r  r  r  r  r  r  cer  r#  r   r   r   _extract_mapped_subtype  s~   




r  c                 C  s$   t | dr
|  }nd }t| |S )N_mapper_property_name)rl  r  r9   clsname_as_plain_name)r  r   r   r   r   _mapper_property_as_plain_name]	  s   

r  )r   T)NN)r
  r  r  r  r  r  r  r  r	  r  r   r  )r
  r  r   r  r   )r  rc   r\  r  r   rc   )r  rc   r   rc   )r  r  r  r  r  r  r   r	  )r  r  r   r   )r  r:  r9  r:  r   r   )r  r:  r  r  r   r   )r  r  r  r   r   r   )r  rj   ry   rz   r  rz   r   r   )r{   r}   r|   r}   r   r}   )TT)r  r  ry   r   r|   r}   r   r}   r  rz   r  r   r  r   r  r   r  r   r   r  )r  rz   r   r}   )
__future__r   r  	functoolsr   r   r  r   r   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   rs  r   r   r   _typingr   r   r   r   r  r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   
interfacesr/   r0   r1   r2   r3   path_registryr4   r6   r   r7   r8   r9   engine.resultr;   r<   r=   r>   r?   r   r@   sql._typingrA   sql.annotationrB   sql.baserC   sql.cache_keyrD   rE   sql.elementsrF   rG   sql.selectablerH   util.langhelpersrI   util.typingrJ   _de_stringify_annotationrK   _eval_name_onlyrL   rM   rN   rO   rP   rQ   rR   rS   rT   contextrU   rV   r  rW   rX   rH  rY   relationshipsrZ   enginer[   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   rf   rg   rh   sql.visitorsri   rj   rk   	frozensetr   partialrY  _de_stringify_partialrv   r   r}   r   r   r  r  Enumr  ColumnAdapterr'  r4  InspectablerC  _self_inspectsrX  r  r  	_inspectsr   r"  GenericAliasr$  r%  r^  rc  rd  r}  re  r  r  r  r  r  r  r  r  	Exceptionr  r  r  r  r   r   r   r   <module>   s  IC
SX<
5 K
   O 4
 ]


 3
L



$

'
bl