
    +h.{                        d Z ddlZddlZddlZddlmZ ddlmZ ddlmZ ddlmZ ddlm	Z	 dd	lm
Z
 dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlm Z  ddlm!Z! ddlm"Z" ddlm#Z# ddl$m%Z% ddl&m'Z' g d Z( ejR                         Z*	 e*e_*        d! Z+ G d" d#e,      Z- ej\                  d$      Z/ ej\                  d%      Z0 ej\                  d&      Z1 ej\                  d'      Z2 ej\                  d(      Z3 G d) d*ejh                        Z5 G d+ d,e      Z6 G d- d.e-      Z7 G d/ d0e-      Z8d1 Z9d2 Z:d3 Z;d4 Z< ejz                         Z>y)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                     | j                   S )z[Given an :class:`.InstanceState`, return the :class:`.Session`
    associated, if any.
    sessionr   s    I/var/www/html/venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py_state_sessionr-   =   s     ==    c                       e Zd ZdZe ej                  dd      d               Ze ej                  d      d               Z	ed        Z
y)	_SessionClassMethodszBClass-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                     t                y)zClose *all* sessions in memory.N)r%   )clss    r,   	close_allz_SessionClassMethods.close_allG   s
     	r.   zsqlalchemy.orm.utilc                 T    t        j                  j                  j                  |i |S )zZReturn an identity key.

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

        )r   	preloadedorm_utilidentity_key)r2   argskwargss      r,   r7   z!_SessionClassMethods.identity_keyS   s$     ~~&&33TDVDDr.   c                     t        |      S )zxReturn the :class:`.Session` to which an object belongs.

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

        )r(   )r2   instances     r,   r(   z#_SessionClassMethods.object_session]   s     h''r.   N)__name__
__module____qualname____doc__classmethodr   
deprecatedr3   preload_moduler7   r(    r.   r,   r0   r0   D   sr    LT__	/ 
 T./E 0 E ( (r.   r0   ACTIVEPREPARED	COMMITTEDDEACTIVECLOSEDc                   ,   e Zd ZdZdZd Zd Z	 	 	 	 ddZed        Z	ed        Z
ed	        Zed
        Zed        Zed        Zed        Zed        Zd Zd Zed        Zed        Zed        Zed        Zed        Zed        Zed        Zy)r$   a8  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                     || _         || _        || _        || _        |j                  j                  |      | _        || _        || _        t        |      | _
        y N)r+   rJ   rK   rM   _execution_optionsunionrL   rN   rO   listrQ   )selfr+   rJ   rK   rL   rN   compile_state_clsevents_todos           r,   __init__zORMExecuteState.__init__   s\     "$'8$!*!=!=!C!C"
 -"3 -r.   c                 :    | j                   | j                  dz   d  S )Nr   )rQ   rP   rX   s    r,   _remaining_eventsz!ORMExecuteState._remaining_events   s!      !9!9A!=!?@@r.   Nc                 `   || j                   }t        | j                        }|r|j                  |       d|d<   |r't        | j                        }|j                  |       n| j                  }| j
                  }|r|j                  |      }| j                  j                  |||||       S )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)	rJ   dictrN   updaterK   rM   rV   r+   execute)rX   rJ   paramsrL   rN   _bind_arguments_paramsrU   s           r,   invoke_statementz 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                 :    | j                   j                  dd      S )a  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)rN   getr]   s    r,   bind_mapperzORMExecuteState.bind_mapper   s    4 ""&&x66r.   c                    | j                   sg S | j                  rg }t               }| j                  j                  D ]l  }|d   }|st        |d      }|s|j                  s(|j                  |vs7|j                  |j                         |j                  |j                         n |S | j                  s| j                  r| j                  gS g S )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setrJ   column_descriptionsr   rj   addappend	is_update	is_deleterl   )rX   resultseendentinsps         r,   all_mapperszORMExecuteState.all_mappers  s    & $$I^^F5D^^77 3k"37D40G-dkk23 M^^t~~$$%%Ir.   c                     | j                   duS )a  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)rO   r]   s    r,   rp   z ORMExecuteState.is_orm_statement2  s     &&d22r.   c                 .    | j                   j                  S )z*return True if this is a SELECT operation.)rJ   rq   r]   s    r,   rq   zORMExecuteState.is_select?  s     ~~'''r.   c                 ^    | j                   j                  xr | j                   j                  S )z+return True if this is an INSERT operation.)rJ   is_dml	is_insertr]   s    r,   r   zORMExecuteState.is_insertD  #     ~~$$A)A)AAr.   c                 ^    | j                   j                  xr | j                   j                  S )z+return True if this is an UPDATE operation.)rJ   r   rv   r]   s    r,   rv   zORMExecuteState.is_updateI  r   r.   c                 ^    | j                   j                  xr | j                   j                  S )z*return True if this is a DELETE operation.)rJ   r   rw   r]   s    r,   rw   zORMExecuteState.is_deleteN  r   r.   c                 j    t        | j                  t        j                  t        j                  f      S rT   )
isinstancerJ   r   UpdateDeleter]   s    r,   _is_crudzORMExecuteState._is_crudS  s     $..3::szz*BCCr.   c                 D    | j                   j                  |      | _         y rT   )rM   rV   rX   optss     r,   update_execution_optionsz(ORMExecuteState.update_execution_optionsW  s    '+'C'C'I'I$'O$r.   c                     | j                   sy 	 | j                  j                  }|j	                  t
        j                  j                        r|S y # t        $ r Y y w xY wrT   )rq   rJ   _compile_optionsAttributeErrorr   r   ORMCompileStatedefault_compile_optionsr   s     r,   _orm_compile_optionsz$ORMExecuteState._orm_compile_options[  sV    ~~	>>22D ??722JJKK  		s   A 	AAc                 .    | j                   j                  S )a  An :class:`.InstanceState` that is using this statement execution
        for a lazy load operation.

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

        )load_options_lazy_loaded_fromr]   s    r,   lazy_loaded_fromz ORMExecuteState.lazy_loaded_fromg  s       222r.   c                 @    | j                         }||j                  S y)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_pathz$ORMExecuteState.loader_strategy_pathv  s'     ((*%%%r.   c                 F    | j                         }|duxr |j                  S )aq  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_loadzORMExecuteState.is_column_load  s(    0 ((*4;D$;$;;r.   c                 f    | j                         }|y| j                  }|duxr |j                   S )az  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)rX   r   paths      r,   is_relationship_loadz$ORMExecuteState.is_relationship_load  s<    ( ((*<((44$44r.   c                     | j                   st        j                  d      | j                  j	                  dt
        j                  j                        S )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)rq   sa_excInvalidRequestErrorrL   rk   r   QueryContextdefault_load_optionsr]   s    r,   r   zORMExecuteState.load_options  sO     ~~,,0  %%))"G$8$8$M$M
 	
r.   c                     | j                   st        j                  d      | j                  j	                  dt
        j                  j                        S )zNReturn 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   rL   rk   r	   BulkUDCompileStatedefault_update_optionsr]   s    r,   update_delete_optionsz%ORMExecuteState.update_delete_options  sP    
 }},,<  %%))$**AA
 	
r.   c                     | j                   j                  D cg c]  }|j                  s|j                  s| c}S c c}w )zzThe sequence of :class:`.UserDefinedOptions` that have been
        associated with the statement being invoked.

        )rJ   _with_options_is_compile_state_is_legacy_option)rX   opts     r,   user_defined_optionsz$ORMExecuteState.user_defined_options  s?     ~~33
((1F1F 
 	
 
s   !=)NNNN)r<   r=   r>   r?   	__slots__r[   r^   rh   propertyrl   r}   rp   rq   r   rv   rw   r   r   r   r   r   r   r   r   r   r   rC   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                       e Zd ZdZdZ	 	 	 ddZed        ZdZ	 ed        Z		 	 	 	 ddZ
ed        Zdd	Zdd
ZddZddZddZd Zd Zd Zd ZddZddZddZd Zd Zd Zd Zy)r"   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                 z   t        j                  |       || _        i | _        || _        || _        |r|j                  | _        t        | _	        |s|rt        j                  d      | j                  |       | | j                  _        | j                  j                  j                  | j                  |        y )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_transactionrD   _stater   r   _take_snapshot_transactiondispatchafter_transaction_create)rX   r+   parentr   r   s        r,   r[   zSessionTransaction.__init__  s     	--g6070K0KD-&,,- 
 	i0 %)!66t||TJr.   c                     | j                   S )aj  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   r]   s    r,   r   zSessionTransaction.parent)  s      ||r.   c                 F    | j                   d uxr | j                  t        u S rT   )r+   r   rD   r]   s    r,   	is_activezSessionTransaction.is_activeC  s    ||4'ADKK6,AAr.   c                    | j                   t        u rt        j                  d      | j                   t        u r|st        j                  d      y | j                   t
        u rN|sK|sH| j                  r$t        j                  d| j                  z  d      |st        j                  d      y y y | j                   t        u rt        j                  |      y )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   rF   r   r   rE   rG   _rollback_exceptionPendingRollbackErrorrH   ResourceClosedError)rX   prepared_okrollback_okdeactive_ok
closed_msgs        r,   _assert_activez!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                 8    | j                   xs | j                   S rT   )r   r   r]   s    r,   _is_transaction_boundaryz+SessionTransaction._is_transaction_boundaryn  s    {{.$,,..r.   c                     | j                           | j                  j                  |fi |}| j                  ||      S rT   )r   r+   get_bind_connection_for_bind)rX   bindkeyrL   r9   binds        r,   
connectionzSessionTransaction.connectionr  s=    $t||$$W77((/@AAr.   c                 R    | j                          t        | j                  | |      S )Nr   )r   r"   r+   )rX   r   s     r,   _beginzSessionTransaction._beginw  s!    !$,,VDDr.   c                     | }d}|rJ||fz  }|j                   |u r	 |S |j                   t        j                  d|z        |j                   }|rJ|S )NrC   z4Transaction %s is not on the active transaction list)r   r   r   )rX   uptocurrentrx   s       r,   _iterate_self_and_parentsz,SessionTransaction._iterate_self_and_parents{  sr    wj F$&  (00J 
 "//  r.   c                 "   | j                   sm| j                  j                  | _        | j                  j                  | _        | j                  j                  | _        | j                  j
                  | _        y |s0| j                  j                  s| j                  j                          t        j                         | _        t        j                         | _        t        j                         | _        t        j                         | _        y rT   )r   r   _new_deleted_dirty_key_switchesr+   	_flushingflushweakrefWeakKeyDictionary)rX   r   s     r,   r   z!SessionTransaction._take_snapshot  s    ,,))DI LL11DM,,--DK!%!;!;D!7!7LL --/	113//1$668r.   c                    | j                   sJ t        | j                        j                  | j                  j                        }| j                  j                  |d       | j                  j                         D ]^  \  }\  }}| j                  j                  j                  |       ||_
        ||vs:| j                  j                  j                  |       ` t        | j                        j                  | j                  j                        D ]  }| j                  j                  |d       ! | j                  j                  rJ | j                  j                  j                         D ]Y  }|r|j                  s|| j                   v s |j#                  |j$                  | j                  j                  j&                         [ y)zmRestore the restoration state taken before a transaction began.

        Corresponds to a rollback.

        Tto_transient)revert_deletionN)r   rr   r   rV   r+   _expunge_statesr   itemsidentity_mapsafe_discardkeyreplacer   _update_impl
all_statesmodifiedr   _expirerb   	_modified)rX   
dirty_only
to_expungesoldkeynewkeys         r,   _restore_snapshotz$SessionTransaction._restore_snapshot  sn    ,,,,^))$,,*;*;<
$$Zd$C#'#5#5#;#;#= 
	5A LL%%2215 AE 
"))11!4
	5 T]]#))$,,*?*?@ 	?ALL%%a%>	? <<((((**557 	GAqDKK/?		!&&$,,";";"E"EF	Gr.   c                 l   | j                   sJ | j                  s| j                  j                  r| j                  j                  j                         D ]<  }|j                  |j                  | j                  j                  j                         > t        j                  j                  t        | j                        | j                         | j                  j                          y| j                  r| j                  j                   j#                  | j                          | j                  j$                  j#                  | j$                         | j                  j                  j#                  | j                         | j                  j&                  j#                  | j&                         yy)zjRemove the restoration state taken before a transaction began.

        Corresponds to a commit.

        N)r   r   r+   expire_on_commitr   r   r   rb   r   statelibInstanceState_detach_statesrW   r   clearr   r   rc   r   r   )rX   r   s     r,   _remove_snapshotz#SessionTransaction._remove_snapshot  s$    ,,,,{{t||<<\\..99; G		!&&$,,";";"E"EFG ""11T]]#T\\ MM![[LL$$TYY/LL&&t{{3LL!!((7LL&&--d.@.@A	 r.   c                 P   | j                          || j                  v r)|rt        j                  d       | j                  |   d   S d}d}| j                  r*| j                  j                  ||      }| j                  s]|S t        |t        j                        r/|}|j                  | j                  v r't        j                  d      |j                         }d}	 |r |j                  di |}| j                  j                  r| j                  |j!                         }nq| j                  r|j#                         }nT|j%                         r4|j'                         r|j)                         }n#|j+                         }d}n|j-                         }t        |t        j                        }|||| fx| j                  |<   | j                  |j                  <   | j                  j.                  j1                  | j                  | |       |S #  |r|j3                           xY w)NzOConnection is already established for the given bind; execution_options ignoredr   FTzMSession already has a Connection associated for the given Connection's EnginerC   )r   r   r   warnr   r   r   r   r   
Connectionr   r   connectrL   r+   twophasebegin_twophasebegin_nestedin_transactionin_nested_transactionget_nested_transactionget_transactionbeginr   after_beginclose)rX   r   rL   local_connectshould_commitconntransactionbind_is_connections           r,   r   z'SessionTransaction._connection_for_bind  s   4$$$ 		< $$T*1--<<<<44T;LMD;;$ 1 12;;$"3"33 444 
 ||~ $"	 -t--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   B8H H%c                     | j                   | j                  j                  st        j                  d      | j                          y )NzD'twophase' mode not enabled, or not root transaction; can't prepare.)r   r+   r  r   r   _prepare_implr]   s    r,   preparezSessionTransaction.prepare  s>    <<#4<<+@+@,,!  	r.   c                    | j                          | j                  | j                  r/| j                  j                  j                  | j                         | j                  j                  }|| ur'|j                  |       D ]  }|j                           | j                  j                  s[t        d      D ]8  }| j                  j                         r n1| j                  j                          : t        j                  d      | j                  _| j                  j                  rI	 t!        | j"                  j%                               D ]  }|d   j'                           	 t.        | _        y t.        | _        y #  t)        j*                         5  | j-                          d d d        n# 1 sw Y   nxY wY t.        | _        y xY w)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   
FlushErrorr  rr   r   valuesr  r   safe_reraiserollbackrE   r   )rX   stxsubtransaction_flush_guardts        r,   r  z SessionTransaction._prepare_impl  sl   <<4;;LL!!//=ll''d?"%"?"?T"?"J (%%'( ||%% %c
 	<<))+""$	
 nn,  <<DLL$9$9$T..5578 #AaDLLN# h	$&&( $MMO$ $ $ s$   -;F G
F1(	G
1F:	6G
c                 :   | j                  d       | j                  t        ur| j                          | j                  | j
                  rt        | j                  j                               D ]  \  }}}}|s|j                           t        | _        | j                  j                  j                  | j                         | j                          | j                          |r(| j                  r| j                  j                  d      S | j                  S )NT)r   _to_root)r   r   rE   r  r   r   rr   r   r'  r#  rF   r+   r   after_commitr  r  )rX   r0  r  transr  	autocloses         r,   r#  zSessionTransaction.commit=  s    -;;h& <<4;;9<!!((*: #5e]I !LLN	# $DKLL!!..t||<!!#

<<&&&55||r.   c                 ,   | j                  dd       | j                  j                  }|| ur'|j                  |       D ]  }|j	                           | }d }| j
                  t        t        fv r| j                         D ]  }|j                  |j                  r	 t        |j                  j                               D ]  }|d   j                           t        |_        | j                  j                  j!                  | j                         t        |_        |j'                  |j                         |} nt        |_         | j                  }	|sA|	j)                         s1t+        j,                  d       |j'                  |j                         | j	                          | j                  r(|r&t#        j$                         d   | j                  _        |rt+        j0                  |d   |d          |	j                  j3                  |	|        |r(| j                  r| j                  j                  d	      S | j                  S #  t#        j$                         }Y UxY w# t        |_        |j'                  |j                         w xY w)
NT)r   r   r   r   )r   z\Session's state has been changed on a non-active transaction - this state will be discarded.r   with_tracebackr/  )r   r+   r   r   r  r   rD   rE   r   r   rr   r   r'  r)  rG   r   after_rollbacksysexc_infor  r%  r   r
  r   raise_after_soft_rollback)
rX   _capture_exceptionr0  r*  r+  boundaryrollback_errr  r-  sesss
             r,   r)  zSessionTransaction.rollbackU  s+   $?ll''d?"%"?"?T"?"J '$$&' ;;68,,#==? 2&&.+2D2D!$[%=%=%D%D%F!G ,AaDMMO, .6*--<<T\\J .6*#55'2'9'9 6   +H)1K&%2( ||DNN$4 II%
 &&(//&B

<<./2||~a/@DLL,KKQQH))$5<<(($(77||K6'*||~-5*#55'2'9'9 6 s   A5II'$I**)Jc                    | j                   r| j                  | j                  _        | j                  | j                  _        | j                  pt        | j                  j                               D ]J  \  }}}}|r|j                          |r|j                  r|j                          |s;|j                          L t        | _        | j                  j                  j                  | j                  |        d | _        d | _        y rT   )r   r   r+   r   r   r   rr   r   r'  
invalidater   r  rH   r   r   after_transaction_end)rX   rA  r   r  r  r3  s         r,   r  zSessionTransaction.close  s    ;;11 LL, %)LL!<<EH!!((*F 'A
K	 ))+ [%:%:%%'$$&' 33DLL$G r.   c                     | j                   S rT   r*   r]   s    r,   _get_subjectzSessionTransaction._get_subject  s    ||r.   c                 &    | j                   t        u S rT   )r   rD   r]   s    r,   _transaction_is_activez)SessionTransaction._transaction_is_active      {{f$$r.   c                 &    | j                   t        u S rT   )r   rH   r]   s    r,   _transaction_is_closedz)SessionTransaction._transaction_is_closed  rG  r.   c                 2    | j                   t        t        fvS rT   )r   rF   rH   r]   s    r,   _rollback_can_be_calledz*SessionTransaction._rollback_can_be_called  s    {{9f"555r.   )NFF)FFFzThis transaction is closedrT   FFF)r<   r=   r>   r?   r   r[   r   r   r   r   r   r   r   r   r   r   r  r  r   r  r  r#  r)  r  rD  rF  rI  rK  rC   r.   r,   r"   r"     s    $L 
 K<  " F B B
 /%9N / /B
E$9 G@B,@D@08t!2%%6r.   r"   c                      e Zd ZdZdZ ej                  d      	 	 	 	 	 	 	 	 	 	 dYd       ZdZdZ	d Z
d	 Zej                  d
        Ze ej                  ddd      d               Zd Zd Zd Zd Zd Zej,                  d        Zd Z ej                  d      dZd       Zd Zd Zd Zd Z	 	 	 d[dZd\dZdej@                  dddfdZ!dej@                  dfd Z"dej@                  dfd!Z#d" Z$d# Z%d$ Z&d% Z'd& Z(d' Z)d( Z*	 	 	 	 	 d]d)Z+d* Z,de-j\                  dfd+Z/eej                  d,               Z0d- Z1d^d.Z2d/ Z3d\d0Z4d1 Z5d\d2Z6d3 Z7d_d4Z8d5 Z9d6 Z:d7 Z;d`d8Z<d9 Z=d: Z>d; Z?d< Z@	 	 	 	 	 dad=ZA	 	 	 	 	 dad>ZBdbd?ZC	 	 	 	 dcd@ZDdA ZEdB ZFd_dCZGdD ZHdE ZIdF ZJdG ZKdH ZLdI ZMdJ ZNd\dKZOdL ZPdM ZQd\dNZR	 	 	 dddOZS	 dedPZTdQ ZUdR ZVd`dSZWedT        ZXdZY	 edU        ZZedV        Z[edW        Z\edX        Z]y)fr!   zManages 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                 D   t        j                         | _        i | _        i | _        || _        i | _        d| _        d| _        d| _	        d| _
        || _        t               | _        || _        || _        || _        |r|rt#        j$                  d      d| _        nd| _        || _        |
r|
nt*        j,                  | _        |	r| j0                  j3                  |	       |*|j5                         D ]  \  }}| j7                  ||        | t8        | j                  <   y)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   ArgumentErrorrP  r  r
   Query
_query_clsinforc   r   	_add_bind	_sessions)rX   r   rX  rU  r  rP  r  bindsrY  r]  	query_clsr   s               r,   r[   zSession.__init__  s   L %557		$ #' &(" 0$8!**B  #DO#DO '0)ekkIIT""[[] *	TsD)* $(	$-- r.   c                     | S rT   rC   r]   s    r,   	__enter__zSession.__enter__  s    r.   c                 $    | j                          y rT   )r  )rX   type_value	tracebacks       r,   __exit__zSession.__exit__  s    

r.   c              #      K   | 5  | j                         5  |  d d d        d d d        y # 1 sw Y   xY w# 1 sw Y   y xY wwrT   r  r]   s    r,   _maker_context_managerzSession._maker_context_manager  sE      	 
	 	 	 	s(   A8,8	A5	8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                 "    | j                         S )a9  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_transactionr]   s    r,   r  zSession.transaction  s    ( ''))r.   c                 R    | j                   s| j                          | j                  S rT   )rU  
_autobeginr   r]   s    r,   ro  zSession._legacy_transaction  s    {{OO   r.   c                     | j                   duS )zReturn True if this :class:`_orm.Session` has begun a transaction.

        .. versionadded:: 1.4

        .. seealso::

            :attr:`_orm.Session.is_active`


        N)r   r]   s    r,   r  zSession.in_transaction  s       ,,r.   c                     | j                   duS )zReturn True if this :class:`_orm.Session` has begun a nested
        transaction, e.g. SAVEPOINT.

        .. versionadded:: 1.4

        Nr   r]   s    r,   r  zSession.in_nested_transaction  s     ''t33r.   c                 p    | j                   }|'|j                  |j                  }||j                  |S )zaReturn the current root transaction in progress, if any.

        .. versionadded:: 1.4

        )r   r   rX   r2  s     r,   r  zSession.get_transaction  s=     !!EMM$=MME EMM$=r.   c                     | j                   S )zcReturn the current nested transaction in progress, if any.

        .. versionadded:: 1.4

        rt  r]   s    r,   r  zSession.get_nested_transaction  s     '''r.   c                     i S )a  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.

        rC   r]   s    r,   r]  zSession.info  s	     	r.   c                 p    | j                   s*| j                  t        | d      }| j                  |u sJ yy)NTr   F)rP  r   r"   rv  s     r,   rq  zSession._autobegin  s:    4#4#4#<&tt<E$$---r.   )rO  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                 D   |r| j                   rt        d      | j                         r|s|s|s| j                  S | j                  h|s|s|rA| j                  j	                  |      }| j                  |u sJ |r(|| _        | j                  S t        j                  d      | j                  S | j                  s/|s|s|rJ t        |       }| j                  |u sJ | j                  S | j                   rJ t        | |      }| j                  |u sJ | j                  S )aC  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.)
rU  NotImplementedErrorrq  r   r   r   r   r   rP  r"   )rX   rz  r   	_subtransr2  s        r,   r  zSession.begin  s<   ` t{{%# 
 ??"6)(((()v))000?((E111/4D,$    ! 00E        iGG&t,E$$---    	 {{"?&tF;E$$---   r.   c                 &    | j                  d      S )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   rj  r]   s    r,   r  zSession.begin_nestedH  s    . zzz&&r.   c                 j    | j                   y| j                   j                  | j                         y)a  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`

        Nr/  )r   r)  rU  r]   s    r,   r)  zSession.rollbacka  s.    , $&&&<r.   c                     | j                   %| j                         st        j                  d      | j                   j	                  | j
                         y)aE  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.r/  )r   rq  r   r   r#  rU  r]   s    r,   r#  zSession.commit|  sH    \ $??$001KLL  $++ 6r.   c                     | j                   %| j                         st        j                  d      | j                   j	                          y)ax  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   rq  r   r   r  r]   s    r,   r  zSession.prepare  s>     $??$001KLL!!#r.   c                 ~    |s|}|j                  dd      }| | j                  di |}| j                  |||      S )an	  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_resultrL   rC   )popr   r   )rX   rN   r  rL   kwr   s         r,   r   zSession.connection  sX    B N!!&$/< 4==2>2D((// ) 
 	
r.   c                 $   t        j                  |        | j                  | j                         r| j                  j	                  ||      S | j                  J | j
                  sJ  |j                  di |}|r |j                  di |}|S )NrC   )r   r   r   rq  r   rP  r  rL   )rX   r   rL   r  r  s        r,   r   zSession._connection_for_bind  s    --d3(DOO,=$$99)    (((v~~##)4))>,=>Dr.   c           	         t        j                  t        j                  |      }|r,t	        j
                  d       |s|}n"|j                  |       n|si }nt        |      }|j                  j                  dd      dk(  rt        j                  |d      }nd}t	        j                  |      }||j                  | |||||du      \  }}n%|j                  d|       |j                  ddi      }|r|j!                         }	n'| j"                  j$                  }	|rt'        |	      |gz   }	|	rQt)        | ||||||	      }
t+        |	      D ]  \  }}||
_         ||
      }|s|c S  |
j.                  }|
j0                  } | j2                  di |}| j4                  r/| j7                  |d      }|j                  t        d	
            }n| j7                  |      }|j9                  ||xs i |      }|r|j;                  | |||||      }|S )aM  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  rC   )r   expectr   StatementRoler   warn_deprecated_20rc   rb   _propagate_attrsrk   r   _get_plugin_class_for_plugincoerce_to_immutabledictorm_pre_session_exec
setdefaultrV   r^   r   do_orm_executerW   r$   	enumeraterP   rJ   rM   r   rP  r   _execute_20orm_setup_cursor_result)rX   rJ   re   rL   rN   ra   
_add_eventr  rY   rZ   orm_exec_stateidxfnrx   r   r  s                   r,   rd   zSession.execute  sY   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 "R582N+!M	" '00I . F Ft}}.~.?? ,,TT,JD 1 7 75)! ,,T2D!!)V\r;LM&>>!F r.   c                 L     | j                   |f|||d|j                         S )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.

        re   rL   rN   )rd   scalarrX   rJ   re   rL   rN   r  s         r,   r  zSession.scalar  s;      t||
/)	

 
 &(	r.   c                 L     | j                   |f|||d|j                         S )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  )rd   scalarsr  s         r,   r  zSession.scalars  s;    . t||
/)	

 
 ')	r.   c                 (    | j                  d       y)a  Close out the transactional resources and ORM objects used by this
        :class:`_orm.Session`.

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

        .. tip::

            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rA  N_close_implr]   s    r,   r  zSession.close  s    < 	E*r.   c                 (    | j                  d       y)a  Close this Session, using connection invalidation.

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

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

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

            import gevent

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

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

        Tr  Nr  r]   s    r,   rA  zSession.invalidate  s    D 	D)r.   c                     | j                          | j                  1| j                  j                         D ]  }|j                  |        y y rT   )expunge_allr   r   r  )rX   rA  r  s      r,   r  zSession._close_impl>  sK    (#00JJL .!!*-. )r.   c                 &   | j                   j                         t        | j                        z   }| j                   j	                          t        j                         | _         i | _        i | _        t        j                  j                  ||        y)zRemove all object instances from this ``Session``.

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

        N)r   r   rW   r   _killr   rR  r   r  r  r  )rX   r   s     r,   r  zSession.expunge_allD  sl     &&113d499oE
!$557	--j$?r.   c                    	 t        |      }|j                  r|| j                  |<   y |j                  r:|| j                  |j                  <   |j
                  D ]  }|| j                  |<    y t        j                  d|z        # t        j                  $ r\}t        |t              s.t        j                  t        j                  d|z        |       n|| j                  |<   Y d }~y Y d }~y d }~ww xY w)Nz!Not an acceptable bind target: %sreplace_context)r   is_selectablerS  	is_mapperclass__all_tablesr   rZ  NoInspectionAvailabler   typer   r:  )rX   r   r   r|   _selectableerrs         r,   r^  zSession._add_bindT  s    	3<D !!%)T",0T[[)#'#3#3 5K04DLL-5 **7#= % ++ 		)c4(((;cA %(	 %)S!		)s   B C6AC11C6c                 (    | j                  ||       y)a  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^  )rX   rj   r   s      r,   rl   zSession.bind_mapperm  s    4 	vt$r.   c                 (    | j                  ||       y)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  )rX   tabler   s      r,   
bind_tablezSession.bind_table  s    4 	ud#r.   c                    |r|S | j                   s| j                  r| j                  S ||cxu r0n n-| j                  r| j                  S t        j                  d      |	 t	        |      }| j                   r|rH|j                  j                  D ]!  }|| j                   v s| j                   |   c S  ||j                  }||j                  j!                  dd      }|D|j"                  j                  j                  D ]!  }|| j                   v s| j                   |   c S  t%        j&                  |      D ]!  }	|	| j                   v s| j                   |	   c S  | j                  r| j                  S d}
d}|r||j                  }|<|j                  r0| j(                  rd}
n!t        j*                  d       |j                  S |rP|j                  j                  r:| j(                  rd}
n+t        j*                  d       |j                  j                  S g }| |j,                  d|z         | |j,                  d	       t        j                  d
dj/                  |      d|
|      # t        j
                  $ rG}t        |t              r+t        j                  t        j                  |      |       n Y d}~]d}~ww xY w)al  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   )rS  r   r   UnboundExecutionErrorr   r  r   r  r   r:  r   UnmappedClassErrorr  __mro__persist_selectabler  rk   rj   r   iteraterU  r  ru   join)rX   rj   r  r   r`   _sa_skip_for_implicit_returningr  r2   r  obj
future_msgfuture_coder   s                r,   r   zSession.get_bind  s   j K$)) 99
 V#yyyy 22!  	  << !==00 1Cdll*#||C001 >#66F!!'!8!8!<!<$d" "--44;;CC 5$,,.#'<<#445 $++F3 1Cdll*#||C001 9999
 
fn..F{{;;+  ++A ";;&((--;;+  ++A "44999GNN;/0GNN+,**yy!:/
 	
q // fd+KK..v6(+
 s   #I6 6K	<KKc                 *     | j                   || fi |S )zhReturn a new :class:`_query.Query` object corresponding to this
        :class:`_orm.Session`.

        )r\  )rX   entitiesr9   s      r,   r
   zSession.queryp  s     tx888r.   c                 X    |j                  ||      }t        j                  | |||      S )az  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)rX   rj   primary_key_identityr  passiver   r   s          r,   _identity_lookupzSession._identity_lookupx  s8    b 22  3 
 ((vsGDDr.   c              #   b   K   | j                   }d| _         	 |  || _         y# || _         w xY ww)ag  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)rX  )rX   rX  s     r,   no_autoflushzSession.no_autoflush  s0     * NN		'J&DNYDNs   /# /	,/c                    | j                   r| j                  s	 | j                          y y y # t        j                  $ rG}|j                  d       t        j                  |t        j                         d          Y d }~y d }~ww xY w)Nzraised as a result of Query-invoked autoflush; consider using a session.no_autoflush block if this flush is occurring prematurelyr   r5  )
rX  r   r   r   StatementError
add_detailr   r:  r8  r9  )rX   es     r,   
_autoflushzSession._autoflush  sp    >>$..A

 #1> (( 
A
 5
 AcllnQ.?@@
As   - B =BBc                 $   	 t        j                  |      }| j                  |       |i k(  rt        j                  d      t        j                  j                  |      }t        j                  t        |            }t!        j"                  | ||j$                  |||      	 !t        j&                  dt)        |      z        y# t        j                  $ r4}t	        j
                  t        j                  |      |       Y d}~d}~ww xY w)al
  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   r:  UnmappedInstanceError_expire_stater   rZ  r
   ForUpdateArg_from_argumentr   selectr   r   load_on_identr   r   r   )rX   r;   attribute_namesr  r   r  stmts          r,   refreshz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                     | j                   j                         D ]2  }|j                  |j                  | j                   j                         4 y)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   rb   r   rX   r   s     r,   
expire_allzSession.expire_all7	  sC    @ &&113 	CEMM%**d&7&7&A&AB	Cr.   c                     	 t        j                  |      }| j                  |       y# t        j                  $ r4}t	        j
                  t        j                  |      |       Y d}~Ud}~ww xY w)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   r  r   r  r   r:  r  r  )rX   r;   r  r   r  s        r,   expirezSession.expireZ	  sb    J	--h7E 	5/2 || 	KK))(3 # 	s   * A1*A,,A1c                    | j                  |       |r|j                  |j                  |       y t        |j                  j
                  j                  d|            }| j                  |       |D ]  \  }}}}| j                  |        y )Nzrefresh-expire)_validate_persistent_expire_attributesrb   rW   managerrj   cascade_iterator_conditional_expire)rX   r   r  cascadedomst_dct_s           r,   r  zSession._expire_state	  s    !!%($$UZZA $$556FNH $$U+#+ .1c4((-.r.   c                     |j                   r1|j                  |j                  | j                  j                         y|| j
                  v r-| j
                  j                  |       |j                  |        yy)z5Expire a state if persistent, else expunge if pendingN)r   r   rb   r   r   r   r  _detach)rX   r   rX  s      r,   r  zSession._conditional_expire	  sV     99MM%**d&7&7&A&ABdiiIIMM% MM$  r.   c                     	 t        j                  |      }j                  | j                  ur!t        j                  dt        |      z        t        |j                  j                  j                  d|            }| j!                  |g|D cg c]	  \  }}}}| c}}}}z          y# t        j                  $ r4}t	        j
                  t        j                  |      |       Y d}~d}~ww xY wc c}}}}w )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   r  r   r  r   r:  r  
session_idrW  r   r   r   rW   r  rj   r  r   )	rX   r;   r   r  r  r  r  r  r  s	            r,   r  zSession.expunge	  s    	--h7E 4==0,,<y?OO  MM  11)UC
 	eW8'L'L1c4'LLM || 	KK))(3 # 	 (Ms   B. C8.C5*C00C5c                    |D ]  }|| j                   v r| j                   j                  |       -| j                  j                  |      r8| j                  j	                  |       | j
                  j                  |d        | j                  s| j                  j
                  j                  |d         t        j                  j                  || |       y )Nr   )
r   r  r   contains_stater   r   r   r  r  r  )rX   statesr   r   s       r,   r   zSession._expunge_states	  s     		<E		!		e$""11%8!!..u5!!%."" !!**..ud;		< 	--D| 	. 	
r.   c                    | j                   j                  xs d}|D ]  }t        |      }|j                         }|"|j	                  |      }t        j                  |d         r|j                  rt        j                  |d         r!t        j                  dt        |      z        |j                  ||_        n|j                  |k7  r~| j                  j                  |       || j                  j                   v r| j                  j                   |   d   }n|j                  }||f| j                  j                   |<   ||_        | j                  j#                  |      }|=|j	                  |      |k(  r)|j                         t%        j&                  d|d       d|_         t*        j,                  j/                  d |D        | j                         | j1                  |       |)|j                  | j2                        D ]  } || |        t5        |      j                  | j2                        D ]  }| j2                  j7                  |        y)	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   8   K   | ]  }||j                   f  y wrT   )rb   ).0r   s     r,   	<genexpr>z/Session._register_persistent.<locals>.<genexpr>
  s     5UeUZZ 5s   )r   pending_to_persistentr   r  _identity_key_from_stater   intersectionallow_partial_pks
issupersetr   r&  r   r   r   r   r   r   r   r   r
  _orphaned_outside_of_sessionr  r  _commit_all_states_register_alteredr   rr   r  )	rX   r  r  r   rj   r  instance_keyorig_keyolds	            r,   _register_persistentzSession._register_persistent	  s2    !% C C Kt 9	;E"5)F ))+C%>>uE **<?;"44 ++LO<..? $E*+	 	 99$ ,EIYY,. %%2259 1 1 ? ??#'#4#4#B#B5#I!#L#(99 $>D%%33E: !-EI
 ''//6O77<L	-II 0<> 6;2s9	;v 	115f5t7H7H	
 	v& ,,,TYY7 3%dE23 [--dii8 	!EIIMM% 	!r.   c                     | j                   rI|D ]C  }|| j                  v rd| j                   j                  |<   +d| j                   j                  |<   E y y NT)r   r   r   )rX   r  r   s      r,   r  zSession._register_altered
  sW     ;DII%48D%%**516:D%%,,U3	; r.   c                 H   | j                   j                  xs d }|D ]  }| j                  rd| j                  j                  |<   ||j	                         }| j
                  j                  |       | j                  j                  |d        d|_        |{ || |        y r  )r   persistent_to_deletedr   r   r  r   r   r  )rX   r  r  r   r  s        r,   _remove_newly_deletedzSession._remove_newly_deleted 
  s     $ C C Kt 	3E  48!!**51$0 iik**51MMeT*!EN %0%dE2!	3r.   c                 $   |r| j                   r| j                  d       	 t        j                  |      }| j                         y# t        j
                  $ r4}t        j                  t	        j                  |      |       Y d}~Td}~ww xY w)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)
rT  _flush_warningr   r  r   r  r   r:  r  _save_or_update_state)rX   r;   _warnr   r  s        r,   rt   zSession.add4
  sz    2 T))0	--h7E 	""5) || 	KK))(3 # 	s   A B*B

Bc                 r    | j                   r| j                  d       |D ]  }| j                  |d        y)a2  Add the given collection of instances to this :class:`_orm.Session`.

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

        .. seealso::

            :meth:`_orm.Session.add`

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

        zSession.add_all()F)r  N)rT  r  rt   )rX   	instancesr;   s      r,   add_allzSession.add_allZ
  s;      34! 	,HHHXUH+	,r.   c                     d|_         | j                  |       t        |      }|j                  d|| j                        D ]  \  }}}}| j                  |        y )NFzsave-update)halt_on)r  _save_or_update_implr   r  _contains_state)rX   r   rj   r  r  r  r  s          r,   r  zSession._save_or_update_staten
  sf    -2*!!%(u%%665$*>*>  7  
 	+OAq#t %%c*	+r.   c                 &   | j                   r| j                  d       	 t        j                  |      }| j                  |d       y# t        j
                  $ r4}t        j                  t	        j                  |      |       Y d}~Wd}~ww xY w)aV  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)
rT  r  r   r  r   r  r   r:  r  _delete_implrX   r;   r   r  s       r,   deletezSession.deletex
  s    *  23	--h7E 	%5 || 	KK))(3 # 	s   A	 	B*BBc                    |j                   $|r!t        j                  dt        |      z        y | j	                  ||      }|| j
                  v ry | j                  j                  |       |r| j                  ||       |r/t        |j                  j                  j                  d|            }|| j
                  |<   |r D ]  \  }}}}	| j                  ||d        y y )NInstance '%s' is not persistedr&  F)r   r   r   r   _before_attachr   r   rt   _after_attachrW   r  rj   r  r$  )
rX   r   r  r#  	to_attachcascade_statesr  r  r  r  s
             r,   r$  zSession._delete_impl
  s    99004y7GG  ''s3	DMM!e$uc* "$$55hFN  #e#1 11c4!!#q%01 r.   c           
      P    | j                  ||t        j                  |||||      S )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  rL   )	_get_implr   load_on_pk_identity)rX   rn   identoptionsr.  r  r  rL   s           r,   rk   zSession.get
  s9    R ~~''/+)/  	
 		
r.   c	           
      6   t        d      rj                         t        |      }	|	r|	j                  st	        j
                  d|z        t        t              }
|
st        j                  d      t              t        |	j                        k7  r8t	        j                  ddj                  d |	j                  D              z        |
rf|	j                  }|r9t        |      j!                        }|rt              |D ]  }|   ||   <    	 t#        fd|	j$                  D              |sZ|	j*                  sN|L| j-                  |	|      }|#t/        |j0                  |	j2                        sy |S |t4        j6                  u ry t8        j:                  j<                  }|r|d|iz  }t?        j@                  |	      jC                  tD              }|$tF        jH                  jK                  |      |_&        |r |jN                  | }|r |jP                  di |} || ||      S # t&        $ rX}t        j(                  t	        j                  d	dj                  d
 |	j$                  D              z        |       Y d }~Zd }~ww xY w)N__composite_values__z(Expected mapped class or mapper, got: %rrT   )defaultzoIncorrect number of values in identifier to formulate primary key for session.get(); primary key columns are %s,c              3   &   K   | ]	  }d |z    ywz'%s'NrC   )r  cs     r,   r  z$Session._get_impl.<locals>.<genexpr>Q  s     #K1FQJ#Ks   c              3   <   K   | ]  }|j                        y wrT   r   )r  propr  s     r,   r  z$Session._get_impl.<locals>.<genexpr>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   :   K   | ]  }d |j                   z    ywr8  r;  )r  r<  s     r,   r  z$Session._get_impl.<locals>.<genexpr>p  s!      # $ #TXX-#s   r  r  _populate_existing)r   rC   ))hasattrr4  r   r  r   rZ  r   rb   r   to_listlenprimary_keyr   r  _pk_synonymsrr   r  rW   _identity_key_propsKeyErrorr:  always_refreshr  
issubclass	__class__r  r   PASSIVE_CLASS_MISMATCHr   r   r   r   r  set_label_styler    r
   r  r  _for_update_argr2  rL   )rX   rn   r  
db_load_fnr2  r.  r  r  rL   rj   is_dictpk_synonymscorrect_keyskr  r;   r   rJ   s     `               r,   r/  zSession._get_impl0  s    ')?@#7#L#L#N V--&&:VC  148#'<<$g$  #$F,>,>(??,,88#K8J8J#KKL   --K";/<<(   +/0D+E() 4 13 -'N4
'+ , & : :, ($( "))' ,,,^ - H # "("4"4fmmDZ>>> ++@@13DEELJJv&66*
	 &(-(:(:(I(I)I% )	))73I3	33H6GHI %	
 	
k  ..I (( #(.(B(B#  %( s   H7 7	J AJJc                 F   | j                   r| j                  d       i }i }|r| j                          t        |       | j                  }	 d| _        | j                  t        j                  |      t        j                  |      ||||      || _        S # || _        w xY w)a  Copy the state of a given instance into a corresponding instance
        within this :class:`.Session`.

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

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

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

        .. 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)loadr2  
_recursive_resolve_conflict_map)	rT  r  r  r   rX  _merger   r  instance_dict)rX   r;   rR  r2  rS  rT  rX  s          r,   mergezSession.merge  s    x  12
 "OOhNN		'"DN;;))(3((2%&;   'DNYDNs   AB 	B c                    t        |      }||v r||   S d}|j                  }	|	|| j                  v r!t        j                  dt        |      z         |st        j                  d      |j                  |      }	t        j                  |	d   vxrB t        j                  |	d          xs' |j                  xr t        j                  |	d          }
nd}
|	| j                  v r	 | j                  |	   }nd }||
r
|	|v r||	   }n|sk|j"                  rt        j                  d      |j$                  j'                         }t        j(                  |      }|	|_        | j+                  |       d}n'|
r%| j-                  |j.                  |	d   |	d   |      }|X|j$                  j'                         }t        j(                  |      }t        j0                  |      }d}| j3                  |       n*t        j(                  |      }t        j0                  |      }|||<   |||	<   ||ur|j4                  |j7                  |||j4                  t        j8                  	      }|j7                  |||j4                  t        j8                  	      }|t        j:                  ur?|t        j:                  ur-||k7  r(t=        j>                  d
|dt        |      d|d      |j@                  |_         |jB                  |_!        |jE                  |       |jF                  D ]  }|jI                  | |||||||        |sB|jK                  || j                         |jL                  jN                  jQ                  |d        |r&|jL                  jN                  jS                  |d        |S # t         $ r d }Y w xY w)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  r2  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   r
  r   r   r   r  r   	NEVER_SETr   r  r	  r
  r   rE  r   class_managernew_instancer  r   rk   r  rV  r  version_id_col_get_state_attr_by_columnPASSIVE_NO_INITIALIZEPASSIVE_NO_RESULTr   StaleDataError	load_pathr   _copy_callablesiterate_propertiesrW  _commit_allr  r   _sa_event_merge_wo_loadrR  )rX   r   
state_dictrR  r2  rS  rT  rj   r\  r   key_is_persistentmergedmerged_statemerged_dictexisting_versionmerged_versionr<  s                    r,   rU  zSession._merge  s    u%Je$$ii;		!		'./ 00"  11%8C * 4 4CF B !**3q622 ,, 9%00Q88	  !%$###**3/
 F> S,A%A.s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(N:,, -%l3*
 
 &+__L"(-(:(:L% ((/11 


 )	
 $$[$2C2CD  ))AAd   ))..|TB_  s   'N/ /N>=N>c                 |    | j                   j                  |      s!t        j                  dt	        |      z        y )Nz3Instance '%s' is not persistent within this Session)r   r   r   r   r   r  s     r,   r  zSession._validate_persistent  s>      //6,,EE"#  7r.   c                 :   |j                   !t        j                  dt        |      z        |j	                         }| j                  ||      }|| j                  vr)|| j                  |<   t        | j                        |_        |r| j                  ||       y y )NzGObject '%s' already has an identity - it can't be registered as pending)
r   r   r   r   r  r)  r   rA  insert_orderr*  )rX   r   r  r+  s       r,   
_save_implzSession._save_impl  s    99 ,,46?6FG 
 iik''s3			!"DIIe!$TYYEuc* r.   c                 8   |j                   !t        j                  dt        |      z        |j                  r3|r|j
                  sy |`n!t        j                  dt        |      z        |j                         }|y | j                  ||      }| j                  j                  |d        |r| j                  j                  |       n| j                  j                  |       |r| j                  ||       y |r| j                  j                  | |       y y )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   rt   r*  r   deleted_to_persistent)rX   r   r   r  r+  s        r,   r   zSession._update_impl  s   99,,09U3CC  >>N00. 1:%0@A  iik ;''s3	%&%%e,!!%(uc*MM//e< r.   c                 b    |j                   | j                  |       y | j                  |       y rT   )r   rq  r   r  s     r,   r   zSession._save_or_update_impl  s&    99OOE"e$r.   c                     	 t        j                  |      }| j                  |      }d|_        |r| j                  ||       yy# t        j                  $ r4}t	        j
                  t        j                  |      |       Y d}~qd}~ww xY w)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   r  r   r  r   r:  r  r)  _load_pendingr*  )rX   r  r   r  r+  s        r,   enable_relationship_loadingz#Session.enable_relationship_loading  s    n	--c2E ''s3	"uc*  || 	KK))#. # 	s   A B*BBc           	      D   | j                          |j                  | j                  k(  ry|j                  rN|j                  t        v r<t	        j
                  dt        |      d|j                  d| j                  d      | j                  j                  | |       y)NFzObject 'z"' is already attached to session 'z' (this is 'z')T)	rq  r  rW  r_  r   r   r   r   before_attachrX   r   r  s      r,   r)  zSession._before_attach  s    t}}, 0 0I =,, U#U%5%5t}}F  	##D%0r.   c                 &   | j                   |_        |j                  r|j                  ||_        | j                  j                  | |       |j                  r| j                  j                  | |       y | j                  j                  | |       y rT   )	rW  r  r   _strong_objr   after_attachr   detached_to_persistenttransient_to_pendingr{  s      r,   r*  zSession._after_attach0  sk    ==>>e//7 #E""4/99MM00u=MM..tU;r.   c                     	 t        j                  |      }| j                        S # t        j                  $ r4}t	        j
                  t        j                  |      |       Y d}~Sd}~ww xY w)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   r  r   r  r   r:  r  r!  r%  s       r,   __contains__zSession.__contains__;  sb    	--h7E ##E** || 	KK))(3 # 	s   ( A/*A**A/c                     t        t        | j                  j                               t        | j                  j                               z         S )zWIterate over all pending or persistent instances within this
        Session.

        )iterrW   r   r'  r   r]   s    r,   __iter__zSession.__iter__K  s?    
 !!#$tD,=,=,D,D,F'GG
 	
r.   c                 X    || j                   v xs | j                  j                  |      S rT   )r   r   r   r  s     r,   r!  zSession._contains_stateT  s'    		!LT%6%6%E%Ee%LLr.   c                     | j                   rt        j                  d      | j                         ry	 d| _         | j	                  |       d| _         y# d| _         w xY w)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   r%  _flush)rX   objectss     r,   r   zSession.flushW  sQ    6 >>,,-JKK>>	#!DNKK "DNUDNs   A 	Ac                 4    t        j                  d|z         y )NzUsage of the '%s' operation is not currently supported within the execution stage of the flush process. Results may not be consistent.  Consider using alternative event listeners or connection-level operations instead.)r   r
  )rX   methods     r,   r  zSession._flush_warning}  s!    		F IOO	
r.   c                 t    | j                   j                          xr | j                   xr | j                   S rT   )r   check_modifiedr   r   r]   s    r,   r%  zSession._is_clean  s9    !!0022 MM!II	
r.   c                 b   | j                   }|s=| j                  s1| j                  s%| j                  j                  j                          y t        |       }| j                  j                  r)| j                  j                  | ||       | j                   }t        | j                        }t        | j                        }t        |      j                  |      }|r9t               }|D ])  }	 t        j                  |      }|j%                         + nd }t               }
|r0|j'                  |      j)                  |      j                  |      }n |j'                  |      j                  |      }|D ]|  }t+        |      j-                  |      }|xr |j.                  }|r!|s|j0                  r| j3                  |g       P|j5                  ||      }|sJ d       |
j%                  |       ~ |r!|j)                  |      j                  |
      }n|j                  |
      }|D ]  }|j5                  |d      }|rJ d        |j6                  sy | j9                  d      x|_        }	 d| _        	 |j?                          d| _        | j                  jA                  | |       |jC                          |s| j                  j                  rtE        | j                  j                        }tF        jH                  jK                  | j                  j                  D cg c]  }||jL                  f c}| j                         t        jN                  d|z         | j                  jQ                  | |       |jS                          y # t        j                  $ r5}	t        j                   t        j"                  |      |	       Y d }	~	d }	~	ww xY w# d| _        w xY wc c}w #  t        jT                         5  |jW                  d	       d d d        Y y # 1 sw Y   Y y xY wxY w)
Nr  )isdeletez*Failed to add object to the flush context!Tr}  F)rV  zAttribute history events accumulated on %d previously clean instances within inner-flush event handlers have been reset, and will not result in database updates. Consider using set_committed_value() within inner-flush event handlers to avoid this warning.r<  ),_dirty_statesr   r   r   r   r  r   r   before_flushrr   
differencer   r  r   r  r   r:  r  rt   rV   r  r   
_is_orphanhas_identityr  r   register_objecthas_workr  r  rT  rd   after_flushfinalize_flush_changesrA  r  r  r  rb   r
  after_flush_postexecr#  r(  r)  )rX   r  dirtyflush_contextdeletednewobjsetr  r   r  	processedproc	is_orphanis_persistent_orphan_regr  len_s                    r,   r  zSession._flush  s   ""T]]499''--/&t,==%%MM&&t]G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$8 5  IIIte$!	%& ''/::9ED%%i0D 	FE 000FDEEE4	F %%26**t*2LL!K+	>#'D -%%'',$MM%%dM:002t00::4,,667&&99 &*%6%6%@%@! 

+ #'"3"3 :  		H
 KOO  MM..t]C s || KK11!4(+ n (-$4	>""$ >$$$=> > >sh   ,N2O. :O 
BO. %O):AO. O%*OO	O&&O. .P.P!P.!P+	&P.+P.c           
          d |D        }|st        |d       }d }t        j                  ||      D ]  \  \  }}}	| j                  ||	|d||d       ! y)a]  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   F   K   | ]  }t        j                  |        y wrT   )r   r  )r  r  s     r,   r  z,Session.bulk_save_objects.<locals>.<genexpr>g  s     Hj//4Hs   !c                 H    t        | j                        | j                  d ufS rT   )idrj   r   r   s    r,   <lambda>z+Session.bulk_save_objects.<locals>.<lambda>p  s    2ell#3UYYd5J"K r.   r;  c                 6    | j                   | j                  d ufS rT   )rj   r   r   s    r,   grouping_keyz/Session.bulk_save_objects.<locals>.grouping_keys  s    LL%))4"788r.   TFN)sorted	itertoolsgroupby_bulk_save_mappings)
rX   r  return_defaultsupdate_changed_onlypreserve_order
obj_statesr  rj   isupdater  s
             r,   bulk_save_objectszSession.bulk_save_objects  sz    @ IH

  KJ
	9 +4*;*;+
 	&VX $$#	r.   c           	      2    | j                  ||dd|d|       y)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  )rX   rj   mappingsr  render_nullss        r,   bulk_insert_mappingszSession.bulk_insert_mappings  s(    ~ 	  	
r.   c           	      2    | j                  ||ddddd       y)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`

        TFNr  )rX   rj   r  s      r,   bulk_update_mappingszSession.bulk_update_mappings  s"    j 	  HdE5%	
r.   c                    t        |      }d| _        | j                  d      }	 |rt        j                  |||||       nt        j
                  ||||||       |j                          d| _        y #  t        j                         5  |j                  d       d d d        n# 1 sw Y   nxY wY HxY w# d| _        w xY w)NTr  r  F)
r   r   r  r	   _bulk_update_bulk_insertr#  r   r(  r)  )	rX   rj   r  r  isstatesr  r  r  r  s	            r,   r  zSession._bulk_save_mappings%  s     "&)jj4j0	#((' ((#    #DN		>""$ >$$$=> > > #DNs0   AA4 4B4
B&	B4&B/	+B42B7 7	C c                 L   t        |      }|j                  sy|j                  }|j                  j                  D ]g  }|st        |j                  d      st        |j                  d      s2|j                  j                  ||t        j                        \  }}}|s|sg y y)a9
  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_historyrY  T)	r   r   rb   r  r   r?  implr  	NO_CHANGE)	rX   r;   include_collectionsr   dict_attradded	unchangedr  s	            r,   is_modifiedzSession.is_modifiedM  s    f X&~~

MM,, 	D'DII'78TYY6*.))*?*?uj&:&: +@ +'UIw 	 r.   c                     | j                   r&| j                  duxr | j                  j                  S | j                  du xs | j                  j                  S )a4  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)rP  r   r   r]   s    r,   r   zSession.is_active  sS    8 ??!!-M$2C2C2M2M $$,K0A0A0K0KKr.   c                 6    | j                   j                         S )zThe set of all persistent states considered dirty.

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

        )r   r  r]   s    r,   r  zSession._dirty_states  s       ..00r.   c                     t        j                  | j                  D cg c]   }|| j                  vr|j	                         " c}      S c c}w )aZ  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  zSession.dirty  sL    0  "//- 		
 	
s   %A
c                 n    t        j                  t        | j                  j	                                     S )zDThe set of all instances marked as 'deleted' within this ``Session``)r   r  rW   r   r'  r]   s    r,   r  zSession.deleted  s'     T]]%9%9%; <==r.   c                 n    t        j                  t        | j                  j	                                     S )zAThe set of all instances marked as 'new' within this ``Session``.)r   r  rW   r   r'  r]   s    r,   r  zSession.new  s'     TYY%5%5%7 899r.   )
NTFTFFNTNN)FFF)NFNrT   )NNNNF)NNrL  )T)NFNNN)TN)TNNN)FTTrM  )^r<   r=   r>   r?   _is_asyncior   deprecated_paramsr[   _trans_context_managerconnection_callablerc  rh  contextmanagerrk  r   deprecated_20r  ro  r  r  r  r  memoized_propertyr]  rq  r  r  r)  r#  r  r   r   
EMPTY_DICTrd   r  r  r  rA  r  r  r^  rl   r  r   r
   r   PASSIVE_OFFr  r  r  r  r  r  r  r  r  r   r  r  r  rt   r  r  r&  r$  rk   r/  rW  rU  r  rq  r   r   rx  r)  r*  r  r  r!  r   r  r%  r  r  r  r  r  r  r   r   r  r  r  r  rC   r.   r,   r!   r!     s    KT

 !}(
}(@ " 
 
 T*0 "&* *!
-4	( 

 
 T
	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                   <    e Zd ZdZdeddddfdZd Zd Zd Zd	 Z	y)
r#   a  A configurable :class:`.Session` factory.

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

    e.g.::

        from sqlalchemy import create_engine
        from sqlalchemy.orm import sessionmaker

        # an Engine, which the Session will use for connection
        # resources
        engine = create_engine('postgresql://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                     ||d<   ||d<   ||d<   ||d<   |||d<   || _         t        |j                  |fi       | _        y)aJ  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   rX  rP  r  Nr]  )r  r  r<   r  )rX   r   r  rX  rP  r  r]  r  s           r,   r[   zsessionmaker.__init__^  sZ    L 6
#;%<!1BvJ 6??VIr:r.   c                 0     |        }|j                         S )am  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


        )rk  )rX   r+   s     r,   r  zsessionmaker.begin  s    & &--//r.   c                     | j                   j                         D ]J  \  }}|dk(  r.d|v r*|j                         }|j                  |d          ||d<   9|j	                  ||       L  | j
                  di |S )ae  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]  rC   )r  r   copyrc   r  r  )rX   local_kwrP  vrz   s        r,   __call__zsessionmaker.__call__  s{     GGMMO 	*DAqF{v1FFH&)*#$ ##Aq)	* t{{&X&&r.   c                 :    | j                   j                  |       y)z(Re)configure the arguments for this sessionmaker.

        e.g.::

            Session = sessionmaker()

            Session.configure(bind=create_engine('sqlite://'))
        N)r  rc   )rX   new_kws     r,   	configurezsessionmaker.configure  s     	vr.   c           	          | j                   j                  d| j                  j                  ddj                  d | j                  j                         D              dS )Nz(class_=r  c              3   0   K   | ]  \  }}|d |  yw)=NrC   )r  rP  r  s      r,   r  z(sessionmaker.__repr__.<locals>.<genexpr>  s     C41aA&Cs   ))rH  r<   r  r  r  r   r]   s    r,   __repr__zsessionmaker.__repr__  sB    NN##KK  IIC477==?CC
 	
r.   )
r<   r=   r>   r?   r!   r[   r  r  r  r  rC   r.   r,   r#   r#     s7    \@ /;b0,'(	
r.   r#   c                  V    t         j                         D ]  } | j                           y)aO  Close all sessions in memory.

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

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

    .. versionadded:: 1.3

    N)r_  r'  r  )r?  s    r,   r%   r%     s%       " 

r.   c                     t        j                  |       }t        |      }|r|j                  |g       |j                  j                          |j                  r|`|j                  r|`|j                  r|`yy)aM  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   r  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                 f   t        j                  |       }|j                  s|j                  rt	        j
                  d      |j                  j                  |      |_        |j                  r|`|j                  |j                         |j                  |j                  |j                         y)a  Make the given transient instance :term:`detached`.

    .. note::

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

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

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

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

    .. seealso::

        :func:`.make_transient`

        :meth:`.Session.enable_relationship_loading`

    zGiven object must be transientN)r   r  r  r   r   r   rj   r  r   re  rb   r  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                     	 t        j                  |       }t        |      S # t        j                  $ r4}t        j                  t        j                  |       |       Y d}~yd}~ww xY w)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   r  r-   r   r  r   r:  r  )r;   r   r  s      r,   r(   r(   E  s\    %))(3 e$$ << 
%%h/	
 	

s   " A)*A$$A))?r?   r  r8  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   symbolrD   rE   rF   rG   rH   MemoizedSlotsr$   r"   r!   r#   r%   r&   r'   r(   counterrV  rC   r.   r,   <module>r      sa   8  
          "       &     .       # ;	 (G'')	  !(6 !(H 
X	4;;z"DKK$	4;;z"	X	p
d(( p
fP6- P6fG1:" G1:TbJ
' J
Z$=@$CN%& r.   