
    ,h&                      % S r SSKJr  SSKrSSKJr  SSKrSSKrSSKrSSKJ	r	  SSKJ
r
  SSKJr  SSKJr  SS	KJr  SS
KJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKrSSKJr  SSKJr  SSKJr  SSKJ r   SSKJ!r!  SSKJ"r"  SSKJ#r#  SSKJ$r$  SS KJ%r&  SS!K'J(r(  SS"K'J)r)  SS#K'J*r*  SS$K'J+r+  SS%K'J,r,  SS&K-J.r.  SS'K-J/r/  SS(K-J0r0  SS)K-J1r1  SS*K-J2r2  SS+K-J3r3  SS,K-J4r4  SS-K-J5r5  SS.K-J6r6  SS/KJ7r7  SS0KJ8r8  SS1K"J9r9  SS2K$J:r:  SS3K%J;r;  SS4K<J=r=  SS5K<J>r>  SS6K<J?r?  SS7K@JArA  S8S9KJBrB  S8SKJ!rC  S8S:KJDrD  S8S;KJErE  S8S<KBJFrF  S8S=KBJGrG  S8S>KHJIrI  S8S?KJJKrK  S8S@KJJLrL  S8SAKMJNrN  S8SBKMJOrO  S8SCKDJPrP  S8SDKDJQrQ  S8SEKDJRrR  S8SFKDJSrS  S8SGKDJTrT  S8SHKDJUrU  S8SIKVJWrW  S8SJKVJXrX  S8SKKYJZrZ  S8SLK[J\r\  S8SMK[J]r]  S8SNKEJ^r^  S8SOK_J`r`  S8SPK_Jara  \R0                  (       a  SSQK'Jbrb  SSRK'Jcrc  SSSK'Jdrd  SSTK'Jere  SSUKfJgrg  SSVKfJhrh  SSWKiJjrj  SSXKkJlrl  SSYK$Jmrm  S8SZKBJnrn  S8S[KBJoro  S8S\KBJprp  S8S]KBJqrq  S8S^KrJsrs  S8S_KrJtrt  S8S`KuJvrv  S8SaKuJwrw  S8SbKuJxrx  S8ScKuJyry  S8SdKzJ{r{  S8SeKJJ|r|  S8SfK}J~r~  S8SgK}Jr  S8ShK}Jr  S8SiK}Jr  S8SjK}Jr  S8SkK}Jr  S8SlK}Jr  S8SmK}Jr  S8SnK}Jr  S8SoK}Jr  S8SpK}Jr  S8SqKVJr  S8SrKVJr  S8SsKJr  S8StKJr  S8SuKJr  S8SvK[Jr  S8SwK[Jr  \" Sx\	Sy9r/ SzQr\GR,                  " 5       rS{\S|'    \\&l        \\	\\	S}4   4   r\\\	4   r\\\(   S~4   r\\\	   SS\4   r\S   r\`S   r " S S\a5      rSS jr " S S5      r " S S\>5      r\" \5      u  rrrrrr " S S\EGRV                  5      r " S S\5      r " S S\=\I5      r " S S\5      r " S S\\L5      r\" SSSy9r " S S\\\   5      rSS jrSS jrSS jrSS jr\EGRn                  " 5       rg)z1Provides the Session class and related utilities.    )annotationsN)Enum)Any)Callable)cast)Dict)Generic)Iterable)Iterator)List)NoReturn)Optional)overload)Sequence)Set)Tuple)Type)TYPE_CHECKING)TypeVar)Union   )
attributes)bulk_persistence)context)descriptor_props)exc)identity)loading)querystate)_O)insp_is_mapper)is_composite_class)is_orm_option)is_user_defined_option)_class_to_mapper)	_none_set)_state_mapper)instance_str)LoaderCallableStatus)object_mapper)object_state)PassiveFlag)	state_str)FromStatement)ORMCompileState)IdentityMap)Query)InstanceState)_StateChange)_StateChangeState)_StateChangeStates)UOWTransaction   )engine)sql)util)
Connection)Engine)TransactionalContext)
dispatcher)EventTarget)inspect)Inspectable)	coercions)dml)roles)Select)TableClause)visitors)_NoArg)CompileState)Table)ForUpdateArg)LABEL_STYLE_TABLENAME_PLUS_COL)IdentitySet)Literal)Protocol)_EntityType)_IdentityKeyType)_InstanceDict)OrmExecuteOptionsParameter)	ORMOption)UserDefinedOption)Mapper)PathRegistry)RowReturningQuery)CursorResult)Result)Row)
RowMapping)Transaction)TwoPhaseTransaction)_CoreAnyExecuteParams)_CoreSingleExecuteParams)_ExecuteOptions)CoreExecuteOptionsParameter)ScalarResult)_InstanceLevelDispatch)_ColumnsClauseArgument)	_InfoType)_T0)_T1)_T2)_T3)_T4)_T5)_T6)_T7)_TypedColumnClauseArgument)
Executable)ExecutableOption)
UpdateBase)ClauseElement)TypedColumnsClauseRole)ForUpdateParameter)TypedReturnsRows_T)bound)SessionSessionTransactionsessionmakerORMExecuteStateclose_all_sessionsmake_transientmake_transient_to_detachedobject_sessionz)weakref.WeakValueDictionary[int, Session]	_sessions.
Mapper[_O]Mapper[Any]rH   )r>   r=   )conditional_savepointrollback_onlycontrol_fullycreate_savepointc                  8    \ rS rSrSr  S       SS jjrSrg)_ConnectionCallableProto   a  a callable that returns a :class:`.Connection` given an instance.

This callable, when present on a :class:`.Session`, is called only from the
ORM's persistence mechanism (i.e. the unit of work flush process) to allow
for connection-per-instance schemes (i.e. horizontal sharding) to be used
as persistence time.

This callable is not present on a plain :class:`.Session`, however
is established when using the horizontal sharding extension.

Nc                    g N )selfmapperinstancekws       N/var/www/auris/envauris/lib/python3.13/site-packages/sqlalchemy/orm/session.py__call__!_ConnectionCallableProto.__call__   s    
     r   NN)r   Optional[Mapper[Any]]r   zOptional[object]r   r   returnr=   )__name__
__module____qualname____firstlineno____doc__r   __static_attributes__r   r   r   r   r      s?    
 )-%)% # 	
 
 r   r   c                    U R                   $ )zSGiven an :class:`.InstanceState`, return the :class:`.Session`
associated, if any.
sessionr    s    r   _state_sessionr      s     ==r   c                      \ rS rSrSr\\R                  " SS5      SS j5       5       r\\R                  " S5        SSSSS.           SS	 jjj5       5       r
\SS
 j5       rSrg)_SessionClassMethods   zBClass-level methods for :class:`.Session`, :class:`.sessionmaker`.z1.3zThe :meth:`.Session.close_all` method is deprecated and will be removed in a future release.  Please refer to :func:`.session.close_all_sessions`.c                    [        5         g)zClose *all* sessions in memory.N)r   )clss    r   	close_all_SessionClassMethods.close_all   s
     	r   zsqlalchemy.orm.utilNr   rowidentity_tokenc               X    [         R                  R                  R                  UUUUUS9$ )zJReturn an identity key.

This is an alias of :func:`.util.identity_key`.

r   )r<   	preloadedorm_utilidentity_key)r   class_identr   r   r   s         r   r   !_SessionClassMethods.identity_key   s5      ~~&&33) 4 
 	
r   c                    [        U5      $ )zhReturn the :class:`.Session` to which an object belongs.

This is an alias of :func:`.object_session`.

)r   )r   r   s     r   r   #_SessionClassMethods.object_session   s     h''r   r   r   Noner   )r   zOptional[Type[Any]]r   Union[Any, Tuple[Any, ...]]r   Optional[Any]r   z%Optional[Union[Row[Any], RowMapping]]r   r   r   z_IdentityKeyType[Any]r   objectr   Optional[Session])r   r   r   r   r   classmethodr<   
deprecatedr   preload_moduler   r   r   r   r   r   r   r      s    L	__	/ 
 	./ '+-1

 #'59(,
#
 +

  
 3
 &
 

 0 
, ( (r   r   c                  ,    \ rS rSrSrSrSrSrSrSr	Sr
g	)
SessionTransactionState   r   r9               r   N)r   r   r   r   ACTIVEPREPARED	COMMITTEDDEACTIVECLOSEDPROVISIONING_CONNECTIONr   r   r   r   r   r      s!    FHIHFr   r   c                  n   \ rS rSr% SrSrS\S'    S\S'    S\S	'    S
\S'    S
\S'    S\S'    S\S'   S\S'   S\S'   S\S'                 S0S jrS1S jr    S2         S3S jjr	\
S4S j5       r\
S5S j5       r\
S6S j5       r\
S6S j5       r\
S6S j5       r\
S6S  j5       r\
S6S! j5       r\
S6S" j5       r\
S6S# j5       r\
S6S$ j5       rS7S% jr  S8S& jr\
S9S' j5       r\
S:S( j5       r\
S6S) j5       r\
S6S* j5       r\
  S;S+ j5       r\
  S<S, j5       r\
S=S- j5       r\
S>S. j5       rS/rg)?r~   i
  a   Represents a call to the :meth:`_orm.Session.execute` method, as passed
to the :meth:`.SessionEvents.do_orm_execute` event hook.

.. versionadded:: 1.4

.. seealso::

    :ref:`session_execute_events` - top level documentation on how
    to use :meth:`_orm.SessionEvents.do_orm_execute`

)r   	statement
parametersexecution_optionslocal_execution_optionsbind_argumentsr   _compile_state_cls_starting_event_idx_events_todo_update_execution_optionsr{   r   rr   r   Optional[_CoreAnyExecuteParams]r   rc   r   r   _BindArgumentsr   Optional[Type[ORMCompileState]]r   intr   z	List[Any]r   Optional[_ExecuteOptions]r   c                    Xl         X l        X0l        X@l        UR                  R                  U5      U l        XPl        X`l        [        U5      U l
        g)zXConstruct a new :class:`_orm.ORMExecuteState`.

this object is constructed internally.

N)r   r   r   r   _execution_optionsunionr   r   r   listr   )r   r   r   r   r   r   compile_state_clsevents_todos           r   __init__ORMExecuteState.__init__`  sP     "$'8$!*!=!=!C!C"
 -"3 -r   c                :    U R                   U R                  S-   S  $ )Nr   )r   r   r   s    r   _remaining_events!ORMExecuteState._remaining_eventsz  s!      !9!9A!=!?@@r   Nc           	        Uc  U R                   n[        U R                  5      nU(       a  UR                  U5        SUS'   U(       a  U R                  (       a  / n[        SU R                  5      n[        R                  " U[        SU5      5       Hg  u  pUb  U	c/  [        R                  " S[        U5       S[        U5       S35      e[        U5      nUR                  U	5        UR                  U5        Mi     OG[        [        SU R                  5      5      nUR                  [        SU5      5        OU R                  nU R                  n
U(       a  U
R                  U5      n
U R                  R!                  UUU
UU S9$ )	a  Execute the statement represented by this
:class:`.ORMExecuteState`, without re-invoking events that have
already proceeded.

This method essentially performs a re-entrant execution of the current
statement for which the :meth:`.SessionEvents.do_orm_execute` event is
being currently invoked.    The use case for this is for event handlers
that want to override how the ultimate
:class:`_engine.Result` object is returned, such as for schemes that
retrieve results from an offline cache or which concatenate results
from multiple executions.

When the :class:`_engine.Result` object is returned by the actual
handler function within :meth:`_orm.SessionEvents.do_orm_execute` and
is propagated to the calling
:meth:`_orm.Session.execute` method, the remainder of the
:meth:`_orm.Session.execute` method is preempted and the
:class:`_engine.Result` object is returned to the caller of
:meth:`_orm.Session.execute` immediately.

:param statement: optional statement to be invoked, in place of the
 statement currently represented by :attr:`.ORMExecuteState.statement`.

:param params: optional dictionary of parameters or list of parameters
 which will be merged into the existing
 :attr:`.ORMExecuteState.parameters` of this :class:`.ORMExecuteState`.

 .. versionchanged:: 2.0 a list of parameter dictionaries is accepted
    for executemany executions.

:param execution_options: optional dictionary of execution options
 will be merged into the existing
 :attr:`.ORMExecuteState.execution_options` of this
 :class:`.ORMExecuteState`.

:param bind_arguments: optional dictionary of bind_arguments
 which will be merged amongst the current
 :attr:`.ORMExecuteState.bind_arguments`
 of this :class:`.ORMExecuteState`.

:return: a :class:`_engine.Result` object with ORM-level results.

.. seealso::

    :ref:`do_orm_execute_re_executing` - background and examples on the
    appropriate usage of :meth:`_orm.ORMExecuteState.invoke_statement`.


T_sa_skip_eventszList[Dict[str, Any]]zgCan't apply executemany parameters to statement; number of parameter sets passed to Session.execute() (zW) does not match number of parameter sets given to ORMExecuteState.invoke_statement() ()zDict[str, Any])r   r   _parent_execute_state)r   dictr   updateis_executemanyr   r   	itertoolszip_longestsa_excInvalidRequestErrorlenappendr   r   r   _execute_internal)r   r   paramsr   r   _bind_arguments_paramsexec_many_parameters_existing_params_new_paramsr   s              r   invoke_statement ORMExecuteState.invoke_statement}  s   r It223"">2-1)* ""'+*DOO($ 6?5J5J(/861$ (/;3F$882256J2K1L M  !$F}A/  (,,<'=$$++K8NN#346" t$4dooFGt$4f=>ooG!99!3!9!9:K!L||--0*"& . 
 	
r   c                >    U R                   R                  SS5      nU$ )aS  Return the :class:`_orm.Mapper` that is the primary "bind" mapper.

For an :class:`_orm.ORMExecuteState` object invoking an ORM
statement, that is, the :attr:`_orm.ORMExecuteState.is_orm_statement`
attribute is ``True``, this attribute will return the
:class:`_orm.Mapper` that is considered to be the "primary" mapper
of the statement.   The term "bind mapper" refers to the fact that
a :class:`_orm.Session` object may be "bound" to multiple
:class:`_engine.Engine` objects keyed to mapped classes, and the
"bind mapper" determines which of those :class:`_engine.Engine` objects
would be selected.

For a statement that is invoked against a single mapped class,
:attr:`_orm.ORMExecuteState.bind_mapper` is intended to be a reliable
way of getting this mapper.

.. versionadded:: 1.4.0b2

.. seealso::

    :attr:`_orm.ORMExecuteState.all_mappers`


r   N)r   get)r   mps     r   bind_mapperORMExecuteState.bind_mapper  s!    4 %)$7$7$;$;Hd$K	r   c                6   U R                   (       d  / $ [        U R                  [        [        45      (       a  / n[        5       nU R                  R                   H  nUS   nU(       d  M  [        USS9nU(       d  M$  UR                  (       d  M7  UR                  U;  d  MI  UR                  UR                  5        UR                  UR                  5        M     U$ U R                  R                  (       a  U R                  (       a  U R                  /$ / $ )a  Return a sequence of all :class:`_orm.Mapper` objects that are
involved at the top level of this statement.

By "top level" we mean those :class:`_orm.Mapper` objects that would
be represented in the result set rows for a :func:`_sql.select`
query, or for a :func:`_dml.update` or :func:`_dml.delete` query,
the mapper that is the main subject of the UPDATE or DELETE.

.. versionadded:: 1.4.0b2

.. seealso::

    :attr:`_orm.ORMExecuteState.bind_mapper`



entityF)raiseerr)is_orm_statement
isinstancer   rG   r0   setcolumn_descriptionsrB   r   addr   is_dmlr  )r   resultseendentinsps         r   all_mappersORMExecuteState.all_mappers  s    & $$I(?@@F5D^^77k3"37Dt40G-dkk2 8 M^^""t'7'7$$%%Ir   c                    U R                   SL$ )a]  return True if the operation is an ORM statement.

This indicates that the select(), insert(), update(), or delete()
being invoked contains ORM entities as subjects.   For a statement
that does not have ORM entities and instead refers only to
:class:`.Table` metadata, it is invoked as a Core SQL statement
and no ORM-level automation takes place.

N)r   r   s    r   r   ORMExecuteState.is_orm_statement)  s     &&d22r   c                6    [        U R                  [        5      $ )z~return True if the parameters are a multi-element list of
dictionaries with more than one dictionary.

.. versionadded:: 2.0

)r	  r   r   r   s    r   r   ORMExecuteState.is_executemany6  s     $//400r   c                .    U R                   R                  $ )a  return True if this is a SELECT operation.

.. versionchanged:: 2.0.30 - the attribute is also True for a
   :meth:`_sql.Select.from_statement` construct that is itself against
   a :class:`_sql.Select` construct, such as
   ``select(Entity).from_statement(select(..))``

)r   	is_selectr   s    r   r  ORMExecuteState.is_select@  s     ~~'''r   c                .    U R                   R                  $ )a  return True if this operation is a
:meth:`_sql.Select.from_statement` operation.

This is independent from :attr:`_orm.ORMExecuteState.is_select`, as a
``select().from_statement()`` construct can be used with
INSERT/UPDATE/DELETE RETURNING types of statements as well.
:attr:`_orm.ORMExecuteState.is_select` will only be set if the
:meth:`_sql.Select.from_statement` is itself against a
:class:`_sql.Select` construct.

.. versionadded:: 2.0.30

)r   is_from_statementr   s    r   r  !ORMExecuteState.is_from_statementL  s     ~~///r   c                h    U R                   R                  =(       a    U R                   R                  $ )a  return True if this is an INSERT operation.

.. versionchanged:: 2.0.30 - the attribute is also True for a
   :meth:`_sql.Select.from_statement` construct that is itself against
   a :class:`_sql.Insert` construct, such as
   ``select(Entity).from_statement(insert(..))``

)r   r  	is_insertr   s    r   r   ORMExecuteState.is_insert]  #     ~~$$A)A)AAr   c                h    U R                   R                  =(       a    U R                   R                  $ )a  return True if this is an UPDATE operation.

.. versionchanged:: 2.0.30 - the attribute is also True for a
   :meth:`_sql.Select.from_statement` construct that is itself against
   a :class:`_sql.Update` construct, such as
   ``select(Entity).from_statement(update(..))``

)r   r  	is_updater   s    r   r$  ORMExecuteState.is_updatei  r"  r   c                h    U R                   R                  =(       a    U R                   R                  $ )a  return True if this is a DELETE operation.

.. versionchanged:: 2.0.30 - the attribute is also True for a
   :meth:`_sql.Select.from_statement` construct that is itself against
   a :class:`_sql.Delete` construct, such as
   ``select(Entity).from_statement(delete(..))``

)r   r  	is_deleter   s    r   r'  ORMExecuteState.is_deleteu  r"  r   c                j    [        U R                  [        R                  [        R                  45      $ r   )r	  r   rE   UpdateDeleter   s    r   _is_crudORMExecuteState._is_crud  s     $..3::szz*BCCr   c                D    U R                   R                  U5      U l         g)z3Update the local execution options with new values.N)r   r   r   optss     r   update_execution_options(ORMExecuteState.update_execution_options  s    '+'C'C'I'I$'O$r   c                    U R                   (       d  g  U R                  R                  nUb0  UR	                  [
        R                  R                  5      (       a  U$ g ! [         a     g f = fr   )r  r   _compile_optionsAttributeErrorr	  r   r1   default_compile_optionsr/  s     r   _orm_compile_options$ORMExecuteState._orm_compile_options  sg     ~~	>>22D ##;;!
 !
 K  		s   A 
A+*A+c                .    U R                   R                  $ )a  An :class:`.InstanceState` that is using this statement execution
for a lazy load operation.

The primary rationale for this attribute is to support the horizontal
sharding extension, where it is available within specific query
execution time hooks created by this extension.   To that end, the
attribute is only intended to be meaningful at **query execution
time**, and importantly not any time prior to that, including query
compilation time.

)load_options_lazy_loaded_fromr   s    r   lazy_loaded_from ORMExecuteState.lazy_loaded_from  s       222r   c                B    U R                  5       nUb  UR                  $ g)zReturn the :class:`.PathRegistry` for the current load path.

This object represents the "path" in a query along relationships
when a particular object or collection is being loaded.

N)r7  _current_pathr/  s     r   loader_strategy_path$ORMExecuteState.loader_strategy_path  s'     ((*%%%r   c                P    U R                  5       nUSL=(       a    UR                  $ )a  Return True if the operation is refreshing column-oriented
attributes on an existing ORM object.

This occurs during operations such as :meth:`_orm.Session.refresh`,
as well as when an attribute deferred by :func:`_orm.defer` is
being loaded, or an attribute that was expired either directly
by :meth:`_orm.Session.expire` or via a commit operation is being
loaded.

Handlers will very likely not want to add any options to queries
when such an operation is occurring as the query should be a straight
primary key fetch which should not have any additional WHERE criteria,
and loader options travelling with the instance
will have already been added to the query.

.. versionadded:: 1.4.0b2

.. seealso::

    :attr:`_orm.ORMExecuteState.is_relationship_load`

N)r7  _for_refresh_stater/  s     r   is_column_loadORMExecuteState.is_column_load  s(    0 ((*4;D$;$;;r   c                z    U R                  5       nUc  gU R                  nUSL=(       a    UR                  (       + $ )a  Return True if this load is loading objects on behalf of a
relationship.

This means, the loader in effect is either a LazyLoader,
SelectInLoader, SubqueryLoader, or similar, and the entire
SELECT statement being emitted is on behalf of a relationship
load.

Handlers will very likely not want to add any options to queries
when such an operation is occurring, as loader options are already
capable of being propagated to relationship loaders and should
be already present.

.. seealso::

    :attr:`_orm.ORMExecuteState.is_column_load`

NF)r7  r@  is_root)r   r0  paths      r   is_relationship_load$ORMExecuteState.is_relationship_load  s<    ( ((*<((44$44r   c                    U R                   (       d  [        R                  " S5      eU R                  R	                  S[
        R                  R                  5      nU$ )z=Return the load_options that will be used for this execution.zRThis ORM execution is not against a SELECT statement so there are no load options._sa_orm_load_options)r  r   r   r   r  r   QueryContextdefault_load_options)r   los     r   r:  ORMExecuteState.load_options  sV     ~~,,0  ""&&"G$8$8$M$M
 	 	r   c                    U R                   (       d  [        R                  " S5      eU R                  R	                  S[
        R                  R                  5      nU$ )zFReturn the update_delete_options that will be used for this
execution.z_This ORM execution is not against an UPDATE or DELETE statement so there are no update options._sa_orm_update_options)r,  r   r   r   r  r   BulkUDCompileStatedefault_update_options)r   uos     r   update_delete_options%ORMExecuteState.update_delete_options  sW     }},,<  ""&&$//FF
 	 	r   c                    U R                   R                   Vs/ s H*  n[        U5      (       d  M  UR                  (       a  M(  UPM,     sn$ s  snf r   )r   _with_optionsr%   _is_compile_stater   opts     r   _non_compile_orm_options(ORMExecuteState._non_compile_orm_options   sI     ~~33
3S! *-*?*? 3
 	
 
s   AAAc                ~    U R                   R                   Vs/ s H  n[        U5      (       d  M  UPM     sn$ s  snf )zjThe sequence of :class:`.UserDefinedOptions` that have been
associated with the statement being invoked.

)r   rY  r&   r[  s     r   user_defined_options$ORMExecuteState.user_defined_options(  s;     ~~33
3%c* 3
 	
 
s   ::)r   r   r   r   r   r   r   r   )r   r{   r   rr   r   r   r   rc   r   r   r   r   r   %List[_InstanceLevelDispatch[Session]])r   rb  )NNNN)
r   zOptional[Executable]r   r   r   z$Optional[OrmExecuteOptionsParameter]r   Optional[_BindArguments]r   Result[Any])r   r   )r   zSequence[Mapper[Any]]r   bool)r0  r   r   r   )r   zwOptional[Union[context.ORMCompileState.default_compile_options, Type[context.ORMCompileState.default_compile_options]]])r   Optional[InstanceState[Any]])r   zOptional[PathRegistry])r   zaUnion[context.QueryContext.default_load_options, Type[context.QueryContext.default_load_options]])r   zUnion[bulk_persistence.BulkUDCompileState.default_update_options, Type[bulk_persistence.BulkUDCompileState.default_update_options]])r   zSequence[ORMOption])r   zSequence[UserDefinedOption]) r   r   r   r   r   	__slots____annotations__r   r   r   propertyr  r  r  r   r  r  r   r$  r'  r,  r1  r7  r<  r@  rD  rI  r:  rV  r]  r`  r   r   r   r   r~   r~   
  s   
I + 0/% '& -,
 #" 8788.. . 4	.
 +. '. ;. ;.4A
 +/26BF37h
'h
 0h
 @	h

 1h
 
h
T  8 " "H 
3 
3 1 1 	( 	( 0 0  	B 	B 	B 	B 	B 	B D DP
, 3 3   < <4 5 52 
 , 
 . 
 
 	
 	
r   r~   c                  .    \ rS rSrSrSr Sr Sr SrSr	g)	SessionTransactionOrigini5  zindicates the origin of a :class:`.SessionTransaction`.

This enumeration is present on the
:attr:`.SessionTransaction.origin` attribute of any
:class:`.SessionTransaction` object.

.. versionadded:: 2.0

r   r   r9   r   r   N)
r   r   r   r   r   	AUTOBEGINBEGINBEGIN_NESTEDSUBTRANSACTIONr   r   r   r   rl  rl  5  s)     I/EHLFN6r   rl  c                     \ rS rSr% SrSrS\S'   S\S'   S\S	'   S
\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'    SrS\S'     S/     S0S jjr      S1S jr	\
S2S j5       r\
S3S j5       r\
S3S j5       r\R                  " \R"                  4\R&                  5       S/       S4S jj5       r\R                  " \R"                  4\R&                  5      S5S6S jj5       r S/   S7S  jjrS8S! jrS5S9S" jjrS8S# jr\R                  " \R"                  4\R&                  5            S:S$ j5       rS8S% jr\R                  " \R"                  4\R8                  5      S8S& j5       r\R                  " \R"                  \R8                  4\R<                  5      S5S;S' jj5       r\R                  " \R"                  \R@                  \R8                  4\R<                  5       S<     S=S( jj5       r!\R                  " \RD                  \R<                  5      S5S>S) jj5       r#S?S* jr$S3S+ jr%S3S, jr&S3S- jr'S.r(g)@r|   iM  a\  A :class:`.Session`-level transaction.

:class:`.SessionTransaction` is produced from the
:meth:`_orm.Session.begin`
and :meth:`_orm.Session.begin_nested` methods.   It's largely an internal
object that in modern use provides a context manager for session
transactions.

Documentation on interacting with :class:`_orm.SessionTransaction` is
at: :ref:`unitofwork_transaction`.


.. versionchanged:: 1.4  The scoping and API methods to work with the
   :class:`_orm.SessionTransaction` object directly have been simplified.

.. seealso::

    :ref:`unitofwork_transaction`

    :meth:`.Session.begin`

    :meth:`.Session.begin_nested`

    :meth:`.Session.rollback`

    :meth:`.Session.commit`

    :meth:`.Session.in_transaction`

    :meth:`.Session.in_nested_transaction`

    :meth:`.Session.get_transaction`

    :meth:`.Session.get_nested_transaction`


NzOptional[BaseException]_rollback_exceptionzKDict[Union[Engine, Connection], Tuple[Connection, Transaction, bool, bool]]_connectionsr{   r   Optional[SessionTransaction]_parentr   _statez5weakref.WeakKeyDictionary[InstanceState[Any], object]_new_deleted_dirtyz>weakref.WeakKeyDictionary[InstanceState[Any], Tuple[Any, Any]]_key_switchesrl  originFrf  nestedc                l   [         R                  " U5        Xl        0 U l        X0l        U[
        R                  L =U l        nX l        UR                  [        R                  L a  [        R                  " S5      eU(       a/  U(       d  [        R                  " S5      eUR                  U l        OU[
        R                   L a  Uc   eOUb   e["        R$                  U l        U R)                  5         X R                  l        U R                  R,                  R/                  U R                  U 5        g )Nz_This Session has been permanently closed and is unable to handle any more transaction requests.zOCan't start a SAVEPOINT transaction when no existing transaction is in progress)r?   _trans_ctx_checkr   rs  ru  rl  ro  r|  r{  _close_state_SessionCloseStater   r   r   _nested_transaction_previous_nested_transactionrp  r   r   rv  _take_snapshot_transactiondispatchafter_transaction_create)r   r   r{  parentr|  s        r   r   SessionTransaction.__init__  s    	--g6%)A)N)NNNf#5#<#<<,,; 
 001 
 180K0KD-/>>>%%%>!>-44 %)!66t||TJr   c                   U[         R                  L aI  U R                  (       a"  [        R                  " SU R                   3SS9e[        R
                  " S5      eU[         R                  L a  [        R                  " S5      eU[         R                  L a  [        R
                  " SSS9e[        R
                  " SUR                  R                  5        S	35      e)
NzThis Session's transaction has been rolled back due to a previous exception during flush. To begin a new transaction with this Session, first issue Session.rollback(). Original exception was: 7s2a)codezThis session is in 'inactive' state, due to the SQL transaction being rolled back; no further SQL can be emitted within this transaction.zThis transaction is closedzVThis session is provisioning a new connection; concurrent operations are not permittediscezThis session is in 'z?' state; no further SQL can be emitted within this transaction.)r   r   rr  r   PendingRollbackErrorr   r   ResourceClosedErrorr   namelower)r   operation_namer!   s      r   _raise_for_prerequisite_state0SessionTransaction._raise_for_prerequisite_state  s     +444''110 150H0H/I	K
    00> 
 -444,,-IJJ-EEE,,/  ,,&uzz'7'7'9&: ;F F r   c                    U R                   $ )a  The parent :class:`.SessionTransaction` of this
:class:`.SessionTransaction`.

If this attribute is ``None``, indicates this
:class:`.SessionTransaction` is at the top of the stack, and
corresponds to a real "COMMIT"/"ROLLBACK"
block.  If non-``None``, then this is either a "subtransaction"
(an internal marker object used by the flush process) or a
"nested" / SAVEPOINT transaction.  If the
:attr:`.SessionTransaction.nested` attribute is ``True``, then
this is a SAVEPOINT, and if ``False``, indicates this a subtransaction.

)ru  r   s    r   r  SessionTransaction.parent  s     ||r   c                d    U R                   S L=(       a    U R                  [        R                  L $ r   )r   rv  r   r   r   s    r   	is_activeSessionTransaction.is_active  s-     LL$ >6===	
r   c                J    U R                   =(       d    U R                  (       + $ r   )r|  ru  r   s    r   _is_transaction_boundary+SessionTransaction._is_transaction_boundary  s    {{.$,,..r   c                ^    U R                   R                  " U40 UD6nU R                  XB5      $ r   )r   get_bind_connection_for_bind)r   bindkeyr   kwargsbinds        r   
connectionSessionTransaction.connection  s.     ||$$W77((AAr   c                    [        U R                  U(       a  [        R                  U 5      $ [        R                  U 5      $ r   )r|   r   rl  ro  rp  )r   r|  s     r   _beginSessionTransaction._begin  sE     "LL  )55 
 	

 .<<
 	
r   c                    U nSnU(       aR  X24-  nUR                   UL a   U$ UR                   c  [        R                  " SU-  5      eUR                   nU(       a  MR  U$ )Nr   z4Transaction %s is not on the active transaction list)ru  r   r   )r   uptocurrentr  s       r   _iterate_self_and_parents,SessionTransaction._iterate_self_and_parents  st     13j F$&  (00J 
 "// g r   c                t   U R                   (       dV  U R                  nUc   eUR                  U l        UR                  U l        UR                  U l        UR
                  U l        g U R                  [        R                  [        R                  4;   nU(       d5  U R                  R                  (       d  U R                  R                  5         [        R                  " 5       U l        [        R                  " 5       U l        [        R                  " 5       U l        [        R                  " 5       U l        g r   )r  ru  rw  rx  ry  rz  r{  rl  rn  rm  r   	_flushingflushweakrefWeakKeyDictionary)r   r  is_begins      r   r  !SessionTransaction._take_snapshot2  s    ,,\\F%%%DI"OODM --DK!'!5!5D;;$**$..#
 
  6 6LL --/	113//1$668r   c                   U R                   (       d   e[        U R                  5      R                  U R                  R                  5      nU R                  R                  USS9  U R                  R                  5        H_  u  nu  pEU R                  R                  R                  U5        XCl
        X2;  d  M:  U R                  R                  R                  U5        Ma     [        U R                  5      R                  U R                  R                  5       H  nU R                  R                  USS9  M     U R                  R                  (       a   eU R                  R                  R                  5        Hf  nU(       a"  UR                  (       d  X0R                   ;   d  M,  UR#                  UR$                  U R                  R                  R&                  5        Mh     g)z]Restore the restoration state taken before a transaction began.

Corresponds to a rollback.

Tto_transient)revert_deletionN)r  r
  rw  r   r   _expunge_statesrz  itemsidentity_mapsafe_discardkeyreplacerx  _update_impl
all_statesmodifiedry  _expirer   	_modified)r   
dirty_only
to_expungesoldkeynewkeys         r   _restore_snapshot$SessionTransaction._restore_snapshotH  sV    ,,,,^))$,,*;*;<
$$Zd$C#'#5#5#;#;#=A LL%%2215 E "))11!4 $> T]]#))$,,*?*?@ALL%%a%> A <<((((**557AqKK/?		!&&$,,";";"E"EF 8r   c                j   U R                   (       d   eU R                  (       d  U R                  R                  (       a  U R                  R                  R                  5        H=  nUR                  UR                  U R                  R                  R                  5        M?     [        R                  R                  [        U R                  5      U R                  5        U R                  R                  5         gU R                  (       a  U R                  nUc   eUR                   R#                  U R                   5        UR$                  R#                  U R$                  5        UR                  R#                  U R                  5        UR&                  R#                  U R&                  5        gg)zZRemove the restoration state taken before a transaction began.

Corresponds to a commit.

N)r  r|  r   expire_on_commitr  r  r  r   r  statelibr4   _detach_statesr   rx  clearru  rw  r   ry  rz  )r   r  r  s      r   _remove_snapshot#SessionTransaction._remove_snapshoth  s    ,,,,{{t||<<\\..99;		!&&$,,";";"E"EF < ""11T]]#T\\ MM![[\\F%%%KKtyy)MM  -OO""4==1  ''(:(:; r   c                b   XR                   ;   a/  U(       a  [        R                  " S5        U R                   U   S   $ [        R                  U l        SnSn U R                  (       aD  U R                  R                  X5      nU R                  (       d  U[        R                  U l        $ Od[        U[        R                  5      (       a3  UnUR                  U R                   ;   a  [        R                  " S5      eOUR                  5       nSn U(       a  UR                   " S0 UD6nU R"                  R$                  (       a  U R                  c  UR'                  5       nGOU R                  (       a  UR)                  5       nOUR+                  5       (       a  U R"                  R,                  nUS:X  a<  UR/                  5       (       a  SnOSnU(       a  [        R                  " S	U< S
35        US;   a?  UR/                  5       (       a  UR1                  5       nOUR3                  5       nUS:X  a  SnO.US:X  a  UR)                  5       nO U5       eUR5                  5       n[        U[        R                  5      nUUUU(       + 4=U R                   U'   U R                   UR                  '   U R"                  R6                  R9                  U R"                  X5        U[        R                  U l        $ !   U(       a  UR;                  5         e = f! [        R                  U l        f = f)NzOConnection is already established for the given bind; execution_options ignoredr   FTzMSession already has a Connection associated for the given Connection's Enginer   r   r   zThe engine provided as bind produced a connection that is already in a transaction. This is usually caused by a core event, such as 'engine_connect', that has left a transaction open. The effective join transaction mode used by this session is z9. To silence this warning, do not leave transactions open)r   r   r   )rs  r<   warnr   r   rv  ru  r  r|  r   r	  r:   r=   r   r   connectr   r   twophasebegin_twophasebegin_nestedin_transactionjoin_transaction_modein_nested_transaction _get_required_nested_transaction_get_required_transactionbeginr  after_beginclose)	r   r  r   local_connectshould_commitconntransactionr  bind_is_connections	            r   r  'SessionTransaction._connection_for_bind  s    $$$ 		< $$T*1---EEX	9||||88 {{d 288DKg # dF$5$566D{{d&7&77$88@  8  <<>D$(MC$11F4EFD <<((T\\-A
 #'"5"5"7K[["&"3"3"5K((**,0LL,N,N),0GG55774F14C1( II!L $9"; <J!J	 - 1   5577 $ E E G ( +/*H*H*JK0OC,1M.2DD&*&7&7&9;&;;u"&**,K &0f6G6G%H" !**	L !!$'$*;*;DKK*H %%11$,,K188DK% !JJL 288DKs-   >L -A%L EK: (A<L :LL L.c                    U R                   c  U R                  R                  (       d  [        R                  " S5      eU R                  5         g )NzD'twophase' mode not enabled, or not root transaction; can't prepare.)ru  r   r  r   r   _prepare_implr   s    r   prepareSessionTransaction.prepare  s>    <<#4<<+@+@,,!  	r   c                   U R                   b  U R                  (       a/  U R                  R                  R	                  U R                  5        U R                  R
                  nUc   eXLa&  UR                  U S9 H  nUR                  5         M     U R                  R                  (       dc  [        S5       H>  nU R                  R                  5       (       a    O4U R                  R                  5         M@     [        R                  " S5      eU R                   cc  U R                  R                  (       aH   [        U R                   R#                  5       5       H   n[%        SUS   5      R'                  5         M"     [.        R0                  U l        g !   [(        R*                  " 5          U R-                  5         S S S 5         MI  ! , (       d  f        NX= f= f)Nr  d   zrOver 100 subsequent flushes have occurred within session.commit() - is an after_flush() hook creating new objects?r`   r   )ru  r|  r   r  before_commitr  r  commitr  range	_is_cleanr  r   
FlushErrorr  r
  rs  valuesr   r  r<   safe_reraiserollbackr   r   rv  )r   stxsubtransaction_flush_guardts        r   r   SessionTransaction._prepare_impl  sZ    <<4;;LL!!//=ll''?"%"?"?T"?"J%%' #K ||%% %c
<<))++""$ !+
 nn,  <<DLL$9$9$T..5578A.!5==? 9 .66	$&&(MMO )(((s+   :AF G.G
?G

G	GGc                :   U R                   [        R                  La8  U R                  [        R                  5         U R	                  5         S S S 5        U R
                  b  U R                  (       a  [        U R                  R                  5       5       H  u  p#pEU(       d  M  UR                  5         M!     [        R                  U l         U R                  R                  R                  U R                  5        U R                  5         U R                  [        R                   5         U R#                  5         S S S 5        U(       a,  U R
                  (       a  U R
                  R                  SS9  g g g ! , (       d  f       GN3= f! , (       d  f       NT= f)NT_to_root)rv  r   r   _expect_stater  ru  r|  r
  rs  r  r  r   r   r  after_commitr  r   r  )r   r  r  transr  	autocloses         r   r  SessionTransaction.commit  s   
 ;;5>>>##$;$D$DE""$ F <<4;;9<!!((*:5] !=LLN	: 2;;DKLL!!..t||<!!# 7 > >?JJL @ LL. %8% FE @?s   E:-F:
F	
Fc                :   U R                   R                  nUc   eX0La&  UR                  U S9 H  nUR                  5         M     U nS nU R                  [
        R                  [
        R                  4;   a  U R                  5        H  nUR                  b  UR                  (       a   [        UR                  R                  5       5       H  nUS   R                  5         M     [
        R                  Ul        U R                   R                  R!                  U R                   5        [
        R                  Ul        UR'                  UR                  S9  Un  O[
        R                  Ul        M     U R                   n	U(       dD  U	R)                  5       (       d/  [*        R,                  " S5        UR'                  UR                  S9  U R/                  [
        R0                  5         U R                  5         S S S 5        U R                  (       a.  U(       a'  ["        R$                  " 5       S   U R                  l        U(       a!  US   (       a  US   R5                  US   5      eU	R                  R7                  X5        U(       a,  U R                  (       a  U R                  R                  SS9  g g g !   ["        R$                  " 5       n GN= f! [
        R                  Ul        UR'                  UR                  S9  f = f! , (       d  f       GN= f)Nr  r   )r  z\Session's state has been changed on a non-active transaction - this state will be discarded.r9   Tr  )r   r  r  r  rv  r   r   r   ru  r|  r
  rs  r  r  r   r  after_rollbacksysexc_infor  r  r<   r  r  r   rr  with_tracebackafter_soft_rollback)
r   _capture_exceptionr  r  r  boundaryrollback_errr  r  sesss
             r   r  SessionTransaction.rollback5  so    ll''?"%"?"?T"?"J$$& #K ;;#**#,,
 
  $==?&&.+2D2D!$[%=%=%D%D%F!GAaDMMO "H .E-M-M*--<<T\\J .E-M-M*#55'2'9'9 6   +H)@)I)IK&%  @( ||DNN$4$4 II%
 &&(//&B 7 > >?JJL @ <<./2||~a/@DLL,LOq/00aAA))$5LL!!4!0 %8G6'*||~-D-M-M*#55'2'9'9 6 ( @?s%   *BJ;,L;KK0L
Lc                L   U R                   (       a  U R                  U R                  l        U R                  U R                  l        [        U R                  R                  5       5       Hz  u  p#pEU(       a  U R                  c  UR                  5         U(       a!  UR                  (       a  UR                  5         U(       d  M[  U R                  b  Mj  UR                  5         M|     [        R                  U l        U R                  nUR                  R!                  X`5        g r   )r|  r  r   r  ru  r  r
  rs  r  
invalidater  r  r   r   rv  r  after_transaction_end)r   r  r  r  r  r  r	  s          r   r  SessionTransaction.closez  s     ;;11 LL, %)LL!AD$$&B
=J] dll2%%'!6!6!!#yT\\1  "B
 .44|| 	++D7r   c                    U R                   $ r   r   r   s    r   _get_subjectSessionTransaction._get_subject  s    ||r   c                :    U R                   [        R                  L $ r   )rv  r   r   r   s    r   _transaction_is_active)SessionTransaction._transaction_is_active      {{5<<<<r   c                :    U R                   [        R                  L $ r   )rv  r   r   r   s    r   _transaction_is_closed)SessionTransaction._transaction_is_closed  r  r   c                4    U R                   [        [        4;  $ r   )rv  r   r   r   s    r   _rollback_can_be_called*SessionTransaction._rollback_can_be_called  s    {{9f"555r   )rs  rx  ry  rz  rw  ru  r  rv  r|  r{  r   r   )r   r{   r{  rl  r  rt  )r  strr!   r6   r   r   r   rt  re  )r  r   r   r   r  r   r   r=   Fr|  rf  r   r|   )r  rt  r   zIterable[SessionTransaction]r   )r  rf  r   r   )r  _SessionBindr   %Optional[CoreExecuteOptionsParameter]r   r=   )r  rf  r   r   FF)r  rf  r  rf  r   r   )r  rf  r   r   )r   r{   ))r   r   r   r   r   rr  ri  r|  r   r  rj  r  r  r  r5   declare_statesr   r   r7   	NO_CHANGEr  r  r  r  r  r  r  r  r   r  r   r  r   r  ANYr  r  r  r  r  r   r   r   r   r|   r|   M  s4   $L 4807  ))##
??CCAA  %$ FD
  04	)K)K ))K -	)KV!*;	B    
 
 / /   	 	'	')+=+G+G 8<B&B 5B 	B
 
BB   	 	'	')+=+G+G	
	
 480	%&9,G@<0   	 	'	')+=+G+Gj9j9 Aj9 
	j9j9X   	 	'	')+B+K+K77@   	 	'	')@)I)IJ&&/	/.   #**#,,#,,	

 	 && BG;1"&;1:>;1	;1;1z    7 > >88>==6r   r|   c                       \ rS rSrSrSrSrSrg)r  i  r   r9   r   r   N)r   r   r   r   r   r   CLOSE_IS_RESETr   r   r   r   r  r    s    FFNr   r  c                     \ rS rSr% SrSrS\S'   S\S'    S\S	'   S\S
'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S '    SS"S"S"S"SS!S"S!S!SS#\R                  S$.                         SS% jjjr	S!r
S&\S''   S!rS(\S)'   SS* jrSS+ jr\R                  SS, j5       rSS- jrSS. jrSS/ jrSS0 jr\R,                  SS1 j5       rSSS2 jjrSSS3 jjrSS4 jrSS5 jrSS6 jrSS7 jr  S     SS8 jjr S       SS9 jjr\  S\RB                  S!S!S!S:S;.               SS< jjj5       r"\  S\RB                  S!S!S!S:S;.               SS= jjj5       r" S\RB                  S!S!S!SS;.               SS> jjjr"\  S\RB                  S!S!S!S?.             SS@ jjj5       r#\  S\RB                  S!S!S!S?.             SSA jjj5       r#\  S\RB                  S!S!S!S?.             SSB jjj5       r# S\RB                  S!S!S!S?.             SSC jjjr#\  S\RB                  S!SD.           SSE jjj5       r$\  S\RB                  S!SD.           SSF jjj5       r$ S\RB                  S!SD.           SSG jjjr$\  S\RB                  S!SD.           SSH jjj5       r%\  S\RB                  S!SD.           SSI jjj5       r% S\RB                  S!SD.           SSJ jjjr%SSK jr&SSL jr'SSM jr(SSSN jjr)SSO jr*SSP jr+      SSQ jr,SSR jr- SS!S!S!SSS.             SST jjjr.\ SSU j5       r/\     SSV j5       r/\       SSW j5       r/\         SSX j5       r/\           SSY j5       r/\             SSZ j5       r/\               SS[ j5       r/\                 SS\ j5       r/\                   SS] j5       r/\       SS^ j5       r/      SS_ jr/S!\0Rb                  S!\RB                  S!4               SS` jjr2\Rf                  \R                  SSa j5       5       r4\Rj                  Rm                  Sb\7Rp                  5      SSc j5       r9  S       SSd jjr:SSe jr; S     SSf jjr<      SSg jr= S     SSh jjr>SSi jr? S     SSj jjr@SSk jrASSl jrB    SSm jrCSSSn jjrDSSo jrESSp jrFSSq jrG        SSr jrHS!SS!S!\RB                  S!Ss.                 SSt jjrIS!SS!S!\RB                  S!Ss.                 SSu jjrJS!SS!S!\RB                  S!Ss.                   SSv jjrKS"S!Sw.       SSx jjrLS!Sy.             SSz jjrMSS{ jrNSS| jrO S     SS} jjrPSS~ jrQSS jrRSS jrSSS jrTSS jrUSS jrVSS jrWSSS jjrXSS jrYSS jrZSSS jjr[   S         SS jjr\  S         SS jjr]      SS jr^                SS jr_ S     SS jjr`\aSS j5       rb\aSS j5       rc\aSS j5       rd\aSS j5       re\aSS j5       rfSrgg!)r{   i  zManages persistence operations for ORM-mapped objects.

The :class:`_orm.Session` is **not safe for use in concurrent threads.**.
See :ref:`session_faq_threadsafe` for background.

The Session's usage paradigm is described at :doc:`/orm/session`.


Fzdispatcher[Session]r  r2   r  zDict[InstanceState[Any], Any]rw  rx  z#Optional[Union[Engine, Connection]]r  z#Dict[_SessionBindKey, _SessionBind]_Session__bindsrf  r  _warn_on_eventsrt  r  r  r   hash_key	autoflushr  enable_baked_queriesr  JoinTransactionModer  zType[Query[Any]]
_query_clsr  r  NTr   )r,  futurer  	autobeginr  bindsr-  info	query_cls
autocommitr  close_resets_onlyc               l   U(       a  [         R                  " S5      e[        R                  " 5       U l        U(       d  [         R                  " S5      e0 U l        0 U l        Xl        0 U l        SU l	        SU l
        SU l        SU l        [        5       U l        XPl        X l        X@l        Xl        US[&        R(                  4;   a  [*        R,                  U l        O[*        R0                  U l        U(       a.  U[2        R4                  ;  a  [         R                  " SU S35      eXl        X`l        U
(       a  U
O[:        R<                  U l        U	(       a  U R@                  RC                  U	5        Ub*  URE                  5        H  u  pU RG                  X5        M     U [H        U R                  '   g)a%  Construct a new :class:`_orm.Session`.

See also the :class:`.sessionmaker` function which is used to
generate a :class:`.Session`-producing callable with a given
set of arguments.

:param autoflush: When ``True``, all query operations will issue a
   :meth:`~.Session.flush` call to this ``Session`` before proceeding.
   This is a convenience feature so that :meth:`~.Session.flush` need
   not be called repeatedly in order for database queries to retrieve
   results.

   .. seealso::

       :ref:`session_flushing` - additional background on autoflush

:param autobegin: Automatically start transactions (i.e. equivalent to
   invoking :meth:`_orm.Session.begin`) when database access is
   requested by an operation.   Defaults to ``True``.    Set to
   ``False`` to prevent a :class:`_orm.Session` from implicitly
   beginning transactions after construction, as well as after any of
   the :meth:`_orm.Session.rollback`, :meth:`_orm.Session.commit`,
   or :meth:`_orm.Session.close` methods are called.

   .. versionadded:: 2.0

   .. seealso::

        :ref:`session_autobegin_disable`

:param bind: An optional :class:`_engine.Engine` or
   :class:`_engine.Connection` to
   which this ``Session`` should be bound. When specified, all SQL
   operations performed by this session will execute via this
   connectable.

:param binds: A dictionary which may specify any number of
   :class:`_engine.Engine` or :class:`_engine.Connection`
   objects as the source of
   connectivity for SQL operations on a per-entity basis.   The keys
   of the dictionary consist of any series of mapped classes,
   arbitrary Python classes that are bases for mapped classes,
   :class:`_schema.Table` objects and :class:`_orm.Mapper` objects.
   The
   values of the dictionary are then instances of
   :class:`_engine.Engine`
   or less commonly :class:`_engine.Connection` objects.
   Operations which
   proceed relative to a particular mapped class will consult this
   dictionary for the closest matching entity in order to determine
   which :class:`_engine.Engine` should be used for a particular SQL
   operation.    The complete heuristics for resolution are
   described at :meth:`.Session.get_bind`.  Usage looks like::

    Session = sessionmaker(
        binds={
            SomeMappedClass: create_engine("postgresql+psycopg2://engine1"),
            SomeDeclarativeBase: create_engine(
                "postgresql+psycopg2://engine2"
            ),
            some_mapper: create_engine("postgresql+psycopg2://engine3"),
            some_table: create_engine("postgresql+psycopg2://engine4"),
        }
    )

   .. seealso::

        :ref:`session_partitioning`

        :meth:`.Session.bind_mapper`

        :meth:`.Session.bind_table`

        :meth:`.Session.get_bind`


:param \class_: Specify an alternate class other than
   ``sqlalchemy.orm.session.Session`` which should be used by the
   returned class. This is the only argument that is local to the
   :class:`.sessionmaker` function, and is not sent directly to the
   constructor for ``Session``.

:param enable_baked_queries: legacy; defaults to ``True``.
   A parameter consumed
   by the :mod:`sqlalchemy.ext.baked` extension to determine if
   "baked queries" should be cached, as is the normal operation
   of this extension.  When set to ``False``, caching as used by
   this particular extension is disabled.

   .. versionchanged:: 1.4 The ``sqlalchemy.ext.baked`` extension is
      legacy and is not used by any of SQLAlchemy's internals. This
      flag therefore only affects applications that are making explicit
      use of this extension within their own code.

:param expire_on_commit:  Defaults to ``True``. When ``True``, all
   instances will be fully expired after each :meth:`~.commit`,
   so that all attribute/object access subsequent to a completed
   transaction will load from the most recent database state.

    .. seealso::

        :ref:`session_committing`

:param future: Deprecated; this flag is always True.

  .. seealso::

    :ref:`migration_20_toplevel`

:param info: optional dictionary of arbitrary data to be associated
   with this :class:`.Session`.  Is available via the
   :attr:`.Session.info` attribute.  Note the dictionary is copied at
   construction time so that modifications to the per-
   :class:`.Session` dictionary will be local to that
   :class:`.Session`.

:param query_cls:  Class which should be used to create new Query
  objects, as returned by the :meth:`~.Session.query` method.
  Defaults to :class:`_query.Query`.

:param twophase:  When ``True``, all transactions will be started as
    a "two phase" transaction, i.e. using the "two phase" semantics
    of the database in use along with an XID.  During a
    :meth:`~.commit`, after :meth:`~.flush` has been issued for all
    attached databases, the :meth:`~.TwoPhaseTransaction.prepare`
    method on each database's :class:`.TwoPhaseTransaction` will be
    called. This allows each database to roll back the entire
    transaction, before each transaction is committed.

:param autocommit: the "autocommit" keyword is present for backwards
    compatibility but must remain at its default value of ``False``.

:param join_transaction_mode: Describes the transactional behavior to
  take when a given bind is a :class:`_engine.Connection` that
  has already begun a transaction outside the scope of this
  :class:`_orm.Session`; in other words the
  :meth:`_engine.Connection.in_transaction()` method returns True.

  The following behaviors only take effect when the :class:`_orm.Session`
  **actually makes use of the connection given**; that is, a method
  such as :meth:`_orm.Session.execute`, :meth:`_orm.Session.connection`,
  etc. are actually invoked:

  * ``"conditional_savepoint"`` - this is the default.  if the given
    :class:`_engine.Connection` is begun within a transaction but
    does not have a SAVEPOINT, then ``"rollback_only"`` is used.
    If the :class:`_engine.Connection` is additionally within
    a SAVEPOINT, in other words
    :meth:`_engine.Connection.in_nested_transaction()` method returns
    True, then ``"create_savepoint"`` is used.

    ``"conditional_savepoint"`` behavior attempts to make use of
    savepoints in order to keep the state of the existing transaction
    unchanged, but only if there is already a savepoint in progress;
    otherwise, it is not assumed that the backend in use has adequate
    support for SAVEPOINT, as availability of this feature varies.
    ``"conditional_savepoint"`` also seeks to establish approximate
    backwards compatibility with previous :class:`_orm.Session`
    behavior, for applications that are not setting a specific mode. It
    is recommended that one of the explicit settings be used.

  * ``"create_savepoint"`` - the :class:`_orm.Session` will use
    :meth:`_engine.Connection.begin_nested()` in all cases to create
    its own transaction.  This transaction by its nature rides
    "on top" of any existing transaction that's opened on the given
    :class:`_engine.Connection`; if the underlying database and
    the driver in use has full, non-broken support for SAVEPOINT, the
    external transaction will remain unaffected throughout the
    lifespan of the :class:`_orm.Session`.

    The ``"create_savepoint"`` mode is the most useful for integrating
    a :class:`_orm.Session` into a test suite where an externally
    initiated transaction should remain unaffected; however, it relies
    on proper SAVEPOINT support from the underlying driver and
    database.

    .. tip:: When using SQLite, the SQLite driver included through
       Python 3.11 does not handle SAVEPOINTs correctly in all cases
       without workarounds. See the sections
       :ref:`pysqlite_serializable` and :ref:`aiosqlite_serializable`
       for details on current workarounds.

  * ``"control_fully"`` - the :class:`_orm.Session` will take
    control of the given transaction as its own;
    :meth:`_orm.Session.commit` will call ``.commit()`` on the
    transaction, :meth:`_orm.Session.rollback` will call
    ``.rollback()`` on the transaction, :meth:`_orm.Session.close` will
    call ``.rollback`` on the transaction.

    .. tip:: This mode of use is equivalent to how SQLAlchemy 1.4 would
       handle a :class:`_engine.Connection` given with an existing
       SAVEPOINT (i.e. :meth:`_engine.Connection.begin_nested`); the
       :class:`_orm.Session` would take full control of the existing
       SAVEPOINT.

  * ``"rollback_only"`` - the :class:`_orm.Session` will take control
    of the given transaction for ``.rollback()`` calls only;
    ``.commit()`` calls will not be propagated to the given
    transaction.  ``.close()`` calls will have no effect on the
    given transaction.

    .. tip:: This mode of use is equivalent to how SQLAlchemy 1.4 would
       handle a :class:`_engine.Connection` given with an existing
       regular database transaction (i.e.
       :meth:`_engine.Connection.begin`); the :class:`_orm.Session`
       would propagate :meth:`_orm.Session.rollback` calls to the
       underlying transaction, but not :meth:`_orm.Session.commit` or
       :meth:`_orm.Session.close` calls.

  .. versionadded:: 2.0.0rc1

:param close_resets_only: Defaults to ``True``. Determines if
  the session should reset itself after calling ``.close()``
  or should pass in a no longer usable state, disabling re-use.

  .. versionadded:: 2.0.22 added flag ``close_resets_only``.
    A future SQLAlchemy version may change the default value of
    this flag to ``False``.

  .. seealso::

    :ref:`session_closing` - Detail on the semantics of
    :meth:`_orm.Session.close` and :meth:`_orm.Session.reset`.

z&autocommit=True is no longer supportedzCThe 'future' parameter passed to Session() may only be set to True.FNTz.invalid selection for join_transaction_mode: "")%r   ArgumentErrorr   WeakInstanceDictr  rw  rx  r  r)  r  r*  r  r  _new_sessionidr+  r1  r,  r  r-  rJ   NO_ARGr  r'  r  r   r.  __args__r  r  r   r3   r/  r3  r   r  	_add_bindr   )r   r  r,  r0  r  r1  r  r2  r-  r3  r4  r5  r  r6  r  s                  r   r   Session.__init__  sv   n &&8  %557&&5 
 		$ #' &("" 0$8! v}} 55 2 A AD 2 9 9D!%&//0 &&)*!-  &;" '0)ekkIIT""[[]	s) + $(	$-- r   zOptional[TransactionalContext]_trans_context_managerz"Optional[_ConnectionCallableProto]connection_callablec                    U $ r   r   r   s    r   	__enter__Session.__enter__  s    r   c                $    U R                  5         g r   )r  )r   type_value	tracebacks       r   __exit__Session.__exit__  s    

r   c              #     #    U    U R                  5          U v   S S S 5        S S S 5        g ! , (       d  f       N= f! , (       d  f       g = f7fr   r  r   s    r   _maker_context_managerSession._maker_context_manager  s/     
  T Ts)   A=,=	A
:	=
AAc                    U R                   SL$ )zReturn True if this :class:`_orm.Session` has begun a transaction.

.. versionadded:: 1.4

.. seealso::

    :attr:`_orm.Session.is_active`


N)r  r   s    r   r  Session.in_transaction  s       ,,r   c                    U R                   SL$ )zrReturn True if this :class:`_orm.Session` has begun a nested
transaction, e.g. SAVEPOINT.

.. versionadded:: 1.4

Nr  r   s    r   r  Session.in_nested_transaction(  s     ''t33r   c                z    U R                   nUb+  UR                  b  UR                  nUb  UR                  b  M  U$ )zQReturn the current root transaction in progress, if any.

.. versionadded:: 1.4

)r  ru  r   r  s     r   get_transactionSession.get_transaction1  s=     !!EMM$=MME EMM$=r   c                    U R                   $ )zSReturn the current nested transaction in progress, if any.

.. versionadded:: 1.4

rR  r   s    r   get_nested_transactionSession.get_nested_transaction<  s     '''r   c                    0 $ )aZ  A user-modifiable dictionary.

The initial value of this dictionary can be populated using the
``info`` argument to the :class:`.Session` constructor or
:class:`.sessionmaker` constructor or factory methods.  The dictionary
here is always local to this :class:`.Session` and can be modified
independently of all other :class:`.Session` objects.

r   r   s    r   r3  Session.infoE  s	     	r   c                   U R                   cr  U(       d'  U R                  (       d  [        R                  " S5      e[	        U U(       a  [
        R                  O[
        R                  5      nU R                   UL d   eU$ U R                   $ )Nz]Autobegin is disabled on this Session; please call session.begin() to start a new transaction)r  r1  r   r   r|   rl  rn  rm  )r   r  r  s      r   _autobegin_tSession._autobegin_tR  s    $00A  '  -221;;E $$---L   r   c                    U R                   nUc  U R                  SS9nU(       d  U$ Uc   eU(       a(  UR                  US9nU R                   UL d   eX l        U$ [        R
                  " S5      e)a  Begin a transaction, or nested transaction,
on this :class:`.Session`, if one is not already begun.

The :class:`_orm.Session` object features **autobegin** behavior,
so that normally it is not necessary to call the
:meth:`_orm.Session.begin`
method explicitly. However, it may be used in order to control
the scope of when the transactional state is begun.

When used to begin the outermost transaction, an error is raised
if this :class:`.Session` is already inside of a transaction.

:param nested: if True, begins a SAVEPOINT transaction and is
 equivalent to calling :meth:`~.Session.begin_nested`. For
 documentation on SAVEPOINT transactions, please see
 :ref:`session_begin_nested`.

:return: the :class:`.SessionTransaction` object.  Note that
 :class:`.SessionTransaction`
 acts as a Python context manager, allowing :meth:`.Session.begin`
 to be used in a "with" block.  See :ref:`session_explicit_begin` for
 an example.

.. seealso::

    :ref:`session_autobegin`

    :ref:`unitofwork_transaction`

    :meth:`.Session.begin_nested`


TrL  r|  z/A transaction is already begun on this Session.)r  r^  r  r  r   r   )r   r|  r  s      r   r  Session.beginf  s    F !!=%%D%1E   LLL/E$$---',$ 	 ,,A r   c                     U R                  SS9$ )a  Begin a "nested" transaction on this Session, e.g. SAVEPOINT.

The target database(s) and associated drivers must support SQL
SAVEPOINT for this method to function correctly.

For documentation on SAVEPOINT
transactions, please see :ref:`session_begin_nested`.

:return: the :class:`.SessionTransaction` object.  Note that
 :class:`.SessionTransaction` acts as a context manager, allowing
 :meth:`.Session.begin_nested` to be used in a "with" block.
 See :ref:`session_begin_nested` for a usage example.

.. seealso::

    :ref:`session_begin_nested`

    :ref:`pysqlite_serializable` - special workarounds required
    with the SQLite driver in order for SAVEPOINT to work
    correctly. For asyncio use cases, see the section
    :ref:`aiosqlite_serializable`.

Tra  rL  r   s    r   r  Session.begin_nested  s    0 zzz&&r   c                R    U R                   c  gU R                   R                  SS9  g)a;  Rollback the current transaction in progress.

If no transaction is in progress, this method is a pass-through.

The method always rolls back
the topmost database transaction, discarding any nested
transactions that may be in progress.

.. seealso::

    :ref:`session_rollback`

    :ref:`unitofwork_transaction`

NTr  )r  r  r   s    r   r  Session.rollback  s*      $&&&5r   c                `    U R                   nUc  U R                  5       nUR                  SS9  g)a  Flush pending changes and commit the current transaction.

When the COMMIT operation is complete, all objects are fully
:term:`expired`, erasing their internal contents, which will be
automatically re-loaded when the objects are next accessed. In the
interim, these objects are in an expired state and will not function if
they are :term:`detached` from the :class:`.Session`. Additionally,
this re-load operation is not supported when using asyncio-oriented
APIs. The :paramref:`.Session.expire_on_commit` parameter may be used
to disable this behavior.

When there is no transaction in place for the :class:`.Session`,
indicating that no operations were invoked on this :class:`.Session`
since the previous call to :meth:`.Session.commit`, the method will
begin and commit an internal-only "logical" transaction, that does not
normally affect the database unless pending flush changes were
detected, but will still invoke event handlers and object expiration
rules.

The outermost database transaction is committed unconditionally,
automatically releasing any SAVEPOINTs in effect.

.. seealso::

    :ref:`session_committing`

    :ref:`unitofwork_transaction`

    :ref:`asyncio_orm_avoid_lazyloads`

NTr  )r  r^  r  rU  s     r   r  Session.commit  s1    @ !!=%%'Ed#r   c                b    U R                   nUc  U R                  5       nUR                  5         g)aH  Prepare the current transaction in progress for two phase commit.

If no transaction is in progress, this method raises an
:exc:`~sqlalchemy.exc.InvalidRequestError`.

Only root transactions of two phase sessions can be prepared. If the
current transaction is not such, an
:exc:`~sqlalchemy.exc.InvalidRequestError` is raised.

N)r  r^  r  rU  s     r   r  Session.prepare  s+     !!=%%'Er   c                    U(       a(  UR                  SS5      nUc  U R                  " S0 UD6nOU R                  5       nU R                  UUS9$ )az  Return a :class:`_engine.Connection` object corresponding to this
:class:`.Session` object's transactional state.

Either the :class:`_engine.Connection` corresponding to the current
transaction is returned, or if no transaction is in progress, a new
one is begun and the :class:`_engine.Connection`
returned (note that no
transactional state is established with the DBAPI until the first
SQL statement is emitted).

Ambiguity in multi-bind or unbound :class:`.Session` objects can be
resolved through any of the optional keyword arguments.   This
ultimately makes usage of the :meth:`.get_bind` method for resolution.

:param bind_arguments: dictionary of bind arguments.  May include
 "mapper", "bind", "clause", other custom arguments that are passed
 to :meth:`.Session.get_bind`.

:param execution_options: a dictionary of execution options that will
 be passed to :meth:`_engine.Connection.execution_options`, **when the
 connection is first procured only**.   If the connection is already
 present within the :class:`.Session`, a warning is emitted and
 the arguments are ignored.

 .. seealso::

    :ref:`session_transaction_isolation`

r  Nr   r   )popr  r  )r   r   r   r  s       r   r  Session.connection  sZ    F !%%fd3D|}}6~6==?D((/ ) 
 	
r   c                    [         R                  " U 5        U R                  nUc  U R                  5       nUR	                  X5      $ r   )r?   r~  r  r^  r  )r   r:   r   r   r  s        r   r  Session._connection_for_bind3  sA     	--d3!!=%%'E))&DDr   .)r   r   r   
_add_event_scalar_resultc                   g r   r   r   r   r   r   r   r   rq  rr  s           r   r   Session._execute_internal@  s     r   c                   g r   r   rt  s           r   r   ru  M  s     r   c          	        [         R                  " [        R                  U5      nU(       d  0 nO[	        U5      nUR
                  R                  SS 5      S:X  aD  [        R                  " US5      n[        (       a!  [        U[        R                  5      (       d   eOS nUR                  SU5        [        R                  " U5      nU(       a  UR!                  5       n	O,U R"                  R$                  n	U(       a  ['        U	5      U/-   n	U	(       a  Ub  UR)                  U UUUUS5      u  nn[+        U UUUUUU	5      n
[-        U	5       H7  u  pXl        U" U
5      nU(       d  M  U(       a  UR1                  5       s  $ Us  $    U
R2                  nU
R4                  nUb  UR)                  U UUUUS5      u  nnU R6                  " S0 UD6nU R9                  U5      nU(       a;  U(       d4  [        (       a  [;        [<        U5      nUR1                  X=(       d    0 US9$ U(       a   UR?                  U UU=(       d    0 UUU5      nOURA                  X=(       d    0 US9nU(       a  UR1                  5       $ U$ )Ncompile_state_pluginormclauseTFrl  r   )!rD   expectrF   StatementRoler   _propagate_attrsr  rK   _get_plugin_class_for_pluginr   r	  r   AbstractORMCompileState
setdefaultr<   coerce_to_immutabledictr   r  do_orm_executer   orm_pre_session_execr~   	enumerater   scalarr   r   r  r  r   rb   orm_execute_statementexecute)r   r   r   r   r   r   rq  rr  r   r   orm_exec_stateidxfn	fn_resultr  r  r  s                    r   r   ru  Z  s    $$U%8%8)D	N!.1N &&**+A4H !- I I5! }!%w'F'F    !%%%h	: 889JK /AACK--66K";/:,> , &::%"% -!!N %[158235n3E	9%(//11(( 2 '00I . F F( "66!! }}.~.((."3}6?;;<R;L    "3"I"I"!#F \\<R;L " F ==?"Mr   r   r   r   rq  c                   g r   r   r   r   r   r   r   r   rq  s          r   r  Session.execute  s     r   c                   g r   r   r  s          r   r  r    s      r   c                   g r   r   r  s          r   r  r    s     r   c          	     *    U R                  UUUUUUS9$ )a  Execute a SQL expression construct.

Returns a :class:`_engine.Result` object representing
results of the statement execution.

E.g.::

    from sqlalchemy import select

    result = session.execute(select(User).where(User.id == 5))

The API contract of :meth:`_orm.Session.execute` is similar to that
of :meth:`_engine.Connection.execute`, the :term:`2.0 style` version
of :class:`_engine.Connection`.

.. versionchanged:: 1.4 the :meth:`_orm.Session.execute` method is
   now the primary point of ORM statement execution when using
   :term:`2.0 style` ORM usage.

:param statement:
    An executable statement (i.e. an :class:`.Executable` expression
    such as :func:`_expression.select`).

:param params:
    Optional dictionary, or list of dictionaries, containing
    bound parameter values.   If a single dictionary, single-row
    execution occurs; if a list of dictionaries, an
    "executemany" will be invoked.  The keys in each dictionary
    must correspond to parameter names present in the statement.

:param execution_options: optional dictionary of execution options,
 which will be associated with the statement execution.  This
 dictionary can provide a subset of the options that are accepted
 by :meth:`_engine.Connection.execution_options`, and may also
 provide additional options understood only in an ORM context.

 .. seealso::

    :ref:`orm_queryguide_execution_options` - ORM-specific execution
    options

:param bind_arguments: dictionary of additional arguments to determine
 the bind.  May include "mapper", "bind", or other custom arguments.
 Contents of this dictionary are passed to the
 :meth:`.Session.get_bind` method.

:return: a :class:`_engine.Result` object.


r  r   r  s          r   r  r  	  s/    x %%/)"7! & 
 	
r   )r   r   c                   g r   r   r   r   r   r   r   r   s         r   r  Session.scalarF	  s     r   c                   g r   r   r  s         r   r  r  Q	  s     r   c               2    U R                   " UU4UUSS.UD6$ )zExecute a statement and return a scalar result.

Usage and parameters are the same as that of
:meth:`_orm.Session.execute`; the return result is a scalar Python
value.

T)r   r   rr  r  r  s         r   r  r  \	  s7    " %%
 0)
 
 	
r   c                   g r   r   r  s         r   scalarsSession.scalarsv	  s     r   c                   g r   r   r  s         r   r  r  	  s      r   c               N    U R                   " U4UUUSS.UD6R                  5       $ )a`  Execute a statement and return the results as scalars.

Usage and parameters are the same as that of
:meth:`_orm.Session.execute`; the return result is a
:class:`_result.ScalarResult` filtering object which
will return single elements rather than :class:`_row.Row` objects.

:return:  a :class:`_result.ScalarResult` object

.. versionadded:: 1.4.24 Added :meth:`_orm.Session.scalars`

.. versionadded:: 1.4.26 Added :meth:`_orm.scoped_session.scalars`

.. seealso::

    :ref:`orm_queryguide_select_orm_entities` - contrasts the behavior
    of :meth:`_orm.Session.execute` to :meth:`_orm.Session.scalars`

F)r   r   r   rr  )r   r  r  s         r   r  r  	  s>    : %%
/) 
 
 ')	r   c                "    U R                  SS9  g)a  Close out the transactional resources and ORM objects used by this
:class:`_orm.Session`.

This expunges all ORM objects associated with this
:class:`_orm.Session`, ends any transaction in progress and
:term:`releases` any :class:`_engine.Connection` objects which this
:class:`_orm.Session` itself has checked out from associated
:class:`_engine.Engine` objects. The operation then leaves the
:class:`_orm.Session` in a state which it may be used again.

.. tip::

    In the default running mode the :meth:`_orm.Session.close`
    method **does not prevent the Session from being used again**.
    The :class:`_orm.Session` itself does not actually have a
    distinct "closed" state; it merely means
    the :class:`_orm.Session` will release all database connections
    and ORM objects.

    Setting the parameter :paramref:`_orm.Session.close_resets_only`
    to ``False`` will instead make the ``close`` final, meaning that
    any further action on the session will be forbidden.

.. versionchanged:: 1.4  The :meth:`.Session.close` method does not
   immediately create a new :class:`.SessionTransaction` object;
   instead, the new :class:`.SessionTransaction` is created only if
   the :class:`.Session` is used again for a database operation.

.. seealso::

    :ref:`session_closing` - detail on the semantics of
    :meth:`_orm.Session.close` and :meth:`_orm.Session.reset`.

    :meth:`_orm.Session.reset` - a similar method that behaves like
    ``close()`` with  the parameter
    :paramref:`_orm.Session.close_resets_only` set to ``True``.

Fr  N_close_implr   s    r   r  Session.close	  s    N 	E*r   c                $    U R                  SSS9  g)a  Close out the transactional resources and ORM objects used by this
:class:`_orm.Session`, resetting the session to its initial state.

This method provides for same "reset-only" behavior that the
:meth:`_orm.Session.close` method has provided historically, where the
state of the :class:`_orm.Session` is reset as though the object were
brand new, and ready to be used again.
This method may then be useful for :class:`_orm.Session` objects
which set :paramref:`_orm.Session.close_resets_only` to ``False``,
so that "reset only" behavior is still available.

.. versionadded:: 2.0.22

.. seealso::

    :ref:`session_closing` - detail on the semantics of
    :meth:`_orm.Session.close` and :meth:`_orm.Session.reset`.

    :meth:`_orm.Session.close` - a similar method will additionally
    prevent re-use of the Session when the parameter
    :paramref:`_orm.Session.close_resets_only` is set to ``False``.
FT)r  is_resetNr  r   s    r   resetSession.reset	  s    . 	ED9r   c                "    U R                  SS9  g)a  Close this Session, using connection invalidation.

This is a variant of :meth:`.Session.close` that will additionally
ensure that the :meth:`_engine.Connection.invalidate`
method will be called on each :class:`_engine.Connection` object
that is currently in use for a transaction (typically there is only
one connection unless the :class:`_orm.Session` is used with
multiple engines).

This can be called when the database is known to be in a state where
the connections are no longer safe to be used.

Below illustrates a scenario when using `gevent
<https://www.gevent.org/>`_, which can produce ``Timeout`` exceptions
that may mean the underlying connection should be discarded::

    import gevent

    try:
        sess = Session()
        sess.add(User())
        sess.commit()
    except gevent.Timeout:
        sess.invalidate()
        raise
    except:
        sess.rollback()
        raise

The method additionally does everything that :meth:`_orm.Session.close`
does, including that all ORM objects are expunged.

Tr  Nr  r   s    r   r  Session.invalidate	  s    D 	D)r   c                   U(       d2  U R                   [        R                  L a  [        R                  U l         U R	                  5         U R
                  b3  U R
                  R                  5        H  nUR                  U5        M     g g r   )r  r  r   r   expunge_allr  r  r  )r   r  r  r  s       r   r  Session._close_impl
  sl    D--1C1J1JJ 2 9 9D(#00JJL!!*-  M )r   c                &   U R                   R                  5       [        U R                  5      -   nU R                   R	                  5         [
        R                  " 5       U l         0 U l        0 U l        [        R                  R                  X5        g)zRemove all object instances from this ``Session``.

This is equivalent to calling ``expunge(obj)`` on all objects in this
``Session``.

N)r  r  r   rw  _killr   r:  rx  r  r4   r  )r   r  s     r   r  Session.expunge_all 
  sj     &&113d499oE
!$557	--j?r   c                (    [        U5      n[        (       a  [        U[        5      (       d   e[        U[        5      (       a  X R
                  U'   g [        U5      (       a:  X R
                  UR                  '   UR                   H  nX R
                  U'   M     g [        R                  " SU-  5      e! [        R                   aG  n[        U[        5      (       d  [        R                  " SU-  5      UeX R
                  U'    S nAg S nAff = f)Nz!Not an acceptable bind target: %s)rB   r   r	  rC   rH   r)  r#   r   _all_tablesr   r9  NoInspectionAvailabletype)r   r  r  r  _selectableerrs         r   r>  Session._add_bind0
  s    	3<D }!$4444$,,%)T"%%,0T[[)#'#3#3K04LL- $4 **7#= % ++ 	)c4((**7#= %)S!	)s   B6 6D
=DDc                &    U R                  X5        g)aB  Associate a :class:`_orm.Mapper` or arbitrary Python class with a
"bind", e.g. an :class:`_engine.Engine` or
:class:`_engine.Connection`.

The given entity is added to a lookup used by the
:meth:`.Session.get_bind` method.

:param mapper: a :class:`_orm.Mapper` object,
 or an instance of a mapped
 class, or any Python class that is the base of a set of mapped
 classes.

:param bind: an :class:`_engine.Engine` or :class:`_engine.Connection`
            object.

.. seealso::

    :ref:`session_partitioning`

    :paramref:`.Session.binds`

    :meth:`.Session.bind_table`


Nr>  )r   r   r  s      r   r  Session.bind_mapperI
  s    8 	v$r   c                &    U R                  X5        g)a1  Associate a :class:`_schema.Table` with a "bind", e.g. an
:class:`_engine.Engine`
or :class:`_engine.Connection`.

The given :class:`_schema.Table` is added to a lookup used by the
:meth:`.Session.get_bind` method.

:param table: a :class:`_schema.Table` object,
 which is typically the target
 of an ORM mapping, or is present within a selectable that is
 mapped.

:param bind: an :class:`_engine.Engine` or :class:`_engine.Connection`
 object.

.. seealso::

    :ref:`session_partitioning`

    :paramref:`.Session.binds`

    :meth:`.Session.bind_mapper`


Nr  )r   tabler  s      r   
bind_tableSession.bind_tableg
  s    4 	u#r   )rz  r  r   _sa_skip_for_implicit_returningc                  U(       a  U$ U R                   (       d  U R                  (       a  U R                  $ Uc6  Uc3  U R                  (       a  U R                  $ [        R                  " S5      eUb   [	        U5      nOSnU R                   (       Ga  U(       aL  UR                  R                   H#  n	XR                   ;   d  M  U R                   U	   s  $    Uc  UR                  nUb  UR                  R                  SS5      n
U
bG  U
R                  R                  R                   H#  n	XR                   ;   d  M  U R                   U	   s  $    [         R"                  " U5       HE  nXR                   ;   d  M  [$        (       a  [        U[&        5      (       d   eU R                   U   s  $    U R                  (       a  U R                  $ / nUb  UR(                  " SU 35        Ub  UR(                  " S5        [        R                  " SSR+                  U5       S35      e! [        R
                   a2  n[        U[        5      (       a  [        R                  " U5      Uee SnAff = f)	a
  Return a "bind" to which this :class:`.Session` is bound.

The "bind" is usually an instance of :class:`_engine.Engine`,
except in the case where the :class:`.Session` has been
explicitly bound directly to a :class:`_engine.Connection`.

For a multiply-bound or unbound :class:`.Session`, the
``mapper`` or ``clause`` arguments are used to determine the
appropriate bind to return.

Note that the "mapper" argument is usually present
when :meth:`.Session.get_bind` is called via an ORM
operation such as a :meth:`.Session.query`, each
individual INSERT/UPDATE/DELETE operation within a
:meth:`.Session.flush`, call, etc.

The order of resolution is:

1. if mapper given and :paramref:`.Session.binds` is present,
   locate a bind based first on the mapper in use, then
   on the mapped class in use, then on any base classes that are
   present in the ``__mro__`` of the mapped class, from more specific
   superclasses to more general.
2. if clause given and ``Session.binds`` is present,
   locate a bind based on :class:`_schema.Table` objects
   found in the given clause present in ``Session.binds``.
3. if ``Session.binds`` is present, return that.
4. if clause given, attempt to return a bind
   linked to the :class:`_schema.MetaData` ultimately
   associated with the clause.
5. if mapper given, attempt to return a bind
   linked to the :class:`_schema.MetaData` ultimately
   associated with the :class:`_schema.Table` or other
   selectable to which the mapper is mapped.
6. No bind can be found, :exc:`~sqlalchemy.exc.UnboundExecutionError`
   is raised.

Note that the :meth:`.Session.get_bind` method can be overridden on
a user-defined subclass of :class:`.Session` to provide any kind
of bind resolution scheme.  See the example at
:ref:`session_custom_partitioning`.

:param mapper:
  Optional mapped class or corresponding :class:`_orm.Mapper` instance.
  The bind can be derived from a :class:`_orm.Mapper` first by
  consulting the "binds" map associated with this :class:`.Session`,
  and secondly by consulting the :class:`_schema.MetaData` associated
  with the :class:`_schema.Table` to which the :class:`_orm.Mapper` is
  mapped for a bind.

:param clause:
    A :class:`_expression.ClauseElement` (i.e.
    :func:`_expression.select`,
    :func:`_expression.text`,
    etc.).  If the ``mapper`` argument is not present or could not
    produce a bind, the given expression construct will be searched
    for a bound element, typically a :class:`_schema.Table`
    associated with
    bound :class:`_schema.MetaData`.

.. seealso::

     :ref:`session_partitioning`

     :paramref:`.Session.binds`

     :meth:`.Session.bind_mapper`

     :meth:`.Session.bind_table`

NzlThis session is not bound to a single Engine or Connection, and no context was provided to locate a binding.plugin_subjectzmapper zSQL expressionz&Could not locate a bind configured on , z or this Session.)r)  r  r   UnboundExecutionErrorrB   r  r	  r  r   UnmappedClassErrorr   __mro__persist_selectabler}  r  r   rI   iterater   rL   r   join)r   r   rz  r  r   r  r   inspected_mapperr  r   r  objr   s                r   r  Session.get_bind
  s    h K$)) 99
 >fnyyyy 22!  #*6?   $ <<<  +22::Cll*#||C00 ; >-@@F!!'!8!8!<!<$d" "--44;;CC,,.#'<<#44  D $++F3Cll*(=#-c5#9#99#9#||C00	 4 9999'NNW%5$678NN+,**4yy!""35
 	
] // fd++008cA	s   5H% %I+9-I&&I+c                    g r   r   )r   _entitys     r   r   Session.query"  s    <?r   c                    g r   r   )r   _colexprs     r   r   r  %  s     (+r   c                    g r   r   )r   _Session__ent0_Session__ent1s      r   r   r  /  s     .1r   c                    g r   r   )r   r  r  _Session__ent2s       r   r   r  4  s     36r   c                    g r   r   )r   r  r  r  _Session__ent3s        r   r   r  9  s     8;r   c                    g r   r   )r   r  r  r  r  _Session__ent4s         r   r   r  B  s     =@r   c                    g r   r   )r   r  r  r  r  r  _Session__ent5s          r   r   r  L  s	     BEr   c                    g r   r   )r   r  r  r  r  r  r  _Session__ent6s           r   r   r  W  s	     GJr   c	                    g r   r   )	r   r  r  r  r  r  r  r  _Session__ent7s	            r   r   r  c  s	     LOr   c                    g r   r   r   entitiesr  s      r   r   r  r  s     r   c                (    U R                   " X40 UD6$ )ag  Return a new :class:`_query.Query` object corresponding to this
:class:`_orm.Session`.

Note that the :class:`_query.Query` object is legacy as of
SQLAlchemy 2.0; the :func:`_sql.select` construct is now used
to construct ORM queries.

.. seealso::

    :ref:`unified_tutorial`

    :ref:`queryguide_toplevel`

    :ref:`query_api_toplevel` - legacy API doc

)r/  r  s      r   r   r  w  s    ( x888r   c                R    UR                  X#S9n[        R                  " XX5      n	U	$ )a  Locate an object in the identity map.

Given a primary key identity, constructs an identity key and then
looks in the session's identity map.  If present, the object may
be run through unexpiration rules (e.g. load unloaded attributes,
check if was deleted).

e.g.::

    obj = session._identity_lookup(inspect(SomeClass), (1,))

:param mapper: mapper in use
:param primary_key_identity: the primary key we are searching for, as
 a tuple.
:param identity_token: identity token that should be used to create
 the identity key.  Used as is, however overriding subclasses can
 repurpose this in order to interpret the value in a special way,
 such as if None then look among multiple target tokens.
:param passive: passive load flag passed to
 :func:`.loading.get_from_identity`, which impacts the behavior if
 the object is found; the object may be validated and/or unexpired
 if the flag allows for SQL to be emitted.
:param lazy_loaded_from: an :class:`.InstanceState` that is
 specifically asking for this identity as a related identity.  Used
 for sharding schemes where there is a correspondence between an object
 and a related object being lazy-loaded (or otherwise
 relationship-loaded).

:return: None if the object is not found in the identity map, *or*
 if the object was unexpired and found to have been deleted.
 if passive flags disallow SQL and the object is expired, returns
 PASSIVE_NO_RESULT.   In all other cases the instance is returned.

.. versionchanged:: 1.4.0 - the :meth:`.Session._identity_lookup`
   method was moved from :class:`_query.Query` to
   :class:`.Session`, to avoid having to instantiate the
   :class:`_query.Query` object.


)r   )identity_key_from_primary_keyr   get_from_identity)
r   r   primary_key_identityr   passiver<  r   r   r  return_values
             r   _identity_lookupSession._identity_lookup  s7    f 22  3 

 00sLr   c              #  ^   #    U R                   nSU l          U v   Xl         g! Xl         f = f7f)a  Return a context manager that disables autoflush.

e.g.::

    with session.no_autoflush:

        some_object = SomeClass()
        session.add(some_object)
        # won't autoflush
        some_object.related_thing = session.query(SomeRelated).first()

Operations that proceed within the ``with:`` block
will not be subject to flushes occurring upon query
access.  This is useful when initializing a series
of objects which involve existing database queries,
where the uncompleted object should not yet be flushed.

FN)r,  )r   r,  s     r   no_autoflushSession.no_autoflush  s+     * NN		'J&NYNs   -" -*-zThis warning originated from the Session 'autoflush' process, which was invoked automatically in response to a user-initiated operation. Consider using ``no_autoflush`` context manager if this warning happended while initializing objects.c                   U R                   (       a$  U R                  (       d   U R                  5         g g g ! [        R                   a=  nUR                  S5        UR                  [        R                  " 5       S   5      eS nAff = f)Nzraised as a result of Query-invoked autoflush; consider using a session.no_autoflush block if this flush is occurring prematurelyr9   )	r,  r  r  r   StatementError
add_detailr  r  r  )r   es     r   
_autoflushSession._autoflush  so     >>$..:

 #1> (( 
:
 5
 &&s||~a'899
:s   7 B8BBc                    [         R                  " U5      nU R                  XB5        U R                  5         U0 :X  a  [        R                  " S5      e[        R                  " U5      n[        R                  " [        U5      5      n[        R                  " U UUR                   UUUSSSS9	 c"  [        R"                  " S[%        U5      -  5      eg! [        R                   a  n[        R                  " U5      UeSnAff = f)aw  Expire and refresh attributes on the given instance.

The selected attributes will first be expired as they would when using
:meth:`_orm.Session.expire`; then a SELECT statement will be issued to
the database to refresh column-oriented attributes with the current
value available in the current transaction.

:func:`_orm.relationship` oriented attributes will also be immediately
loaded if they were already eagerly loaded on the object, using the
same eager loading strategy that they were loaded with originally.

.. versionadded:: 1.4 - the :meth:`_orm.Session.refresh` method
   can also refresh eagerly loaded attributes.

:func:`_orm.relationship` oriented attributes that would normally
load using the ``select`` (or "lazy") loader strategy will also
load **if they are named explicitly in the attribute_names
collection**, emitting a SELECT statement for the attribute using the
``immediate`` loader strategy.  If lazy-loaded relationships are not
named in :paramref:`_orm.Session.refresh.attribute_names`, then
they remain as "lazy loaded" attributes and are not implicitly
refreshed.

.. versionchanged:: 2.0.4  The :meth:`_orm.Session.refresh` method
   will now refresh lazy-loaded :func:`_orm.relationship` oriented
   attributes for those which are named explicitly in the
   :paramref:`_orm.Session.refresh.attribute_names` collection.

.. tip::

    While the :meth:`_orm.Session.refresh` method is capable of
    refreshing both column and relationship oriented attributes, its
    primary focus is on refreshing of local column-oriented attributes
    on a single instance. For more open ended "refresh" functionality,
    including the ability to refresh the attributes on many objects at
    once while having explicit control over relationship loader
    strategies, use the
    :ref:`populate existing <orm_queryguide_populate_existing>` feature
    instead.

Note that a highly isolated transaction will return the same values as
were previously read in that same transaction, regardless of changes
in database state outside of that transaction.   Refreshing
attributes usually only makes sense at the start of a transaction
where database rows have not yet been accessed.

:param attribute_names: optional.  An iterable collection of
  string attribute names indicating a subset of attributes to
  be refreshed.

:param with_for_update: optional boolean ``True`` indicating FOR UPDATE
  should be used, or may be a dictionary containing flags to
  indicate a more specific set of FOR UPDATE flags for the SELECT;
  flags should match the parameters of
  :meth:`_query.Query.with_for_update`.
  Supersedes the :paramref:`.Session.refresh.lockmode` parameter.

.. seealso::

    :ref:`session_expire` - introductory material

    :meth:`.Session.expire`

    :meth:`.Session.expire_all`

    :ref:`orm_queryguide_populate_existing` - allows any ORM query
    to refresh objects as they would be loaded normally.

Nzqwith_for_update should be the boolean value True, or a dictionary with options.  A blank dictionary is ambiguous.T)refresh_statewith_for_updateonly_load_propsrequire_pk_colsr  is_user_refreshzCould not refresh instance '%s')r   instance_stater   NO_STATEUnmappedInstanceError_expire_stater  r   r9  rM   _from_argumentr;   selectr,   r   load_on_identr  r   r*   )r   r   attribute_namesr  r!   r  stmts          r   refreshSession.refresh  s   V	?--h7E 	52 	b &&3  '55oFJJ}X'>?!!		# / / $ " $   ,,1L4JJ !1 || 	?++H53>	?s   C D)D  Dc                    U R                   R                  5        H3  nUR                  UR                  U R                   R                  5        M5     g)a"  Expires all persistent instances within this Session.

When any attributes on a persistent instance is next accessed,
a query will be issued using the
:class:`.Session` object's current transactional context in order to
load all expired attributes for the given instance.   Note that
a highly isolated transaction will return the same values as were
previously read in that same transaction, regardless of changes
in database state outside of that transaction.

To expire individual objects and individual attributes
on those objects, use :meth:`Session.expire`.

The :class:`.Session` object's default behavior is to
expire all state whenever the :meth:`Session.rollback`
or :meth:`Session.commit` methods are called, so that new
state can be loaded for the new transaction.   For this reason,
calling :meth:`Session.expire_all` is not usually needed,
assuming the transaction is isolated.

.. seealso::

    :ref:`session_expire` - introductory material

    :meth:`.Session.expire`

    :meth:`.Session.refresh`

    :meth:`_orm.Query.populate_existing`

N)r  r  r  r   r  r   r!   s     r   
expire_allSession.expire_allt  s<    @ &&113EMM%**d&7&7&A&AB 4r   c                     [         R                  " U5      nU R                  X25        g! [        R                   a  n[        R                  " U5      UeSnAff = f)a  Expire the attributes on an instance.

Marks the attributes of an instance as out of date. When an expired
attribute is next accessed, a query will be issued to the
:class:`.Session` object's current transactional context in order to
load all expired attributes for the given instance.   Note that
a highly isolated transaction will return the same values as were
previously read in that same transaction, regardless of changes
in database state outside of that transaction.

To expire all objects in the :class:`.Session` simultaneously,
use :meth:`Session.expire_all`.

The :class:`.Session` object's default behavior is to
expire all state whenever the :meth:`Session.rollback`
or :meth:`Session.commit` methods are called, so that new
state can be loaded for the new transaction.   For this reason,
calling :meth:`Session.expire` only makes sense for the specific
case that a non-ORM SQL statement was emitted in the current
transaction.

:param instance: The instance to be refreshed.
:param attribute_names: optional list of string attribute names
  indicating a subset of attributes to be expired.

.. seealso::

    :ref:`session_expire` - introductory material

    :meth:`.Session.expire`

    :meth:`.Session.refresh`

    :meth:`_orm.Query.populate_existing`

N)r   r  r   r  r  r  )r   r   r   r!   r  s        r   expireSession.expire  sQ    N	?--h7E 	52 || 	?++H53>	?s   * AAAc                (   U R                  U5        U(       a  UR                  UR                  U5        g [        UR                  R
                  R                  SU5      5      nU R                  U5        U H  u  pEpgU R                  U5        M     g )Nzrefresh-expire)_validate_persistent_expire_attributesr   r   managerr   cascade_iterator_conditional_expire)r   r!   r   cascadedomst_dct_s           r   r  Session._expire_state  s|    
 	!!%($$UZZA $$556FNH $$U+#+c((- $,r   c                    UR                   (       a1  UR                  UR                  U R                  R                  5        gXR
                  ;   a-  U R
                  R                  U5        UR                  U 5        gg)z5Expire a state if persistent, else expunge if pendingN)r  r  r   r  r  rw  rm  _detach)r   r!   r,  s      r   r  Session._conditional_expire  sT    
 99MM%**d&7&7&A&ABiiIIMM% MM$  r   c                    [         R                  " U5      nUR
                  U R                  La"  [        R                  " S[        U5      -  5      e[        UR                  R                  R                  SU5      5      nU R                  U/U VVVVs/ s H  u  pVpxUPM
     snnnn-   5        g! [        R                   a  n[        R                  " U5      UeSnAff = fs  snnnnf )zRemove the `instance` from this ``Session``.

This will free all internal references to the instance.  Cascading
will be applied according to the *expunge* cascade rule.

Nz*Instance %s is not present in this Sessionexpunge)r   r  r   r  r  
session_idr+  r   r   r/   r   r  r   r  r  )	r   r   r!   r  r  r  r  r  r  s	            r   r  Session.expunge  s    	?--h7E 4==0,,<y?OO  MM  11)UC
 	eW8'L8c8'LLM || 	?++H53>	? (Ms   B2 C%2C"CC"c                   U H  nX0R                   ;   a  U R                   R                  U5        M/  U R                  R                  U5      (       a9  U R                  R	                  U5        U R
                  R                  US 5        M  U R                  (       d  M  U R                  R
                  R                  US 5        M     [        R                  R                  XUS9  g )Nr  )
rw  rm  r  contains_stater  rx  r  r  r4   r  )r   statesr  r!   s       r   r  Session._expunge_states  s     E		!		e$""11%88!!..u5!!%.""" !!**..ud;  	--| 	. 	
r   c                   U R                   R                  =(       d    SnU GH  n[        U5      nUR                  5       nUc  M$  UR	                  U5      n[
        R                  " US   5      (       a  UR                  (       a  [
        R                  " US   5      (       a"  [        R                  " S[        U5      -  5      eUR                  c  Xcl        OUR                  U:w  aq  U R                  R                  U5        U R                  nUc   eX7R                   ;   a  UR                   U   S   nOUR                  nUU4UR                   U'   Xcl        U R                  R#                  U5      n	U	bA  UR	                  U	5      U:X  a,  U	R                  5       b  [$        R&                  " SU< S35        SUl        GM     [*        R,                  R/                  S U 5       U R                  5        U R1                  U5        Ub*  UR                  U R2                  5       H  nU" X5        M     [5        U5      R                  U R2                  5       H  nU R2                  R7                  U5        M      g)	zRegister all persistent objects from a flush.

This is used both for pending objects moving to the persistent
state as well as already persistent objects.

Nr   aO  Instance %s has a NULL identity key.  If this is an auto-generated value, check that the database table allows generation of new primary key values, and that the mapped Column object is configured to expect these generated values.  Ensure also that this flush() is not occurring at an inappropriate time, such as within a load() event.r   z)Identity map already had an identity for z|, replacing it with newly flushed object.   Are there load operations occurring inside of an event handler within the flush?Fc              3  <   #    U  H  oUR                   4v   M     g 7fr   )r   ).0r!   s     r   	<genexpr>/Session._register_persistent.<locals>.<genexpr>M  s     5fUUZZ fs   )r  pending_to_persistentr)   r  _identity_key_from_stater(   intersectionallow_partial_pks
issupersetr   r  r/   r  r  r  r  rz  r  r<   r  _orphaned_outside_of_sessionr  r4   _commit_all_states_register_alteredrw  r
  rm  )
r   r   r'  r!   r   r  instance_keyr  orig_keyolds
             r   _register_persistentSession._register_persistent  s&    !% C C KtE"5)F ))+C%>>uE **<?;;"44 ++LO<<..? $E*+	 	 99$ ,IYY,. %%2259 --E ,,, 3 33#(#6#6u#=a#@#(99 $2E''. !-I
 ''//6O77<L	-II 0<> 6;2u x 	115f5t7H7H	
 	v& ,,,TYY7%d2 8 [--dii8EIIMM%  9r   c                    U R                   (       aM  U HF  nX R                  ;   a  SU R                   R                  U'   M-  SU R                   R                  U'   MH     g g NT)r  rw  ry  )r   r   r!   s      r   r.  Session._register_alteredZ  sP    II%48D%%**516:D%%,,U3	   r   c                d   U R                   R                  =(       d    S nU H  nU R                  (       a  SU R                  R                  U'   Ub  UR	                  5       nU R
                  R                  U5        U R                  R                  US 5        SUl        Uc  M  U" X5        M     g r5  )r  persistent_to_deletedr  rx  r  r  r  rm  )r   r   r8  r!   r  s        r   _remove_newly_deletedSession._remove_newly_deletedb  s     !% C C KtE  48!!**51$0 iik**51MMeT*!EN %0%d2! r   c                   U(       a"  U R                   (       a  U R                  S5         [        R                  " U5      nU R                  U5        g! [        R
                   a  n[        R                  " U5      UeSnAff = f)a  Place an object into this :class:`_orm.Session`.

Objects that are in the :term:`transient` state when passed to the
:meth:`_orm.Session.add` method will move to the
:term:`pending` state, until the next flush, at which point they
will move to the :term:`persistent` state.

Objects that are in the :term:`detached` state when passed to the
:meth:`_orm.Session.add` method will move to the :term:`persistent`
state directly.

If the transaction used by the :class:`_orm.Session` is rolled back,
objects which were transient when they were passed to
:meth:`_orm.Session.add` will be moved back to the
:term:`transient` state, and will no longer be present within this
:class:`_orm.Session`.

.. seealso::

    :meth:`_orm.Session.add_all`

    :ref:`session_adding` - at :ref:`session_basics`

zSession.add()N)r*  _flush_warningr   r  r   r  r  _save_or_update_state)r   r   _warnr!   r  s        r   r  Session.addx  sk    2 T))0	?--h7E 	""5) || 	?++H53>	?s   A B'A>>Bc                z    U R                   (       a  U R                  S5        U H  nU R                  USS9  M     g)a  Add the given collection of instances to this :class:`_orm.Session`.

See the documentation for :meth:`_orm.Session.add` for a general
behavioral description.

.. seealso::

    :meth:`_orm.Session.add`

    :ref:`session_adding` - at :ref:`session_basics`

zSession.add_all()F)r>  N)r*  r<  r  )r   	instancesr   s      r   add_allSession.add_all  s6      34!HHHXUH+ "r   c                    SUl         U R                  U5        [        U5      nUR                  SXR                  S9 H  u  p4pVU R                  U5        M     g )NFzsave-update)halt_on)r,  _save_or_update_implr)   r  _contains_state)r   r!   r   r  r  r  r  s          r   r=  Session._save_or_update_state  s[    -2*!!%(u%%665*>*>  7  
OA# %%c* 
r   c                    U R                   (       a  U R                  S5         [        R                  " U5      nU R                  X!SS9  g! [        R
                   a  n[        R                  " U5      UeSnAff = f)a  Mark an instance as deleted.

The object is assumed to be either :term:`persistent` or
:term:`detached` when passed; after the method is called, the
object will remain in the :term:`persistent` state until the next
flush proceeds.  During this time, the object will also be a member
of the :attr:`_orm.Session.deleted` collection.

When the next flush proceeds, the object will move to the
:term:`deleted` state, indicating a ``DELETE`` statement was emitted
for its row within the current transaction.   When the transaction
is successfully committed,
the deleted object is moved to the :term:`detached` state and is
no longer present within this :class:`_orm.Session`.

.. seealso::

    :ref:`session_deleting` - at :ref:`session_basics`

zSession.delete()NT)head)r*  r<  r   r  r   r  r  _delete_implr   r   r!   r  s       r   deleteSession.delete  so    *  23	?--h7E 	%5 || 	?++H53>	?s   A A;A66A;c                   UR                   c*  U(       a"  [        R                  " S[        U5      -  5      eg U R	                  X5      nXR
                  ;   a  g U R                  R                  U5        U(       a  U R                  X5        U(       a0  [        UR                  R                  R                  SU5      5      nOS nX R
                  U'   U(       a/  [        (       a  Uc   eU H  u  pgpU R                  XS5        M     g g )NInstance '%s' is not persistedrM  F)r  r   r   r/   _before_attachrx  r  r  _after_attachr   r  r   r  r   rK  )
r   r!   r  rJ  	to_attachcascade_statesr  r  r  r  s
             r   rK  Session._delete_impl  s     99004y7GG  ''3	MM!e$u* "$$55hFN "N"e}%111#1c!!#%0 $2 r   optionspopulate_existingr  r   r   r   c               L    U R                  UU[        R                  UUUUUUS9	$ )a  Return an instance based on the given primary key identifier,
or ``None`` if not found.

E.g.::

    my_user = session.get(User, 5)

    some_object = session.get(VersionedFoo, (5, 10))

    some_object = session.get(VersionedFoo, {"id": 5, "version_id": 10})

.. versionadded:: 1.4 Added :meth:`_orm.Session.get`, which is moved
   from the now legacy :meth:`_orm.Query.get` method.

:meth:`_orm.Session.get` is special in that it provides direct
access to the identity map of the :class:`.Session`.
If the given primary key identifier is present
in the local identity map, the object is returned
directly from this collection and no SQL is emitted,
unless the object has been marked fully expired.
If not present,
a SELECT is performed in order to locate the object.

:meth:`_orm.Session.get` also will perform a check if
the object is present in the identity map and
marked as expired - a SELECT
is emitted to refresh the object as well as to
ensure that the row is still present.
If not, :class:`~sqlalchemy.orm.exc.ObjectDeletedError` is raised.

:param entity: a mapped class or :class:`.Mapper` indicating the
 type of entity to be loaded.

:param ident: A scalar, tuple, or dictionary representing the
 primary key.  For a composite (e.g. multiple column) primary key,
 a tuple or dictionary should be passed.

 For a single-column primary key, the scalar calling form is typically
 the most expedient.  If the primary key of a row is the value "5",
 the call looks like::

    my_object = session.get(SomeClass, 5)

 The tuple form contains primary key values typically in
 the order in which they correspond to the mapped
 :class:`_schema.Table`
 object's primary key columns, or if the
 :paramref:`_orm.Mapper.primary_key` configuration parameter were
 used, in
 the order used for that parameter. For example, if the primary key
 of a row is represented by the integer
 digits "5, 10" the call would look like::

     my_object = session.get(SomeClass, (5, 10))

 The dictionary form should include as keys the mapped attribute names
 corresponding to each element of the primary key.  If the mapped class
 has the attributes ``id``, ``version_id`` as the attributes which
 store the object's primary key value, the call would look like::

    my_object = session.get(SomeClass, {"id": 5, "version_id": 10})

:param options: optional sequence of loader options which will be
 applied to the query, if one is emitted.

:param populate_existing: causes the method to unconditionally emit
 a SQL query and refresh the object with the newly loaded data,
 regardless of whether or not the object is already present.

:param with_for_update: optional boolean ``True`` indicating FOR UPDATE
  should be used, or may be a dictionary containing flags to
  indicate a more specific set of FOR UPDATE flags for the SELECT;
  flags should match the parameters of
  :meth:`_query.Query.with_for_update`.
  Supersedes the :paramref:`.Session.refresh.lockmode` parameter.

:param execution_options: optional dictionary of execution options,
 which will be associated with the query execution if one is emitted.
 This dictionary can provide a subset of the options that are
 accepted by :meth:`_engine.Connection.execution_options`, and may
 also provide additional options understood only in an ORM context.

 .. versionadded:: 1.4.29

 .. seealso::

    :ref:`orm_queryguide_execution_options` - ORM-specific execution
    options

:param bind_arguments: dictionary of additional arguments to determine
 the bind.  May include "mapper", "bind", or other custom arguments.
 Contents of this dictionary are passed to the
 :meth:`.Session.get_bind` method.

 .. versionadded: 2.0.0rc1

:return: The object instance, or ``None``.

rV  )	_get_implr   load_on_pk_identity)	r   r  r   rW  rX  r  r   r   r   s	            r   r  Session.get  s<    ^ ~~''/+)/)  

 
	
r   c               d    U R                  UUUUUUUUS9n	U	c  [        R                  " S5      eU	$ )a  Return exactly one instance based on the given primary key
identifier, or raise an exception if not found.

Raises :class:`_exc.NoResultFound` if the query selects no rows.

For a detailed documentation of the arguments see the
method :meth:`.Session.get`.

.. versionadded:: 2.0.22

:return: The object instance.

.. seealso::

    :meth:`.Session.get` - equivalent method that instead
      returns ``None`` if no row was found with the provided primary
      key

rV  z&No row was found when one was required)r  r   NoResultFound)
r   r  r   rW  rX  r  r   r   r   r   s
             r   get_oneSession.get_onez  sU    @ 88/+)/)  	
 &&8  r   c          
       ^ [        T5      (       aA  [        T5      [        R                  ;   a$  [        R                  [        T5         n
U
" T5      m[	        U5      nUb  UR
                  (       d  [        R                  " SU-  5      e[        T[        5      nU(       d  [        R                  " TS /S9m[        T5      [        UR                  5      :w  a9  [        R                  " SSR                  S UR                   5       5      -  5      eU(       ar  UR                   nU(       a?  [#        U5      R%                  T5      nU(       a  [        T5      mU H  nTU   TX   '   M      ['        U4S jUR(                   5       5      mU(       d]  UR,                  (       dL  UcI  U R/                  UTUUU	S	9nUb  [        UUR0                  5      (       d  g U$ U[2        R4                  Ld   e[6        R8                  R:                  nU(       a  US
U0-  n[<        R>                  " U5      RA                  [B        5      nUb  [D        RF                  " U5      Ul$        U(       a  URJ                  " U6 nU" U UTUUUU	S9$ ! [*         a?  n[        R                  " SSR                  S UR(                   5       5      -  5      UeS nAff = f)Nz(Expected mapped class or mapper, got: %r)defaultzoIncorrect number of values in identifier to formulate primary key for session.get(); primary key columns are %s,c              3  ,   #    U  H
  nS U-  v   M     g7fz'%s'Nr   )r$  cs     r   r%  $Session._get_impl.<locals>.<genexpr>  s     #K8J1FQJ8Js   c              3  B   >#    U  H  nTUR                      v   M     g 7fr   r  )r$  propr  s     r   r%  rg    s!      , : )2 :s   zIncorrect names of values in identifier to formulate primary key for session.get(); primary key attribute names are %s (synonym names are also accepted)c              3  @   #    U  H  nS UR                   -  v   M     g7fre  ri  )r$  rj  s     r   r%  rg    s       $>D )$>s   )r   r   r   _populate_existing)r:  r   r   r   )&r$   r  r   _composite_gettersrB   	is_mapperr   r9  r	  r   r<   to_listr   primary_keyr   r  _pk_synonymsr
  r)  r   _identity_key_propsKeyErroralways_refreshr  r   r+   PASSIVE_CLASS_MISMATCHr   rM  rN  r;   r  set_label_stylerN   rM   r  _for_update_argrW  )r   r  r  
db_load_fnrW  rX  r  r   r   r   getterr   is_dictpk_synonymscorrect_keyskr  r   r:  r   s     `                 r   rZ  Session._get_impl  s    344)*223 &88)*F $**>#? '.v>!1!1&&:VC  148#'<<$tf$  #$F,>,>(??,,88#K8J8J#KKL   --K";/<<(   +/0D+E()03 -[^< *
'+ , & : :, ($" "))',,$-"3- - H # "(FMM:: #7#N#NNNN ++@@13DEELJJv&66*
	 &(4(C(C)I% !))73I %)/)
 	
i  	00E hh $*$>$>  	s   -J 
K
:KK
)loadrW  c          	     T   U R                   (       a  U R                  S5        0 n0 nU(       a  U R                  5         [        U5        U R                  n SU l        U R                  [        R                  " U5      [        R                  " U5      UUUUS9X`l        $ ! X`l        f = f)a	  Copy the state of a given instance into a corresponding instance
within this :class:`.Session`.

:meth:`.Session.merge` examines the primary key attributes of the
source instance, and attempts to reconcile it with an instance of the
same primary key in the session.   If not found locally, it attempts
to load the object from the database based on primary key, and if
none can be located, creates a new instance.  The state of each
attribute on the source instance is then copied to the target
instance.  The resulting target instance is then returned by the
method; the original source instance is left unmodified, and
un-associated with the :class:`.Session` if not already.

This operation cascades to associated instances if the association is
mapped with ``cascade="merge"``.

See :ref:`unitofwork_merging` for a detailed discussion of merging.

:param instance: Instance to be merged.
:param load: Boolean, when False, :meth:`.merge` switches into
 a "high performance" mode which causes it to forego emitting history
 events as well as all database access.  This flag is used for
 cases such as transferring graphs of objects into a :class:`.Session`
 from a second level cache, or to transfer just-loaded objects
 into the :class:`.Session` owned by a worker thread or process
 without re-querying the database.

 The ``load=False`` use case adds the caveat that the given
 object has to be in a "clean" state, that is, has no pending changes
 to be flushed - even if the incoming object is detached from any
 :class:`.Session`.   This is so that when
 the merge operation populates local attributes and
 cascades to related objects and
 collections, the values can be "stamped" onto the
 target object as is, without generating any history or attribute
 events, and without the need to reconcile the incoming data with
 any existing related objects or collections that might not
 be loaded.  The resulting objects from ``load=False`` are always
 produced as "clean", so it is only appropriate that the given objects
 should be "clean" as well, else this suggests a mis-use of the
 method.
:param options: optional sequence of loader options which will be
 applied to the :meth:`_orm.Session.get` method when the merge
 operation loads the existing version of the object from the database.

 .. versionadded:: 1.4.24


.. seealso::

    :func:`.make_transient_to_detached` - provides for an alternative
    means of "merging" a single object into the :class:`.Session`

zSession.merge()F)r  rW  
_recursive_resolve_conflict_map)	r*  r<  r  r,   r,  _merger   r  instance_dict)r   r   r  rW  r  r  r,  s          r   mergeSession.merge+  s    |  1279
EGOOhNN		'"DN;;))(3((2%&;   'NYNs   AB B')rW  c                  [        U5      nX;   a  [        [        XQ   5      $ SnUR                  n	U	c  XR                  ;   a"  [
        R                  " S[        U5      -  5        U(       d  [        R                  " S5      eUR                  U5      n	[        R                  U	S   ;  =(       aV    [        R                  " U	S   5      (       + =(       d1    UR                  =(       a    [        R                   " U	S   5      (       + n
OSn
U R"                  R%                  U	5      nUc  U
(       a  X;   a  [        [        Xi   5      nOU(       dq  UR&                  (       a  [        R                  " S5      eUR(                  R+                  5       n[,        R.                  " U5      nXl        U R1                  U5        SnO)U
(       a"  U R%                  UR2                  U	S   U	S   US9nUcZ  UR(                  R+                  5       n[,        R.                  " U5      n[,        R4                  " U5      nSnU R7                  U5        O,[,        R.                  " U5      n[,        R4                  " U5      nXU'   XU	'   XLGa  UR8                  b  UR;                  UUUR8                  [<        R>                  S	9nUR;                  UUUR8                  [<        R>                  S	9nU[        R@                  LaD  U[        R@                  La1  X:w  a,  [B        RD                  " S
U< S[        U5      < SU< S35      eURF                  Ul#        URH                  Ul$        URK                  U5        URL                   H  nURO                  U UUUUUUU5        M     U(       dA  URQ                  XR"                  5        URR                  RT                  RW                  US 5        U(       a&  URR                  RT                  RY                  US 5        U$ )NFzrInstance %s is already pending in this Session yet is being merged again; this is probably not what you want to dozmerge() with load=False option does not support objects transient (i.e. unpersisted) objects.  flush() all changes on mapped instances before merging with load=False.r   Tzmerge() with load=False option does not support objects marked as 'dirty'.  flush() all changes on mapped instances before merging with load=False.r9   )r   rW  r  zVersion id 'z' on merged state z" does not match existing version 'zT'. Leave the version attribute unset when merging to update the most recent version.)-r)   r   r"   r  rw  r<   r  r/   r   r   r(  r+   	NEVER_SETr(   r)  r*  r+  r  r  r  class_managernew_instancer   r  r  r   r  r=  version_id_col_get_state_attr_by_columnr.   PASSIVE_NO_INITIALIZEPASSIVE_NO_RESULTr   StaleDataError	load_pathr:  _copy_callablesiterate_propertiesr  _commit_allr  r  _sa_event_merge_wo_loadr  )r   r!   
state_dictrW  r  r  r  r   r  r  key_is_persistentmergedmerged_statemerged_dictexisting_versionmerged_versionrj  s                    r   r  Session._merge  s    +51J-..ii ;		!		'./ 00"  11%8C 4 > >cG ! ! **3q622 ,, 9%00Q88  !%""&&s+> S%Ab"7"<=>> 44K 
  --::<)88@#& !!,/#"MMF#&q6#	 "  >))668F%44V<L$226:KL&&|4%44V<L$226:K"5%+c" $$$0#)#C#C))'==	 $D $  "(!A!A ))'==	 "B " %/AAB&/AAB(:,, -%l3*
 
 &+__L"(-(:(:L% ((/11

 )	 2 $$[2C2CD  ))AAd   ))..|TBr   c                    U R                   R                  U5      (       d"  [        R                  " S[	        U5      -  5      eg )Nz3Instance '%s' is not persistent within this Session)r  r  r   r   r/   r  s     r   r  Session._validate_persistent!  sA      //66,,EE"#  7r   c                D   UR                   b"  [        R                  " S[        U5      -  5      eUR	                  5       nU R                  X5      nXR                  ;  a(  X R                  U'   [        U R                  5      Ul        U(       a  U R                  X5        g g )NzGObject '%s' already has an identity - it can't be registered as pending)
r  r   r   r/   r  rQ  rw  r   insert_orderrR  )r   r!   r  rS  s       r   
_save_implSession._save_impl(  s    99 ,,46?6FG 
 iik''3			!"IIe!$TYYEu* r   c                v   UR                   c"  [        R                  " S[        U5      -  5      eUR                  (       a>  U(       a  UR
                  (       d  g U?O"[        R                  " S[        U5      -  5      eUR                  5       nUc  g U R                  X5      nU R                  R                  US 5        U(       a  U R                  R                  U5        OU R                  R                  U5        U(       a  U R                  X5        g U(       a  U R                  R                  X5        g g )NrP  zsInstance '%s' has been deleted.  Use the make_transient() function to send this object back to the transient state.)r  r   r   r/   rx  	_attachedr  rQ  rm  r  r  r  rR  r  deleted_to_persistent)r   r!   r  r  rS  s        r   r  Session._update_impl7  s    99,,09U3CC  >>N00. 1:%0@A  iik ;''3	%&%%e,!!%(u*MM//< r   c                d    UR                   c  U R                  U5        g U R                  U5        g r   )r  r  r  r  s     r   rF  Session._save_or_update_impl_  s&    99OOE"e$r   c                     [         R                  " U5      nU R                  X!5      nSUl        U(       a  U R                  X!5        gg! [        R                   a  n[        R                  " U5      UeSnAff = f)a  Associate an object with this :class:`.Session` for related
object loading.

.. warning::

    :meth:`.enable_relationship_loading` exists to serve special
    use cases and is not recommended for general use.

Accesses of attributes mapped with :func:`_orm.relationship`
will attempt to load a value from the database using this
:class:`.Session` as the source of connectivity.  The values
will be loaded based on foreign key and primary key values
present on this object - if not present, then those relationships
will be unavailable.

The object will be attached to this session, but will
**not** participate in any persistence operations; its state
for almost all purposes will remain either "transient" or
"detached", except for the case of relationship loading.

Also note that backrefs will often not work as expected.
Altering a relationship-bound attribute on the target object
may not fire off a backref event, if the effective value
is what was already loaded from a foreign-key-holding value.

The :meth:`.Session.enable_relationship_loading` method is
similar to the ``load_on_pending`` flag on :func:`_orm.relationship`.
Unlike that flag, :meth:`.Session.enable_relationship_loading` allows
an object to remain transient while still being able to load
related items.

To make a transient object associated with a :class:`.Session`
via :meth:`.Session.enable_relationship_loading` pending, add
it to the :class:`.Session` using :meth:`.Session.add` normally.
If the object instead represents an existing identity in the database,
it should be merged using :meth:`.Session.merge`.

:meth:`.Session.enable_relationship_loading` does not improve
behavior when the ORM is used normally - object references should be
constructed at the object level, not at the foreign key level, so
that they are present in an ordinary way before flush()
proceeds.  This method is not intended for general use.

.. seealso::

    :paramref:`_orm.relationship.load_on_pending` - this flag
    allows per-relationship loading of many-to-ones on items that
    are pending.

    :func:`.make_transient_to_detached` - allows for an object to
    be added to a :class:`.Session` without SQL emitted, which then
    will unexpire attributes on access.

NT)r   r  r   r  r  rQ  _load_pendingrR  )r   r  r!   r  rS  s        r   enable_relationship_loading#Session.enable_relationship_loadinge  sq    n	:--c2E ''3	"u*  || 	:++C0c9	:s   A
 
A:A55A:c           	     Z   U R                  5         UR                  U R                  :X  a  gUR                  (       aT  UR                  [        ;   a@  [        R
                  " S[        U5      < SUR                  < SU R                  < S35      eU R                  R                  X5        g)NFzObject 'z"' is already attached to session 'z' (this is 'z')T)	r^  r  r+  r   r   r   r/   r  before_attachr   r!   r  s      r   rQ  Session._before_attach  s    t}}, 0 0I =,, U#U%5%5t}}F  	##D0r   c                4   U R                   Ul        UR                  (       a  UR                  c  X!l        U R                  R                  X5        UR                  (       a  U R                  R                  X5        g U R                  R                  X5        g r   )	r+  r  r  _strong_objr  after_attachr  detached_to_persistenttransient_to_pendingr  s      r   rR  Session._after_attach  sc    ==>>e//7 #""4/99MM00=MM..t;r   c                     [         R                  " U5      nU R                  U5      $ ! [        R                   a  n[        R                  " U5      UeSnAff = f)zReturn True if the instance is associated with this session.

The instance may be pending or persistent within the Session for a
result of True.

N)r   r  r   r  r  rG  rL  s       r   __contains__Session.__contains__  sS    	?--h7E ##E** || 	?++H53>	?s   ) AAAc                    [        [        U R                  R                  5       5      [        U R                  R                  5       5      -   5      $ )zGIterate over all pending or persistent instances within this
Session.

)iterr   rw  r  r  r   s    r   __iter__Session.__iter__  s?    
 !!#$tD,=,=,D,D,F'GG
 	
r   c                b    XR                   ;   =(       d    U R                  R                  U5      $ r   )rw  r  r  r  s     r   rG  Session._contains_state  s%    		!LT%6%6%E%Ee%LLr   c                    U R                   (       a  [        R                  " S5      eU R                  5       (       a  g SU l         U R	                  U5        SU l         g! SU l         f = f)au  Flush all the object changes to the database.

Writes out all pending object creations, deletions and modifications
to the database as INSERTs, DELETEs, UPDATEs, etc.  Operations are
automatically ordered by the Session's unit of work dependency
solver.

Database operations will be issued in the current transactional
context and do not affect the state of the transaction, unless an
error occurs, in which case the entire transaction is rolled back.
You may flush() as often as you like within a transaction to move
changes from Python to the database's transaction buffer.

:param objects: Optional; restricts the flush operation to operate
  only on elements that are in the given collection.

  This feature is for an extremely narrow set of use cases where
  particular objects may need to be operated upon before the
  full flush() occurs.  It is not intended for general use.

zSession is already flushingNTF)r  r   r   r  _flush)r   objectss     r   r  Session.flush  sT    . >>,,-JKK>>	#!DNKK "DNUDNs   A 	A(c                6    [         R                  " SU-  5        g )NzUsage of the '%s' operation is not currently supported within the execution stage of the flush process. Results may not be consistent.  Consider using alternative event listeners or connection-level operations instead.)r<   r  )r   methods     r   r<  Session._flush_warning  s!    		F IOO	
r   c                    U R                   R                  5       (       + =(       a)    U R                  (       + =(       a    U R                  (       + $ r   )r  check_modifiedrx  rw  r   s    r   r  Session._is_clean  s9    !!0022 MM!II	
r   c                   U R                   nU(       dG  U R                  (       d6  U R                  (       d%  U R                  R                  R                  5         g [        U 5      nU R                  R                  (       a(  U R                  R                  XU5        U R                   n[        U R                  5      n[        U R                  5      n[        U5      R                  U5      nU(       a<  [        5       nU H+  n [        R                  " U5      nUR!                  U5        M-     OS n[        5       n
U(       a0  UR#                  U5      R%                  U5      R                  U5      nO UR#                  U5      R                  U5      nU H  n['        U5      R)                  U5      nU=(       a    UR*                  nU(       a,  U(       d%  UR,                  (       a  U R/                  U/5        Me  UR1                  XS9nU(       d   S5       eU
R!                  U5        M     U(       a!  UR%                  U5      R                  U
5      nOUR                  U
5      nU H!  nUR1                  USS9nU(       a  M   S5       e   UR2                  (       d  g U R5                  5       R7                  5       =Ul        n SU l         UR=                  5         SU l        U R                  R?                  X5        URA                  5         U(       d  U R                  R                  (       a  [C        U R                  R                  5      n[D        RF                  RI                  U R                  R                   Vs/ s H  nXRJ                  4PM     snU R                  S9  [L        RN                  " SU-  5        U R                  RQ                  X5        URS                  5         g ! [        R                   a  n	[        R                  " U5      U	eS n	A	ff = f! SU l        f = fs  snf !   [L        RT                  " 5          URW                  SS9  S S S 5         g ! , (       d  f        g = f= f)N)isdeletez*Failed to add object to the flush context!TF)r  zAttribute history events accumulated on %d previously clean instances within inner-flush event handlers have been reset, and will not result in database updates. Consider using set_committed_value() within inner-flush event handlers to avoid this warning.r  ),_dirty_statesrx  rw  r  r  r  r8   r  before_flushr
  
differencer   r  r   r  r  r  r   r)  r)   
_is_orphanhas_identityr,  r  register_objecthas_workr^  r  r  r*  r  after_flushfinalize_flush_changesr   r  r4   r-  r   r<   r  after_flush_postexecr  r  r  )r   r  dirtyflush_contextdeletednewobjsetr  r!   r  	processedproc	is_orphanis_persistent_orphan_regr  len_s                    r   r  Session._flush  s   ""T]]499''--/&t,==%%MM&&tGD &&Edmm$$))nE
%%g. UF@&55a8E 

5!  F E	 99U#008CCGLD99U#..w7DE%e,77>I#,#C1C1C  ,66$$eW-$44 5  IIIte$! & ''/::9ED%%i0DE 000FD4EEE4  %%262C2C2E2L2L2NN!K+	>#'D -%%'',$MM%%d:002t00::4,,667&&99 &*%6%6%@%@%@E 

+%@ #'"3"3 :  		H
 KOO  MM..tC m || @33A6C?@h (-$4	>""$$$$= %$$$sh   O,P0 P B$P0  P+AP0 ,P PP	P((P0 0Q3Q!Q3!
Q0	+Q30Q3c                    S U 5       nU(       d  [        US S9n    S	S jn[        R                  " XV5       H  u  u  pxn	U R                  UU	USUUSS9  M     g)
a
  Perform a bulk save of the given list of objects.

.. legacy::

    This method is a legacy feature as of the 2.0 series of
    SQLAlchemy.   For modern bulk INSERT and UPDATE, see
    the sections :ref:`orm_queryguide_bulk_insert` and
    :ref:`orm_queryguide_bulk_update`.

    For general INSERT and UPDATE of existing ORM mapped objects,
    prefer standard :term:`unit of work` data management patterns,
    introduced in the :ref:`unified_tutorial` at
    :ref:`tutorial_orm_data_manipulation`.  SQLAlchemy 2.0
    now uses :ref:`engine_insertmanyvalues` with modern dialects
    which solves previous issues of bulk INSERT slowness.

:param objects: a sequence of mapped object instances.  The mapped
 objects are persisted as is, and are **not** associated with the
 :class:`.Session` afterwards.

 For each object, whether the object is sent as an INSERT or an
 UPDATE is dependent on the same rules used by the :class:`.Session`
 in traditional operation; if the object has the
 :attr:`.InstanceState.key`
 attribute set, then the object is assumed to be "detached" and
 will result in an UPDATE.  Otherwise, an INSERT is used.

 In the case of an UPDATE, statements are grouped based on which
 attributes have changed, and are thus to be the subject of each
 SET clause.  If ``update_changed_only`` is False, then all
 attributes present within each object are applied to the UPDATE
 statement, which may help in allowing the statements to be grouped
 together into a larger executemany(), and will also reduce the
 overhead of checking history on attributes.

:param return_defaults: when True, rows that are missing values which
 generate defaults, namely integer primary key defaults and sequences,
 will be inserted **one at a time**, so that the primary key value
 is available.  In particular this will allow joined-inheritance
 and other multi-table mappings to insert correctly without the need
 to provide primary key values ahead of time; however,
 :paramref:`.Session.bulk_save_objects.return_defaults` **greatly
 reduces the performance gains** of the method overall.  It is strongly
 advised to please use the standard :meth:`_orm.Session.add_all`
 approach.

:param update_changed_only: when True, UPDATE statements are rendered
 based on those attributes in each state that have logged changes.
 When False, all attributes present are rendered into the SET clause
 with the exception of primary key attributes.

:param preserve_order: when True, the order of inserts and updates
 matches exactly the order in which the objects are given.   When
 False, common types of objects are grouped into inserts
 and updates, to allow for more batching opportunities.

.. seealso::

    :doc:`queryguide/dml`

    :meth:`.Session.bulk_insert_mappings`

    :meth:`.Session.bulk_update_mappings`

c              3  N   #    U  H  n[         R                  " U5      v   M     g 7fr   )r   r  )r$  r  s     r   r%  ,Session.bulk_save_objects.<locals>.<genexpr>  s     Hj//44s   #%c                H    [        U R                  5      U R                  S L4$ r   )idr   r  r    s    r   <lambda>+Session.bulk_save_objects.<locals>.<lambda>  s    2ell#3UYYd5J"Kr   ri  c                6    U R                   U R                  S L4$ r   )r   r  r    s    r   grouping_key/Session.bulk_save_objects.<locals>.grouping_key  s     LL%))4"788r   TFisupdateisstatesreturn_defaultsupdate_changed_onlyrender_nullsN)r!   InstanceState[_O]r   zTuple[Mapper[_O], bool])sortedr   groupby_bulk_save_mappings)
r   r  r  r  preserve_order
obj_statesr  r   r  r   s
             r   bulk_save_objectsSession.bulk_save_objects  s    V IH

  KJ
	9$	9$	9
 +4*;*;+
&V $$! /$7" % +
r   c           
     .    U R                  UUSSUSUS9  g)a
  Perform a bulk insert of the given list of mapping dictionaries.

.. legacy::

    This method is a legacy feature as of the 2.0 series of
    SQLAlchemy.   For modern bulk INSERT and UPDATE, see
    the sections :ref:`orm_queryguide_bulk_insert` and
    :ref:`orm_queryguide_bulk_update`.  The 2.0 API shares
    implementation details with this method and adds new features
    as well.

:param mapper: a mapped class, or the actual :class:`_orm.Mapper`
 object,
 representing the single kind of object represented within the mapping
 list.

:param mappings: a sequence of dictionaries, each one containing the
 state of the mapped row to be inserted, in terms of the attribute
 names on the mapped class.   If the mapping refers to multiple tables,
 such as a joined-inheritance mapping, each dictionary must contain all
 keys to be populated into all tables.

:param return_defaults: when True, the INSERT process will be altered
 to ensure that newly generated primary key values will be fetched.
 The rationale for this parameter is typically to enable
 :ref:`Joined Table Inheritance <joined_inheritance>` mappings to
 be bulk inserted.

 .. note:: for backends that don't support RETURNING, the
    :paramref:`_orm.Session.bulk_insert_mappings.return_defaults`
    parameter can significantly decrease performance as INSERT
    statements can no longer be batched.   See
    :ref:`engine_insertmanyvalues`
    for background on which backends are affected.

:param render_nulls: When True, a value of ``None`` will result
 in a NULL value being included in the INSERT statement, rather
 than the column being omitted from the INSERT.   This allows all
 the rows being INSERTed to have the identical set of columns which
 allows the full set of rows to be batched to the DBAPI.  Normally,
 each column-set that contains a different combination of NULL values
 than the previous row must omit a different series of columns from
 the rendered INSERT statement, which means it must be emitted as a
 separate statement.   By passing this flag, the full set of rows
 are guaranteed to be batchable into one batch; the cost however is
 that server-side defaults which are invoked by an omitted column will
 be skipped, so care must be taken to ensure that these are not
 necessary.

 .. warning::

    When this flag is set, **server side default SQL values will
    not be invoked** for those columns that are inserted as NULL;
    the NULL value will be sent explicitly.   Care must be taken
    to ensure that no server-side default functions need to be
    invoked for the operation as a whole.

.. seealso::

    :doc:`queryguide/dml`

    :meth:`.Session.bulk_save_objects`

    :meth:`.Session.bulk_update_mappings`

Fr  Nr  )r   r   mappingsr  r  s        r   bulk_insert_mappingsSession.bulk_insert_mappings  s-    R 	  + %% 	! 	
r   c           
     .    U R                  UUSSSSSS9  g)a  Perform a bulk update of the given list of mapping dictionaries.

.. legacy::

    This method is a legacy feature as of the 2.0 series of
    SQLAlchemy.   For modern bulk INSERT and UPDATE, see
    the sections :ref:`orm_queryguide_bulk_insert` and
    :ref:`orm_queryguide_bulk_update`.  The 2.0 API shares
    implementation details with this method and adds new features
    as well.

:param mapper: a mapped class, or the actual :class:`_orm.Mapper`
 object,
 representing the single kind of object represented within the mapping
 list.

:param mappings: a sequence of dictionaries, each one containing the
 state of the mapped row to be updated, in terms of the attribute names
 on the mapped class.   If the mapping refers to multiple tables, such
 as a joined-inheritance mapping, each dictionary may contain keys
 corresponding to all tables.   All those keys which are present and
 are not part of the primary key are applied to the SET clause of the
 UPDATE statement; the primary key values, which are required, are
 applied to the WHERE clause.


.. seealso::

    :doc:`queryguide/dml`

    :meth:`.Session.bulk_insert_mappings`

    :meth:`.Session.bulk_save_objects`

TFr  Nr  )r   r   r  s      r   bulk_update_mappingsSession.bulk_update_mappings?  s-    L 	  ! % 	! 	
r   c          	        [        U5      nSU l        U R                  5       R                  5       n U(       a  [        R
                  " UUUUUS9  O[        R                  " UUUUUUS9  UR                  5         SU l        g !   [        R                  " 5          UR                  SS9  S S S 5         M:  ! , (       d  f        NI= f= f! SU l        f = f)NT)r  r  )r  r  r  r  F)r'   r  r^  r  r   _bulk_update_bulk_insertr  r<   r  r  )	r   r   r  r  r  r  r  r  r  s	            r   r  Session._bulk_save_mappingso  s     "&)'')002	# --%(; !--%$3!-   #DN		>""$$$$= %$$$ #DNsB   A	B CB5*C2C
 5
C	?CC
 CC
 
	Cc                   [        U5      nUR                  (       d  gUR                  nUR                  R                   H}  nU(       d  [        UR                  S5      (       d  [        UR                  S5      (       d  MB  UR                  R                  X4[        R                  S9u  pgnU(       d	  U(       d  M}    g   g)a	  Return ``True`` if the given instance has locally
modified attributes.

This method retrieves the history for each instrumented
attribute on the instance and performs a comparison of the current
value to its previously flushed or committed value, if any.

It is in effect a more expensive and accurate
version of checking for the given instance in the
:attr:`.Session.dirty` collection; a full test for
each attribute's net "dirty" status is performed.

E.g.::

    return session.is_modified(someobject)

A few caveats to this method apply:

* Instances present in the :attr:`.Session.dirty` collection may
  report ``False`` when tested with this method.  This is because
  the object may have received change events via attribute mutation,
  thus placing it in :attr:`.Session.dirty`, but ultimately the state
  is the same as that loaded from the database, resulting in no net
  change here.
* Scalar attributes may not have recorded the previously set
  value when a new value was applied, if the attribute was not loaded,
  or was expired, at the time the new value was received - in these
  cases, the attribute is assumed to have a change, even if there is
  ultimately no net change against its database value. SQLAlchemy in
  most cases does not need the "old" value when a set event occurs, so
  it skips the expense of a SQL call if the old value isn't present,
  based on the assumption that an UPDATE of the scalar value is
  usually needed, and in those few cases where it isn't, is less
  expensive on average than issuing a defensive SELECT.

  The "old" value is fetched unconditionally upon set only if the
  attribute container has the ``active_history`` flag set to ``True``.
  This flag is set typically for primary key attributes and scalar
  object references that are not a simple many-to-one.  To set this
  flag for any arbitrary mapped column, use the ``active_history``
  argument with :func:`.column_property`.

:param instance: mapped instance to be tested for pending changes.
:param include_collections: Indicates if multivalued collections
 should be included in the operation.  Setting this to ``False`` is a
 way to detect only local-column based properties (i.e. scalar columns
 or many-to-one foreign keys) that would result in an UPDATE for this
 instance upon flush.

Fget_collectionget_historyr  T)
r-   r  r   r  r   hasattrimplr
  r.   r$  )	r   r   include_collectionsr!   dict_attradded	unchangedr  s	            r   is_modifiedSession.is_modified  s    j X&~~

MM,,D'DII'788TYY66*.))*?*?k&;&; +@ +'Uw  - r   c                X    U R                   SL =(       d    U R                   R                  $ )a  True if this :class:`.Session` not in "partial rollback" state.

.. versionchanged:: 1.4 The :class:`_orm.Session` no longer begins
   a new transaction immediately, so this attribute will be False
   when the :class:`_orm.Session` is first instantiated.

"partial rollback" state typically indicates that the flush process
of the :class:`_orm.Session` has failed, and that the
:meth:`_orm.Session.rollback` method must be emitted in order to
fully roll back the transaction.

If this :class:`_orm.Session` is not in a transaction at all, the
:class:`_orm.Session` will autobegin when it is first used, so in this
case :attr:`_orm.Session.is_active` will return True.

Otherwise, if this :class:`_orm.Session` is within a transaction,
and that transaction has not been rolled back internally, the
:attr:`_orm.Session.is_active` will also return True.

.. seealso::

    :ref:`faq_session_rollback`

    :meth:`_orm.Session.in_transaction`

N)r  r  r   s    r   r  Session.is_active  s&    8   D(GD,=,=,G,GGr   c                6    U R                   R                  5       $ )zThe set of all persistent states considered dirty.

This method returns all states that were modified including
those that were possibly deleted.

)r  r  r   s    r   r  Session._dirty_states  s       ..00r   c                    [        U R                   Vs/ s H$  nXR                  ;  d  M  UR                  5       PM&     sn5      $ s  snf )a  The set of all persistent instances considered dirty.

E.g.::

    some_mapped_object in session.dirty

Instances are considered dirty when they were modified but not
deleted.

Note that this 'dirty' calculation is 'optimistic'; most
attribute-setting or collection modification operations will
mark an instance as 'dirty' and place it in this set, even if
there is no net change to the attribute's value.  At flush
time, the value of each attribute is compared to its
previously saved value, and if there's no net change, no SQL
operation will occur (this is a more expensive operation so
it's only done at flush time).

To check if an instance has actionable net changes to its
attributes, use the :meth:`.Session.is_modified` method.

)rO   r  rx  r  r  s     r   r  Session.dirty  sK    0  "///E- 		/
 	
s
   AAc                p    [         R                  " [        U R                  R	                  5       5      5      $ )zDThe set of all instances marked as 'deleted' within this ``Session``)r<   rO   r   rx  r  r   s    r   r  Session.deleted,  s'     T]]%9%9%; <==r   c                p    [         R                  " [        U R                  R	                  5       5      5      $ )zAThe set of all instances marked as 'new' within this ``Session``.)r<   rO   r   rw  r  r   s    r   r  Session.new2  s'     TYY%5%5%7 899r   )__bindsr  rx  r  r  rw  r/  r  r*  r1  r,  r  r-  r  r+  r  r  r  r   )r  Optional[_SessionBind]r,  rf  r0  Literal[True]r  rf  r1  rf  r  rf  r2  z-Optional[Dict[_SessionBindKey, _SessionBind]]r-  rf  r3  Optional[_InfoType]r4  zOptional[Type[Query[Any]]]r5  zLiteral[False]r  r.  r6  zUnion[bool, _NoArg])r   _Sr   r"  )rF  r   rG  r   rH  r   r   r   )r   r"  r   zIterator[_S]re  r  )r   rh   r  )r  rf  r   r|   r  )r   r|   r   r   )r   rc  r   r!  r   r=   )r:   r   r   r!  r   r   r   r=   )r   rr   r   "Optional[_CoreSingleExecuteParams]r   rU   r   rc  r   r   rq  r   rr  r   r   r   )r   rr   r   r   r   rU   r   rc  r   r   rq  r   rr  rf  r   rd  )r   rr   r   r   r   rU   r   rc  r   r   rq  r   rr  rf  r   r   )r   zTypedReturnsRows[_T]r   r   r   rU   r   rc  r   r   rq  r   r   z
Result[_T])r   rt   r   r   r   rU   r   rc  r   r   rq  r   r   zCursorResult[Any])r   rr   r   r   r   rU   r   rc  r   r   rq  r   r   rd  )r   TypedReturnsRows[Tuple[_T]]r   r#  r   rU   r   rc  r   r   r   zOptional[_T])r   rr   r   r#  r   rU   r   rc  r   r   r   r   )r   r$  r   r   r   rU   r   rc  r   r   r   zScalarResult[_T])r   rr   r   r   r   rU   r   rc  r   r   r   zScalarResult[Any])r  rf  r  rf  r   r   )r  _SessionBindKeyr  r   r   r   )r   _EntityBindKey[_O]r  r   r   r   )r  rH   r  r   r   r   )r   zOptional[_EntityBindKey[_O]]rz  zOptional[ClauseElement]r  r  r   Optional[bool]r  rf  r   r   r   zUnion[Engine, Connection])r  z_EntityType[_O]r   z	Query[_O])r  zTypedColumnsClauseRole[_T]r   zRowReturningQuery[Tuple[_T]])r  
_TCCA[_T0]r  
_TCCA[_T1]r   z"RowReturningQuery[Tuple[_T0, _T1]])r  r(  r  r)  r  
_TCCA[_T2]r   z'RowReturningQuery[Tuple[_T0, _T1, _T2]])
r  r(  r  r)  r  r*  r  
_TCCA[_T3]r   z,RowReturningQuery[Tuple[_T0, _T1, _T2, _T3]])r  r(  r  r)  r  r*  r  r+  r  
_TCCA[_T4]r   z1RowReturningQuery[Tuple[_T0, _T1, _T2, _T3, _T4]])r  r(  r  r)  r  r*  r  r+  r  r,  r  
_TCCA[_T5]r   z6RowReturningQuery[Tuple[_T0, _T1, _T2, _T3, _T4, _T5]])r  r(  r  r)  r  r*  r  r+  r  r,  r  r-  r  
_TCCA[_T6]r   z;RowReturningQuery[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6]])r  r(  r  r)  r  r*  r  r+  r  r,  r  r-  r  r.  r  z
_TCCA[_T7]r   z@RowReturningQuery[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6, _T7]])r  z_ColumnsClauseArgument[Any]r  r   r   z
Query[Any])r   r   r  r   r   r   r  r.   r<  rg  r   rU   r   rc  r   z)Union[Optional[_O], LoaderCallableStatus])r   zIterator[Session])r   r   r   Optional[Iterable[str]]r  rw   r   r   )r   r   r   r/  r   r   )r!   InstanceState[Any]r   r/  r   r   )r!   r0  r,  r'  r   r   r   r   r   r   )r   Iterable[InstanceState[Any]]r  rf  r   r   )r   zSet[InstanceState[Any]]r   r   )r   r2  r   r   )T)r   r   r>  rf  r   r   )rA  Iterable[object]r   r   )r!   r0  r   r   )r!   r0  r  r   rJ  rf  r   r   )r  r&  r   _PKIdentityArgumentrW  Optional[Sequence[ORMOption]]rX  rf  r  rw   r   r   r   rU   r   rc  r   Optional[_O])r  r&  r   r4  rW  r5  rX  rf  r  rw   r   r   r   rU   r   rc  r   r"   )r  r&  r  r4  rx  zCallable[..., _O]rW  z$Optional[Sequence[ExecutableOption]]rX  rf  r  rw   r   r   r   rU   r   rc  r   r6  )r   r"   r  rf  rW  r5  r   r"   )r!   r  r  rT   rW  r5  r  rf  r  zDict[Any, object]r  z#Dict[_IdentityKeyType[Any], object]r   r"   )r!   r0  r  rf  r   r   )r  r   r   r   )r!   r0  r  r   r   rf  )r!   r0  r  r   r   r   )r   r   r   rf  )r   zIterator[object])r!   r0  r   rf  )r  zOptional[Sequence[Any]]r   r   )r  r   r   r   )r  zOptional[Sequence[object]]r   r   )FTT)
r  r3  r  rf  r  rf  r  rf  r   r   r"  )
r   r   r  Iterable[Dict[str, Any]]r  rf  r  rf  r   r   )r   r   r  r7  r   r   )r   r   r  z<Union[Iterable[InstanceState[_O]], Iterable[Dict[str, Any]]]r  rf  r  rf  r  rf  r  rf  r  rf  r   r   )r   r   r  rf  r   rf  )r   r2  )r   rO   )hr   r   r   r   r   _is_asynciori  rJ   r<  r   r@  rA  rC  rI  
contextlibcontextmanagerrM  r  r  rV  rY  r<   memoized_propertyr3  r^  r  r  r  r  r  r  r  r   
EMPTY_DICTr   r  r  r  r  r  r  r  r  r>  r  r  r  r   r.   PASSIVE_OFFr  non_memoized_propertyr  langhelperstag_method_for_warningsr   	SAWarningr  r  r  r	  r  r  r  r  r2  r.  r9  r  rB  r=  rM  rK  r  r_  rZ  r  r  r  r  r  rF  r  rQ  rR  r  r  rG  r  r<  r  r  r  r  r  r  r  rj  r  r  r  r  r  r   r   r   r   r{   r{     s*    K!! ('++
--00O..55MON..  $$ (,k(  $!%?C%)$(04%*5L17k($k( 	k(
 k( k( k( k( =k( #k( "k( .k( #k(  3k( /k(\	 >B:A>B;B  
-4	( 

 
!(5n'46*$$L& 48CG.
0.
 A.
 
	.
f DHEE AE 	E
 
E  6:

 9=37/3$((+

 3

 6
 1
  -
 "
 &
 

 
  37

 9=37/3$("

 0

 6
 1
  -
 "
 
 

 
 37A
 9=37/3$($AA 0A
 6A 1A  -A "A A 
AF  37	
 9=37/3$(	'	 0	
 6	 1	  -	 "	 
	 	  37	 
 9=37/3$(	 	  0	 
 6	  1	   -	  "	  
	  	   37	
 9=37/3$(		 0	
 6	 1	  -	 "	 
	 	 37C

 9=37/3$(C
C
 0C

 6C
 1C
  -C
 "C
 
C
J  6:
 9=37. 3
 6 1  
   6:
 9=37 3
 6 1  
  6:

 9=37

 3

 6
 1
 
 

4  37
 9=37. 0
 6 1  
   37 
 9=37   0 
 6  1    
    37$
 9=37$$ 0$
 6$ 1$ $ 
$L'+R:2"*H.@ 2%(%0<%	%<$< 04]
 +/'+*.05]
,]
 (	]

 %]
 (]
 *.]
 ]
 
#]
~ ? ?+2+	%+ + 1 1*41	+1 1 6 6*46>H6	06 6 ;; ; 	;
 ; 
6; ; @@ @ 	@
 @ @ 
;@ @ EE E 	E
 E E E 
@E E 	J	J 	J 		J
 	J 	J 	J 	J 
E	J 	J 
O
O 
O 	
O
 
O 
O 
O 
O 
O 
J
O 
O 4@C	 949@C9	94 #*669=8<3799 :9 	9
 9 79 69 19 
39v 
'   '4 
--	8 	::& 48.2	ww 1w ,	w
 
wr!CH LP+3+31H+3	+3Z.!. 1. 
	.& FJ	 '	 4B	 		 N, JO
2
BF
	
"Q!f;323	3,!*F,(+6>%1'%1.4%1<@%1	%1X 26"'.2(,8<37y
"y
 #y

 /y
  y
 ,y
 &y
 6y
 1y
 
y
@ 26"'.2(,8<370"0 #0
 /0  0 ,0 &0 60 10 
0p 9="'.2(,8<37}
"}
 2}
 &	}
 6}
  }
 ,}
 &}
 6}
 1}
 
}
F 15U'U' 	U'
 /U' 
U'x 26] ] "]
 /] ] &]  C] 
]~+  BG&='&=:>&=	&=P%?+B"	<+
M #D

u>t !&$(#g!g g "	g
 g 
gZ !&"Q
Q
 +Q
 	Q

 Q
 
Q
f.
!.
-E.
	.
`'#'# O'#
 '# '# '# "'# '# 
'#T =AJJ59J	JX H H: 1 1 
 
> > >
 : :r   r{   r"  c                      \ rS rSr% SrS\S'   \ SSSSS.           SS jjj5       r\ SSSSS.           SS jjj5       r S\S
S
S	S.           SS jjjrSS jr	SS jr
SS jrSS jrSrg	)r}   i<  a  A configurable :class:`.Session` factory.

The :class:`.sessionmaker` factory generates new
:class:`.Session` objects when called, creating them given
the configurational arguments established here.

e.g.::

    from sqlalchemy import create_engine
    from sqlalchemy.orm import sessionmaker

    # an Engine, which the Session will use for connection
    # resources
    engine = create_engine("postgresql+psycopg2://scott:tiger@localhost/")

    Session = sessionmaker(engine)

    with Session() as session:
        session.add(some_object)
        session.add(some_other_object)
        session.commit()

Context manager use is optional; otherwise, the returned
:class:`_orm.Session` object may be closed explicitly via the
:meth:`_orm.Session.close` method.   Using a
``try:/finally:`` block is optional, however will ensure that the close
takes place even if there are database errors::

    session = Session()
    try:
        session.add(some_object)
        session.add(some_other_object)
        session.commit()
    finally:
        session.close()

:class:`.sessionmaker` acts as a factory for :class:`_orm.Session`
objects in the same way as an :class:`_engine.Engine` acts as a factory
for :class:`_engine.Connection` objects.  In this way it also includes
a :meth:`_orm.sessionmaker.begin` method, that provides a context
manager which both begins and commits a transaction, as well as closes
out the :class:`_orm.Session` when complete, rolling back the transaction
if any errors occur::

    Session = sessionmaker(engine)

    with Session.begin() as session:
        session.add(some_object)
        session.add(some_other_object)
    # commits transaction, closes session

.. versionadded:: 1.4

When calling upon :class:`_orm.sessionmaker` to construct a
:class:`_orm.Session`, keyword arguments may also be passed to the
method; these arguments will override that of the globally configured
parameters.  Below we use a :class:`_orm.sessionmaker` bound to a certain
:class:`_engine.Engine` to produce a :class:`_orm.Session` that is instead
bound to a specific :class:`_engine.Connection` procured from that engine::

    Session = sessionmaker(engine)

    # bind an individual session to a connection

    with engine.connect() as connection:
        with Session(bind=connection) as session:
            ...  # work with session

The class also includes a method :meth:`_orm.sessionmaker.configure`, which
can be used to specify additional keyword arguments to the factory, which
will take effect for subsequent :class:`.Session` objects generated. This
is usually used to associate one or more :class:`_engine.Engine` objects
with an existing
:class:`.sessionmaker` factory before it is first used::

    # application starts, sessionmaker does not have
    # an engine bound yet
    Session = sessionmaker()

    # ... later, when an engine URL is read from a configuration
    # file or other events allow the engine to be created
    engine = create_engine("sqlite:///foo.db")
    Session.configure(bind=engine)

    sess = Session()
    # work with session

.. seealso::

    :ref:`session_getting` - introductory text on creating
    sessions using :class:`.sessionmaker`.

Type[_S]r   .)r,  r  r3  c                   g r   r   r   r  r   r,  r  r3  r   s          r   r   sessionmaker.__init__  s     r   c                   g r   r   )r   r  r,  r  r3  r   s         r   r   rF    s     r   NT)r   r,  r  r3  c               p    XS'   X6S'   XFS'   Ub  XVS'   X`l         [        UR                  U40 5      U l        g)a  Construct a new :class:`.sessionmaker`.

All arguments here except for ``class_`` correspond to arguments
accepted by :class:`.Session` directly.  See the
:meth:`.Session.__init__` docstring for more details on parameters.

:param bind: a :class:`_engine.Engine` or other :class:`.Connectable`
 with
 which newly created :class:`.Session` objects will be associated.
:param class\_: class to use in order to create new :class:`.Session`
 objects.  Defaults to :class:`.Session`.
:param autoflush: The autoflush setting to use with newly created
 :class:`.Session` objects.

 .. seealso::

    :ref:`session_flushing` - additional background on autoflush

:param expire_on_commit=True: the
 :paramref:`_orm.Session.expire_on_commit` setting to use
 with newly created :class:`.Session` objects.

:param info: optional dictionary of information that will be available
 via :attr:`.Session.info`.  Note this dictionary is *updated*, not
 replaced, when the ``info`` parameter is specified to the specific
 :class:`.Session` construction operation.

:param \**kw: all other keyword arguments are passed to the
 constructor of newly created :class:`.Session` objects.

r  r,  r  Nr3  )r   r  r   r   rE  s          r   r   rF    sF    R 6
#;!1vJ 6??VIr:r   c                0    U " 5       nUR                  5       $ )a-  Produce a context manager that both provides a new
:class:`_orm.Session` as well as a transaction that commits.


e.g.::

    Session = sessionmaker(some_engine)

    with Session.begin() as session:
        session.add(some_object)

    # commits transaction, closes session

.. versionadded:: 1.4


)rM  )r   r   s     r   r  sessionmaker.begin  s    & &--//r   c                    U R                   R                  5        HL  u  p#US:X  a0  SU;   a*  UR                  5       nUR                  US   5        XAS'   M;  UR	                  X#5        MN     U R
                  " S0 UD6$ )a@  Produce a new :class:`.Session` object using the configuration
established in this :class:`.sessionmaker`.

In Python, the ``__call__`` method is invoked on an object when
it is "called" in the same way as a function::

    Session = sessionmaker(some_engine)
    session = Session()  # invokes sessionmaker.__call__()

r3  r   )r   r  copyr   r  r   )r   local_kwr}  vr  s        r   r   sessionmaker.__call__  sn     GGMMODAF{v1FFH&)*#$ ##A) $ {{&X&&r   c                :    U R                   R                  U5        g)z(Re)configure the arguments for this sessionmaker.

e.g.::

    Session = sessionmaker()

    Session.configure(bind=create_engine("sqlite://"))
N)r   r   )r   new_kws     r   	configuresessionmaker.configure  s     	vr   c           	         U R                   R                  < SU R                  R                  < SSR                  S U R                  R                  5        5       5      < S3$ )Nz(class_=r  c              3  8   #    U  H  u  pU< S U< 3v   M     g7f)=Nr   )r$  r}  rN  s      r   r%  (sessionmaker.__repr__.<locals>.<genexpr>   s     C?41A&?s   r   )	__class__r   r   r  r   r  r   s    r   __repr__sessionmaker.__repr__  sB    NN##KK  IIC477==?CC
 	
r   )r   r   ).)r  r  r   rC  r,  rf  r  rf  r3  r!  r   r   )r   z'sessionmaker[Session]'r  r  r,  rf  r  rf  r3  r!  r   r   r   )r   z%contextlib.AbstractContextManager[_S])rM  r   r   r"  )rQ  r   r   r   )r   r  )r   r   r   r   r   ri  r   r   r{   r  r   rR  rY  r   r   r   r   r}   r}   <  s?   \|  (+	
 !$$'	$	 		
 	 	 "	 	 	  (+ !$$'%$ 	
  "   (,1; #!%$(1;$1; 	1;
 1; 1; "1; 1;f0,'(	
r   r}   c                 Z    [         R                  5        H  n U R                  5         M     g)a3  Close all sessions in memory.

This function consults a global registry of all :class:`.Session` objects
and calls :meth:`.Session.close` on them, which resets them to a clean
state.

This function is not for general use but may be useful for test suites
within the teardown scheme.

.. versionadded:: 1.3

N)r   r  r  )r	  s    r   r   r   $  s        "

 #r   c                    [         R                  " U 5      n[        U5      nU(       a  UR                  U/5        UR                  R                  5         UR                  (       a  U?UR                  (       a  U?UR                  (       a  U?gg)a  Alter the state of the given instance so that it is :term:`transient`.

.. note::

    :func:`.make_transient` is a special-case function for
    advanced use cases only.

The given mapped instance is assumed to be in the :term:`persistent` or
:term:`detached` state.   The function will remove its association with any
:class:`.Session` as well as its :attr:`.InstanceState.identity`. The
effect is that the object will behave as though it were newly constructed,
except retaining any attribute / collection values that were loaded at the
time of the call.   The :attr:`.InstanceState.deleted` flag is also reset
if this object had been deleted as a result of using
:meth:`.Session.delete`.

.. warning::

    :func:`.make_transient` does **not** "unexpire" or otherwise eagerly
    load ORM-mapped attributes that are not currently loaded at the time
    the function is called.   This includes attributes which:

    * were expired via :meth:`.Session.expire`

    * were expired as the natural effect of committing a session
      transaction, e.g. :meth:`.Session.commit`

    * are normally :term:`lazy loaded` but are not currently loaded

    * are "deferred" (see :ref:`orm_queryguide_column_deferral`) and are
      not yet loaded

    * were not present in the query which loaded this object, such as that
      which is common in joined table inheritance and other scenarios.

    After :func:`.make_transient` is called, unloaded attributes such
    as those above will normally resolve to the value ``None`` when
    accessed, or an empty collection for a collection-oriented attribute.
    As the object is transient and un-associated with any database
    identity, it will no longer retrieve these values.

.. seealso::

    :func:`.make_transient_to_detached`

N)	r   r  r   r  expired_attributesr  	callablesr  rx  )r   r!   r  s      r   r   r   6  sq    ^ %%h/EuA	5'" 
""$ OyyI~~N r   c                   [         R                  " U 5      nUR                  (       d  UR                  (       a  [        R
                  " S5      eUR                  R                  U5      Ul        UR                  (       a  U?UR                  UR                  5        UR                  UR                  UR                  5        g)ae  Make the given transient instance :term:`detached`.

.. note::

    :func:`.make_transient_to_detached` is a special-case function for
    advanced use cases only.

All attribute history on the given instance
will be reset as though the instance were freshly loaded
from a query.  Missing attributes will be marked as expired.
The primary key attributes of the object, which are required, will be made
into the "key" of the instance.

The object can then be added to a session, or merged
possibly with the load=False flag, at which point it will look
as if it were loaded that way, without emitting SQL.

This is a special use case function that differs from a normal
call to :meth:`.Session.merge` in that a given persistent state
can be manufactured without any SQL calls.

.. seealso::

    :func:`.make_transient`

    :meth:`.Session.enable_relationship_loading`

zGiven object must be transientN)r   r  r  r  r   r   r   r(  rx  r  r   r  unloaded)r   r!   s     r   r   r   w  s    : %%h/E599(()IJJ55e<EI~~N	ejj!	UZZ8r   c                     [         R                  " U 5      n[        U5      $ ! [        R                   a  n[        R
                  " U 5      UeSnAff = f)zReturn the :class:`.Session` to which the given instance belongs.

This is essentially the same as the :attr:`.InstanceState.session`
accessor.  See that attribute for details.

N)r   r  r   r   r  r  )r   r!   r  s      r   r   r     sM    %))(3 e$$ << ;''1s:;s   # AAA)r!   r0  r   r   r   r1  r   )r   
__future__r   r9  enumr   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   r   r   r   r!   r  _typingr"   r#   r$   r%   r&   baser'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   state_changesr5   r6   r7   
unitofworkr8   r:   r   r;   r<   r=   r>   engine.utilr?   eventr@   rA   
inspectionrB   rC   rD   rE   rF   rG   rH   rI   sql.baserJ   rK   
sql.schemarL   sql.selectablerM   rN   rO   util.typingrP   rQ   rR   rS   rT   rU   
interfacesrV   rW   r   rX   path_registryrY   rZ   r[   r\   r]   r^   engine.baser_   r`   engine.interfacesra   rb   rc   rd   engine.resultre   rf   sql._typingrg   rh   ri   rj   rk   rl   rm   rn   ro   rp   rq   _TCCArr   rs   sql.dmlrt   sql.elementsru   	sql.rolesrv   rw   rx   ry   __all__WeakValueDictionaryr   ri  r4  r  r   _EntityBindKeyr%  r   r.  r   r   r   r   tupler   r   r   r   r   r   MemoizedSlotsr~   rl  r|   r  r{   r"  r}   r   r   r   r   counterr;  r   r   r   <module>r     s   8 "    
                                # ' " + "    &     " $ !    ' , - &       .     $        #  ) ;  ! "	$)&3%-+(%#)19<3?,.4'!!!!!!!!A%+$,231T	 ! 
4   CsCx01 c3htBx-.S	=-DE+, x */( /(d /   JOJ F)Xv/F
h
d(( h
V7t 70Y	6'; Y	6x G6:"K G6:Tl T#e
' e
P$>B$9N%  r   