iddZddlZddlZddlZddlmZddlmZddlmZddlmZddlm Z dd lm Z dd lm Z dd l mZdd l mZdd l mZddl mZddl mZddl mZddl mZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZ gdZ!ej"Z# dZ$Gdde%Z&ej'dZ(ej'dZ)ej'd Z*ej'd!Z+ej'd"Z,Gd#d$e%Z-Gd%d&e&Z.Gd'd(e&Z/d)Z0d*Z1d+Z2d,Z3ej4Z5dS)-z1Provides the Session class and related utilities.N) attributes)exc)identity)loading) persistence)querystate)_class_to_mapper) _none_set) _state_mapper) instance_str) object_mapper) object_state) state_str)SessionExtension)UOWTransaction)engine)sql)util)inspect) expression)SessionSessionTransactionr sessionmakercZ|jr# t|jS#t$rYnwxYwdS)z\Given an :class:`.InstanceState`, return the :class:`.Session` associated, if any. N) session_id _sessionsKeyErrorr s K/opt/cloudlinux/venv/lib/python3.11/site-packages/sqlalchemy/orm/session.py_state_sessionr#-sG   U-. .    D  4s  ((ceZdZdZeejdddZeejddZ edZ dS) _SessionClassMethodszBClass-level methods for :class:`.Session`, :class:`.sessionmaker`.z1.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"tdS)zClose *all* sessions in memory.N)close_all_sessions)clss r" close_allz_SessionClassMethods.close_all=s zsqlalchemy.orm.utilc|j|i|S)zZReturn an identity key. This is an alias of :func:`.util.identity_key`. ) identity_key)r(orm_utilargskwargss r"r,z!_SessionClassMethods.identity_keyIs%x$d5f555r*c t|S)zxReturn the :class:`.Session` to which an object belongs. This is an alias of :func:`.object_session`. )object_session)r(instances r"r1z#_SessionClassMethods.object_sessionSsh'''r*N) __name__ __module__ __qualname____doc__ classmethodr deprecatedr) dependenciesr,r1r*r"r%r%:sLLT_  /  [ T,--66.-[6(([(((r*r%ACTIVEPREPARED COMMITTEDDEACTIVECLOSEDceZdZdZdZddZedZdZ edZ ddZ ed Z dd Z dd Z dd Zd ZddZdZdZdZdZdZddZddZdZdZdS)raA :class:`.Session`-level transaction. :class:`.SessionTransaction` is a mostly behind-the-scenes object not normally referenced directly by application code. It coordinates among multiple :class:`_engine.Connection` objects, maintaining a database transaction for each one individually, committing or rolling them back all at once. It also provides optional two-phase commit behavior which can augment this coordination operation. The :attr:`.Session.transaction` attribute of :class:`.Session` refers to the current :class:`.SessionTransaction` object in use, if any. The :attr:`.SessionTransaction.parent` attribute refers to the parent :class:`.SessionTransaction` in the stack of :class:`.SessionTransaction` objects. If this attribute is ``None``, then this is the top of the stack. If non-``None``, then this :class:`.SessionTransaction` refers either to a so-called "subtransaction" or a "nested" transaction. A "subtransaction" is a scoping concept that demarcates an inner portion of the outermost "real" transaction. A nested transaction, which is indicated when the :attr:`.SessionTransaction.nested` attribute is also True, indicates that this :class:`.SessionTransaction` corresponds to a SAVEPOINT. **Life Cycle** A :class:`.SessionTransaction` is associated with a :class:`.Session` in its default mode of ``autocommit=False`` immediately, associated with no database connections. As the :class:`.Session` is called upon to emit SQL on behalf of various :class:`_engine.Engine` or :class:`_engine.Connection` objects, a corresponding :class:`_engine.Connection` and associated :class:`.Transaction` is added to a collection within the :class:`.SessionTransaction` object, becoming one of the connection/transaction pairs maintained by the :class:`.SessionTransaction`. The start of a :class:`.SessionTransaction` can be tracked using the :meth:`.SessionEvents.after_transaction_create` event. The lifespan of the :class:`.SessionTransaction` ends when the :meth:`.Session.commit`, :meth:`.Session.rollback` or :meth:`.Session.close` methods are called. At this point, the :class:`.SessionTransaction` removes its association with its parent :class:`.Session`. A :class:`.Session` that is in ``autocommit=False`` mode will create a new :class:`.SessionTransaction` to replace it immediately, whereas a :class:`.Session` that's in ``autocommit=True`` mode will remain without a :class:`.SessionTransaction` until the :meth:`.Session.begin` method is called. The end of a :class:`.SessionTransaction` can be tracked using the :meth:`.SessionEvents.after_transaction_end` event. **Nesting and Subtransactions** Another detail of :class:`.SessionTransaction` behavior is that it is capable of "nesting". This means that the :meth:`.Session.begin` method can be called while an existing :class:`.SessionTransaction` is already present, producing a new :class:`.SessionTransaction` that temporarily replaces the parent :class:`.SessionTransaction`. When a :class:`.SessionTransaction` is produced as nested, it assigns itself to the :attr:`.Session.transaction` attribute, and it additionally will assign the previous :class:`.SessionTransaction` to its :attr:`.Session.parent` attribute. The behavior is effectively a stack, where :attr:`.Session.transaction` refers to the current head of the stack, and the :attr:`.SessionTransaction.parent` attribute allows traversal up the stack until :attr:`.SessionTransaction.parent` is ``None``, indicating the top of the stack. When the scope of :class:`.SessionTransaction` is ended via :meth:`.Session.commit` or :meth:`.Session.rollback`, it restores its parent :class:`.SessionTransaction` back onto the :attr:`.Session.transaction` attribute. The purpose of this stack is to allow nesting of :meth:`.Session.rollback` or :meth:`.Session.commit` calls in context with various flavors of :meth:`.Session.begin`. This nesting behavior applies to when :meth:`.Session.begin_nested` is used to emit a SAVEPOINT transaction, and is also used to produce a so-called "subtransaction" which allows a block of code to use a begin/rollback/commit sequence regardless of whether or not its enclosing code block has begun a transaction. The :meth:`.flush` method, whether called explicitly or via autoflush, is the primary consumer of the "subtransaction" feature, in that it wishes to guarantee that it works within in a transaction block regardless of whether or not the :class:`.Session` is in transactional mode when the method is called. Note that the flush process that occurs within the "autoflush" feature as well as when the :meth:`.Session.flush` method is used **always** creates a :class:`.SessionTransaction` object. This object is normally a subtransaction, unless the :class:`.Session` is in autocommit mode and no transaction exists at all, in which case it's the outermost transaction. Any event-handling logic or other inspection logic needs to take into account whether a :class:`.SessionTransaction` is the outermost transaction, a subtransaction, or a "nested" / SAVEPOINT transaction. .. seealso:: :meth:`.Session.rollback` :meth:`.Session.commit` :meth:`.Session.begin` :meth:`.Session.begin_nested` :attr:`.Session.is_active` :meth:`.SessionEvents.after_transaction_create` :meth:`.SessionEvents.after_transaction_end` :meth:`.SessionEvents.after_commit` :meth:`.SessionEvents.after_rollback` :meth:`.SessionEvents.after_soft_rollback` NFc||_i|_||_||_t|_|s|rt jd|jjr| |jj |j|dS)NzOCan't start a SAVEPOINT transaction when no existing transaction is in progress) session _connections_parentnestedr;_statesa_excInvalidRequestError_enable_transaction_accounting_take_snapshotdispatchafter_transaction_create)selfrBparentrEs r"__init__zSessionTransaction.__init__s     & ,-  < 6 "    ! ! ! 66t|TJJJJJr*c|jS)ajThe 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 )rDrMs r"rNzSessionTransaction.parents |r*c0|jduo |jtuSN)rBrFr;rQs r" is_activezSessionTransaction.is_actives|4'ADK6,AAr*This transaction is closedc|jturtjd|jtur|stjddS|jt urE|s=|s=|jrtjd|jzd|stjddSdSdS|jturtj|dS)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: %s7s2a)codezThis session is in 'inactive' state, due to the SQL transaction being rolled back; no further SQL can be emitted within this transaction.) rFr=rGrHr<r>_rollback_exceptionr?ResourceClosedError)rM prepared_ok rollback_ok deactive_ok closed_msgs r"_assert_activez!SessionTransaction._assert_active s, ;) # #,> [H $ $ 0B   [H $ $ { + 46 2 3 $% 4F     [F " ",Z88 8# "r*c |jp|j SrS)rErDrQs r"_is_transaction_boundaryz+SessionTransaction._is_transaction_boundary3s{.$,..r*c |||jj|fi|}|||SrS)r_rBget_bind_connection_for_bind)rMbindkeyexecution_optionsr/binds r" connectionzSessionTransaction.connection7sG $t|$W7777((/@AAAr*cX|t|j||S)NrE)r_rrB)rMrEs r"_beginzSessionTransaction._begin<s+ !$,VDDDDr*c|}d}|r7||fz }|j|urn'|jtjd|z|j}|7|S)Nr:z4Transaction %s is not on the active transaction list)rDrGrH)rMuptocurrentresults r"_iterate_self_and_parentsz,SessionTransaction._iterate_self_and_parents@sr * wj F$&&(0J "/ * r*c|jsF|jj|_|jj|_|jj|_|jj|_dS|jjs|jtj |_tj |_tj |_tj |_dSrS) rarD_new_deleted_dirty _key_switchesrB _flushingflushweakrefWeakKeyDictionaryrQs r"rJz!SessionTransaction._take_snapshotRs,  )DI L1DM,-DK!%!;D  F|% ! L   -// 133 /11 $688r*c|jsJt|j|jj}|j|d|jD]Q\}\}}|jj |||_ ||vr|jj |Rt|j |jj D]}|j |d|jj rJ|jjD]>}|r|js ||jvr*||j|jjj?dS)zmRestore the restoration state taken before a transaction began. Corresponds to a rollback. T to_transient)revert_deletionN)rasetrrunionrB_expunge_statesruitems identity_map safe_discardkeyreplacers _update_impl all_statesmodifiedrt_expiredict _modified)rM dirty_only to_expungesoldkeynewkeys r"_restore_snapshotz$SessionTransaction._restore_snapshotbs ,,,,^^))$,*;<<  $$Zd$CCC#'#5#;#;#=#= 5 5 A L % 2 21 5 5 5AE "" )11!444T]##))$,*?@@ ? ?A L % %a % > > > ><((((*5577 G GA G GqDK/?/? !&$,";"EFFF G Gr*c|jsJ|js|jjr|jjD],}||j|jjj-tj t|j |j|j dS|jr|jj|j|jj|j|jj |j |jj|jdSdS)zjRemove the restoration state taken before a transaction began. Corresponds to a commit. N)rarErBexpire_on_commitrrrrrstatelib InstanceState_detach_stateslistrsclearrDrrupdatertru)rMrs r"_remove_snapshotz#SessionTransaction._remove_snapshots@ ,,,,{ Bt|< B\.99;; G G !&$,";"EFFFF  " 1 1T]##T\    M   ! ! ! ! ! [ B L  $ $TY / / / L  & &t{ 3 3 3 L ! ( ( 7 7 7 L & - -d.@ A A A A A  B Br*c(|||jvr)|rtjd|j|dSd}|jr%|j||}|js|SnUt|tj r%|}|j|jvrtj dn| }d} |r |j di|}|jjr|j|}n0|jr|}n|}||||ufx|j|<|j|j<|jj|j|||S#|r|xYw)NzOConnection is already established for the given bind; execution_options ignoredrFzMSession already has a Connection associated for the given Connection's EngineTr:)r_rCrwarnrDrdrE isinstancer ConnectionrGrH_contextual_connectrfrBtwophasebegin_twophase begin_nestedbeginrK after_beginclose)rMrgrf local_connectconn transactions r"rdz'SessionTransaction._connection_for_binds  4$ $ $   <$T*1- - < %<44T;LMMD;   $ 122 %;$"333 444 //11 $    C-t-BB0ABB|$ +)="1133  +"//11 "jjll D H D d #d&7 &D L ! - -dlD$ G G GK   s A'E88Fc||j |jjstjd|dS)NzD'twophase' mode not enabled, or not root transaction; can't prepare.)rDrBrrGrH _prepare_implrQs r"preparezSessionTransaction.preparesH < #4<+@ #,!  r*c,||j|jr$|jj|j|jj}||ur-||D]}||jj sZtdD]6}|j rn.|j 7tjd|j|jjr t!|jD]}|dnF#t)j5|dddn #1swxYwYYnxYwt.|_dS)NrmdzrOver 100 subsequent flushes have occurred within session.commit() - is an after_flush() hook creating new objects?r)r_rDrErBrK before_commitrrpcommitrvrange _is_cleanrwr FlushErrorrr~rCvaluesrr safe_reraiserollbackr<rF)rMstxsubtransaction _flush_guardts r"rz SessionTransaction._prepare_impls  < 4;  L ! / / = = =l& d??"%"?"?T"?"J"J ( (%%''''|%  %c   <))++E ""$$$$n, < DL$9  $T.557788##AaDLLNNNN# $&(($$MMOOO$$$$$$$$$$$$$$$ s1>AEFE8, F8E< <F?E< Fc|d|jtur||j|jrt |jD]}|d t|_|j j |j |j jr|||jS)NT)r[r)r_rFr<rrDrEr~rCrrr=rBrK after_commitrIrr)rMrs r"rzSessionTransaction.commits --- ;h & &    < 4; *113344  ! #DK L ! . .t| < < <|: (%%''' |r*c|dd|jj}||ur-||D]}||}d}|jt tfvr4|D]}|j|j r t|j D]}|d t|_|jj|jn#t#j}YnxYwt|_|jjr||j n9#t|_|jjr||j wwxYw|}nt|_ |j}|sJ|jrC|s/t-jd||j ||jr%|r#t#jd|j_|r"t-j|d|d|j|||jS) NT)r[r\rr)rz\Session's state has been changed on a non-active transaction - this state will be discarded.rwith_traceback)r_rBrrprrFr;r<rDrEr~rCrrr>rKafter_rollbacksysexc_inforIrrrrrYraise_after_soft_rollback) rM_capture_exceptionrrboundary rollback_errrrsesss r"rzSessionTransaction.rollbacks $???l& d??"%"?"?T"?"J"J ' '$$&&&& ;68, , ,#==?? 2 2 &.+2D. !$[%=%D%D%F%F!G!G,,AaDMMOOOO-5 * -<|dd|jjdS|a |dS#t j5|dddn#1swxYwYYdSYdSxYw|dS)NT)r]r[)r_rBrrrrr)rMtype_value tracebacks r"__exit__zSessionTransaction.__exit__]s $??? < # + F = $  $&(($$MMOOO$$$$$$$$$$$$$$$$$$$$$ MMOOOOOs-?BA5) B5A9 9B<A9 =B)NF)FFFrUrSF)r3r4r5r6rYrOpropertyrNrErTr_rarhrkrprJrrrdrrrrrrrr:r*r"rresssjKKKK"X"FBBXB / %9%9%9%9N//X/BBBB EEEE$999 GGGG@BBB,333j@$;;;;z!!!!,     r*rc$eZdZdZdZejddd dNd ZdZdZ ej d Z dOd Z d Z dZdZdZ dPdZdQdZdRdZdRdZdZdZdZdZdZdZdZdSdZdZeejdZ dZ! dRd Z"d!Z#dQd"Z$d#Z%d$Z&ej'd%d&d'Z(d(Z)dTd)Z*d*Z+d+Z,d,Z-dUd-Z.d.Z/d/Z0d0Z1d1Z2dUd2Z3 dVd3Z4d4Z5d5Z6dTd6Z7d7Z8d8Z9d9Z:d:Z;d;ZdQd>Z?d?Z@d@ZAdQdAZB dWdBZC dOdCZDdDZEdEZFejdFGdXdHZGedIZHdZI edJZJedKZKedLZLedMZMdS)YrzManages persistence operations for ORM-mapped objects. The Session's usage paradigm is described at :doc:`/orm/session`. ) __contains____iter__addadd_allrrrrrhdeleteexecuteexpire expire_allexpunge expunge_allrwrc is_modifiedbulk_save_objectsbulk_insert_mappingsbulk_update_mappingsmerger refreshrscalar)z1.0aThe :paramref:`.Session.weak_identity_map` parameter as well as the strong-referencing identity map are deprecated, and will be removed in a future release. For the use case where objects present in a :class:`.Session` need to be automatically strong referenced, see the recipe at :ref:`session_referencing_behavior` for an event-based approach to maintaining strong identity references. )0.7zxThe :paramref:`.Session._enable_transaction_accounting` parameter is deprecated and will be removed in a future release.)rz:class:`.SessionExtension` is deprecated in favor of the :class:`.SessionEvents` listener interface. The :paramref:`.Session.extension` parameter will be removed in a future release.)weak_identity_maprI extensionNTFc |dvrtj|_ntj|_||_i|_i|_||_i|_d|_ d|_ d|_ t|_ ||_||_||_| |_||_||_| r| n t(j|_| r|j| | r,t3j| D]} t7j|| |0|D]\}}||||js||t@|j <dS)aConstruct 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: .. warning:: The autocommit flag is **not for general use**, and if it is used, queries should only be invoked within the span of a :meth:`.Session.begin` / :meth:`.Session.commit` pair. Executing queries outside of a demarcated transaction is a legacy mode of usage, and can in some cases lead to concurrent connection checkouts. Defaults to ``False``. When ``True``, the :class:`.Session` does not keep a persistent transaction running, and will acquire connections from the engine on an as-needed basis, returning them immediately after their use. 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 is used to explicitly start transactions. .. seealso:: :ref:`session_autocommit` :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. :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``, all caching is disabled, including baked queries defined by the calling application as well as those used internally. Setting this flag to ``False`` can significantly reduce memory use, however will also degrade performance for those areas that make use of baked queries (such as relationship loaders). Additionally, baked query logic in the calling application or potentially within the ORM that may be malfunctioning due to cache key collisions or similar can be flagged by observing if this flag resolves the issue. .. versionadded:: 1.2 :param _enable_transaction_accounting: A legacy-only flag which when ``False`` disables *all* 0.5-style object accounting on transaction boundaries. :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 extension: An optional :class:`~.SessionExtension` instance, or a list of such instances, which will receive pre- and post- commit and flush events, as well as a post-rollback event. :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`. .. versionadded:: 0.9.0 :param query_cls: Class which should be used to create new Query objects, as returned by the :meth:`~.Session.query` method. Defaults to :class:`_query.Query`. :param twophase: When ``True``, all transactions will be started as a "two phase" transaction, i.e. using the "two phase" semantics of the database in use along with an XID. During a :meth:`~.commit`, after :meth:`~.flush` has been issued for all attached databases, the :meth:`~.TwoPhaseTransaction.prepare` method on each database's :class:`.TwoPhaseTransaction` will be called. This allows each database to roll back the entire transaction, before each transaction is committed. :param weak_identity_map: Defaults to ``True`` - when set to ``False``, objects placed in the :class:`.Session` will be strongly referenced until explicitly removed or the :class:`.Session` is closed. TNFN)!rWeakInstanceDict _identity_clsStrongInstanceDictrrrrsrg_Session__bindsrv_warn_on_eventsr_new_sessionidhash_key autoflushrrenable_baked_queriesrIrr Query _query_clsinforrto_listr_adapt_listenerr _add_bindrr )rMrgrrrIrrrbindsrrr query_clsextrs r"rOzSession.__init__srz  , ,!)!:D  !)!Close this Session. This clears all items and ends any transaction in progress. If this session were created with ``autocommit=False``, a new transaction is immediately begun. Note that this new transaction does not use any connection resources until they are first needed. FrN _close_implrQs r"rz Session.closes! E*****r*c2|ddS)aClose 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 all :class:`_engine.Connection` objects. This can be called when the database is known to be in a state where the connections are no longer safe to be used. E.g.:: try: sess = Session() sess.add(User()) sess.commit() except gevent.Timeout: sess.invalidate() raise except: sess.rollback() raise This clears all items and ends any transaction in progress. If this session were created with ``autocommit=False``, a new transaction is immediately begun. Note that this new transaction does not use any connection resources until they are first needed. .. versionadded:: 0.9.9 TrNrrQs r"rzSession.invalidate&s"@ D)))))r*c||j1|jD]}||dSdSrS)rrrpr)rMrrs r"rzSession._close_implHsd    '#/IIKK . . !!*---- ( ' . .r*c|jt|jz}||_i|_i|_t j||dS)zRemove all object instances from this ``Session``. This is equivalent to calling ``expunge(obj)`` on all objects in this ``Session``. N) rrrrrrrsrrr)rMrs r"rzSession.expunge_allNsf&1133d49ooE  ..00  --j$?????r*c t|}|jr ||j|<dS|jr%||j|j<|jD] }||j|< dSt jd|z#t j$r\}t|ts,tj t jd|z|n||j|<Yd}~dSYd}~dSd}~wwxYw)Nz!Not an acceptable bind target: %sreplace_context) r is_selectabler is_mapperclass_ _all_tablesrG ArgumentErrorNoInspectionAvailablertyperr)rMrrginsp selectableerrs r"rzSession._add_bind]sB 3<#6F!!-f4HHH//ADL((#|A...) 9 9  fcn: ; ;   ;   2f/4 2,1 1   NN;/ 0 0 0   NN+ , , ,* Fyy!! #   sAB?BBc |j||fi|S)zZReturn a new :class:`_query.Query` object corresponding to this :class:`.Session`.)r)rMentitiesr/s r"r z Session.query1s tx88888r*c#VK|j}d|_ |V||_dS#||_wxYw)agReturn a context manager that disables autoflush. e.g.:: with session.no_autoflush: some_object = SomeClass() session.add(some_object) # won't autoflush some_object.related_thing = session.query(SomeRelated).first() Operations that proceed within the ``with:`` block will not be subject to flushes occurring upon query access. This is useful when initializing a series of objects which involve existing database queries, where the uncompleted object should not yet be flushed. FN)r)rMrs r" no_autoflushzSession.no_autoflush7sB*N  'JJJ&DNNNYDN & & & &s (c|jr}|jsx |dS#tj$rM}|dt j|tj dYd}~dSd}~wwxYwdSdS)Nzraised as a result of Query-invoked autoflush; consider using a session.no_autoflush block if this flush is occurring prematurelyrr) rrvrwrGStatementError add_detailrrrr)rMes r" _autoflushzSession._autoflushSs > A$. A A ( A A A  5  AclnnQ.?@@@@@@@@@@ A A A A As&BAA==Bc tj|}nD#tj$r2}t jtj||Yd}~nd}~wwxYw||||ikrtj d|r tj |}n0|.|durtj }n|rtj di|}nd}tj| t||j||| $tjdt%|zdS)a{Expire and refresh the attributes on the given instance. A query will be issued to the database and all attributes will be refreshed with their current database value. Lazy-loaded relational attributes will remain lazily loaded, so that the instance-wide refresh operation will be followed immediately by the lazy load of that attribute. Eagerly-loaded relational attributes will eagerly load within the single refresh operation. 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 - usage of :meth:`~Session.refresh` usually only makes sense if non-ORM SQL statement were emitted in the ongoing transaction, or if autocommit mode is turned on. :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. .. versionadded:: 1.2 :param lockmode: Passed to the :class:`~sqlalchemy.orm.query.Query` as used by :meth:`~sqlalchemy.orm.query.Query.with_lockmode`. Superseded by :paramref:`.Session.refresh.with_for_update`. .. seealso:: :ref:`session_expire` - introductory material :meth:`.Session.expire` :meth:`.Session.expire_all` :meth:`_orm.Query.populate_existing` rNzqwith_for_update should be the boolean value True, or a dictionary with options. A blank dictionary is ambiguous.T) refresh_statewith_for_updateonly_load_propszCould not refresh instance '%s'r:)rinstance_staterNO_STATErrUnmappedInstanceError _expire_staterGr"r LockmodeArgparse_legacy_queryr load_on_identrrrHr)rMr2attribute_namesrFlockmoder r's r"rzSession.refreshcsl -h77EE|    K)(33 #           5/222 b &3   '#/BB8LLOO  ($&&"'"3"5"5  '"'"3"F"Fo"F"F"&  ! =2233 # / /     ,1L4J4JJ   A(AAc|jD]'}||j|jj(dS)aExpires 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)rrrrrrMr s r"rzSession.expire_allsP@&1133 C CE MM%*d&7&A B B B B C Cr*c tj|}nD#tj$r2}t jtj||Yd}~nd}~wwxYw|||dS)aExpire 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` rN)rrHrrIrrrJrK)rMr2rOr r's r"rzSession.expiresJ -h77EE|    K)(33 #           5/22222rQc0|||r||j|dSt|jjd|}|||D]\}}}}||dS)Nzrefresh-expire)_validate_persistent_expire_attributesrrmanagerr cascade_iterator_conditional_expire)rMr rOcascadedomst_dct_s r"rKzSession._expire_states !!%(((  .  $ $UZ A A A A A $556FNNH  $ $U + + +#+ . .1c4((---- . .r*c|jr'||j|jjdS||jvr1|j|||dSdS)z5Expire a state if persistent, else expunge if pendingN)rrrrrrrpop_detachrSs r"rZzSession._conditional_expire!sq 9 MM%*d&7&A B B B B B di   IMM% MM$      r*rzThe :meth:`.Session.prune` method is deprecated along with :paramref:`.Session.weak_identity_map`. This method will be removed in a future release.c4|jS)aRemove unreferenced instances cached in the identity map. Note that this method is only meaningful if "weak_identity_map" is set to False. The default weak identity map is self-pruning. Removes any object in this Session's identity map that is not referenced in user code, modified, new or scheduled for deletion. Returns the number of objects pruned. )rprunerQs r"rdz Session.prune*s" &&(((r*c tj|}nD#tj$r2}t jtj||Yd}~nd}~wwxYw|j|jur$tj dt|zt|j jd|}||gd|DzdS)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. rNz*Instance %s is not present in this Sessionrcg|] \}}}}| Sr:r:).0r\r]r^r_s r" z#Session.expunge..Ss 'L'L'L1c4'L'L'Lr*)rrHrrIrrrJrrrGrHrrrXr rYr)rMr2r r'r[s r"rzSession.expunge=s -h77EE|    K)(33 #            4= 0 0,z/Session._register_persistent..s) 5 5UeUZ 5 5 5 5 5 5r*)rKpending_to_persistentrobj_identity_key_from_stater intersectionallow_partial_pks issupersetrrrrrrrrurrr_orphaned_outside_of_sessionrr_commit_all_states_register_alteredrrr~ra) rMrkrqr r rr instance_keyorig_keyolds r"_register_persistentzSession._register_persistentds!% C Kt9 ;9 ;E"5))F))++C%>>uEE *<?;;"4!+LO<< .?$E**+   9$ ,EIIY,..%225999 0 >>>#'#3#A%#H#K#(9 $=D$259!-EI '//66O77<< LL -II0<||> 6;211 5 5f 5 5 5t7H    v&&& ,,,TY77 3 3%%dE2222[[--di88 ! !E IMM%  ! !r*c|jr4|jr/|D].}||jvrd|jj|<d|jj|<+dSdSdSNT)rIrrrrt)rMrkr s r"ryzSession._register_alteredsw  . :43C : : :DI%%37D$)%0059D$+E22  : : : : : :r*c&|jjpd}|D]}|jr|jrd|jj|<||}|j||j|dd|_| |||dSr) rKpersistent_to_deletedrIrrsrrrrra)rMrkrr rrs r"_remove_newly_deletedzSession._remove_newly_deleteds $ C Kt 3 3E2 8t7G 837 )%0$0iikk   * *5 1 1 1 M  eT * * *!EN%0%%dE222! 3 3r*c |r|jr|d tj|}nD#tj$r2}t jt j||Yd}~nd}~wwxYw| |dS)zPlace an object in the ``Session``. Its state will be persisted to the database on the next flush operation. Repeated calls to ``add()`` will be ignored. The opposite of ``add()`` is ``expunge()``. z Session.add()rN) r_flush_warningrrHrrIrrrJ_save_or_update_state)rMr2_warnr r's r"rz Session.adds  1T) 1    0 0 0 -h77EE|    K)(33 #           ""5)))))s5A6(A11A6cv|jr|d|D]}||ddS)z:Add the given collection of instances to this ``Session``.zSession.add_all()F)rN)rrr)rM instancesr2s r"rzSession.add_allsV   5    3 4 4 4! , ,H HHXUH + + + + , ,r*cd|_||t|}|d||jD]\}}}}||dS)NFz save-update)halt_on)rw_save_or_update_implrrY_contains_state)rMr r r\r]r^r_s r"rzSession._save_or_update_states-2* !!%(((u%%%66 5$*> 7   + +OAq#t  % %c * * * * + +r*c"|jr|d tj|}nD#tj$r2}t jt j||Yd}~nd}~wwxYw| ||ddS)zfMark an instance as deleted. The database delete operation occurs upon ``flush()``. zSession.delete()rNT)head) rrrrHrrIrrrJ _delete_implrMr2r r's r"rzSession.deletes   4    2 3 3 3 -h77EE|    K)(33 #           %55555s3A4(A//A4c|j(|r$tjdt|zdS|||}||jvrdS|j||r||||r-t|j j d|}||j|<|r!|D] \}}}} | ||ddSdS)NInstance '%s' is not persistedrF)rrGrHr_before_attachrsrr _after_attachrrXr rYr) rMr rrr to_attachcascade_statesr\r]r^r_s r"rzSession._delete_impls' 9  04y7G7GG''s33 DM ! ! F e$$$  +   uc * * *  " $55hFFN # e  1#1 1 11c4!!#q%0000 1 1 1 1r*cL|jr|di}i}|r|t||j} d|_|t j|t j||||||_S#||_wxYw)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. .. seealso:: :func:`.make_transient_to_detached` - provides for an alternative means of "merging" a single object into the :class:`.Session` zSession.merge()F)load _recursive_resolve_conflict_map) rrrCrr_mergerrH instance_dict)rMr2rrrrs r"rz Session.merge1sn   3    1 2 2 2 "   OO   hN  '"DN;;)(33(22%&; 'DNNYDN & & & &s AB B#c t|}||vr||Sd}|j}|||jvr$tjdt |z|st jd||}tj |dvo  ?S,A%A%A.s3 ?> 4K  -::<<)8@@ #&  !!,///# " ?FM2266s1v>> >)6688F%4V<  FNN0.1:%0@0@Aiikk ; F''s33  %&&&  )   % %e , , , ,   ! !% ( ( (  =   uc * * * * *  = M / /e < < < < < = =r*cl|j||dS||dSrS)rrrrSs r"rzSession._save_or_update_implQ s< 9  OOE " " " " "   e $ $ $ $ $r*ctj|}|||}d|_|r|||dSdS)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. TN)rrHr _load_pendingr)rMrrr rs r"enable_relationship_loadingz#Session.enable_relationship_loadingW s`n)#..''s33 "  +   uc * * * * * + +r*c |j|jkrdS|jrC|jtvr5tjdt |d|jd|jd|j||dS)NFzObject 'z"' is already attached to session 'z ' (this is 'z')T)rrr rGrHrrK before_attachrMr rrs r"rzSession._before_attach s  t} , ,5    0I = =,,U####U%5%5%5t}}}F  ##D%000tr*c|j|_|jr|j||_|j|||jr|j||dS|j||dSrS) rrr _strong_objrK after_attachrdetached_to_persistenttransient_to_pendingrs r"rzSession._after_attach s= > $e/7 #E  ""4/// 9 < M 0 0u = = = = = M . .tU ; ; ; ; ;r*c tj|}nD#tj$r2}t jtj||Yd}~nd}~wwxYw||S)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. rN)rrHrrIrrrJrrs r"rzSession.__contains__ s -h77EE|    K)(33 #           ##E***rQctt|jt|jzS)zWIterate over all pending or persistent instances within this Session. )iterrrrrrrQs r"rzSession.__iter__ sK  !!## $ $tD,=,D,D,F,F'G'G G   r*cH||jvp|j|SrS)rrrrjrSs r"rzSession._contains_state s% !LT%6%E%Ee%L%LLr*c|jrtjd|rdS d|_||d|_dS#d|_wxYw)aFlush 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. zSession is already flushingNTF)rvrGrHr_flush)rMobjectss r"rwz Session.flush st6 > L,-JKK K >>    F #!DN KK "DNNNUDN " " " "s A A!c4tjd|zdS)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.)rr)rMmethods r"rzSession._flush_warning s3  FIO O     r*cV|j o|j o|j SrS)rcheck_modifiedrsrrrQs r"rzSession._is_clean s5!0022 2 M! I  r*cN|j}|s.|js'|js |jjdSt |}|jjr#|j||||j}t|j}t|j}t| |}|rt}|D]q} tj |}nD#tj$r2} tjtj|| Yd} ~ nd} ~ wwxYw||rnd}t} |r<||| |} n(|| |} | D]}t+||} | o|j} | r | s|jr||gO||| }|s Jd| ||r)|| | } n| | } | D]%}||d}|s Jd&|jsdS|dx|_} d|_ |d|_n #d|_wxYw|j |||!|sv|jjrjtE|jj}tFj$%d|jjD|jtj&d |z|j'|||(dS#tj)5|*d dddYdS#1swxYwYYdSxYw) Nr)isdeletez*Failed to add object to the flush context!TrFc g|] }||jf Sr:rnros r"rhz"Session._flush..^ s/! +r*)rzAttribute 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_statesrsrrrrrrrK before_flushr~ differencerrHrrIrrrJrrrtr _is_orphan has_identityrwrregister_objecthas_workrrrr after_flushfinalize_flush_changesrrrrxrafter_flush_postexecrrr)rMrdirty flush_contextdeletednewobjsetr\r r' processedproc is_orphanis_persistent_orphan_regrlen_s r"rzSession._flush s"" T] 49    ' - - / / / F&t,, = % ' M & &t]G D D D&Edm$$$)nnE %%g..  UUF " "&5a88EE|K1!44(+  5!!!! "FEE   899U##0088CCGLLDD99U##..w77D % %E%e,,77>>I#,#C1C  %, %6 % $$eW----$44$85IIIIII e$$$$  1''//::9EEDD%%i00D F FE 000FFD E EE E E E E%  F26** 3=3 3  !K+ >#'D  -%%'''',$$u$,,,, M % %dM : : :  0 0 2 2 2 t0: 4,677&99%)%6%@#'"3 : H KO O M . .t] C C C     >"$$ > >$$$=== > > > > > > > > > > > > > > > > > > > >saC**D+9(D&&D+OK80O8 LCOP$1P P$P P$P P$c d}d|D}|st||}tj||D]#\\}}} ||| |d||d$dS)aPerform 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, unless the ``return_defaults`` flag is also set, in which case primary key attributes and server-side default values will be populated. .. versionadded:: 1.0.0 .. warning:: 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. **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. :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"|j|jdufSrS)r rr s r"rz&Session.bulk_save_objects..key sL%)4"78 8r*c3>K|]}tj|VdSrS)rrH)rgrrs r"rpz,Session.bulk_save_objects.. s-HHj/44HHHHHHr*)rTFN)sorted itertoolsgroupby_bulk_save_mappings) rMrreturn_defaultsupdate_changed_onlypreserve_orderr obj_statesr isupdaterks r"rzSession.bulk_save_objects| sn 9 9 9IHHHH  5 444J*3*;J*L*L   & VX  $ $#      r*c <|||dd|d|dS)aFPerform 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 .. warning:: 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. **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` FNr)rMr mappingsr render_nullss r"rzSession.bulk_insert_mappings s<v              r*c <|||ddddddS)aPerform 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 .. warning:: 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. **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)rMr rs r"rzSession.bulk_update_mappingsJ s6b   HdE5%     r*ct|}d|_|d} |rtj|||||ntj|||||||nH#tj5| ddddn #1swxYwYYnxYwd|_dS#d|_wxYw)NTrrF) r rvrr _bulk_update _bulk_insertrrrr) rMr rrisstatesrrrrs r"rzSession._bulk_save_mappings sG"&))jjj66  # (' (#      >"$$ > >$$$=== > > > > > > > > > > > > > > >#DNNNUDN " " " "sBAA76C7B< B/# B</B3 3B<6B3 7B<:C C)z0.8zThe :paramref:`.Session.is_modified.passive` flag is deprecated and will be removed in a future release. The flag is no longer used and is ignored.rc t|}|jsdS|j}|jjD]a}|st |jdst |jds/|j||tj\}}} |s| rdSbdS)aZ 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. :param passive: not used Fget_collection get_historyrT) rrrrXrhasattrimplr NO_CHANGE) rMr2include_collectionsrr dict_attradded unchangedrs r"rzSession.is_modified sxX&&~ 5 M,  D' DI'788 TY 66 *.)*?*?uj&:+@++ 'UIw  tt 5r*c(|jo |jjS)a2 True if this :class:`.Session` is in "transaction mode" and is not in "partial rollback" state. The :class:`.Session` in its default mode of ``autocommit=False`` is essentially always in "transaction mode", in that a :class:`.SessionTransaction` is associated with it as soon as it is instantiated. This :class:`.SessionTransaction` is immediately replaced with a new one as soon as it is ended, due to a rollback, commit, or close operation. "Transaction mode" does *not* indicate whether or not actual database connection resources are in use; the :class:`.SessionTransaction` object coordinates among zero or more actual database transactions, and starts out with none, accumulating individual DBAPI connections as different data sources are used within its scope. The best way to track when a particular :class:`.Session` has actually begun to use DBAPI resources is to implement a listener using the :meth:`.SessionEvents.after_begin` method, which will deliver both the :class:`.Session` as well as the target :class:`_engine.Connection` to a user-defined event listener. The "partial rollback" state refers to when an "inner" transaction, typically used during a flush, encounters an error and emits a rollback of the DBAPI connection. At this point, the :class:`.Session` is in "partial rollback" and awaits for the user to call :meth:`.Session.rollback`, in order to close out the transaction stack. It is in this "partial rollback" period that the :attr:`.is_active` flag returns False. After the call to :meth:`.Session.rollback`, the :class:`.SessionTransaction` is replaced with a new one and :attr:`.is_active` returns ``True`` again. When a :class:`.Session` is used in ``autocommit=True`` mode, the :class:`.SessionTransaction` is only instantiated within the scope of a flush call, or when :meth:`.Session.begin` is called. So :attr:`.is_active` will always be ``False`` outside of a flush or :meth:`.Session.begin` block in this mode, and will be ``True`` within the :meth:`.Session.begin` block as long as it doesn't enter "partial rollback" state. From all the above, it follows that the only purpose to this flag is for application frameworks that wish to detect if a "rollback" is necessary within a generic error handling routine, for :class:`.Session` objects that would otherwise be in "partial rollback" mode. In a typical integration case, this is also not necessary as it is standard practice to emit :meth:`.Session.rollback` unconditionally within the outermost exception catch. To track the transactional state of a :class:`.Session` fully, use event listeners, primarily the :meth:`.SessionEvents.after_begin`, :meth:`.SessionEvents.after_commit`, :meth:`.SessionEvents.after_rollback` and related events. )rrTrQs r"rTzSession.is_active sp>D$4$>>r*c4|jS)zThe set of all persistent states considered dirty. This method returns all states that were modified including those that were possibly deleted. )rrrQs r"rzSession._dirty_statesB s ..000r*cNtjfdjDS)aZThe 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. cJg|]}|jv | Sr:)rsrr)rgr rMs r"rhz!Session.dirty..e s8    -- ---r*)r IdentitySetrrQs`r"rz Session.dirtyL sC0    !/      r*crtjt|jS)zDThe set of all instances marked as 'deleted' within this ``Session``)rrrrsrrQs r"rzSession.deletedl s+T]%9%9%;%; < <===r*crtjt|jS)zAThe set of all instances marked as 'new' within this ``Session``.)rrrrrrrQs r"rz Session.newr s+TY%5%5%7%7 8 8999r*) NTTTFFNNNTNN)FF)NNNFNrS)NNN)NNr)T)TNN)FTTr)Nr3r4r5r6public_methodsrdeprecated_paramsrOconnection_callablermemoized_propertyrrrrrrrhrdrrrrrrrr*r-rcr rcontextmanagerr>rCrrrrKrZr8rdrrr}ryrrrrrrrrrVrrrrrrrrrrwrrrrrrrrrTrrrrrr:r*r"rrksN:T  (  !4'+! I(I(I(10I(VKF    > > > > @'''2((((""""""H###*  O O O O b    J J J J X + + + * * *D... @ @ @2%%%8$$$8A A A A F999  ''X'4AAA& ]]]]~!C!C!CF,3,3,3,3\ . . .   T_  ' ) )  )NNN0     P!P!P!d:::333(****.,,,+++666& 1 1 1DM'M'M'M'f" SSSSj + + +$=$=$=$=L%%% ;+;+;+z    < < <+++    MMM$#$#$#$#L      {>{>{>{>@  ggggTEJc c c c J3 3 3 j&#&#&#PT IIIIV7?7?X7?rL 11X1  X >>>X> ::X:::r*rc8eZdZdZdeddddfdZdZdZdZdS) ra3A 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.:: # global scope Session = sessionmaker(autoflush=False) # later, in a local scope, create and use a session: sess = Session() Any keyword arguments sent to the constructor itself will override the "configured" keywords:: Session = sessionmaker() # bind an individual session to a connection sess = Session(bind=connection) The class also includes a method :meth:`.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 Session = sessionmaker() # ... later engine = create_engine('sqlite:///foo.db') Session.configure(bind=engine) sess = Session() .. seealso:: :ref:`session_getting` - introductory text on creating sessions using :class:`.sessionmaker`. NTFc ||d<||d<||d<||d<|||d<||_t|j|fi|_dS)alConstruct 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. .. versionadded:: 0.9.0 :param \**kw: all other keyword arguments are passed to the constructor of newly created :class:`.Session` objects. rgrrrNr)r r$r3r )rMrgr rrrrr s r"rOzsessionmaker.__init__ s_P6 #;%<!1   BvJ6?VIr:: r*c |jD]Z\}}|dkr9d|vr5|}||d||d<D|||[|jdi|S)aeProduce 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__() rr:)r rcopyr setdefaultr )rMlocal_kwkvds r"__call__zsessionmaker.__call__ sGMMOO * *DAqF{{v11FFHH&)***#$  ##Aq))))t{&&X&&&r*c :|j|dS)z(Re)configure the arguments for this sessionmaker. e.g.:: Session = sessionmaker() Session.configure(bind=create_engine('sqlite://')) N)r r)rMnew_kws r" configurezsessionmaker.configure s vr*c |jjd|jjddd|jDdS)Nz(class_=r0c3*K|]\}}|d|VdS)=Nr:)rgr!r"s r"rpz(sessionmaker.__repr__.. s1CC41aAA&CCCCCCr*)) __class__r3r r9r rrQs r"__repr__zsessionmaker.__repr__ sV N # # # K IICC47==??CCC C C C C  r*) r3r4r5r6rrOr$r'r-r:r*r"rry su,,` 1;1;1;1;f'''(        r*rcftD]}|dS)aOClose 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 rr)rs r"r'r' s8  "" r*ctj|}t|}|r||g|j|jr|`|jr|`|jr|`dSdS)aMAlter 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) rrHr#rexpired_attributesr callablesrrs)r2r rs r"make_transientr2 s\  %h / /EuA# 5'""" ""$$$  O y I ~ NNNr*c6tj|}|js|jrt jd|j||_|jr|`| |j | |j |j dS)aMake 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. .. versionadded:: 0.9.5 .. seealso:: :func:`.make_transient` :meth:`.Session.enable_relationship_loading` zGiven object must be transientN) rrHrrrGrHr rsrsrrrWunloaded_expirable)r2r s r"make_transient_to_detachedr5T s>  %h / /E K59K()IJJJ 55e<r?rrrr'r2r5r1counterrr:r*r"rAsm87 """"""333333&&&&&& """""" P O O 'G ' ) ) ?   !(!(!(!(!(6!(!(!(H X   4;z " " DK $ $ 4;z " " X  CCCCCCCCLK(:K(:K(:K(:K(:"K(:K(:K(:\PF F F F F 'F F F R$===@&C&C&CR%%%&r*