U alp@sFdZddlZddlZddlZddlmZddlmZddlmZddlmZddlm Z dd lm Z dd lm Z dd lm Z dd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddl$m%Z%ddl&m'Z'd d!d"d#d$d%d&d'gZ(e)Z*e*e _*d(d)Z+Gd*d+d+e,Z-e.d,Z/e.d-Z0e.d.Z1e.d/Z2e.d0Z3Gd1d#d#ej4Z5Gd2d!d!eZ6Gd3d d e-Z7Gd4d"d"e-Z8d5d$Z9d6d%Z:d7d&Z;d8d'ZdS)9z1Provides the Session class and related utilities.N) attributes)context)exc)identity)loading) persistence)querystate)_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_COLSessionSessionTransaction sessionmakerORMExecuteStateclose_all_sessionsmake_transientmake_transient_to_detachedobject_sessioncCs|jS)z[Given an :class:`.InstanceState`, return the :class:`.Session` associated, if any. sessionr r*WC:\Users\vtejo\AppData\Local\Temp\pip-unpacked-wheel-nyjtotrf\sqlalchemy\orm\session.py_state_session=sr,c@sJeZdZdZeeddddZeedddZ ed d Z d S) _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`.cCs tdS)zClose *all* sessions in memory.N)r$)clsr*r*r+ close_allGs z_SessionClassMethods.close_allzsqlalchemy.orm.utilcOstjjj||S)zZReturn an identity key. This is an alias of :func:`.util.identity_key`. )rZ preloadedZorm_util identity_key)r.argskwargsr*r*r+r0Ssz!_SessionClassMethods.identity_keycCst|S)zxReturn the :class:`.Session` to which an object belongs. This is an alias of :func:`.object_session`. )r')r.instancer*r*r+r']sz#_SessionClassMethods.object_sessionN) __name__ __module__ __qualname____doc__ classmethodr deprecatedr/Zpreload_moduler0r'r*r*r*r+r-Ds  r-ACTIVEPREPARED COMMITTEDDEACTIVECLOSEDc@seZdZdZdZddZddZd,dd Zed d Z ed d Z eddZ eddZ eddZ eddZeddZeddZddZddZeddZed d!Zed"d#Zed$d%Zed&d'Zed(d)Zed*d+ZdS)-r#a8Represents 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 parametersexecution_optionslocal_execution_optionsbind_arguments_compile_state_cls_starting_event_idx _events_todoZ_update_execution_optionscCs@||_||_||_||_|j||_||_||_t ||_ dSN) r)r?r@rB_execution_optionsunionrArCrDlistrF)selfr)r?r@rArCcompile_state_cls events_todor*r*r+__init__s zORMExecuteState.__init__cCs|j|jddS)Nr)rFrErKr*r*r+_remaining_eventssz!ORMExecuteState._remaining_eventsNcCsx|dkr|j}t|j}|r&||d|d<|rHt|j}||n|j}|j}|rb||}|jj|||||dS)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`. NT_sa_skip_events)_parent_execute_state) r?dictrCupdater@rBrIr)execute)rKr?paramsrArCZ_bind_arguments_paramsrHr*r*r+invoke_statements(6     z ORMExecuteState.invoke_statementcCs|jddS)aReturn 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)rCgetrOr*r*r+ bind_mapperszORMExecuteState.bind_mappercCs|js gS|jrpg}t}|jjD]H}|d}|r"t|dd}|r"|jr"|j|kr"||j||jq"|S|j s||j r|j gSgSdS)aReturn 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)ZraiseerrN) is_orm_statement is_selectsetr?Zcolumn_descriptionsrrYaddappend is_update is_deleter[)rKresultseendentinspr*r*r+ all_mappers s     zORMExecuteState.all_mapperscCs |jdk S)areturn 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)rDrOr*r*r+r]2s z ORMExecuteState.is_orm_statementcCs|jjS)z*return True if this is a SELECT operation.)r?r^rOr*r*r+r^?szORMExecuteState.is_selectcCs|jjo|jjS)z+return True if this is an INSERT operation.)r?is_dml is_insertrOr*r*r+rkDszORMExecuteState.is_insertcCs|jjo|jjS)z+return True if this is an UPDATE operation.)r?rjrbrOr*r*r+rbIszORMExecuteState.is_updatecCs|jjo|jjS)z*return True if this is a DELETE operation.)r?rjrcrOr*r*r+rcNszORMExecuteState.is_deletecCst|jtjtjfSrG) isinstancer?rZUpdateZDeleterOr*r*r+_is_crudSszORMExecuteState._is_crudcKs|j||_dSrG)rBrIrKoptsr*r*r+update_execution_optionsWsz(ORMExecuteState.update_execution_optionscCs,|js dS|jj}|tjjr$|SdSdSrG)r^r?Z_compile_optionsrlrZORMCompileStateZdefault_compile_optionsrnr*r*r+_orm_compile_options[s z$ORMExecuteState._orm_compile_optionscCs|jjS)aAn :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_optionsZ_lazy_loaded_fromrOr*r*r+lazy_loaded_fromds z ORMExecuteState.lazy_loaded_fromcCs|}|dk r|jSdSdS)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)rqZ _current_pathrnr*r*r+loader_strategy_pathssz$ORMExecuteState.loader_strategy_pathcCs|}|dk o|jS)aqReturn 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)rqZ_for_refresh_staternr*r*r+is_column_loadszORMExecuteState.is_column_loadcCs*|}|dkrdS|j}|dk o(|j S)azReturn 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)rqrtZis_root)rKropathr*r*r+is_relationship_loads z$ORMExecuteState.is_relationship_loadcCs"|jstd|jdtjjS)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.Z_sa_orm_load_options)r^sa_excInvalidRequestErrorrArZr QueryContextdefault_load_optionsrOr*r*r+rrszORMExecuteState.load_optionscCs"|jstd|jdtjjS)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.Z_sa_orm_update_options)rmrxryrArZrZBulkUDCompileStateZdefault_update_optionsrOr*r*r+update_delete_optionssz%ORMExecuteState.update_delete_optionscCsdd|jjDS)zzThe sequence of :class:`.UserDefinedOptions` that have been associated with the statement being invoked. cSsg|]}|js|js|qSr*)Z_is_compile_stateZ_is_legacy_option).0optr*r*r+ sz8ORMExecuteState.user_defined_options..)r?Z _with_optionsrOr*r*r+user_defined_optionssz$ORMExecuteState.user_defined_options)NNNN)r4r5r6r7 __slots__rNrPrXpropertyr[rir]r^rkrbrcrmrprqrsrtrurwrrr|rr*r*r*r+r#osR   P  $             c@seZdZdZdZd-ddZeddZdZedd Z d.d d Z ed dZ d/ddZ d0ddZ d1ddZd2ddZd3ddZddZddZddZdd Zd4d!d"Zd5d#d$Zd6d%d&Zd'd(Zd)d*Zd+d,ZdS)7r!aA :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` NFcCspt|||_i|_||_||_|r.|j|_t|_ |sF|rFt d|j |d||j_ |jj|j|dS)NzOCan't start a SAVEPOINT transaction when no existing transaction is in progress autobegin)r_trans_ctx_checkr) _connections_parentnested_nested_transaction_previous_nested_transactionr:_staterxry_take_snapshot _transactiondispatchZafter_transaction_create)rKr)parentrrr*r*r+rNs  zSessionTransaction.__init__cCs|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 )rrOr*r*r+r&szSessionTransaction.parentcCs|jdk o|jtkSrG)r)rr:rOr*r*r+ is_active@szSessionTransaction.is_activeThis transaction is closedcCs|jtkrtdnl|jtkr0|stdnR|jtkrn|s|s|jr^tjd|jddq|stdn|jtkrt |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: %sZ7s2acodezThis session is in 'inactive' state, due to the SQL transaction being rolled back; no further SQL can be emitted within this transaction.) rr<rxryr;r=_rollback_exceptionZPendingRollbackErrorr>ZResourceClosedError)rK prepared_ok rollback_okZ deactive_okZ closed_msgr*r*r+_assert_activeDs0     z!SessionTransaction._assert_activecCs|jp |j SrG)rrrOr*r*r+_is_transaction_boundaryksz+SessionTransaction._is_transaction_boundarycKs$||jj|f|}|||SrG)rr)get_bind_connection_for_bind)rKZbindkeyrAr2bindr*r*r+ connectionoszSessionTransaction.connectioncCs|t|j||dS)Nr)rr!r))rKrr*r*r+_begintszSessionTransaction._begincCsJ|}d}|rF||f7}|j|kr$qFq|jdkr>td|q|j}q|S)Nr*z4Transaction %s is not on the active transaction list)rrxry)rKuptocurrentrdr*r*r+_iterate_self_and_parentsxs   z,SessionTransaction._iterate_self_and_parentscCst|js2|jj|_|jj|_|jj|_|jj|_dS|sH|jjsH|jt |_t |_t |_t |_dSrG) rr_new_deleted_dirty _key_switchesr) _flushingflushweakrefWeakKeyDictionary)rKrr*r*r+rs         z!SessionTransaction._take_snapshotcCs|js tt|j|jj}|jj|dd|jD]6\}\}}|jj |||_ ||kr8|jj |q8t|j |jj D]}|jj|ddq|jj rt|jj D],}|r|js||jkr||j|jj jqdS)zmRestore the restoration state taken before a transaction began. Corresponds to a rollback. T to_transient)revert_deletionN)rAssertionErrorr_rrIr)_expunge_statesritems identity_map safe_discardkeyreplacer _update_impl all_statesmodifiedr_expirerS _modified)rK dirty_onlyZ to_expungesZoldkeyZnewkeyr*r*r+_restore_snapshots  z$SessionTransaction._restore_snapshotcCs|js t|js`|jjr`|jjD]}||j|jjj q$t j t |j|j|jnF|jr|jj|j|jj|j|jj|j|jj|jdS)zjRemove the restoration state taken before a transaction began. Corresponds to a commit. N)rrrr)expire_on_commitrrrrSrstatelib InstanceState_detach_statesrJrclearrrrTrr)rKrr*r*r+_remove_snapshots  z#SessionTransaction._remove_snapshotcCs`|||jkr.|r td|j|dSd}d}|jrV|j||}|js|Sn4t|tj r~|}|j|jkrt dn | }d}zp|r|j f|}|jjr|jdkr|}n@|jr|}n0|r|r|}q|}d}n|}Wn|r|YnFXt|tj }|||| f|j|<|j|j<|jj|j|||SdS)NzOConnection is already established for the given bind; execution_options ignoredrFTzMSession already has a Connection associated for the given Connection's Engine)rrrwarnrrrrlr ConnectionrxryconnectrAr)twophaseZbegin_twophase begin_nestedin_transactionin_nested_transactionget_nested_transactionget_transactionbegincloserZ after_begin)rKrrAZ local_connect should_commitconn transactionZbind_is_connectionr*r*r+rs\         z'SessionTransaction._connection_for_bindcCs(|jdk s|jjstd|dS)NzD'twophase' mode not enabled, or not root transaction; can't prepare.)rr)rrxry _prepare_implrOr*r*r+prepares zSessionTransaction.preparec Cs||jdks|jr(|jj|j|jj}||k rR|j|dD] }|qD|jj st dD]}|j rtq|j qbt d|jdkr|jjrz$t|jD]}|dqWn(t|W5QRXYnXt|_dS)NrdzrOver 100 subsequent flushes have occurred within session.commit() - is an after_flush() hook creating new objects?r)rrrr)rZ before_commitrrcommitrrange _is_cleanrr FlushErrorrr_rvaluesrr safe_reraiserollbackr;r)rKstxsubtransactionZ _flush_guardtr*r*r+rs.     z SessionTransaction._prepare_implcCs|jdd|jtk r||jdks.|jrtt|jD]\}}}}|r<| qrrZafter_transaction_end)rKrrrrrr*r*r+rs$    zSessionTransaction.closecCs|jSrGr(rOr*r*r+ _get_subjectszSessionTransaction._get_subjectcCs |jtkSrG)rr:rOr*r*r+_transaction_is_activesz)SessionTransaction._transaction_is_activecCs |jtkSrG)rr>rOr*r*r+_transaction_is_closedsz)SessionTransaction._transaction_is_closed)NFF)FFFr)N)F)N)F)F)F)FF)F)r4r5r6r7rrNrrrrrrrrrrrrrrrrrrrrrr*r*r*r+r!sB&    '      B  : c @seZdZdZejdddddZdZdZd d Z d d Z ej d dZ e ejddddddZddZddZddZddZddZejddZd d!Zejd"d#dd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zdd.d/Zdd0d1Zdejdddfd2d3Z dejdfd4d5Z!d6d7Z"d8d9Z#d:d;Z$dd?Z&d@dAZ'dBdCZ(ddDdEZ)dFdGZ*de+j,dfdHdIZ-e ej dJdKZ.dLdMZ/ddNdOZ0dPdQZ1ddRdSZ2dTdUZ3ddVdWZ4dXdYZ5ddZd[Z6d\d]Z7d^d_Z8d`daZ9ddbdcZ:dddeZ;dfdgZddldmZ?ddndoZ@ddpdqZAddrdsZBdtduZCdvdwZDddxdyZEdzd{ZFd|d}ZGd~dZHddZIddZJddZKddZLdddZMddZNddZOdddZPdddZQdddZRddZSddZTdddZUe ddZVdZWe ddZXe ddZYe ddZZe ddZ[dS)r zManages persistence operations for ORM-mapped objects. The Session's usage paradigm is described at :doc:`/orm/session`. )2.0aOThe :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.) autocommitNTFc Cst|_i|_i|_||_i|_d|_d|_d|_ d|_ ||_ t |_ ||_||_||_|rt|rltdd|_nd|_||_| r| ntj|_| r|j| |dk r|D]\} }|| |q|t|j <dS)a2Construct 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. :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 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)rWeakInstanceDictrrrr_Session__bindsr_warn_on_eventsrrfuture_new_sessionidhash_key autoflushrenable_baked_queriesrx ArgumentErrorrrr ZQuery _query_clsinforTr _add_bind _sessions) rKrrrrrrZbindsrrZ query_clsrr*r*r+rNs<'  zSession.__init__cCs|SrGr*rOr*r*r+ __enter__szSession.__enter__cCs |dSrG)r)rKtype_value tracebackr*r*r+__exit__szSession.__exit__c cs.| | |VW5QRXW5QRXdSrGrrOr*r*r+_maker_context_managers zSession._maker_context_managerz :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`.) alternativeZwarn_on_attribute_accesscCs|S)a9The 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_transactionrOr*r*r+rszSession.transactioncCs|js||jSrG)r _autobeginrrOr*r*r+rszSession._legacy_transactioncCs |jdk S)zReturn True if this :class:`_orm.Session` has begun a transaction. .. versionadded:: 1.4 .. seealso:: :attr:`_orm.Session.is_active` N)rrOr*r*r+rs zSession.in_transactioncCs |jdk S)zReturn True if this :class:`_orm.Session` has begun a nested transaction, e.g. SAVEPOINT. .. versionadded:: 1.4 NrrOr*r*r+rszSession.in_nested_transactioncCs$|j}|dk r |jdk r |j}q|S)zaReturn the current root transaction in progress, if any. .. versionadded:: 1.4 N)rrrKrr*r*r+rszSession.get_transactioncCs|jS)zcReturn the current nested transaction in progress, if any. .. versionadded:: 1.4 rrOr*r*r+rszSession.get_nested_transactioncCsiS)aA user-modifiable dictionary. The initial value of this dictionary can be populated using the ``info`` argument to the :class:`.Session` constructor or :class:`.sessionmaker` constructor or factory methods. The dictionary here is always local to this :class:`.Session` and can be modified independently of all other :class:`.Session` objects. r*rOr*r*r+rs z Session.infocCs2|js.|jdkr.t|dd}|j|ks*tdSdS)NTrF)rrr!rrr*r*r+rs  zSession._autobegin)rzThe :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.)subtransactionscCs|r|jrtd|r,|s,|s,|s,|jS|jdk rv|sB|sB|rj|jj|d}|j|ks^t|rt||_qtdnR|j s|s|s|rtt |}|j|kstn$|jrtt ||d}|j|kst|jS)aCBegin 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.Nrz/A transaction is already begun on this Session.) rNotImplementedErrorrrrrrrxryrr!)rKr r _subtransrr*r*r+rs00      z Session.begincCs |jddS)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. TrrrOr*r*r+r>szSession.begin_nestedcCs |jdkr n|jj|jddS)aRollback 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)rrrrOr*r*r+rWs zSession.rollbackcCs0|jdkr|std|jj|jddS)aFlush pending changes and commit the current transaction. If no transaction is in progress, the method will first "autobegin" a new transaction and commit. 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` NNo transaction is begun.r)rrrxryrrrOr*r*r+rrs  zSession.commitcCs*|jdkr|std|jdS)axPrepare 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 )rrrxryrrOr*r*r+rs  zSession.preparecKs8|s|}|dd}|dkr(|jf|}|j|||dS)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 rN)close_with_resultrA)poprr)rKrCr rAkwrr*r*r+rsA  zSession.connectioncKsbt||jdk s|r*|j||S|jdks8t|jsBt|jf|}|r^|jf|}|SrG) rrrrrrrrrA)rKrrArrr*r*r+rs    zSession._connection_for_bindc Ksttj|}|r2td|s&|}q:||n|s:i}|jdddkrZt |d}nd}t |}|dk r| ||||||dk \}}n| d||ddi}|r|} n|jj} |rt| |g} | r"t||||||| } t| D]"\} } | | _| | } | r| Sq| j}| j}|jf|}|jrV|j|dd}|td d }n ||}|||pni|} |r||||||| } | S) aMExecute 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:`_future.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.Zcompile_state_pluginNZormclause future_resultT)r F)r)rexpectrZ StatementRolerwarn_deprecated_20rT_propagate_attrsrZrZ_get_plugin_class_for_pluginZcoerce_to_immutabledictZorm_pre_session_exec setdefaultrIrPrZdo_orm_executerJr# enumeraterEr?rBrrrrSZ _execute_20Zorm_setup_cursor_result)rKr?rVrArCrRZ _add_eventrrLrMZorm_exec_stateidxfnrdrrr*r*r+rUsA          zSession.executecKs|j|f|||d|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. )rVrArC)rUscalar)rKr?rVrArCrr*r*r+rszSession.scalarcCs|jdddS)aClose 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` FrN _close_implrOr*r*r+rsz Session.closecCs|jdddS)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 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 `_, 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. TrNrrOr*r*r+rs"zSession.invalidatecCs0||jdk r,|jD]}||qdSrG) expunge_allrrr)rKrrr*r*r+rs zSession._close_implcCs<|jt|j}t|_i|_i|_tj ||dS)zRemove all object instances from this ``Session``. This is equivalent to calling ``expunge(obj)`` on all objects in this ``Session``. N) rrrJrrrrrrr)rKrr*r*r+r s  zSession.expunge_allc Csz t|}WnRtjk r^}z2t|tsDtjtd||dn ||j|<W5d}~XYnLX|j rr||j|<n8|j r||j|j <|j D]}||j|<qntd|dS)Nz!Not an acceptable bind target: %sZreplace_context) rrxNoInspectionAvailablerltyperrrrZ is_selectableZ is_mapperclass_Z _all_tables)rKrrrherrZ _selectabler*r*r+rs(     zSession._add_bindcCs|||dS)aAssociate 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` Nr)rKrYrr*r*r+r[1szSession.bind_mappercCs|||dS)aAssociate 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#)rKtablerr*r*r+ bind_tableMszSession.bind_tablec Cs:|r|S|js|jr|jS||kr.dkrHnn|jr>|jStd|dk rz t|}WnFtjk r}z&t|trtj t ||dnW5d}~XYnX|jr^|r|j j D]}||jkr|j|Sq|dkr|j}|dk r^|jdd}|dk r2|jj j D] }||jkr|j|Sqt|D] } | |jkr<|j| Sq<|jrl|jSd} d} |r|dkr|j}|dk r|jr|jrd} ntd|jS|r|jjr|jrd} ntd|jjSg} |dk r| d||dk r| d tjd d | | f| d dS) 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.rplugin_subjectzr 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 %szSQL expressionz;Could not locate a bind configured on %s or this Session.%s, r)rrrxZUnboundExecutionErrorrrrlr rrrZUnmappedClassErrorr!__mro__Zpersist_selectablerrZrYrZiteraterrrajoin) rKrYrrrQZ_sa_skip_for_implicit_returningr"r.r&objZ future_msgZ future_coderr*r*r+risU               zSession.get_bindcOs|j||f|S)zhReturn a new :class:`_query.Query` object corresponding to this :class:`_orm.Session`. )r)rKentitiesr2r*r*r+r 4sz Session.querycCs|j||d}t||||S)azLocate 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)Zidentity_key_from_primary_keyrZget_from_identity)rKrYprimary_key_identityr.passiversrr*r*r+_identity_lookup<s 1zSession._identity_lookupccs$|j}d|_z |VW5||_XdS)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)rKrr*r*r+ no_autoflushrs  zSession.no_autoflushc Csb|jr^|js^z |WnDtjk r\}z$|dtj|t ddW5d}~XYnXdS)Nzraised as a result of Query-invoked autoflush; consider using a session.no_autoflush block if this flush is occurring prematurelyrr) rrrrxZStatementErrorZ add_detailrrrr)rKer*r*r+ _autoflushs  zSession._autoflushc Cszt|}Wn8tjk rF}ztjt||dW5d}~XYnX||||ikrft dt j |}t t|}tj|||j|||ddkrtdt|dS)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 ` 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. rNzqwith_for_update should be the boolean value True, or a dictionary with options. A blank dictionary is ambiguous.)Z refresh_statewith_for_updateZonly_load_propszCould not refresh instance '%s')rinstance_staterNO_STATErrUnmappedInstanceError _expire_staterxrr ForUpdateArg_from_argumentrselectrrZ load_on_identrryr)rKr3attribute_namesr5r r"Zstmtr*r*r+refreshs8:    zSession.refreshcCs&|jD]}||j|jjq 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)rrrrSrrKr r*r*r+ expire_alls zSession.expire_allc CsXzt|}Wn8tjk rF}ztjt||dW5d}~XYnX|||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)rr6rr7rrr8r9)rKr3r=r r"r*r*r+expire s%zSession.expirecCs\|||r||j|n:t|jjd|}|||D]\}}}}||q@dS)Nzrefresh-expire)_validate_persistent_expire_attributesrSrJmanagerrYcascade_iterator_conditional_expire)rKr r=cascadedomst_dct_r*r*r+r9L s  zSession._expire_statecCs>|jr||j|jjn ||jkr:|j|||dS)z5Expire a state if persistent, else expunge if pendingN)rrrSrrrrZ_detach)rKr rr*r*r+rFZ s   zSession._conditional_expirec Cszt|}Wn8tjk rF}ztjt||dW5d}~XYnX|j|jk rft dt |t |j jd|}||gdd|DdS)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 SessionexpungecSsg|]\}}}}|qSr*r*)r}rHrIrJrKr*r*r+ry s z#Session.expunge..)rr6rr7rrr8 session_idrrxryrrJrDrYrEr)rKr3r r"rGr*r*r+rLc s  zSession.expungecCsv|D]Z}||jkr |j|q|j|rH|j||j|dq|jr|jj|dqtjj |||ddS)Nr) rrrcontains_staterrrrrr)rKstatesrr r*r*r+r{ s   zSession._expunge_statesc Cs|jjp d}|D]}t|}|}|dk r||}t|drL|jrZt|drlt dt ||j dkr~||_ nP|j |kr|j |||jjkr|jj|d}n|j }||f|jj|<||_ |j |}|dk r|||kr|dk rtd|fd|_qtjdd|D|j |||dk rf||jD]}|||qTt||jD]}|j|qvdS) 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. NraOInstance %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.rzIdentity map already had an identity for %s, replacing it with newly flushed object. Are there load operations occurring inside of an event handler within the flush?Fcss|]}||jfVqdSrGrSr}r r*r*r+ sz/Session._register_persistent..)rpending_to_persistentrr+_identity_key_from_stater intersectionallow_partial_pks issupersetrrrrrrrrrrr_orphaned_outside_of_sessionrr_commit_all_states_register_alteredrr_r) rKrOrSr rYr+Z instance_keyZorig_keyoldr*r*r+_register_persistent sf                zSession._register_persistentcCs8|jr4|D](}||jkr&d|jj|<q d|jj|<q dSNT)rrr)rKrOr r*r*r+rZ s  zSession._register_alteredcCsn|jjp d}|D]X}|jr&d|jj|<|dk r6|}|j||j|dd|_|dk r|||qdSr])rpersistent_to_deletedrrr+rrr)rKrOr^r r+r*r*r+_remove_newly_deleted s   zSession._remove_newly_deletedc Csj|r|jr|dzt|}Wn8tjk rZ}ztjt||dW5d}~XYnX| |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_warningrr6rr7rrr8_save_or_update_state)rKr3_warnr r"r*r*r+r` s  z Session.addcCs,|jr|d|D]}|j|ddqdS)z:Add the given collection of instances to this ``Session``.zSession.add_all()F)rbN)rr`r`)rKZ instancesr3r*r*r+add_all s zSession.add_allcCsFd|_||t|}|jd||jdD]\}}}}||q*dS)NFz save-update)Zhalt_on)rX_save_or_update_implrrE_contains_state)rKr rYrHrIrJrKr*r*r+ra s zSession._save_or_update_statec Csl|jr|dzt|}Wn8tjk rV}ztjt||dW5d}~XYnX|j ||dddS)zfMark an instance as deleted. The database delete operation occurs upon ``flush()``. zSession.delete()rNT)head) rr`rr6rr7rrr8 _delete_implrKr3r r"r*r*r+delete" s zSession.deletec Cs|jdkr&|r"tdt|ndS|||}||jkr@dS|j||r\||||rtt |j j d|}||j|<|r|D]\}}}} | ||dqdS)NInstance '%s' is not persistedriF)rrxryr_before_attachrrr` _after_attachrJrDrYrErg) rKr r+rf to_attachZcascade_statesrHrIrJrKr*r*r+rg5 s(       zSession._delete_implc Cs|j||tj||||dS)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. :return: The object instance, or ``None``. )populate_existingr5r.) _get_implrZload_on_pk_identity)rKr\identoptionsrnr5r.r*r*r+rZW s[z Session.getc  stdrt|} tt} | s6tjddtt| jkrht dd dd| jD| rzt fdd| j DWnLtk r} z.tjt d d d d| j D| d W5d} ~ XYnX|s0| js0|dkr0|j| |d } | dk r t| j| jsdS| S| tjkr0dStjj} |rJ| d |i7} t| t}|dk rrtj ||_!|r|j"|}|r|j#f|}|||| dS)N__composite_values__rG)defaultzmIncorrect number of values in identifier to formulate primary key for query.get(); primary key columns are %s,css|]}d|VqdSz'%s'Nr*)r}cr*r*r+rR sz$Session._get_impl..c3s|]}|jVqdSrGrr}propr/r*r+rR sztIncorrect names of values in identifier to formulate primary key for query.get(); primary key attribute names are %scss|]}d|jVqdSrurwrxr*r*r+rR srr-Z_populate_existing)rr)$hasattrrrrrlrSrZto_listlenZ primary_keyrxryr*rJZ_identity_key_propsKeyErrorrZalways_refreshr1 issubclass __class__r!rZPASSIVE_CLASS_MISMATCHrrzr{rr<Zset_label_stylerr r:r;Z_for_update_argrqrA)rKr\r/Z db_load_fnrqrnr5r.rArYZis_dictr"r3rrr?r*rzr+ro s             zSession._get_implcCsj|jr|di}i}|r$|t||j}z*d|_|jt|t||||dWS||_XdS)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_mapN) rr`r4rr_mergerr6 instance_dict)rKr3rrrrr*r*r+merge s$7  z Session.mergec Cst|}||kr||Sd}|j}|dkr||jkrFtdt||sTtd||}t j |dkot |d p|j ot |d } nd} ||jkrz|j|} Wqtk rd} YqXnd} | dkrR| r||kr||} nb|s2|jrtd|j} t | } || _|| d}n | rR|j|j|d|dd} | dkr|j} t | } t | } d}|| nt | } t | } | ||<| ||<|| k rj|jdk r*|j|||jt jd } |j| | |jt jd }| t jk r*|t jk r*| |kr*td | t| |f|j | _ |j!| _!| "||j#D]}|$|||| | |||qJ|s~| %| |j|r| j&j'(| d| S) 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.rTzmerge() with load=False option does not support objects marked as 'dirty'. flush() all changes on mapped instances before merging with load=False.rr-r0zVersion id '%s' on merged state %s does not match existing version '%s'. Leave the version attribute unset when merging to update the most recent version.))rrrrrrrxryrTrZ NEVER_SETr rUrVrWrr}rZ class_manager new_instancer6rrZr!rraZversion_id_colZ_get_state_attr_by_columnZPASSIVE_NO_INITIALIZEZPASSIVE_NO_RESULTrZStaleDataErrorZ load_pathrrZ_copy_callablesZiterate_propertiesr _commit_allrDrr)rKr Z state_dictrrrrYrrZkey_is_persistentmergedZ merged_stateZ merged_dictZexisting_versionZmerged_versionryr*r*r+rm s                       zSession._mergecCs"|j|stdt|dS)Nz3Instance '%s' is not persistent within this Session)rrNrxryrr?r*r*r+rB s  zSession._validate_persistentcCsd|jdk rtdt||}|||}||jkrP||j|<t|j|_|r`| ||dS)NzGObject '%s' already has an identity - it can't be registered as pending) rrxryrr+rkrr|Z insert_orderrl)rKr r+rmr*r*r+ _save_impl s     zSession._save_implcCs|jdkrtdt||jrH|r6|js0dS|`ntdt||}|dkr\dS|||}|j|d|r|j |n |j ||r| ||n|r|j ||dS)NrjzsInstance '%s' has been deleted. Use the make_transient() function to send this object back to the transient state.)rrxryrrZ _attachedr+rkrrrr`rlrZdeleted_to_persistent)rKr rr+rmr*r*r+r s4    zSession._update_implcCs$|jdkr||n ||dSrG)rrrr?r*r*r+rd> s  zSession._save_or_update_implc Csnzt|}Wn8tjk rF}ztjt||dW5d}~XYnX|||}d|_|rj| ||dS)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. rNT) rr6rr7rrr8rkZ _load_pendingrl)rKr+r r"rmr*r*r+enable_relationship_loadingD s7 z#Session.enable_relationship_loadingcCsV||j|jkrdS|jrD|jtkrDtdt||j|jf|j||dS)NFz>Object '%s' is already attached to session '%s' (this is '%s')T) rrMrrrxryrrZ before_attachrKr r+r*r*r+rk s zSession._before_attachcCsT|j|_|jr|jdkr||_|j|||jrB|j||n|j||dSrG) rrMrZ _strong_objrZ after_attachrZdetached_to_persistentZtransient_to_pendingrr*r*r+rl szSession._after_attachc CsRzt|}Wn8tjk rF}ztjt||dW5d}~XYnX||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)rr6rr7rrr8rerhr*r*r+ __contains__ szSession.__contains__cCs tt|jt|jS)zWIterate over all pending or persistent instances within this Session. )iterrJrrrrOr*r*r+__iter__ szSession.__iter__cCs||jkp|j|SrG)rrrNr?r*r*r+re szSession._contains_statecCs>|jrtd|rdSzd|_||W5d|_XdS)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 flushingNFT)rrxryr_flush)rKobjectsr*r*r+r s z Session.flushcCstd|dS)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)rKmethodr*r*r+r` s zSession._flush_warningcCs|j o|j o|j SrG)rZcheck_modifiedrrrOr*r*r+r s  zSession._is_cleanc Cs|j}|s&|js&|js&|jjdSt|}|jjrL|j||||j}t |j}t |j}t | |}|rt }|D]V}zt |}Wn8t jk r} ztjt || dW5d} ~ XYnX||q|nd}t } |r||| |} n|| |} | D]h}t||} | o,|j} | rP| sP|jrP||gn&|j|| d}|sltd| |q|r|| | } n | | } | D]"}|j|dd}|stdq|jsdS|jdd|_}zd|_z | W5d|_X|j!|||"|s`|jjr`t#|jj}t$j%j&dd|jjD|jd t'd ||j(|||)Wn,t*|j+dd W5QRXYnXdS) Nr)Zisdeletez*Failed to add object to the flush context!Tr FcSsg|]}||jfqSr*rPrQr*r*r+rR sz"Session._flush..)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_statesrrrrrrrZ before_flushr_ differencerr6rr7rrr8r`rIrUrZ _is_orphanZ has_identityrXrZregister_objectrZhas_workrrrrUZ after_flushZfinalize_flush_changesr|rrrYrZafter_flush_postexecrrr)rKrdirtyZ flush_contextdeletednewZobjsetrHr r" processedprocZ is_orphanZis_persistent_orphanZ_regrZlen_r*r*r+r s         zSession._flushc CsZdd}dd|D}|s&t||d}t||D]"\\}}} ||| |d||dq2dS) 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` cSs|j|jdk fSrG)rYrr r*r*r+r sz&Session.bulk_save_objects..keycss|]}t|VqdSrG)rr6)r}r+r*r*r+rR sz,Session.bulk_save_objects..rwTFN)sorted itertoolsgroupby_bulk_save_mappings) rKrreturn_defaultsupdate_changed_onlyZpreserve_orderrZ obj_statesrYisupdaterOr*r*r+bulk_save_objectsp sW zSession.bulk_save_objectsc Cs|||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)rKrYmappingsr render_nullsr*r*r+bulk_insert_mappings s[zSession.bulk_insert_mappingsc Cs|||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)rKrYrr*r*r+bulk_update_mappings>s1zSession.bulk_update_mappingsc Cst|}d|_|jdd}zjz8|r6t|||||nt|||||||Wn,t|j ddW5QRXYnXW5d|_XdS)NTrFr) r rrrZ _bulk_updateZ _bulk_insertrrrr) rKrYrrZisstatesrrrrr*r*r+rss2     zSession._bulk_save_mappingsc Cspt|}|jsdS|j}|jjD]J}|s4t|jds t|jdsBq |jj||tjd\}}}|sd|r dSq dS)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. FZget_collection get_historyrTN) rrrSrDrr{implrZ NO_CHANGE) rKr3Zinclude_collectionsr Zdict_attraddedZ unchangedrr*r*r+ is_modifieds(3    zSession.is_modifiedcCs.|jr|jdk o|jjS|jdkp(|jjSdS)a4True 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)rrrrOr*r*r+rszSession.is_activecCs |jS)zThe set of all persistent states considered dirty. This method returns all states that were modified including those that were possibly deleted. )rrrOr*r*r+rszSession._dirty_statescstfddjDS)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. csg|]}|jkr|qSr*)rr+rQrOr*r+r9s z!Session.dirty..)r IdentitySetrrOr*rOr+r s  z Session.dirtycCstt|jS)zDThe set of all instances marked as 'deleted' within this ``Session``)rrrJrrrOr*r*r+r@szSession.deletedcCstt|jS)zAThe set of all instances marked as 'new' within this ``Session``.)rrrJrrrOr*r*r+rFsz Session.new) NTFTFFNTNN)FFF)NFN)N)NNNNF)NN)N)N)F)T)NFNN)NFNNN)T)TNN)F)N)N)FTT)FF)T)\r4r5r6r7rZdeprecated_paramsrNZ_trans_context_managerZconnection_callablerrcontextmanagerrrZ deprecated_20rrrrrrZmemoized_propertyrrrrrrrrr EMPTY_DICTrUrrrrrrr[r%rr rZ PASSIVE_OFFr1r2r4r>r@rAr9rFrLrr\rZr_r`rcrarirgrZrorrrBrrrdrrkrlrrrerr`rrrrrrrrrrrrrr*r*r*r+r s.  A         G$ N  '  $ L  6  ]# .  R   & j b S  &D   & ~ j e5( J "   c@sFeZdZdZdeddddfddZddZd d Zd d Zd dZ dS)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`. NTFcKsL||d<||d<||d<||d<|dk r0||d<||_t|j|fi|_dS)aJConstruct 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. rrrrNr)rr r4r!)rKrr!rrrrrr*r*r+rNs&zsessionmaker.__init__cCs|}|S)amProduce a context manager that both provides a new :class:`_orm.Session` as well as a transaction that commits. e.g.:: Session = sessionmaker(some_engine) with Session.begin() as session: session.add(some_object) # commits transaction, closes session .. versionadded:: 1.4 )r)rKr)r*r*r+rszsessionmaker.begincKs\|jD]D\}}|dkrBd|krB|}||d||d<q |||q |jf|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__() r)rrcopyrTrr!)rKZlocal_kwkvrfr*r*r+__call__s  zsessionmaker.__call__cKs|j|dS)z(Re)configure the arguments for this sessionmaker. e.g.:: Session = sessionmaker() Session.configure(bind=create_engine('sqlite://')) N)rrT)rKZnew_kwr*r*r+ configures zsessionmaker.configurecCs,d|jj|jjddd|jDfS)Nz%s(class_=%r, %s)r(css|]\}}d||fVqdS)z%s=%rNr*)r}rrr*r*r+rRsz(sessionmaker.__repr__..)rr4r!r*rrrOr*r*r+__repr__s zsessionmaker.__repr__) r4r5r6r7r rNrrrrr*r*r*r+r"Ms` 1 cCstD] }|qdS)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)rrr)rr*r*r+r$s cCsNt|}t|}|r"||g|j|jr6|`|jr@|`|jrJ|`dS)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) rr6r,rZexpired_attributesrZ callablesrr)r3r rr*r*r+r%,s.   cCsXt|}|js|jr td|j||_|jr8|`| |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. .. seealso:: :func:`.make_transient` :meth:`.Session.enable_relationship_loading` zGiven object must be transientN) rr6rMrrxryrYrTrrrSrCZunloaded_expirable)r3r r*r*r+r&ls    c CsTzt|}Wn8tjk rF}ztjt||dW5d}~XYn Xt|SdS)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. rN)rr6rr7rrr8r,)r3r r"r*r*r+r's)?r7rrrr'rrrrrrr r rbaser r rrrrrZ unitofworkrrrxrrZ engine.utilrZ inspectionrrrrrZsql.baserZsql.selectabler__all__WeakValueDictionaryrr,objectr-symbolr:r;r<r=r>Z MemoizedSlotsr#r!r r"r$r%r&r'counterrr*r*r*r+s                             $     rS5N@'