
    -h.{                        S 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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 Qr(\RR                  " 5       r* \*\l*        S! r+ " S" S#\,5      r-\R\                  " S$5      r/\R\                  " S%5      r0\R\                  " S&5      r1\R\                  " S'5      r2\R\                  " S(5      r3 " S) S*\Rh                  5      r5 " S+ S,\5      r6 " S- S.\-5      r7 " S/ S0\-5      r8S1 r9S2 r:S3 r;S4 r<\Rz                  " 5       r>g)5z1Provides the Session class and related utilities.    N   )
attributes)context)exc)identity)loading)persistence)querystate)_class_to_mapper)	_none_set)_state_mapper)instance_str)object_mapper)object_state)	state_str)UOWTransaction   )engine)sql)util)TransactionalContext)inspect)	coercions)dml)roles)visitors)CompileState)LABEL_STYLE_TABLENAME_PLUS_COL)SessionSessionTransactionsessionmakerORMExecuteStateclose_all_sessionsmake_transientmake_transient_to_detachedobject_sessionc                     U R                   $ )zSGiven an :class:`.InstanceState`, return the :class:`.Session`
associated, if any.
sessionr   s    kC:\Users\ROHAN GUPTA\OneDrive\Desktop\mathbuddy-assessment\venv\Lib\site-packages\sqlalchemy/orm/session.py_state_sessionr-   =   s     ==    c                       \ rS rSrSr\\R                  " SS5      S 5       5       r\\R                  " S5      S 5       5       r
\S 5       rS	rg
)_SessionClassMethodsD   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_allG   s
     	r.   zsqlalchemy.orm.utilc                 V    [         R                  R                  R                  " U0 UD6$ )zJReturn an identity key.

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

)r   	preloadedorm_utilidentity_key)r3   argskwargss      r,   r9   !_SessionClassMethods.identity_keyS   s$     ~~&&33TDVDDr.   c                     [        U5      $ )zhReturn the :class:`.Session` to which an object belongs.

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

)r(   )r3   instances     r,   r(   #_SessionClassMethods.object_session]   s     h''r.    N)__name__
__module____qualname____firstlineno____doc__classmethodr   
deprecatedr4   preload_moduler9   r(   __static_attributes__r@   r.   r,   r0   r0   D   sn    L	__	/ 
 	./E 0 E ( (r.   r0   ACTIVEPREPARED	COMMITTEDDEACTIVECLOSEDc                   6   \ rS rSrSrSrS rS r    SS jr\	S 5       r
\	S	 5       r\	S
 5       r\	S 5       r\	S 5       r\	S 5       r\	S 5       r\	S 5       rS rS r\	S 5       r\	S 5       r\	S 5       r\	S 5       r\	S 5       r\	S 5       r\	S 5       rSrg)r$   o   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_arguments_compile_state_cls_starting_event_idx_events_todo_update_execution_optionsc                     Xl         X l        X0l        X@l        UR                  R                  U5      U l        XPl        X`l        [        U5      U l
        g N)r+   rQ   rR   rT   _execution_optionsunionrS   rU   rV   listrX   )selfr+   rQ   rR   rS   rU   compile_state_clsevents_todos           r,   __init__ORMExecuteState.__init__   sP     "$'8$!*!=!=!C!C"
 -"3 -r.   c                 :    U R                   U R                  S-   S  $ )Nr   )rX   rW   r_   s    r,   _remaining_events!ORMExecuteState._remaining_events   s!      !9!9A!=!?@@r.   Nc                 z   Uc  U R                   n[        U R                  5      nU(       a  UR                  U5        SUS'   U(       a'  [        U R                  5      nUR                  U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 which will be merged
 into the existing :attr:`.ORMExecuteState.parameters` of this
 :class:`.ORMExecuteState`.

: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_events)_parent_execute_state)	rQ   dictrU   updaterR   rT   r]   r+   execute)r_   rQ   paramsrS   rU   _bind_arguments_paramsr\   s           r,   invoke_statement ORMExecuteState.invoke_statement   s    l It223"">2-1)*4??+GNN6"ooG!99!3!9!9:K!L||##"& $ 
 	
r.   c                 :    U R                   R                  SS5      $ )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`


mapperN)rU   getre   s    r,   bind_mapperORMExecuteState.bind_mapper   s    4 ""&&x66r.   c                    U R                   (       d  / $ U R                  (       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                  (       d  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	is_selectsetrQ   column_descriptionsr   rt   addappend	is_update	is_deleterv   )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~~$$%%Ir.   c                     U R                   SL$ )aS  return True if the operation is an ORM statement.

This indicates that the select(), 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)rV   re   s    r,   r{    ORMExecuteState.is_orm_statement2  s     &&d22r.   c                 .    U R                   R                  $ )z*return True if this is a SELECT operation.)rQ   r|   re   s    r,   r|   ORMExecuteState.is_select?  s     ~~'''r.   c                 h    U R                   R                  =(       a    U R                   R                  $ )z+return True if this is an INSERT operation.)rQ   is_dml	is_insertre   s    r,   r   ORMExecuteState.is_insertD  #     ~~$$A)A)AAr.   c                 h    U R                   R                  =(       a    U R                   R                  $ )z+return True if this is an UPDATE operation.)rQ   r   r   re   s    r,   r   ORMExecuteState.is_updateI  r   r.   c                 h    U R                   R                  =(       a    U R                   R                  $ )z*return True if this is a DELETE operation.)rQ   r   r   re   s    r,   r   ORMExecuteState.is_deleteN  r   r.   c                 j    [        U R                  [        R                  [        R                  45      $ r[   )
isinstancerQ   r   UpdateDeletere   s    r,   _is_crudORMExecuteState._is_crudS  s     $..3::szz*BCCr.   c                 D    U R                   R                  U5      U l         g r[   )rT   r]   r_   optss     r,   update_execution_options(ORMExecuteState.update_execution_optionsW  s    '+'C'C'I'I$'O$r.   c                     U R                   (       d  g  U R                  R                  nUR	                  [
        R                  R                  5      (       a  U$ g ! [         a     g f = fr[   )r|   rQ   _compile_optionsAttributeErrorr   r   ORMCompileStatedefault_compile_optionsr   s     r,   _orm_compile_options$ORMExecuteState._orm_compile_options[  sY    ~~	>>22D ??722JJKK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_fromre   s    r,   lazy_loaded_from ORMExecuteState.lazy_loaded_fromg  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)r   _current_pathr   s     r,   loader_strategy_path$ORMExecuteState.loader_strategy_pathv  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)r   _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)r   r   is_root)r_   r   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      $ )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|   sa_excInvalidRequestErrorrS   ru   r   QueryContextdefault_load_optionsre   s    r,   r   ORMExecuteState.load_options  sO     ~~,,0  %%))"G$8$8$M$M
 	
r.   c                     U R                   (       d  [        R                  " S5      eU R                  R	                  S[
        R                  R                  5      $ )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   rS   ru   r	   BulkUDCompileStatedefault_update_optionsre   s    r,   update_delete_options%ORMExecuteState.update_delete_options  sP    
 }},,<  %%))$**AA
 	
r.   c                     U R                   R                   Vs/ s H+  nUR                  (       a  M  UR                  (       a  M)  UPM-     sn$ s  snf )zjThe sequence of :class:`.UserDefinedOptions` that have been
associated with the statement being invoked.

)rQ   _with_options_is_compile_state_is_legacy_option)r_   opts     r,   user_defined_options$ORMExecuteState.user_defined_options  sJ     ~~33
3(( 141F1F 3
 	
 
s   AAA)rV   rX   rU   rS   rT   rR   r+   rQ   )NNNN)rA   rB   rC   rD   rE   	__slots__rb   rf   rq   propertyrv   r   r{   r|   r   r   r   r   r   r   r   r   r   r   r   r   r   rI   r@   r.   r,   r$   r$   o   sn   
I.*A
 N
` 7 76 " "H 
3 
3 ( ( 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S jr\S 5       rSr	 \S 5       r
    SS jr\S	 5       rSS
 jrSS jrSS jrSS jrSS jrS rS rS rS rSS jrSS jrSS jrS rS rS rS rSrg) r"   i  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`


NFc                    [         R                  " U5        Xl        0 U l        X l        X0l        U(       a  UR                  U l        [        U l	        U(       d  U(       a  [        R                  " S5      eU R                  US9  X R                  l        U R                  R                  R                  U R                  U 5        g )NzOCan't start a SAVEPOINT transaction when no existing transaction is in progress	autobegin)r   _trans_ctx_checkr+   _connections_parentnested_nested_transaction_previous_nested_transactionrJ   _stater   r   _take_snapshot_transactiondispatchafter_transaction_create)r_   r+   parentr   r   s        r,   rb   SessionTransaction.__init__  s     	--g6070K0KD-&,,- 
 	i0 %)!66t||TJr.   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"
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.

.. versionadded:: 1.0.16 - use ._parent for previous versions

)r   re   s    r,   r   SessionTransaction.parent)  s      ||r.   c                 P    U R                   S L=(       a    U R                  [        L $ r[   )r+   r   rJ   re   s    r,   	is_activeSessionTransaction.is_activeC  s    ||4'ADKK6,AAr.   c                    U R                   [        L a  [        R                  " S5      eU R                   [        L a  U(       d  [        R                  " S5      eg U R                   [
        L aa  U(       dY  U(       dQ  U R                  (       a"  [        R                  " SU R                  -  SS9eU(       d  [        R                  " S5      eg g g U R                   [        L a  [        R                  " U5      eg )Nz\This session is in 'committed' state; no further SQL can be emitted within this transaction.z[This session is in 'prepared' state; no further SQL can be emitted within this transaction.zThis 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: %s7s2acodezThis session is in 'inactive' state, due to the SQL transaction being rolled back; no further SQL can be emitted within this transaction.)
r   rL   r   r   rK   rM   _rollback_exceptionPendingRollbackErrorrN   ResourceClosedError)r_   prepared_okrollback_okdeactive_ok
closed_msgs        r,   _assert_active!SessionTransaction._assert_activeG  s     ;;)#,,>  [[H$00B  
 [[H${++ 556
 223 $  % 44F  % (3;" [[F",,Z88 #r.   c                 J    U R                   =(       d    U R                  (       + $ r[   )r   r   re   s    r,   _is_transaction_boundary+SessionTransaction._is_transaction_boundaryn  s    {{.$,,..r.   c                 ~    U R                  5         U R                  R                  " U40 UD6nU R                  XB5      $ r[   )r   r+   get_bind_connection_for_bind)r_   bindkeyrS   r;   binds        r,   
connectionSessionTransaction.connectionr  s8    ||$$W77((AAr.   c                 J    U R                  5         [        U R                  XS9$ )Nr   )r   r"   r+   )r_   r   s     r,   _beginSessionTransaction._beginw  s    !$,,DDr.   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)r   r   r   )r_   uptocurrentr   s       r,   _iterate_self_and_parents,SessionTransaction._iterate_self_and_parents{  sr    j F$&  (00J 
 "// g r.   c                 H   U R                   (       dm  U R                  R                  U l        U R                  R                  U l        U R                  R                  U l        U R                  R
                  U l        g 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   r   _new_deleted_dirty_key_switchesr+   	_flushingflushweakrefWeakKeyDictionary)r_   r   s     r,   r   !SessionTransaction._take_snapshot  s    ,,))DI LL11DM,,--DK!%!;!;D!7!7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}   r  r]   r+   _expunge_statesr  itemsidentity_mapsafe_discardkeyreplacer	  _update_impl
all_statesmodifiedr
  _expirerk   	_modified)r_   
dirty_only
to_expungesoldkeynewkeys         r,   _restore_snapshot$SessionTransaction._restore_snapshot  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                    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                  R                   R#                  U R                   5        U R                  R$                  R#                  U R$                  5        U R                  R                  R#                  U R                  5        U R                  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  rk   r  statelibInstanceState_detach_statesr^   r	  clearr   r  rl   r
  r  )r_   r"  s     r,   _remove_snapshot#SessionTransaction._remove_snapshot  s    ,,,,{{t||<<\\..99;		!&&$,,";";"E"EF < ""11T]]#T\\ MM![[LL$$TYY/LL&&t{{3LL!!((7LL&&--d.@.@A	 r.   c                    U R                  5         XR                  ;   a/  U(       a  [        R                  " S5        U R                  U   S   $ SnSnU R                  (       a/  U R                  R                  X5      nU R                  (       d  U$ 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OU R                  (       a  UR#                  5       nO^UR%                  5       (       a9  UR'                  5       (       a  UR)                  5       nO#UR+                  5       nSnOUR-                  5       n[        U[        R                  5      nUUUU(       + 4=U R                  U'   U R                  UR                  '   U R                  R.                  R1                  U R                  X5        U$ !   U(       a  UR3                  5         e = 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   r   warnr   r   r   r   r   
Connectionr   r   connectrS   r+   twophasebegin_twophasebegin_nestedin_transactionin_nested_transactionget_nested_transactionget_transactionbeginr   after_beginclose)r_   r   rS   local_connectshould_commitconntransactionbind_is_connections           r,   r   'SessionTransaction._connection_for_bind  s   $$$ 		< $$T*1--<<<<44TMD;;  $ 1 122;;$"3"33 444  4 ||~ $"	 --B0AB||$$)="113"//1$$&& --//"&"="="?K"&"6"6"8K$)M"jjl ",D&2C2C!D &&	H Dd#d&7&7&D LL!!--dllDGK!	 

s   8CI I!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.)r   r+   r3  r   r   _prepare_implre   s    r,   prepareSessionTransaction.prepare  s>    <<#4<<+@+@,,!  	r.   c                    U R                  5         U R                  b  U R                  (       a/  U R                  R                  R                  U R                  5        U R                  R                  n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                  cY  U R                  R                  (       a>   [!        U R"                  R%                  5       5       H  nUS   R'                  5         M     [.        U l        g !   [(        R*                  " 5          U R-                  5         S S S 5         M?  ! , (       d  f        NN= f= f)Nr  d   zrOver 100 subsequent flushes have occurred within session.commit() - is an after_flush() hook creating new objects?r   )r   r   r   r+   r   before_commitr   r  commitr  range	_is_cleanr  r   
FlushErrorr3  r}   r   valuesrE  r   safe_reraiserollbackrK   r   )r_   stxsubtransaction_flush_guardts        r,   rD   SessionTransaction._prepare_impl  sI   <<4;;LL!!//=ll''?"%"?"?T"?"J%%' #K ||%% %c
<<))++""$ !+
 nn,  <<DLL$9$9$T..5578AaDLLN 9 	$&&(MMO )(((s*   =F G%G6G
G	GGc                 \   U R                  SS9  U R                  [        La  U R                  5         U R                  b  U R
                  (       a  [        U R                  R                  5       5       H  u  p#pEU(       d  M  UR                  5         M!     [        U l        U R                  R                  R                  U R                  5        U R                  5         U R                  5         U(       a*  U R                  (       a  U R                  R                  SS9$ U R                  $ )NT)r   _to_root)r   r   rK   rD  r   r   r}   r   rO  rK  rL   r+   r   after_commitr-  r<  )r_   rY  r?  transr>  	autocloses         r,   rK  SessionTransaction.commit=  s    -;;h& <<4;;9<!!((*:5] !=LLN	: $DKLL!!..t||<!!#

<<&&&55||r.   c                 j   U R                  SSS9  U R                  R                  nX0La&  UR                  U S9 H  nUR	                  5         M     U nS nU 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     [        Ul        U R                  R                  R!                  U R                  5        [        Ul        UR'                  UR                  S9  Un  O[        Ul        M     U R                  n	U(       dD  U	R)                  5       (       d/  [*        R,                  " S5        UR'                  UR                  S9  U R	                  5         U R                  (       a.  U(       a'  ["        R$                  " 5       S   U R                  l        U(       a  [*        R0                  " US   US   S9  U	R                  R3                  X5        U(       a*  U R                  (       a  U R                  R                  SS	9$ U R                  $ !   ["        R$                  " 5       n GNq= f! [        Ul        UR'                  UR                  S9  f = f)
NT)r   r   rH  r   )r   z\Session's state has been changed on a non-active transaction - this state will be discarded.r   with_tracebackrX  )r   r+   r   r  r<  r   rJ   rK   r   r   r}   r   rO  rQ  rM   r   after_rollbacksysexc_infor%  rM  r   r0  r   raise_after_soft_rollback)
r_   _capture_exceptionrY  rR  rS  boundaryrollback_errr@  rU  sesss
             r,   rQ  SessionTransaction.rollbackU  s   $?ll''?"%"?"?T"?"J$$& #K ;;68,,#==?&&.+2D2D!$[%=%=%D%D%F!GAaDMMO "H .6*--<<T\\J .6*#55'2'9'9 6   +H)1K&%  @( ||DNN$4$4 II%
 &&(//&B

<<./2||~a/@DLL,KKQQH))$5<<(($(77||K6'*||~-5*#55'2'9'9 6 s   !A7I//J	J&J2c                 H   U R                   (       a  U R                  U R                  l        U R                  U R                  l        U R                  c  [        U R                  R                  5       5       H^  u  p#pEU(       a  UR                  5         U(       a!  UR                  (       a  UR                  5         U(       d  MN  UR                  5         M`     [        U l        U R                  R                  R                  U R                  U 5        S U l        S U l        g r[   )r   r   r+   r   r   r   r}   r   rO  
invalidater   r<  rN   r   r   after_transaction_end)r_   rl  r   r@  r>  r\  s         r,   r<  SessionTransaction.close  s    ;;11 LL, %)LL!<<EH!!((*FA
 ))+ [%:%:%%'9$$&F 33DLL$G r.   c                     U R                   $ r[   r*   re   s    r,   _get_subjectSessionTransaction._get_subject  s    ||r.   c                 &    U R                   [        L $ r[   )r   rJ   re   s    r,   _transaction_is_active)SessionTransaction._transaction_is_active      {{f$$r.   c                 &    U R                   [        L $ r[   )r   rN   re   s    r,   _transaction_is_closed)SessionTransaction._transaction_is_closed  ru  r.   c                 4    U R                   [        [        4;  $ r[   )r   rL   rN   re   s    r,   _rollback_can_be_called*SessionTransaction._rollback_can_be_called  s    {{9f"555r.   )
r   r	  r
  r  r  r   r   r   r   r+   )NFF)FFFzThis transaction is closedr[   FFF)rA   rB   rC   rD   rE   r   rb   r   r   r   r   r   r   r   r   r  r   r%  r-  r   rE  rD  rK  rQ  r<  rp  rs  rw  rz  rI   r@   r.   r,   r"   r"     s    $L 
 K<  " F B B
 /%9N / /B
E$9 G@B,@D@08t!2%%6r.   r"   c                   "   \ rS rSrSrSr\R                  " SS9          S[S j5       rSr	Sr
S	 rS
 r\R                  S 5       r\\R                   " SSSS9S 5       5       rS rS rS rS rS r\R.                  S 5       rS r\R                  " SS9S\S j5       rS rS rS rS r   S]S jrS^S jr S\RB                  SSS4S  jr"S\RB                  S4S! jr#S\RB                  S4S" jr$S# r%S$ r&S% r'S& r(S' r)S( r*S) r+     S_S* jr,S+ r-S\.R^                  S4S, jr0\\R                  S- 5       5       r1S. r2S`S/ jr3S0 r4S^S1 jr5S2 r6S^S3 jr7S4 r8SaS5 jr9S6 r:S7 r;S8 r<SbS9 jr=S: r>S; r?S< r@S= rA     ScS> jrB     ScS? jrCSdS@ jrD    SeSA jrESB rFSC rGSaSD jrHSE rISF rJSG rKSH rLSI rMSJ rNSK rOS^SL jrPSM rQSN rRS^SO jrS   SfSP jrT SgSQ jrUSR rVSS rWSbST jrX\SU 5       rYSrZ \SV 5       r[\SW 5       r\\SX 5       r]\SY 5       r^SZr_g)hr!   i  z|Manages persistence operations for ORM-mapped objects.

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


F)2.0aO  The :paramref:`.Session.autocommit` parameter is deprecated and will be removed in SQLAlchemy version 2.0.  The :class:`_orm.Session` now features "autobegin" behavior such that the :meth:`.Session.begin` method may be called if a transaction has not yet been started yet.  See the section :ref:`session_explicit_begin` for background.)
autocommitNTc                 f   [         R                  " 5       U l        0 U l        0 U l        Xl        0 U l        SU l        SU l        SU l	        SU l
        X0l        [        5       U l        X l        X@l        Xl        U(       a%  U(       a  ["        R$                  " S5      eSU l        OSU l        X`l        U
(       a  U
O[*        R,                  U l        U	(       a  U R0                  R3                  U	5        Ub*  UR5                  5        H  u  pU R7                  X5        M     U [8        U R                  '   g)a  Construct a new Session.

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

:param autocommit:
  Defaults to ``False``. When ``True``, the
  :class:`.Session` does not automatically begin transactions for
  individual statement executions, will acquire connections from the
  engine on an as-needed basis, releasing to the connection pool
  after each statement. Flushes will begin and commit (or possibly
  rollback) their own transaction if no transaction is present.
  When using this mode, the
  :meth:`.Session.begin` method may be used to explicitly start
  transactions, but the usual "autobegin" behavior is not present.

: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. It's typical that ``autoflush`` is used in conjunction
   with ``autocommit=False``. In this scenario, explicit calls to
   :meth:`~.Session.flush` are rarely needed; you usually only need to
   call :meth:`~.Session.commit` (which flushes) to finalize changes.

   .. seealso::

       :ref:`session_flushing` - additional background on autoflush

: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://engine1'),
        SomeDeclarativeBase: create_engine('postgresql://engine2'),
        some_mapper: create_engine('postgresql://engine3'),
        some_table: create_engine('postgresql://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: defaults to ``True``.  A flag 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: if True, use 2.0 style transactional and engine
  behavior.  Future mode includes the following behaviors:

  * The :class:`_orm.Session` will not use "bound" metadata in order
    to locate an :class:`_engine.Engine`; the engine or engines in use
    must be specified to the constructor of :class:`_orm.Session` or
    otherwise be configured against the :class:`_orm.sessionmaker`
    in use

  * The "subtransactions" feature of :meth:`_orm.Session.begin` is
    removed in version 2.0 and is disabled when the future flag is
    set.

  * The behavior of the :paramref:`_orm.relationship.cascade_backrefs`
    flag on a :func:`_orm.relationship` will always assume
    "False" behavior.

  .. versionadded:: 1.4

  .. 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.

FNz,Cannot use autocommit mode with future=True.T)r   WeakInstanceDictr  r  r	  r   _Session__bindsr  _warn_on_eventsr   r   future_new_sessionidhash_key	autoflushr(  enable_baked_queriesr   ArgumentErrorr  r3  r
   Query
_query_clsinforl   r  	_add_bind	_sessions)r_   r   r  r  r(  r  r3  bindsr  r  	query_clsr  s               r,   rb   Session.__init__  s    L %557		$ #' &(" 0$8!**B  #DO#DO '0)ekkIIT""[[]	s) + $(	$-- r.   c                     U $ r[   r@   re   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:  re   s    r,   _maker_context_managerSession._maker_context_manager  s/     
  T Ts)   A=,=	A
:	=
AAz :attr:`_orm.Session.transaction`zFor context manager use, use :meth:`_orm.Session.begin`.  To access the current root transaction, use :meth:`_orm.Session.get_transaction`.)alternativewarn_on_attribute_accessc                 "    U R                  5       $ )a  The current active or inactive :class:`.SessionTransaction`.

May be None if no transaction has begun yet.

.. versionchanged:: 1.4  the :attr:`.Session.transaction` attribute
   is now a read-only descriptor that also may return None if no
   transaction has begun yet.


)_legacy_transactionre   s    r,   r@  Session.transaction  s    ( ''))r.   c                 \    U R                   (       d  U R                  5         U R                  $ r[   )r  
_autobeginr   re   s    r,   r  Session._legacy_transaction  s    {{OO   r.   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   re   s    r,   r6  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   re   s    r,   r7  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   r   r_   r[  s     r,   r9  Session.get_transaction  s=     !!EMM$=MME EMM$=r.   c                     U R                   $ )zSReturn the current nested transaction in progress, if any.

.. versionadded:: 1.4

r  re   s    r,   r8  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@   re   s    r,   r  Session.info  s	     	r.   c                 x    U R                   (       d)  U R                  c  [        U SS9nU R                  UL d   egg)NTr   F)r  r   r"   r  s     r,   r  Session._autobegin  s:    4#4#4#<&tt<E$$---r.   )r  zThe :paramref:`_orm.Session.begin.subtransactions` flag is deprecated and will be removed in SQLAlchemy version 2.0.  See the documentation at :ref:`session_subtransactions` for background on a compatible alternative pattern.)subtransactionsc                    U(       a  U R                   (       a  [        S5      eU R                  5       (       a!  U(       d  U(       d  U(       d  U R                  $ U R                  bn  U(       d  U(       d  U(       aC  U R                  R	                  US9nU R                  UL d   eU(       a  X@l        U R                  $ [        R                  " S5      eU R                  (       d@  U(       d  U(       d  U(       a   e[        U 5      nU R                  UL d   e U R                  $ U R                   (       a   e[        XS9nU R                  UL d   eU R                  $ )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`.

:param subtransactions: if True, indicates that this
 :meth:`~.Session.begin` can create a "subtransaction".

: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_autocommit` for
 an example.

.. seealso::

    :ref:`session_autobegin`

    :ref:`unitofwork_transaction`

    :meth:`.Session.begin_nested`


z>subtransactions are not implemented in future Session objects.r   z/A transaction is already begun on this Session.)
r  NotImplementedErrorr  r   r   r   r   r   r  r"   )r_   r  r   	_subtransr[  s        r,   r:  Session.begin  s-   ` t{{%# 
 ??"6)(((()v))000?((E111/4,$    ! 00E   iGG&t,E$$---    	 {{"?&t;E$$---   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.

Tr   r  re   s    r,   r5  Session.begin_nestedH  s    . zzz&&r.   c                 f    U R                   c  gU R                   R                  U R                  S9  g)aG  Rollback the current transaction in progress.

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

In :term:`1.x-style` use, this method rolls back the topmost
database transaction if no nested transactions are in effect, or
to the current nested transaction if one is in effect.

When
:term:`2.0-style` use is in effect via the
:paramref:`_orm.Session.future` flag, 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`

NrX  )r   rQ  r  re   s    r,   rQ  Session.rollbacka  s.    , $&&&<r.   c                     U R                   c+  U R                  5       (       d  [        R                  " S5      eU R                   R	                  U R
                  S9  g)a5  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.

If :term:`1.x-style` use is in effect and there are currently
SAVEPOINTs in progress via :meth:`_orm.Session.begin_nested`,
the operation will release the current SAVEPOINT but not commit
the outermost database transaction.

If :term:`2.0-style` use is in effect via the
:paramref:`_orm.Session.future` flag, the outermost database
transaction is committed unconditionally, automatically releasing any
SAVEPOINTs in effect.

When using legacy "autocommit" mode, this method is only
valid to call if a transaction is actually in progress, else
an error is raised.   Similarly, when using legacy "subtransactions",
the method will instead close out the current "subtransaction",
rather than the actual database transaction, if a transaction
is in progress.

.. seealso::

    :ref:`session_committing`

    :ref:`unitofwork_transaction`

    :ref:`asyncio_orm_avoid_lazyloads`

NNo transaction is begun.rX  )r   r  r   r   rK  r  re   s    r,   rK  Session.commit|  sK    \ $??$$001KLL  $++ 6r.   c                     U R                   c+  U R                  5       (       d  [        R                  " S5      eU R                   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.

Nr  )r   r  r   r   rE  re   s    r,   rE  Session.prepare  sA     $??$$001KLL!!#r.   c                     U(       d  UnUR                  SS5      nUc  U R                  " S0 UD6nU R                  UUUS9$ )a  Return a :class:`_engine.Connection` object corresponding to this
:class:`.Session` object's transactional state.

If this :class:`.Session` is configured with ``autocommit=False``,
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).

Alternatively, if this :class:`.Session` is configured with
``autocommit=True``, an ad-hoc :class:`_engine.Connection` is returned
using :meth:`_engine.Engine.connect` on the underlying
:class:`_engine.Engine`.

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 bind:
  deprecated; use bind_arguments

:param mapper:
  deprecated; use bind_arguments

:param clause:
  deprecated; use bind_arguments

:param close_with_result: Passed to :meth:`_engine.Engine.connect`,
  indicating the :class:`_engine.Connection` should be considered
  "single use", automatically closing when the first result set is
  closed.  This flag only has an effect if this :class:`.Session` is
  configured with ``autocommit=True`` and does not already have a
  transaction in progress.

  .. deprecated:: 1.4  this parameter is deprecated and will be removed
     in SQLAlchemy 2.0

: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`

:param \**kw:
  deprecated; use bind_arguments

r   N)close_with_resultrS   r@   )popr   r   )r_   rU   r  rS   kwr   s         r,   r   Session.connection  sV    B N!!&$/<==2>2D((// ) 
 	
r.   c                 F   [         R                  " U 5        U R                  c  U R                  5       (       a  U R                  R	                  X5      $ U R                  b   eU R
                  (       d   eUR                  " S0 UD6nU(       a  UR                  " S0 UD6nU$ )Nr@   )r   r   r   r  r   r  r2  rS   )r_   r   rS   r  r?  s        r,   r   Session._connection_for_bind  s    --d3(DOO,=,=$$99    (((~~##))>,=>Dr.   c           	         [         R                  " [        R                  U5      nU(       a2  [        R
                  " S5        U(       d  UnO'UR                  U5        OU(       d  0 nO[        U5      nUR                  R                  SS5      S:X  a  [        R                  " US5      nOSn[        R                  " U5      nUb  UR                  U UUUUUSL5      u  nnO%UR                  SU5        UR                  SS05      nU(       a  UR!                  5       n	O,U R"                  R$                  n	U(       a  ['        U	5      U/-   n	U	(       aV  [)        U UUUUUU	5      n
[+        U	5       H  u  pXl        U" U
5      nU(       d  M  Us  $    U
R.                  nU
R0                  nU R2                  " S0 UD6nU R4                  (       a)  U R7                  USS9nUR                  [        S	S
95      nOU R7                  U5      nUR9                  X=(       d    0 U5      nU(       a  UR;                  U UUUUU5      nU$ )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:`_future.Connection.execute`, the :term:`2.0 style` version
of :class:`_future.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.

: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.

:param mapper:
  deprecated; use the bind_arguments dictionary

:param bind:
  deprecated; use the bind_arguments dictionary

:param \**kw:
  deprecated; use the bind_arguments dictionary

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


zPassing bind arguments to Session.execute() as keyword arguments is deprecated and will be removed SQLAlchemy 2.0. Please use the bind_arguments parameter.compile_state_pluginNormclausefuture_resultT)r  F)r  r@   )r   expectr   StatementRoler   warn_deprecated_20rl   rk   _propagate_attrsru   r   _get_plugin_class_for_plugincoerce_to_immutabledictorm_pre_session_exec
setdefaultr]   rf   r   do_orm_executer^   r$   	enumeraterW   rQ   rT   r   r  r   _execute_20orm_setup_cursor_result)r_   rQ   rn   rS   rU   rj   
_add_eventr  r`   ra   orm_exec_stateidxfnr   r   r?  s                   r,   rm   Session.execute  sN   B $$U%8%8)D	##;
 "!#%%b)N!.1N &&**+A4H !- I I5! !% 889JK( "66!%T1! %%h	: 1 7 7 $'! !/AACK--66K";/:,>,!!N %[1582N+6!M	 2 '00I . F F}}.~.?? ,,TT,JD 1 7 75)! ,,T2D!!)\r;LM&>>!F r.   c                 L    U R                   " U4UUUS.UD6R                  5       $ )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.

rn   rS   rU   )rm   scalarr_   rQ   rn   rS   rU   r  s         r,   r  Session.scalar  s9      ||
/)	

 
 &(	r.   c                 L    U R                   " U4UUU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`

r  )rm   scalarsr  s         r,   r  Session.scalars  s9    . ||
/)	

 
 ')	r.   c                 "    U R                  SS9  g)al  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::

    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.

.. 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`

Frl  N_close_implre   s    r,   r<  Session.close  s    < 	E*r.   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  re   s    r,   rl  Session.invalidate  s    D 	D)r.   c                     U R                  5         U R                  b3  U R                  R                  5        H  nUR                  U5        M     g g r[   )expunge_allr   r  r<  )r_   rl  r@  s      r,   r  Session._close_impl>  sG    (#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^   r  _killr   r  r	  r)  r*  r+  )r_   r  s     r,   r  Session.expunge_allD  sj     &&113d499oE
!$557	--j?r.   c                     [        U5      nUR                  (       a  X R                  U'   g UR                  (       a:  X R                  UR                  '   UR
                   H  nX R                  U'   M     g [        R                  " SU-  5      e! [        R                   a^  n[        U[        5      (       d1  [        R                  " [        R                  " SU-  5      US9   S nAg X R                  U'    S nAg S nAff = f)Nz!Not an acceptable bind target: %sreplace_context)r   is_selectabler  	is_mapperclass__all_tablesr   r  NoInspectionAvailabler   typer   rd  )r_   r  r   r   _selectableerrs         r,   r  Session._add_bindT  s    	3<D !!%)T",0T[[)#'#3#3K04LL- $4 **7#= % ++ 		)c4((((;cA %(	 %)S!		)s   B D%AC>+C>>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_   rt   r   s      r,   rv   Session.bind_mapperm  s    4 	v$r.   c                 &    U R                  X5        g)a<  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_table  s    4 	u#r.   c                 \   U(       a  U$ U R                   (       d  U R                  (       a  U R                  $ Xs=L a  c6  O  O3U R                  (       a  U R                  $ [        R                  " S5      eUb   [	        U5      nU R                   (       a  U(       aL  UR                  R                   H#  nXpR                   ;   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XpR                   ;   d  M  U R                   U   s  $    [$        R&                  " U5       H#  n	XR                   ;   d  M  U R                   U	   s  $    U R                  (       a  U R                  $ Sn
SnU(       a  Uc  UR                  nUbG  UR                  (       a6  U R(                  (       a  Sn
O"[        R*                  " S5        UR                  $ U(       a[  UR                  R                  (       a@  U R(                  (       a  Sn
O,[        R*                  " S5        UR                  R                  $ / nUb  UR,                  " SU-  5        Ub  UR,                  " S	5        [        R                  " S
SR/                  U5      < SU
< 3US9e! [        R
                   aJ  n[        U[        5      (       a/  [        R                  " [        R                  " U5      US9   SnAGNe 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 :func:`.mapper` mapped class or instance of
  :class:`_orm.Mapper`.   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.r  plugin_subject zr A bind was located via legacy bound metadata, but since future=True is set on this Session, this bind is ignored.zThis Session located a target engine via bound metadata; as this functionality will be removed in SQLAlchemy 2.0, an Engine object should be passed to the Session() constructor directly.z	mapper %szSQL expressionz&Could not locate a bind configured on , z or this Session.r   )r  r   r   UnboundExecutionErrorr   r  r   r  r   rd  r   UnmappedClassErrorr  __mro__persist_selectabler  ru   rt   r   iterater  r  r   join)r_   rt   r  r   ri   _sa_skip_for_implicit_returningr   r3   r
  obj
future_msgfuture_coder   s                r,   r   Session.get_bind  s   j K$)) 99
 ##yyyy 22!  	  << !==00Cll*#||C00 1 >#66F!!'!8!8!<!<$d" "--44;;CC,,.#'<<#44  D $++F3Cll*#||C00 4 9999
 
fn..F{{;;+  ++A ";;&((--;;+  ++A "44999NN;/0NN+,**yy!:/
 	
q // fd++KK..v6(+ 
 s   :K L+!>L&%L&&L+c                 (    U R                   " X40 UD6$ )zXReturn a new :class:`_query.Query` object corresponding to this
:class:`_orm.Session`.

)r  )r_   entitiesr;   s      r,   r
   Session.queryp  s     x888r.   c                 N    UR                  X#S9n[        R                  " XXd5      $ )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.


identity_token)identity_key_from_primary_keyr   get_from_identity)r_   rt   primary_key_identityr  passiver   r  s          r,   _identity_lookupSession._identity_lookupx  s2    b 22  3 
 ((sDDr.   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   -" -*-c                 (   U R                   (       a$  U R                  (       d   U R                  5         g g g ! [        R                   aF  nUR                  S5        [        R                  " U[        R                  " 5       S   S9   S nAg 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 prematurelyr   r_  )
r  r  r  r   StatementError
add_detailr   rd  rb  rc  )r_   es     r,   
_autoflushSession._autoflush  sm    >>$..A

 #1> (( 
A
 5
 AcllnQ.?@
As   7 B<BBc           	      ,    [         R                  " U5      nU R                  WU5        U0 :X  a  [        R                  " S5      e[        R                  R                  U5      n[        R                  " [        U5      5      n[         R"                  " U UUR$                  UUUS9 c"  [        R&                  " S[)        U5      -  5      eg! [        R                   a3  n[        R
                  " [        R                  " U5      US9   SnANSnAff = f)a	  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.
Unloaded relationship attributes will remain unloaded, as will
relationship attributes that were originally lazy loaded.

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

.. 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.

r  Nzqwith_for_update should be the boolean value True, or a dictionary with options.  A blank dictionary is ambiguous.)refresh_statewith_for_updateonly_load_propszCould not refresh instance '%s')r   instance_stater   NO_STATEr   rd  UnmappedInstanceError_expire_stater   r  r
   ForUpdateArg_from_argumentr   selectr   r   load_on_identr  r   r   )r_   r>   attribute_namesr/  r   r   stmts          r,   refreshSession.refresh  s    t	--h7E 	5/2b &&3   ,,;;OLzz-12!!		# / /  ,,1L4JJ ' || 	KK))(3 #	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` should not be needed when
autocommit is ``False``, 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  rk   r  r_   r   s     r,   
expire_allSession.expire_all7	  s<    @ &&113EMM%**d&7&7&A&AB 4r.   c                      [         R                  " U5      nU R                  WU5        g! [        R                   a3  n[        R
                  " [        R                  " U5      US9   SnANUS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`

r  N)r   r1  r   r2  r   rd  r3  r4  )r_   r>   r9  r   r   s        r,   expireSession.expireZ	  s]    J	--h7E 	5/2 || 	KK))(3 #	s   + A2)A--A2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_attributesrk   r^   managerrt   cascade_iterator_conditional_expire)r_   r   r9  cascadedomst_dct_s           r,   r4  Session._expire_state	  sz    !!%($$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  rk   r  r  r  r  _detach)r_   r   r  s      r,   rI  Session._conditional_expire	  sT     99MM%**d&7&7&A&ABiiIIMM% MM$  r.   c                     [         R                  " U5      nW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                   a3  n[        R
                  " [        R                  " U5      US9   SnANS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.

r  Nz*Instance %s is not present in this Sessionexpunge)r   r1  r   r2  r   rd  r3  
session_idr  r   r   r   r^   rG  rt   rH  r  )	r_   r>   r   r   rJ  rK  rL  rM  rN  s	            r,   rT  Session.expunge	  s    	--h7E 4==0,,<y?OO  MM  11)UC
 	eW8'L8c8'LLM || 	KK))(3 #	 (Ms   B2 C<2C9)C44C9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  )
r  r  r  contains_stater  r	  r   r)  r*  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  a~  U R                  R                  U5        X0R                  R                   ;   a  U R                  R                   U   S   nOUR                  nUU4U R                  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[   )rk   ).0r   s     r,   	<genexpr>/Session._register_persistent.<locals>.<genexpr>
  s     5fUUZZ fs   )r   pending_to_persistentr   r  _identity_key_from_stater   intersectionallow_partial_pks
issupersetr   rN  r   r  r  r  r   r  r  r   r0  _orphaned_outside_of_sessionr)  r*  _commit_all_states_register_alteredr  r}   r  )	r_   rY  r`  r   rt   r  instance_key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 1 1 ? ??#'#4#4#B#B5#I!#L#(99 $>D%%33E: !-I
 ''//6O77<L	-II 0<> 6;2s v 	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   r  r
  )r_   rY  r   s      r,   rg  Session._register_altered
  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 rn  )r   persistent_to_deletedr   r	  r  r  r  r  )r_   rY  rq  r   r  s        r,   _remove_newly_deletedSession._remove_newly_deleted 
  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                  W5        g! [        R
                   a3  n[        R                  " [        R                  " U5      US9   SnANTS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()r  N)
r  _flush_warningr   r1  r   r2  r   rd  r3  _save_or_update_state)r_   r>   _warnr   r   s        r,   r   Session.add4
  su    2 T))0	--h7E 	""5) || 	KK))(3 #	s   A B')B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)rw  N)r  ru  r   )r_   	instancesr>   s      r,   add_allSession.add_allZ
  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)re  _save_or_update_implr   rH  _contains_state)r_   r   rt   rK  rL  rM  rN  s          r,   rv  Session._save_or_update_staten
  s[    -2*!!%(u%%665*>*>  7  
OA# %%c* 
r.   c                 ,   U R                   (       a  U R                  S5         [        R                  " U5      nU R                  WUSS9  g! [        R
                   a3  n[        R                  " [        R                  " U5      US9   SnANTS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()r  NT)head)
r  ru  r   r1  r   r2  r   rd  r3  _delete_implr_   r>   r   r   s       r,   deleteSession.deletex
  s{    *  23	--h7E 	%5 || 	KK))(3 #	s   A B )BB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(       a/  [        UR                  R                  R                  SU5      5      nX R
                  U'   U(       a  W H  u  pgpU R                  XS5        M     g g )NInstance '%s' is not persistedr  F)r  r   r   r   _before_attachr	  r  r   _after_attachr^   rG  rt   rH  r  )
r_   r   r  r  	to_attachcascade_statesrK  rL  rM  rN  s
             r,   r  Session._delete_impl
  s    99004y7GG  ''3	MM!e$u* "$$55hFN  #e#1c!!#%0 $2 r.   c                 J    U R                  UU[        R                  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 deprecated :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

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

)populate_existingr/  r  rS   )	_get_implr   load_on_pk_identity)r_   ry   identoptionsr  r/  r  rS   s           r,   ru   Session.get
  s9    R ~~''/+)/  	
 		
r.   c	           
        ^ [        TS5      (       a  TR                  5       m[        U5      n	U	(       a  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(       dd  U	R*                  (       dS  UcP  U R-                  U	TUS9nUb(  [/        UR0                  U	R2                  5      (       d  g U$ U[4        R6                  L a  g [8        R:                  R<                  nU(       a  USU0-  n[>        R@                  " U	5      RC                  [D        5      nUb$  [F        RH                  RK                  U5      Ul&        U(       a  URN                  " U6 nU(       a  URP                  " S0 UD6nU" U UTUS9$ ! [&         aW  n[        R(                  " [        R                  " S	SR                  S
 U	R$                   5       5      -  5      US9   S nAGNwS nAff = f)N__composite_values__z(Expected mapped class or mapper, got: %rr[   )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>Q  s     #K8J1FQJ8Js   c              3   B   >#    U  H  nTUR                      v   M     g 7fr[   r  )r]  propr   s     r,   r^  r  e  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r  r  )r]  r  s     r,   r^  r  p  s       #(B #TXX-(Bs   r  r  _populate_existing)r   r@   ))hasattrr  r   r  r   r  r   rk   r   to_listlenprimary_keyr   r  _pk_synonymsr}   rb  r^   _identity_key_propsKeyErrorrd  always_refreshr"  
issubclass	__class__r  r   PASSIVE_CLASS_MISMATCHr   r   r   r   r7  set_label_styler    r
   r5  r6  _for_update_argr  rS   )r_   ry   r   
db_load_fnr  r  r/  r  rS   rt   is_dictpk_synonymscorrect_keyskr   r>   r   rQ   s     `               r,   r  Session._get_impl0  s    ')?@@#7#L#L#N V--&&:VC  148#'<<$g$  #$F,>,>(??,,88#K8J8J#KKL   --K";/<<(   +/0D+E() 13 -'N *
'+ , & : :, ($( "))' ,,,^ - H # "("4"4fmmDDZ>>> ++@@13DEELJJv&66*
	 &(-(:(:(I(I)I% !))73I!33H6GHI %	
 	
k  ..I (( #(.(B(B#  %( s    I: :
KAKK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)an
  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.

.. versionchanged:: 1.1 - :meth:`.Session.merge` will now reconcile
   pending objects with overlapping primary keys in the same way
   as persistent.  See :ref:`change_3601` for discussion.

: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)loadr  
_recursive_resolve_conflict_map)	r  ru  r+  r   r  _merger   r1  instance_dict)r_   r>   r  r  r  r  r  s          r,   mergeSession.merge  s    x  12
 "OOhNN		'"DN;;))(3((2%&;   'NYNs   AB B'c                    [        U5      nX;   a  XQ   $ 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
XR                  ;   a   U R                  U	   nOS nUc  U
(       a
  X;   a  Xi   nOU(       dq  UR"                  (       a  [        R                  " S5      eUR$                  R'                  5       n[        R(                  " U5      nXl        U R+                  U5        SnO)U
(       a"  U R-                  UR.                  U	S   U	S   US9nUcZ  UR$                  R'                  5       n[        R(                  " U5      n[        R0                  " U5      nSnU R3                  U5        O,[        R(                  " U5      n[        R0                  " U5      nXU'   XU	'   XLGa  UR4                  b  UR7                  UUUR4                  [        R8                  S	9nUR7                  UUUR4                  [        R8                  S	9nU[        R:                  LaD  U[        R:                  La1  X:w  a,  [<        R>                  " S
U< S[        U5      < SU< S35      eUR@                  Ul         URB                  Ul!        URE                  U5        URF                   H  nURI                  U UUUUUUU5        M     U(       dA  URK                  XR                  5        URL                  RN                  RQ                  US 5        U(       a&  URL                  RN                  RS                  US 5        U$ ! [          a    S n GNf = f)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.r   )r  r  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   r0  r   r   r   ra  r   	NEVER_SETr   rb  rc  rd  r  r  r  class_managernew_instancer1  r  ru   r  r  rv  version_id_col_get_state_attr_by_columnPASSIVE_NO_INITIALIZEPASSIVE_NO_RESULTr   StaleDataError	load_pathr   _copy_callablesiterate_propertiesr  _commit_allrG  r   _sa_event_merge_wo_loadr  )r_   r   
state_dictr  r  r  r  rt   r  r  key_is_persistentmergedmerged_statemerged_dictexisting_versionmerged_versionr  s                    r,   r  Session._merge  s    u%$$ii;		!		'./ 00"  11%8C * 4 4CF B !**3q622 ,, 9%00Q88	  !%###**3/
 F> S%A.3>> 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 " %J,H,HH&j.J.JJ(:,, -%l3*
 
 &+__L"(-(:(:L% ((/11

 )	 2 $$[2C2CD  ))AAd   ))..|TB_  s   O5 5PPc                     U R                   R                  U5      (       d"  [        R                  " S[	        U5      -  5      eg )Nz3Instance '%s' is not persistent within this Session)r  rX  r   r   r   r>  s     r,   rE  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  r  r  r  insert_orderr  )r_   r   r  r  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 )Nr  zsInstance '%s' has been deleted.  Use the make_transient() function to send this object back to the transient state.)r  r   r   r   r	  	_attachedr  r  r  r  r  r   r  r   deleted_to_persistent)r_   r   r  r  r  s        r,   r  Session._update_impl  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,   r  Session._save_or_update_impl  s&    99OOE"e$r.   c                 *    [         R                  " U5      nU R                  WU5      nSUl        U(       a  U R                  X!5        gg! [        R                   a3  n[        R
                  " [        R                  " U5      US9   SnANuS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.

r  NT)
r   r1  r   r2  r   rd  r3  r  _load_pendingr  )r_   r  r   r   r  s        r,   enable_relationship_loading#Session.enable_relationship_loading  s}    n	--c2E ''s3	"u*  || 	KK))#. #	s   A B)BB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  rU  r  r  r   r   r   r   before_attachr_   r   r  s      r,   r  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  rU  r  _strong_objr   after_attachr  detached_to_persistenttransient_to_pendingr  s      r,   r  Session._after_attach0  sc    ==>>e//7 #""4/99MM00=MM..t;r.   c                      [         R                  " U5      nU R                  W5      $ ! [        R                   a3  n[        R
                  " [        R                  " U5      US9   SnANSS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.

r  N)r   r1  r   r2  r   rd  r3  r  r  s       r,   __contains__Session.__contains__;  s]    	--h7E ##E** || 	KK))(3 #	s   ) A0)A++A0c                     [        [        U R                  R                  5       5      [        U R                  R                  5       5      -   5      $ )zGIterate over all pending or persistent instances within this
Session.

)iterr^   r  rO  r  re   s    r,   __iter__Session.__iter__K  s?    
 !!#$tD,=,=,D,D,F'GG
 	
r.   c                 b    XR                   ;   =(       d    U R                  R                  U5      $ r[   )r  r  rX  r>  s     r,   r  Session._contains_stateT  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)a  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.

For ``autocommit`` Sessions with no active manual transaction, flush()
will create a transaction on the fly that surrounds the entire set of
operations into the flush.

: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   rM  _flush)r_   objectss     r,   r  Session.flushW  sT    6 >>,,-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   r0  )r_   methods     r,   ru  Session._flush_warning}  s!    		F IOO	
r.   c                     U R                   R                  5       (       + =(       a)    U R                  (       + =(       a    U R                  (       + $ r[   )r  check_modifiedr	  r  re   s    r,   rM  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%                  W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R0                  (       a  U R3                  U/5        Me  UR5                  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R5                  USS9nU(       a  M   S5       e   UR6                  (       d  g U R9                  SS9=Ul        n SU l         UR?                  5         SU l        U R                  RA                  X5        URC                  5         U(       d  U R                  R                  (       a  [E        U R                  R                  5      n[F        RH                  RK                  U R                  R                   Vs/ s H  nXRL                  4PM     snU R                  S9  [        RN                  " SU-  5        U R                  RQ                  X5        URS                  5         g ! [        R                   a4  n	[        R                   " [        R"                  " U5      U	S9   S n	A	GNS n	A	ff = f! SU l        f = fs  snf !   [        RT                  " 5          URW                  SS	9  S S S 5         g ! , (       d  f        g = f= f)
Nr  )isdeletez*Failed to add object to the flush context!Tr  F)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.rf  ),_dirty_statesr	  r  r  r  r,  r   r   before_flushr}   
differencer   r1  r   r2  r   rd  r3  r   r]   rb  r   
_is_orphanhas_identityre  r  register_objecthas_workr:  r@  r  rm   after_flushfinalize_flush_changesr  r)  r*  rf  rk   r0  after_flush_postexecrK  rP  rQ  )r_   r  dirtyflush_contextdeletednewobjsetrK  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  %%26**t*2LL!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 s || KK11!4(+ n (-$4	>""$$$$= %$$$sh   O5P9 =P( B$P9 1P4AP9 P%1)P  P%(	P11P9 9Q<Q* Q<*
Q9	4Q<9Q<c           
          S U 5       nU(       d  [        US S9nS n[        R                  " XV5       H  u  u  pxn	U R                  UU	USUUS5        M!     g)a5  Perform a bulk save of the given list of objects.

The bulk save feature allows mapped objects to be used as the
source of simple INSERT and UPDATE operations which can be more easily
grouped together into higher performing "executemany"
operations; the extraction of data from the objects is also performed
using a lower-latency process that ignores whether or not attributes
have actually been modified in the case of UPDATEs, and also ignores
SQL expressions.

The objects as given are not added to the session and no additional
state is established on them. If the
:paramref:`_orm.Session.bulk_save_objects.return_defaults` flag is set,
then server-generated primary key values will be assigned to the
returned objects, but **not server side defaults**; this is a
limitation in the implementation. If stateful objects are desired,
please use the standard :meth:`_orm.Session.add_all` approach or
as an alternative newer mass-insert features such as
:ref:`orm_dml_returning_objects`.

.. legacy::

    The bulk save feature allows for a lower-latency INSERT/UPDATE
    of rows at the expense of most other unit-of-work features.
    Features such as object management, relationship handling,
    and SQL clause support are silently omitted in favor of raw
    INSERT/UPDATES of records.

    In SQLAlchemy 2.0, improved versions of the bulk insert/update
    methods are introduced, with clearer behavior and
    documentation, new capabilities, and much better performance.

    For 1.4 use, **please read the list of caveats at**
    :ref:`bulk_operations_caveats` **before using this method, and
    fully test and confirm the functionality of all code developed
    using these systems.**

: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.

 .. versionadded:: 1.3

.. seealso::

    :ref:`bulk_operations`

    :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   r1  )r]  r  s     r,   r^  ,Session.bulk_save_objects.<locals>.<genexpr>g  s     Hj//44s   #%c                 H    [        U R                  5      U R                  S L4$ r[   )idrt   r  r   s    r,   <lambda>+Session.bulk_save_objects.<locals>.<lambda>p  s    2ell#3UYYd5J"Kr.   r  c                 6    U R                   U R                  S L4$ r[   )rt   r  r   s    r,   grouping_key/Session.bulk_save_objects.<locals>.grouping_keys  s    LL%))4"788r.   TFN)sorted	itertoolsgroupby_bulk_save_mappings)
r_   r  return_defaultsupdate_changed_onlypreserve_order
obj_statesr$  rt   isupdaterY  s
             r,   bulk_save_objectsSession.bulk_save_objects  sq    @ IH

  KJ
	9 +4*;*;+
&V $$#+
r.   c           	      2    U R                  UUSSUSU5        g)a  Perform a bulk insert of the given list of mapping dictionaries.

The bulk insert feature allows plain Python dictionaries to be used as
the source of simple INSERT operations which can be more easily
grouped together into higher performing "executemany"
operations.  Using dictionaries, there is no "history" or session
state management features in use, reducing latency when inserting
large numbers of simple rows.

The values within the dictionaries as given are typically passed
without modification into Core :meth:`_expression.Insert` constructs,
after
organizing the values within them across the tables to which
the given mapper is mapped.

.. versionadded:: 1.0.0

.. legacy::

    The bulk insert feature allows for a lower-latency INSERT
    of rows at the expense of most other unit-of-work features.
    Features such as object management, relationship handling,
    and SQL clause support are silently omitted in favor of raw
    INSERT of records.

    In SQLAlchemy 2.0, improved versions of the bulk insert/update
    methods are introduced, with clearer behavior and
    documentation, new capabilities, and much better performance.

    For 1.4 use, **please read the list of caveats at**
    :ref:`bulk_operations_caveats` **before using this method, and
    fully test and confirm the functionality of all code developed
    using these systems.**

: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, 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_insert_mappings.return_defaults`
 **greatly reduces the performance gains** of the method overall.
 If the rows
 to be inserted only refer to a single table, then there is no
 reason this flag should be set as the returned default information
 is not used.

: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.

 .. versionadded:: 1.1

.. seealso::

    :ref:`bulk_operations`

    :meth:`.Session.bulk_save_objects`

    :meth:`.Session.bulk_update_mappings`

FNr)  )r_   rt   mappingsr*  render_nullss        r,   bulk_insert_mappingsSession.bulk_insert_mappings  s(    ~ 	  	
r.   c           	      0    U R                  XSSSSS5        g)a  Perform a bulk update of the given list of mapping dictionaries.

The bulk update feature allows plain Python dictionaries to be used as
the source of simple UPDATE operations which can be more easily
grouped together into higher performing "executemany"
operations.  Using dictionaries, there is no "history" or session
state management features in use, reducing latency when updating
large numbers of simple rows.

.. versionadded:: 1.0.0

.. legacy::

    The bulk update feature allows for a lower-latency UPDATE
    of rows at the expense of most other unit-of-work features.
    Features such as object management, relationship handling,
    and SQL clause support are silently omitted in favor of raw
    UPDATES of records.

    In SQLAlchemy 2.0, improved versions of the bulk insert/update
    methods are introduced, with clearer behavior and
    documentation, new capabilities, and much better performance.

    For 1.4 use, **please read the list of caveats at**
    :ref:`bulk_operations_caveats` **before using this method, and
    fully test and confirm the functionality of all code developed
    using these systems.**

: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::

    :ref:`bulk_operations`

    :meth:`.Session.bulk_insert_mappings`

    :meth:`.Session.bulk_save_objects`

TFNr2  )r_   rt   r3  s      r,   bulk_update_mappingsSession.bulk_update_mappings  s     j 	  dE5%	
r.   c                    [        U5      nSU l        U R                  SS9n U(       a  [        R                  " UUUUU5        O[        R
                  " UUUUUU5        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)NTr  r  F)
r   r  r:  r	   _bulk_update_bulk_insertrK  r   rP  rQ  )	r_   rt   r3  r.  isstatesr*  r+  r4  r@  s	            r,   r)  Session._bulk_save_mappings%  s     "&)jj4j0	#((' ((#    #DN		>""$$$$= %$$$ #DNsB   AA8 8B<B*B<'B? *
B9	4B<7B? 9B<<B? ?	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 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  rk   rG  r   r  implrA  	NO_CHANGE)	r_   r>   include_collectionsr   dict_attradded	unchangedr  s	            r,   is_modifiedSession.is_modifiedM  s    f X&~~

MM,,D'DII'788TYY66*.))*?*?j&:&: +@ +'Uw  - r.   c                     U R                   (       a+  U R                  SL=(       a    U R                  R                  $ 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   re   s    r,   r   Session.is_active  sS    8 ??!!-M$2C2C2M2M $$,K0A0A0K0KKr.   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  re   s    r,   r  Session._dirty_states  s       ..00r.   c                     [         R                  " 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.

)r   IdentitySetr  r	  r  r>  s     r,   r  Session.dirty  sQ    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   rP  r^   r	  rO  re   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   rP  r^   r  rO  re   s    r,   r  Session.new  s'     TYY%5%5%7 899r.   )__bindsr	  r  r   r  r  r   r  r  r  r   r  r(  r  r  r  r3  )
NTFTFFNTNN)FFF)NFNr[   )NNNNF)NNr|  )T)NFNNN)TN)TNNN)FTTr}  )`rA   rB   rC   rD   rE   _is_asyncior   deprecated_paramsrb   _trans_context_managerconnection_callabler  r  contextmanagerr  r   deprecated_20r@  r  r6  r7  r9  r8  memoized_propertyr  r  r:  r5  rQ  rK  rE  r   r   
EMPTY_DICTrm   r  r  r<  rl  r  r  r  rv   r  r   r
   r   PASSIVE_OFFr"  r%  r+  r;  r?  rB  r4  rI  rT  r  rk  rg  rr  r   r{  rv  r  r  ru   r  r  r  rE  r  r  r  r  r  r  r  r  r  r  ru  rM  r  r/  r5  r8  r)  rI  r   r  r  r  r  r  rI   r@   r.   r,   r!   r!     s    K	

 !}(
}(@ " 
 
 	*0 "&* *!
-4	( 

 
 

	G!	G!R'2=627h$& 	L
\$ //"cP //6 //>+@"*H.@ 2%8$< (-I
V9 &&4El 	'  '4A [z!CF,3\. N0
P!d;3($*L,(+ 6D 1L r
r t
lS'r "\|+$=L%B+H"	<+ 
M$#L

y>|  zz EJg
R7
r&#PHT  L  LD L 1 1 
 
> > >
 : :r.   r!   c                   F    \ rS rSrSrS\SSSS4S jrS rS rS	 r	S
 r
Srg)r#   i  ax  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://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`.

NTFc                 x    XS'   X7S'   XGS'   XWS'   Ub  XgS'   Xpl         [        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.
:param autocommit: The autocommit setting to use with newly created
 :class:`.Session` objects.
: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  r(  Nr  )r  r  rA   r  )r_   r   r  r  r  r(  r  r  s           r,   rb   sessionmaker.__init__^  sN    L 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


)r  )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$ )a5  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()
    session = Session()  # invokes sessionmaker.__call__()

r  r@   )r  r  copyrl   r  r  )r_   local_kwr  vr   s        r,   __call__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  rl   )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  rh  s      r,   r^  (sessionmaker.__repr__.<locals>.<genexpr>  s     C?41A&?s   ))r  rA   r  r  r  r  re   s    r,   __repr__sessionmaker.__repr__  sB    NN##KK  IIC477==?CC
 	
r.   )r  r  )rA   rB   rC   rD   rE   r!   rb   r:  ri  rm  rt  rI   r@   r.   r,   r#   r#     s7    \@ /;b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  rO  r<  )ri  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" via :ref:`deferred` 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   r1  r-   r  expired_attributesr,  	callablesr  r	  )r>   r   r"  s      r,   r&   r&     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   r1  rU  r  r   r   rt   ra  r	  r  rk   rF  unloaded_expirable)r>   r   s     r,   r'   r'     s    : %%h/E599(()IJJ55e<EI~~N	ejj!	UZZ)A)ABr.   c                      [         R                  " U 5      n[        U5      $ ! [        R                   a3  n[
        R                  " [        R                  " U 5      US9   SnAg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.

r  N)r   r1  r-   r   r2  r   rd  r3  )r>   r   r   s      r,   r(   r(   E  sW    %))(3 e$$ << 
%%h/	

s   # A*)A%%A*)?rE   r'  rb  r  r  r   r   r   r   r   r	   r
   r   r)  baser   r   r   r   r   r   r   
unitofworkr   r   r   r   r   engine.utilr   
inspectionr   r   r   r   r   sql.baser   sql.selectabler    __all__WeakValueDictionaryr  r-   objectr0   symbolrJ   rK   rL   rM   rN   MemoizedSlotsr$   r"   r!   r#   r%   r&   r'   r(   counterr  r@   r.   r,   <module>r     sS   8  
          "       &     .       # ;	 '')	  !(6 !(H 
X	;;z"KK$	;;z"	X	p
d(( p
fP6- P6fG1:" G1:TbJ
' J
Z$=@$CN%& r.   