U kf@sDUdZddlmZddlZddlmZddlZddlZddlZddlm Z ddlm Z ddlm Z ddlm Z dd lm Z dd lmZdd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$dd lm%Z&dd!l'm(Z(dd"l'm)Z)dd#l'm*Z*dd$l'm+Z+dd%l'm,Z,dd&l-m.Z.dd'l-m/Z/dd(l-m0Z0dd)l-m1Z1dd*l-m2Z2dd+l-m3Z3dd,l-m4Z4dd-l-m5Z5dd.l-m6Z6dd/lm7Z7dd0lm8Z8dd1l"m9Z9dd2l$m:Z:dd3l%m;Z;dd4lZ>dd6llHmIZId8d?lJmKZKd8d@lJmLZLd8dAlMmNZNd8dBlMmOZOd8dClDmPZPd8dDlDmQZQd8dElDmRZRd8dFlDmSZSd8dGlDmTZTd8dHlDmUZUd8dIlVmWZWd8dJlVmXZXd8dKlYmZZZd8dLl[m\Z\d8dMl[m]Z]d8dNlEm^Z^d8dOl_m`Z`d8dPl_maZaejrddQl'mbZbddRl'mcZcddSl'mdZdddTl'meZeddUlfmgZgddVlfmhZhddWlimjZjddXlkmlZlddYl$mmZmd8dZlBmnZnd8d[lBmoZod8d\lBmpZpd8d]lBmqZqd8d^lrmsZsd8d_lrmtZtd8d`lumvZvd8dalumwZwd8dblumxZxd8dclumyZyd8ddlzm{Z{d8delJm|Z|d8dfl}m~Z~d8dgl}mZd8dhl}mZd8dil}mZd8djl}mZd8dkl}mZd8dll}mZd8dml}mZd8dnl}mZd8dol}mZd8dpl}mZd8dqlVmZd8drlVmZd8dslmZd8dtlmZd8dulmZd8dvl[mZd8dwl[mZedxe dyZdzd{d|d}d~dddgZeZded<ee&_ee ee dffZe ee fZeee(dfZeee ddefZedZe`dZGdddeaZdddddZGdddZGddde>Zee\ZZZZZZGdd}d}eEjZGdddeZGdd{d{e=eIZGdddeZGddzdzeeLZeddzdyZGdd|d|ee eZdddd~ZdddddZdddddZdddddZeEZdS)z1Provides the Session class and related utilities.) annotationsN)Enum)Any)Callable)cast)Dict)Generic)Iterable)Iterator)List)NoReturn)Optional)overload)Sequence)Set)Tuple)Type) TYPE_CHECKING)TypeVar)Union) attributes)bulk_persistence)context)descriptor_props)exc)identity)loading)querystate)_O)insp_is_mapper)is_composite_class) is_orm_optionis_user_defined_option)_class_to_mapper) _none_set) _state_mapper) instance_str)LoaderCallableStatus) object_mapper) object_state) PassiveFlag) state_str) FromStatement)ORMCompileState) IdentityMap)Query) InstanceState) _StateChange)_StateChangeState)_StateChangeStates)UOWTransaction)engine)sql)util) Connection)Engine)TransactionalContext) dispatcher) EventTarget)inspect) Inspectable) coercions)dml)roles)Select) TableClause)visitors)_NoArg) CompileState)Table) ForUpdateArg)LABEL_STYLE_TABLENAME_PLUS_COL) IdentitySet)Literal)Protocol) _EntityType)_IdentityKeyType) _InstanceDict)OrmExecuteOptionsParameter) ORMOption)UserDefinedOption)Mapper) PathRegistry)RowReturningQuery) CursorResult)Result)Row) RowMapping) Transaction)TwoPhaseTransaction)_CoreAnyExecuteParams)_CoreSingleExecuteParams)_ExecuteOptions)CoreExecuteOptionsParameter) ScalarResult)_InstanceLevelDispatch)_ColumnsClauseArgument) _InfoType)_T0)_T1)_T2)_T3)_T4)_T5)_T6)_T7)_TypedColumnClauseArgument) Executable)ExecutableOption) UpdateBase) ClauseElement)TypedColumnsClauseRole)ForUpdateParameter)TypedReturnsRows_T)boundSessionSessionTransaction sessionmakerORMExecuteStateclose_all_sessionsmake_transientmake_transient_to_detachedobject_sessionz)weakref.WeakValueDictionary[int, Session] _sessions. Mapper[_O] Mapper[Any]rH)r>r=)conditional_savepoint rollback_only control_fullycreate_savepointc@s&eZdZdZd ddddddd ZdS) _ConnectionCallableProtoaa callable that returns a :class:`.Connection` given an instance. This callable, when present on a :class:`.Session`, is called only from the ORM's persistence mechanism (i.e. the unit of work flush process) to allow for connection-per-instance schemes (i.e. horizontal sharding) to be used as persistence time. This callable is not present on a plain :class:`.Session`, however is established when using the horizontal sharding extension. NOptional[Mapper[Any]]zOptional[object]rr=)mapperinstancekwreturncKsdSN)selfrrrrrF/opt/hc_python/lib64/python3.8/site-packages/sqlalchemy/orm/session.py__call__sz!_ConnectionCallableProto.__call__)NN)__name__ __module__ __qualname____doc__rrrrrrsrInstanceState[Any]Optional[Session]r rcCs|jS)z[Given an :class:`.InstanceState`, return the :class:`.Session` associated, if any. sessionrrrr_state_sessionsrc @steZdZdZeeddddddZeeddd d d d d d d dd ddddZ edddddZ 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`.NonercCs tdS)zClose *all* sessions in memory.N)r)clsrrr close_alls z_SessionClassMethods.close_allzsqlalchemy.orm.utilNrrowidentity_tokenzOptional[Type[Any]]Union[Any, Tuple[Any, ...]] Optional[Any]z%Optional[Union[Row[Any], RowMapping]]z_IdentityKeyType[Any])class_identrrrrcCstjjj|||||dS)zZReturn an identity key. This is an alias of :func:`.util.identity_key`. r)r<Z preloadedZorm_util identity_key)rrrrrrrrrrsz!_SessionClassMethods.identity_keyobjectrrrcCst|S)zxReturn the :class:`.Session` to which an object belongs. This is an alias of :func:`.object_session`. )r)rrrrrrsz#_SessionClassMethods.object_session)NN) rrrr classmethodr< deprecatedrZpreload_modulerrrrrrrs$ rc@s$eZdZdZdZdZdZdZdZdS)SessionTransactionStaterr9N) rrrACTIVEPREPARED COMMITTEDDEACTIVECLOSEDPROVISIONING_CONNECTIONrrrrrs rc@seZdZUdZdZded<ded<ded<d ed <d ed <d ed <ded<ded<ded<ded<dddd d dddddZddddZdZdddd d!d"d#d$Ze d%dd&d'Z e d(dd)d*Z e d+dd,d-Z e d+dd.d/Z e d+dd0d1Ze d+dd2d3Ze d+dd4d5Ze d+dd6d7Ze d+dd8d9Ze d+dd:d;Zdd?d@ZdAddBdCZe dDddEdFZe dGddHdIZe d+ddJdKZe d+ddLdMZe dNddOdPZe dQddRdSZe dTddUdVZe dWddXdYZdS)[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_argumentsr_compile_state_cls_starting_event_idx _events_todo_update_execution_optionsr{rrrrOptional[_CoreAnyExecuteParams]rrcrr_BindArgumentsrzOptional[Type[ORMCompileState]]rintrz List[Any]rOptional[_ExecuteOptions]rz%List[_InstanceLevelDispatch[Session]])rrrrrcompile_state_cls events_todocCs@||_||_||_||_|j||_||_||_t ||_ dS)zhConstruct a new :class:`_orm.ORMExecuteState`. this object is constructed internally. N) rrrr_execution_optionsunionrrrlistr)rrrrrrrrrrr__init__`szORMExecuteState.__init__rcCs|j|jddS)Nr)rrrrrr_remaining_eventszsz!ORMExecuteState._remaining_eventsNzOptional[Executable]z$Optional[OrmExecuteOptionsParameter]Optional[_BindArguments] Result[Any])rparamsrrrc Cs|dkr|j}t|j}|r&||d|d<|r|jrg}td|j}t|td|D]T\}} |dksr| dkrt dt |dt |dt|}|| | |qZqttd|j}|td|n|j}|j } |r| |} |jj||| ||d S) aExecute the statement represented by this :class:`.ORMExecuteState`, without re-invoking events that have already proceeded. This method essentially performs a re-entrant execution of the current statement for which the :meth:`.SessionEvents.do_orm_execute` event is being currently invoked. The use case for this is for event handlers that want to override how the ultimate :class:`_engine.Result` object is returned, such as for schemes that retrieve results from an offline cache or which concatenate results from multiple executions. When the :class:`_engine.Result` object is returned by the actual handler function within :meth:`_orm.SessionEvents.do_orm_execute` and is propagated to the calling :meth:`_orm.Session.execute` method, the remainder of the :meth:`_orm.Session.execute` method is preempted and the :class:`_engine.Result` object is returned to the caller of :meth:`_orm.Session.execute` immediately. :param statement: optional statement to be invoked, in place of the statement currently represented by :attr:`.ORMExecuteState.statement`. :param params: optional dictionary of parameters or list of parameters which will be merged into the existing :attr:`.ORMExecuteState.parameters` of this :class:`.ORMExecuteState`. .. versionchanged:: 2.0 a list of parameter dictionaries is accepted for executemany executions. :param execution_options: optional dictionary of execution options will be merged into the existing :attr:`.ORMExecuteState.execution_options` of this :class:`.ORMExecuteState`. :param bind_arguments: optional dictionary of bind_arguments which will be merged amongst the current :attr:`.ORMExecuteState.bind_arguments` of this :class:`.ORMExecuteState`. :return: a :class:`_engine.Result` object with ORM-level results. .. seealso:: :ref:`do_orm_execute_re_executing` - background and examples on the appropriate usage of :meth:`_orm.ORMExecuteState.invoke_statement`. NT_sa_skip_eventszList[Dict[str, Any]]zgCan't apply executemany parameters to statement; number of parameter sets passed to Session.execute() (zW) does not match number of parameter sets given to ORMExecuteState.invoke_statement() ()zDict[str, Any])rr_parent_execute_state)rdictrupdateis_executemanyrr itertools zip_longestsa_excInvalidRequestErrorlenappendrrr_execute_internal) rrrrrZ_bind_arguments_paramsZexec_many_parametersZ_existing_paramsZ _new_paramsrrrrinvoke_statement}sJ9     z ORMExecuteState.invoke_statementrcCs|jdd}|S)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` rN)rget)rmprrr bind_mapperszORMExecuteState.bind_mapperzSequence[Mapper[Any]]cCs|js gSt|jttfrzg}t}|jjD]H}|d}|r,t|dd}|r,|jr,|j|kr,| |j| |jq,|S|jj r|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 isinstancerrGr0setZcolumn_descriptionsrBraddris_dmlr)rresultseendZentinsprrr all_mapperss    zORMExecuteState.all_mappersboolcCs |jdk S)areturn True if the operation is an ORM statement. This indicates that the select(), insert(), update(), or delete() being invoked contains ORM entities as subjects. For a statement that does not have ORM entities and instead refers only to :class:`.Table` metadata, it is invoked as a Core SQL statement and no ORM-level automation takes place. N)rrrrrr)s z ORMExecuteState.is_orm_statementcCs t|jtS)zreturn True if the parameters are a multi-element list of dictionaries with more than one dictionary. .. versionadded:: 2.0 )rrrrrrrr6szORMExecuteState.is_executemanycCs|jjS)a8return True if this is a SELECT operation. .. versionchanged:: 2.0.30 - the attribute is also True for a :meth:`_sql.Select.from_statement` construct that is itself against a :class:`_sql.Select` construct, such as ``select(Entity).from_statement(select(..))`` )r is_selectrrrrr@s zORMExecuteState.is_selectcCs|jjS)areturn True if this operation is a :meth:`_sql.Select.from_statement` operation. This is independent from :attr:`_orm.ORMExecuteState.is_select`, as a ``select().from_statement()`` construct can be used with INSERT/UPDATE/DELETE RETURNING types of statements as well. :attr:`_orm.ORMExecuteState.is_select` will only be set if the :meth:`_sql.Select.from_statement` is itself against a :class:`_sql.Select` construct. .. versionadded:: 2.0.30 )ris_from_statementrrrrrLsz!ORMExecuteState.is_from_statementcCs|jjo|jjS)a9return True if this is an INSERT operation. .. versionchanged:: 2.0.30 - the attribute is also True for a :meth:`_sql.Select.from_statement` construct that is itself against a :class:`_sql.Insert` construct, such as ``select(Entity).from_statement(insert(..))`` )rr is_insertrrrrr]s zORMExecuteState.is_insertcCs|jjo|jjS)a9return True if this is an UPDATE operation. .. versionchanged:: 2.0.30 - the attribute is also True for a :meth:`_sql.Select.from_statement` construct that is itself against a :class:`_sql.Update` construct, such as ``select(Entity).from_statement(update(..))`` )rr is_updaterrrrris zORMExecuteState.is_updatecCs|jjo|jjS)a8return True if this is a DELETE operation. .. versionchanged:: 2.0.30 - the attribute is also True for a :meth:`_sql.Select.from_statement` construct that is itself against a :class:`_sql.Delete` construct, such as ``select(Entity).from_statement(delete(..))`` )rr is_deleterrrrrus zORMExecuteState.is_deletecCst|jtjtjfSr)rrrEZUpdateDeleterrrr_is_crudszORMExecuteState._is_crudrr)optsrcKs|j||_dS)z3Update the local execution options with new values.N)rrrrrrrupdate_execution_optionssz(ORMExecuteState.update_execution_optionszwOptional[Union[context.ORMCompileState.default_compile_options, Type[context.ORMCompileState.default_compile_options]]]cCsP|js dSz |jj}Wntk r,YdSX|dk rH|tjjrH|SdSdSr)rrZ_compile_optionsAttributeErrorrrr1Zdefault_compile_optionsrrrr_orm_compile_optionss  z$ORMExecuteState._orm_compile_optionsOptional[InstanceState[Any]]cCs|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_fromrrrrlazy_loaded_froms z ORMExecuteState.lazy_loaded_fromzOptional[PathRegistry]cCs|}|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)rZ _current_pathrrrrloader_strategy_pathsz$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)rZ_for_refresh_staterrrris_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)rris_root)rrpathrrris_relationship_loads z$ORMExecuteState.is_relationship_loadzaUnion[context.QueryContext.default_load_options, Type[context.QueryContext.default_load_options]]cCs&|jstd|jdtjj}|S)z=Return the load_options that will be used for this execution.zRThis ORM execution is not against a SELECT statement so there are no load options.Z_sa_orm_load_options)rrrrrr QueryContextdefault_load_options)rlorrrrs zORMExecuteState.load_optionszUnion[bulk_persistence.BulkUDCompileState.default_update_options, Type[bulk_persistence.BulkUDCompileState.default_update_options]]cCs&|jstd|jdtjj}|S)zNReturn the update_delete_options that will be used for this execution.z_This ORM execution is not against an UPDATE or DELETE statement so there are no update options.Z_sa_orm_update_options)rrrrrrZBulkUDCompileStateZdefault_update_options)rZuorrrupdate_delete_optionss z%ORMExecuteState.update_delete_optionszSequence[ORMOption]cCsdd|jjDS)NcSsg|]}t|r|js|qSr)r$Z_is_compile_state.0optrrr "sz.rZ _with_optionsrrrr_non_compile_orm_options sz(ORMExecuteState._non_compile_orm_optionszSequence[UserDefinedOption]cCsdd|jjDS)zzThe sequence of :class:`.UserDefinedOptions` that have been associated with the statement being invoked. cSsg|]}t|r|qSrr%r rrrr .sz8ORMExecuteState.user_defined_options..r rrrruser_defined_options(sz$ORMExecuteState.user_defined_options)NNNN)rrrr __slots____annotations__rrrpropertyrrrrrrrrrrrrrrrrrrrrrrrrr~ sr    j$       c@s eZdZdZdZdZdZdZdS)SessionTransactionOriginzindicates the origin of a :class:`.SessionTransaction`. This enumeration is present on the :attr:`.SessionTransaction.origin` attribute of any :class:`.SessionTransaction` object. .. versionadded:: 2.0 rrr9rN)rrrr AUTOBEGINBEGIN BEGIN_NESTEDSUBTRANSACTIONrrrrr5s  rc@s\eZdZUdZdZded<ded<ded<d ed <d ed <d ed<d ed<d ed<ded<ded<dZded<dXddd dddZdddddd Ze d d!d"d#Z e dd!d$d%Z e dd!d&d'Z e ejfejdYd(d)d*d+d,d-d.Ze ejfejdZddd/d0d1Zd[d d2d3d4d5Zd6d!d7d8Zd\dd6d9d:d;Zd6d!dd?d+d@dAdBZd6d!dCdDZe ejfejd6d!dEdFZe ejejfejd]dd6dGdHdIZe ejejejfejd^ddd6dJdKdLZ e ej!ejd_dd6dMdNdOZ"dd!dPdQZ#dd!dRdSZ$dd!dTdUZ%dd!dVdWZ&dS)`r|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` NzOptional[BaseException]_rollback_exceptionzKDict[Union[Engine, Connection], Tuple[Connection, Transaction, bool, bool]] _connectionsr{rOptional[SessionTransaction]_parentr_statez5weakref.WeakKeyDictionary[InstanceState[Any], object]_new_deleted_dirtyz>weakref.WeakKeyDictionary[InstanceState[Any], Tuple[Any, Any]] _key_switchesroriginFrnested)rr!parentcCst|||_i|_||_|tjk|_}||_|j t j krHt d|rd|sZt d|j|_n$|tjkr||dk stn |dksttj|_|||j_|jj|j|dS)Nz_This Session has been permanently closed and is unable to handle any more transaction requests.zOCan't start a SAVEPOINT transaction when no existing transaction is in progress)r?_trans_ctx_checkrrrrrr"r! _close_state_SessionCloseStaterrr_nested_transaction_previous_nested_transactionrAssertionErrorrrr_take_snapshot _transactiondispatchZafter_transaction_create)rrr!r#r"rrrrs.     zSessionTransaction.__init__strr6r )operation_namer rcCs|tjkr4|jr(tjd|jddq|tdnH|tjkrJtdn2|tjkrdtjdddntd|j d dS) NzThis Session's transaction has been rolled back due to a previous exception during flush. To begin a new transaction with this Session, first issue Session.rollback(). Original exception was: Z7s2a)codezThis session is in 'inactive' state, due to the SQL transaction being rolled back; no further SQL can be emitted within this transaction.zThis transaction is closedzVThis session is provisioning a new connection; concurrent operations are not permittedZiscezThis session is in 'z?' state; no further SQL can be emitted within this transaction.) rrrrZPendingRollbackErrorrrZResourceClosedErrorrnamelower)rr.r rrr_raise_for_prerequisite_states&      z0SessionTransaction._raise_for_prerequisite_statercCs|jS)aaThe parent :class:`.SessionTransaction` of this :class:`.SessionTransaction`. If this attribute is ``None``, indicates this :class:`.SessionTransaction` is at the top of the stack, and corresponds to a real "COMMIT"/"ROLLBACK" block. If non-``None``, then this is either a "subtransaction" (an internal marker object used by the flush process) or a "nested" / SAVEPOINT transaction. If the :attr:`.SessionTransaction.nested` attribute is ``True``, then this is a SAVEPOINT, and if ``False``, indicates this a subtransaction. )rrrrrr#szSessionTransaction.parentcCs|jdk o|jtjkSr)rrrrrrrr is_actives  zSessionTransaction.is_activecCs|jp |j Sr)r"rrrrr_is_transaction_boundarysz+SessionTransaction._is_transaction_boundaryrrrr=)bindkeyrkwargsrcKs|jj|f|}|||Sr)rget_bind_connection_for_bind)rr5rr6bindrrr connections zSessionTransaction.connectionr"rcCst|j|rtjntj|Sr)r|rrrr)rr"rrr_beginszSessionTransaction._beginzIterable[SessionTransaction])uptorcCsJ|}d}|rF||f7}|j|kr$qFq|jdkr>td|q|j}q|S)Nrz4Transaction %s is not on the active transaction list)rrr)rr=currentrrrr_iterate_self_and_parentss   z,SessionTransaction._iterate_self_and_parentsrcCs|js<|j}|dk st|j|_|j|_|j|_|j|_dS|jtj tj fk}|sd|j j sd|j t|_t|_t|_t|_dSr)r4rr)rrrr r!rrrr _flushingflushweakrefWeakKeyDictionary)rr#Zis_beginrrrr*2s$      z!SessionTransaction._take_snapshot) dirty_onlyrcCs|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)r4r)rrrr_expunge_statesr items identity_map safe_discardkeyreplacer _update_impl all_statesmodifiedr_expirer _modified)rrDZ to_expungesZoldkeyZnewkeyrrr_restore_snapshotHs  z$SessionTransaction._restore_snapshotcCs|js t|js`|jjr`|jjD]}||j|jjj q$t j t |j|j|jnP|jr|j}|dk sxt|j|j|j|j|j|j|j|jdS)zjRemove the restoration state taken before a transaction began. Corresponds to a commit. N)r4r)r"rexpire_on_commitrJrOrQrrRstatelibr4_detach_statesrrclearrrrrr )rrSr#rrr_remove_snapshoths    z#SessionTransaction._remove_snapshot _SessionBind%Optional[CoreExecuteOptionsParameter])r9rrc Cs||jkr&|rtd|j|dStj|_d}d}z|jr`|j||}|j s|WSn4t |t j r|}|j |jkrt dn |}d}z|r|jf|}|jjr|jdkr|}n|j r|}n|rr|jj}|dkr|rd}nd}|rtd |d |d krN|r6|}n|}|dkrpd}n"|dkrb|}ndszt|n|}Wn|r|YnJXt |t j }|||| f|j|<|j|j <|jj|j|||WSW5tj|_XdS) NzOConnection is already established for the given bind; execution_options ignoredrFTzMSession already has a Connection associated for the given Connection's EnginerrrzThe engine provided as bind produced a connection that is already in a transaction. This is usually caused by a core event, such as 'engine_connect', that has left a transaction open. The effective join transaction mode used by this session is z9. To silence this warning, do not leave transactions open)rr)rr<warnrrrrrr8r"rr:r=rrconnectrrtwophaseZbegin_twophase begin_nestedin_transactionjoin_transaction_modein_nested_transactionZ _get_required_nested_transactionZ_get_required_transactionr)begincloser,Z after_begin) rr9rZ local_connect should_commitconn transactionraZbind_is_connectionrrrr8s                  z'SessionTransaction._connection_for_bindcCs(|jdk s|jjstd|dS)NzD'twophase' mode not enabled, or not root transaction; can't prepare.)rrr^rr _prepare_implrrrrprepares zSessionTransaction.preparec Cs|jdks|jr |jj|j|jj}|dk s4t||k rV|j|dD] }|qH|jj st dD]}|j rxq|j qft d|jdkr|jjrz*t|jD]}td|dqWn(t|W5QRXYnXtj|_dS)Nr=dzrOver 100 subsequent flushes have occurred within session.commit() - is an after_flush() hook creating new objects?r`r)rr"rr,Z before_commitr+r)r?commitr@range _is_cleanrAr FlushErrorr^rrvaluesrrir< safe_reraiserollbackrrr)rstxsubtransactionZ _flush_guardtrrrrhs.      z SessionTransaction._prepare_impl)_to_rootrc Cs|jtjk r,|tj|W5QRX|jdks<|jrt|j D]\}}}}|rJ| qJtj |_|j j |j ||tj|W5QRX|r|jr|jj dddS)NTrv)rrr _expect_staterhrr"rrrprlrrr,Z after_commitrYrrd)rrvrftransre autocloserrrrls    zSessionTransaction.commit)_capture_exceptionrvrc Cs|jj}|dk st||k r6|j|dD] }|q(|}d}|jtjtjfkr|D]}|j dksl|j rzVzd?d@Zdd>dAdBZdd>dCdDZdd>dEdFZejdGd>dHdIZdnddJdKdLdMZdoddJdNdOdPZdJd>dQdRZd7d>dSdTZd7d>dUdVZd7d>dWdXZdpdYdZd[d\d]d^Zdqd_dZd6d[d`dadbZedrej d d d dcdddedfdgdYdhdhd%d6didjdkZ!edsej d d d dcdddedldgdYdhdhddmdidndkZ!dtej d d d ddddedldgdYdhdhdd6didodkZ!eduej d d d dpdqdldgdYdhdhdrdsdtduZ"edvej d d d dpdvdldgdYdhdhdwdsdxduZ"edwej d d d dpdedldgdYdhdhdmdsdyduZ"dxej d d d dpdedldgdYdhdhdmdsdzduZ"edyej d d{d|dfdgdYd6d}d~ddZ#edzej d d{dedfdgdYd6d6d~ddZ#d{ej d d{dedfdgdYd6d6d~ddZ#ed|ej d d{d|dldgdYd6dd~ddZ$ed}ej d d{dedldgdYd6dd~ddZ$d~ej d d{dedldgdYd6dd~ddZ$d7d>ddZ%d7d>ddZ&d7d>ddZ'dddd7dddZ(d7d>ddZ)dd_d7dddZ*dd_d7dddZ+dd_d7dddZ,dd d d ddddd$ddd6ddddZ-edddddZ.edddddZ.eddddddZ.edddddddZ.eddddddddZ.edddddddddZ.eddddddddĜddZ.edddddddddȜddZ.edddddddddd̜ ddZ.edd6ddМddZ.dd6ddМddZ.d e/j0d ej d fddd6dddgdYdd؜ddڄZ1ej2e jdd>dd݄Z3ej45de6j7d7d>ddZ8ddddd7dddZ9d7d>ddZ:dddd7dddZ;ddd7dddZ<dddd7dddZ=dd7dddZ>dddd7dddZ?dd7dddZ@dd7dddZAdd7dddZBdddd7dddZCdd7dddZDdd7d d d ZEdd7dd d ZFdddd7dddZGd dd d ej d dddddddhdgdYdd ddZHd dd d ej d dddddddhdgdYdd ddZId dd d ej d ddddddddhdgdYdd ddZJd!d d ddddd!d"d#ZKd d$d%d&ddd'd(dd)d*d+ZLdd7d d,d-ZMdd7d d.d/ZNdddd7d0d1d2ZOdd7d d3d4ZPdd7d5d6d7ZQdddd8d9d:ZRddd7d8d;d<ZSdddd=d>ZTd?d>d@dAZUddd dBdCZVddDd7dEdFdGZWd6d7dHdIdJZXdd>dKdLZYddMd7dEdNdOZZdddddd7dPdQdRZ[ddSdTddd7dUdVdWZ\dSdTd7dXdYdZZ]dӐd[dddddd7d\d]d^Z^ddddd_d`daZ_e`dd>dbdcZae`dd>dddeZbe`dfd>dgdhZce`dfd>didjZde`dfd>dkdlZed S(r{a Manages persistence operations for ORM-mapped objects. The :class:`_orm.Session` is **not safe for use in concurrent threads.**. See :ref:`session_faq_threadsafe` for background. The Session's usage paradigm is described at :doc:`/orm/session`. Fzdispatcher[Session]r,r2rJzDict[InstanceState[Any], Any]rrz#Optional[Union[Engine, Connection]]r9z#Dict[_SessionBindKey, _SessionBind]_Session__bindsrr@_warn_on_eventsrr+r'rhash_key autoflushrUenable_baked_queriesr^JoinTransactionModerazType[Query[Any]] _query_clsr&r%NTr) rfuturerU autobeginr^bindsrinfo query_cls autocommitraclose_resets_onlyOptional[_SessionBind]z Literal[True]z-Optional[Dict[_SessionBindKey, _SessionBind]]Optional[_InfoType]zOptional[Type[Query[Any]]]zLiteral[False]zUnion[bool, _NoArg]) r9rrrUrr^rrrrrrarc Cs| rtdt|_|s&tdi|_i|_||_i|_d|_ d|_ d|_ d|_ t |_||_||_||_||_| s| tjkrtj|_ntj|_| r| tjkrtd| d| |_||_| r| ntj|_| r|j !| |dk r |"D]\}}|#||q|t$|j<dS)a'+Construct a new :class:`_orm.Session`. See also the :class:`.sessionmaker` function which is used to generate a :class:`.Session`-producing callable with a given set of arguments. :param autoflush: When ``True``, all query operations will issue a :meth:`~.Session.flush` call to this ``Session`` before proceeding. This is a convenience feature so that :meth:`~.Session.flush` need not be called repeatedly in order for database queries to retrieve results. .. seealso:: :ref:`session_flushing` - additional background on autoflush :param autobegin: Automatically start transactions (i.e. equivalent to invoking :meth:`_orm.Session.begin`) when database access is requested by an operation. Defaults to ``True``. Set to ``False`` to prevent a :class:`_orm.Session` from implicitly beginning transactions after construction, as well as after any of the :meth:`_orm.Session.rollback`, :meth:`_orm.Session.commit`, or :meth:`_orm.Session.close` methods are called. .. versionadded:: 2.0 .. seealso:: :ref:`session_autobegin_disable` :param bind: An optional :class:`_engine.Engine` or :class:`_engine.Connection` to which this ``Session`` should be bound. When specified, all SQL operations performed by this session will execute via this connectable. :param binds: A dictionary which may specify any number of :class:`_engine.Engine` or :class:`_engine.Connection` objects as the source of connectivity for SQL operations on a per-entity basis. The keys of the dictionary consist of any series of mapped classes, arbitrary Python classes that are bases for mapped classes, :class:`_schema.Table` objects and :class:`_orm.Mapper` objects. The values of the dictionary are then instances of :class:`_engine.Engine` or less commonly :class:`_engine.Connection` objects. Operations which proceed relative to a particular mapped class will consult this dictionary for the closest matching entity in order to determine which :class:`_engine.Engine` should be used for a particular SQL operation. The complete heuristics for resolution are described at :meth:`.Session.get_bind`. Usage looks like:: Session = sessionmaker(binds={ SomeMappedClass: create_engine('postgresql+psycopg2://engine1'), SomeDeclarativeBase: create_engine('postgresql+psycopg2://engine2'), some_mapper: create_engine('postgresql+psycopg2://engine3'), some_table: create_engine('postgresql+psycopg2://engine4'), }) .. seealso:: :ref:`session_partitioning` :meth:`.Session.bind_mapper` :meth:`.Session.bind_table` :meth:`.Session.get_bind` :param \class_: Specify an alternate class other than ``sqlalchemy.orm.session.Session`` which should be used by the returned class. This is the only argument that is local to the :class:`.sessionmaker` function, and is not sent directly to the constructor for ``Session``. :param enable_baked_queries: legacy; defaults to ``True``. A parameter consumed by the :mod:`sqlalchemy.ext.baked` extension to determine if "baked queries" should be cached, as is the normal operation of this extension. When set to ``False``, caching as used by this particular extension is disabled. .. versionchanged:: 1.4 The ``sqlalchemy.ext.baked`` extension is legacy and is not used by any of SQLAlchemy's internals. This flag therefore only affects applications that are making explicit use of this extension within their own code. :param expire_on_commit: Defaults to ``True``. When ``True``, all instances will be fully expired after each :meth:`~.commit`, so that all attribute/object access subsequent to a completed transaction will load from the most recent database state. .. seealso:: :ref:`session_committing` :param future: Deprecated; this flag is always True. .. seealso:: :ref:`migration_20_toplevel` :param info: optional dictionary of arbitrary data to be associated with this :class:`.Session`. Is available via the :attr:`.Session.info` attribute. Note the dictionary is copied at construction time so that modifications to the per- :class:`.Session` dictionary will be local to that :class:`.Session`. :param query_cls: Class which should be used to create new Query objects, as returned by the :meth:`~.Session.query` method. Defaults to :class:`_query.Query`. :param twophase: When ``True``, all transactions will be started as a "two phase" transaction, i.e. using the "two phase" semantics of the database in use along with an XID. During a :meth:`~.commit`, after :meth:`~.flush` has been issued for all attached databases, the :meth:`~.TwoPhaseTransaction.prepare` method on each database's :class:`.TwoPhaseTransaction` will be called. This allows each database to roll back the entire transaction, before each transaction is committed. :param autocommit: the "autocommit" keyword is present for backwards compatibility but must remain at its default value of ``False``. :param join_transaction_mode: Describes the transactional behavior to take when a given bind is a :class:`_engine.Connection` that has already begun a transaction outside the scope of this :class:`_orm.Session`; in other words the :meth:`_engine.Connection.in_transaction()` method returns True. The following behaviors only take effect when the :class:`_orm.Session` **actually makes use of the connection given**; that is, a method such as :meth:`_orm.Session.execute`, :meth:`_orm.Session.connection`, etc. are actually invoked: * ``"conditional_savepoint"`` - this is the default. if the given :class:`_engine.Connection` is begun within a transaction but does not have a SAVEPOINT, then ``"rollback_only"`` is used. If the :class:`_engine.Connection` is additionally within a SAVEPOINT, in other words :meth:`_engine.Connection.in_nested_transaction()` method returns True, then ``"create_savepoint"`` is used. ``"conditional_savepoint"`` behavior attempts to make use of savepoints in order to keep the state of the existing transaction unchanged, but only if there is already a savepoint in progress; otherwise, it is not assumed that the backend in use has adequate support for SAVEPOINT, as availability of this feature varies. ``"conditional_savepoint"`` also seeks to establish approximate backwards compatibility with previous :class:`_orm.Session` behavior, for applications that are not setting a specific mode. It is recommended that one of the explicit settings be used. * ``"create_savepoint"`` - the :class:`_orm.Session` will use :meth:`_engine.Connection.begin_nested()` in all cases to create its own transaction. This transaction by its nature rides "on top" of any existing transaction that's opened on the given :class:`_engine.Connection`; if the underlying database and the driver in use has full, non-broken support for SAVEPOINT, the external transaction will remain unaffected throughout the lifespan of the :class:`_orm.Session`. The ``"create_savepoint"`` mode is the most useful for integrating a :class:`_orm.Session` into a test suite where an externally initiated transaction should remain unaffected; however, it relies on proper SAVEPOINT support from the underlying driver and database. .. tip:: When using SQLite, the SQLite driver included through Python 3.11 does not handle SAVEPOINTs correctly in all cases without workarounds. See the sections :ref:`pysqlite_serializable` and :ref:`aiosqlite_serializable` for details on current workarounds. * ``"control_fully"`` - the :class:`_orm.Session` will take control of the given transaction as its own; :meth:`_orm.Session.commit` will call ``.commit()`` on the transaction, :meth:`_orm.Session.rollback` will call ``.rollback()`` on the transaction, :meth:`_orm.Session.close` will call ``.rollback`` on the transaction. .. tip:: This mode of use is equivalent to how SQLAlchemy 1.4 would handle a :class:`_engine.Connection` given with an existing SAVEPOINT (i.e. :meth:`_engine.Connection.begin_nested`); the :class:`_orm.Session` would take full control of the existing SAVEPOINT. * ``"rollback_only"`` - the :class:`_orm.Session` will take control of the given transaction for ``.rollback()`` calls only; ``.commit()`` calls will not be propagated to the given transaction. ``.close()`` calls will have no effect on the given transaction. .. tip:: This mode of use is equivalent to how SQLAlchemy 1.4 would handle a :class:`_engine.Connection` given with an existing regular database transaction (i.e. :meth:`_engine.Connection.begin`); the :class:`_orm.Session` would propagate :meth:`_orm.Session.rollback` calls to the underlying transaction, but not :meth:`_orm.Session.commit` or :meth:`_orm.Session.close` calls. .. versionadded:: 2.0.0rc1 :param close_resets_only: Defaults to ``True``. Determines if the session should reset itself after calling ``.close()`` or should pass in a no longer usable state, disabling re-use. .. versionadded:: 2.0.22 added flag ``close_resets_only``. A future SQLAlchemy version may change the default value of this flag to ``False``. .. seealso:: :ref:`session_closing` - Detail on the semantics of :meth:`_orm.Session.close` and :meth:`_orm.Session.reset`. z&autocommit=True is no longer supportedzCThe 'future' parameter passed to Session() may only be set to True.FNz.invalid selection for join_transaction_mode: "")%r ArgumentErrorrWeakInstanceDictrJrrr9rr@rr+r'_new_sessionidrrrrUrrJNO_ARGr&rr%rr__args__rar^rr3rrrrI _add_bindr)rr9rrrUrr^rrrrrrarrLrrrrsXt     zSession.__init__zOptional[TransactionalContext]_trans_context_managerz"Optional[_ConnectionCallableProto]connection_callable_S)rrcCs|Srrrrrr __enter__ szSession.__enter__rr)type_value tracebackrcCs |dSr)rd)rrrrrrr__exit__szSession.__exit__z Iterator[_S]c cs.| | |VW5QRXW5QRXdSrrcrrrr_maker_context_managers zSession._maker_context_managerrcCs |jdk S)zReturn True if this :class:`_orm.Session` has begun a transaction. .. versionadded:: 1.4 .. seealso:: :attr:`_orm.Session.is_active` N)r+rrrrr`s zSession.in_transactioncCs |jdk S)zReturn True if this :class:`_orm.Session` has begun a nested transaction, e.g. SAVEPOINT. .. versionadded:: 1.4 Nr'rrrrrb$szSession.in_nested_transactioncCs$|j}|dk r |jdk r |j}q|S)zaReturn the current root transaction in progress, if any. .. versionadded:: 1.4 N)r+rrryrrrget_transaction-szSession.get_transactioncCs|jS)zcReturn the current nested transaction in progress, if any. .. versionadded:: 1.4 rrrrrget_nested_transaction8szSession.get_nested_transactionrhcCsiS)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. rrrrrrAs z Session.infor|)rcrcCsL|jdkrF|s|jstdt||r,tjntj}|j|ksBt|S|jS)Nz]Autobegin is disabled on this Session; please call session.begin() to start a new transaction) r+rrrr|rrrr))rrcryrrr _autobegin_tNs  zSession._autobegin_tr;cCsb|j}|dkr"|jdd}|s"|S|dk s.t|rT|j|d}|j|ksLt||_n td|S)aBegin a transaction, or nested transaction, on this :class:`.Session`, if one is not already begun. The :class:`_orm.Session` object features **autobegin** behavior, so that normally it is not necessary to call the :meth:`_orm.Session.begin` method explicitly. However, it may be used in order to control the scope of when the transactional state is begun. When used to begin the outermost transaction, an error is raised if this :class:`.Session` is already inside of a transaction. :param nested: if True, begins a SAVEPOINT transaction and is equivalent to calling :meth:`~.Session.begin_nested`. For documentation on SAVEPOINT transactions, please see :ref:`session_begin_nested`. :return: the :class:`.SessionTransaction` object. Note that :class:`.SessionTransaction` acts as a Python context manager, allowing :meth:`.Session.begin` to be used in a "with" block. See :ref:`session_explicit_begin` for an example. .. seealso:: :ref:`session_autobegin` :ref:`unitofwork_transaction` :meth:`.Session.begin_nested` NTrr"z/A transaction is already begun on this Session.)r+rr)r<r'rr)rr"ryrrrrcbs#   z Session.begincCs |jddS)atBegin a "nested" transaction on this Session, e.g. SAVEPOINT. The target database(s) and associated drivers must support SQL SAVEPOINT for this method to function correctly. For documentation on SAVEPOINT transactions, please see :ref:`session_begin_nested`. :return: the :class:`.SessionTransaction` object. Note that :class:`.SessionTransaction` acts as a context manager, allowing :meth:`.Session.begin_nested` to be used in a "with" block. See :ref:`session_begin_nested` for a usage example. .. seealso:: :ref:`session_begin_nested` :ref:`pysqlite_serializable` - special workarounds required with the SQLite driver in order for SAVEPOINT to work correctly. For asyncio use cases, see the section :ref:`aiosqlite_serializable`. Trrrrrrr_szSession.begin_nestedcCs|jdkr n|jjdddS)a{Rollback the current transaction in progress. If no transaction is in progress, this method is a pass-through. The method always rolls back the topmost database transaction, discarding any nested transactions that may be in progress. .. seealso:: :ref:`session_rollback` :ref:`unitofwork_transaction` NTrw)r+rrrrrrrrs zSession.rollbackcCs&|j}|dkr|}|jdddS)aeFlush pending changes and commit the current transaction. When the COMMIT operation is complete, all objects are fully :term:`expired`, erasing their internal contents, which will be automatically re-loaded when the objects are next accessed. In the interim, these objects are in an expired state and will not function if they are :term:`detached` from the :class:`.Session`. Additionally, this re-load operation is not supported when using asyncio-oriented APIs. The :paramref:`.Session.expire_on_commit` parameter may be used to disable this behavior. When there is no transaction in place for the :class:`.Session`, indicating that no operations were invoked on this :class:`.Session` since the previous call to :meth:`.Session.commit`, the method will begin and commit an internal-only "logical" transaction, that does not normally affect the database unless pending flush changes were detected, but will still invoke event handlers and object expiration rules. The outermost database transaction is committed unconditionally, automatically releasing any SAVEPOINTs in effect. .. seealso:: :ref:`session_committing` :ref:`unitofwork_transaction` :ref:`asyncio_orm_avoid_lazyloads` NTrw)r+rrlrrrrrls zSession.commitcCs"|j}|dkr|}|dS)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. N)r+rrirrrrris zSession.preparerr[r=)rrrcCs<|r&|dd}|dkr.|jf|}n|}|j||dS)a"Return a :class:`_engine.Connection` object corresponding to this :class:`.Session` object's transactional state. Either the :class:`_engine.Connection` corresponding to the current transaction is returned, or if no transaction is in progress, a new one is begun and the :class:`_engine.Connection` returned (note that no transactional state is established with the DBAPI until the first SQL statement is emitted). Ambiguity in multi-bind or unbound :class:`.Session` objects can be resolved through any of the optional keyword arguments. This ultimately makes usage of the :meth:`.get_bind` method for resolution. :param bind_arguments: dictionary of bind arguments. May include "mapper", "bind", "clause", other custom arguments that are passed to :meth:`.Session.get_bind`. :param execution_options: a dictionary of execution options that will be passed to :meth:`_engine.Connection.execution_options`, **when the connection is first procured only**. If the connection is already present within the :class:`.Session`, a warning is emitted and the arguments are ignored. .. seealso:: :ref:`session_transaction_isolation` r9Nr)popr7r8)rrrr9rrrr:s# zSession.connectionrZ)r:rrrcKs,t||j}|dkr |}|||Sr)r?r$r+rr8)rr:rrryrrrr8/s  zSession._connection_for_bind.)rrr _add_event_scalar_resultrrz"Optional[_CoreSingleExecuteParams]rUr)rrrrrrrrcCsdSrrrrrrrrrrrrrr<s zSession._execute_internalrrcCsdSrrrrrrrIs cCsttj|}|si}nt|}|jdddkrTt|d}t rdt |t j sdt nd}|d|t|}|r||} n|jj} |rt| |g} | r|dk r||||||d\}}t||||||| } t| D]4\} } | | _| | } | r|r| S| Sq| j}| j}|dk r<||||||d\}}|jf|}||}|r|st rntt|}|j||p|i|dS|r| |||pi|||}n|j!||pi|d}|r|S|SdS)NZcompile_state_pluginZormclauseTFr)"rDexpectrFZ StatementRoler_propagate_attrsrrKZ_get_plugin_class_for_pluginrrrZAbstractORMCompileStater) setdefaultr<Zcoerce_to_immutabledictrr,Zdo_orm_executerZorm_pre_session_execr~ enumeraterscalarrrr7r8rrbZorm_execute_statementexecute)rrrrrrrrrrZorm_exec_stateidxfnZ fn_resultr9rfrrrrrVs                 rrrrzTypedReturnsRows[_T]z Result[_T])rrrrrrrcCsdSrrrrrrrrrrrrrs zSession.executertzCursorResult[Any]cCsdSrrrrrrrs cCsdSrrrrrrrs cCs|j||||||dS)aExecute a SQL expression construct. Returns a :class:`_engine.Result` object representing results of the statement execution. E.g.:: from sqlalchemy import select result = session.execute( select(User).where(User.id == 5) ) The API contract of :meth:`_orm.Session.execute` is similar to that of :meth:`_engine.Connection.execute`, the :term:`2.0 style` version of :class:`_engine.Connection`. .. versionchanged:: 1.4 the :meth:`_orm.Session.execute` method is now the primary point of ORM statement execution when using :term:`2.0 style` ORM usage. :param statement: An executable statement (i.e. an :class:`.Executable` expression such as :func:`_expression.select`). :param params: Optional dictionary, or list of dictionaries, containing bound parameter values. If a single dictionary, single-row execution occurs; if a list of dictionaries, an "executemany" will be invoked. The keys in each dictionary must correspond to parameter names present in the statement. :param execution_options: optional dictionary of execution options, which will be associated with the statement execution. This dictionary can provide a subset of the options that are accepted by :meth:`_engine.Connection.execution_options`, and may also provide additional options understood only in an ORM context. .. seealso:: :ref:`orm_queryguide_execution_options` - ORM-specific execution options :param bind_arguments: dictionary of additional arguments to determine the bind. May include "mapper", "bind", or other custom arguments. Contents of this dictionary are passed to the :meth:`.Session.get_bind` method. :return: a :class:`_engine.Result` object. rrrrrrrs=)rrzTypedReturnsRows[Tuple[_T]]z Optional[_T])rrrrrrcKsdSrrrrrrrrrrrrC s zSession.scalarcKsdSrrrrrrrN s cKs|j||f||dd|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. T)rrrrrrrrrY szScalarResult[_T]cKsdSrrrrrrscalarss s zSession.scalarszScalarResult[Any]cKsdSrrrrrrr~ s cKs |j|f|||dd|S)aExecute a statement and return the results as scalars. Usage and parameters are the same as that of :meth:`_orm.Session.execute`; the return result is a :class:`_result.ScalarResult` filtering object which will return single elements rather than :class:`_row.Row` objects. :return: a :class:`_result.ScalarResult` object .. versionadded:: 1.4.24 Added :meth:`_orm.Session.scalars` .. versionadded:: 1.4.26 Added :meth:`_orm.scoped_session.scalars` .. seealso:: :ref:`orm_queryguide_select_orm_entities` - contrasts the behavior of :meth:`_orm.Session.execute` to :meth:`_orm.Session.scalars` F)rrrr)rrrrrrr scCs|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:: In the default running mode the :meth:`_orm.Session.close` method **does not prevent the Session from being used again**. The :class:`_orm.Session` itself does not actually have a distinct "closed" state; it merely means the :class:`_orm.Session` will release all database connections and ORM objects. Setting the parameter :paramref:`_orm.Session.close_resets_only` to ``False`` will instead make the ``close`` final, meaning that any further action on the session will be forbidden. .. versionchanged:: 1.4 The :meth:`.Session.close` method does not immediately create a new :class:`.SessionTransaction` object; instead, the new :class:`.SessionTransaction` is created only if the :class:`.Session` is used again for a database operation. .. seealso:: :ref:`session_closing` - detail on the semantics of :meth:`_orm.Session.close` and :meth:`_orm.Session.reset`. :meth:`_orm.Session.reset` - a similar method that behaves like ``close()`` with the parameter :paramref:`_orm.Session.close_resets_only` set to ``True``. FrN _close_implrrrrrd s'z Session.closecCs|jddddS)a Close out the transactional resources and ORM objects used by this :class:`_orm.Session`, resetting the session to its initial state. This method provides for same "reset-only" behavior that the :meth:`_orm.Session.close` method has provided historically, where the state of the :class:`_orm.Session` is reset as though the object were brand new, and ready to be used again. This method may then be useful for :class:`_orm.Session` objects which set :paramref:`_orm.Session.close_resets_only` to ``False``, so that "reset only" behavior is still available. .. versionadded:: 2.0.22 .. seealso:: :ref:`session_closing` - detail on the semantics of :meth:`_orm.Session.close` and :meth:`_orm.Session.reset`. :meth:`_orm.Session.close` - a similar method will additionally prevent re-use of the Session when the parameter :paramref:`_orm.Session.close_resets_only` is set to ``False``. FT)ris_resetNrrrrrreset sz Session.resetcCs|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. TrNrrrrrr s"zSession.invalidate)rrrcCsH|s|jtjkrtj|_||jdk rD|jD]}||q4dSr)r%r&rr expunge_allr+r?rd)rrrrgrrrr s  zSession._close_implcCsF|jt|j}|jt|_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) rJrOrrZ_killrrrrVr4rW)rrOrrrr s   zSession.expunge_all_SessionBindKey)rLr9rc Csz t|}WnJtjk rV}z*t|ts}zt||W5d}~XYnX|||||ikrftdt |}t t |}tj|||j|||dddd dkrtdt|dS)a Expire and refresh attributes on the given instance. The selected attributes will first be expired as they would when using :meth:`_orm.Session.expire`; then a SELECT statement will be issued to the database to refresh column-oriented attributes with the current value available in the current transaction. :func:`_orm.relationship` oriented attributes will also be immediately loaded if they were already eagerly loaded on the object, using the same eager loading strategy that they were loaded with originally. .. versionadded:: 1.4 - the :meth:`_orm.Session.refresh` method can also refresh eagerly loaded attributes. :func:`_orm.relationship` oriented attributes that would normally load using the ``select`` (or "lazy") loader strategy will also load **if they are named explicitly in the attribute_names collection**, emitting a SELECT statement for the attribute using the ``immediate`` loader strategy. If lazy-loaded relationships are not named in :paramref:`_orm.Session.refresh.attribute_names`, then they remain as "lazy loaded" attributes and are not implicitly refreshed. .. versionchanged:: 2.0.4 The :meth:`_orm.Session.refresh` method will now refresh lazy-loaded :func:`_orm.relationship` oriented attributes for those which are named explicitly in the :paramref:`_orm.Session.refresh.attribute_names` collection. .. tip:: While the :meth:`_orm.Session.refresh` method is capable of refreshing both column and relationship oriented attributes, its primary focus is on refreshing of local column-oriented attributes on a single instance. For more open ended "refresh" functionality, including the ability to refresh the attributes on many objects at once while having explicit control over relationship loader strategies, use the :ref:`populate existing ` feature instead. Note that a highly isolated transaction will return the same values as were previously read in that same transaction, regardless of changes in database state outside of that transaction. Refreshing attributes usually only makes sense at the start of a transaction where database rows have not yet been accessed. :param attribute_names: optional. An iterable collection of string attribute names indicating a subset of attributes to be refreshed. :param with_for_update: optional boolean ``True`` indicating FOR UPDATE should be used, or may be a dictionary containing flags to indicate a more specific set of FOR UPDATE flags for the SELECT; flags should match the parameters of :meth:`_query.Query.with_for_update`. Supersedes the :paramref:`.Session.refresh.lockmode` parameter. .. seealso:: :ref:`session_expire` - introductory material :meth:`.Session.expire` :meth:`.Session.expire_all` :ref:`orm_queryguide_populate_existing` - allows any ORM query to refresh objects as they would be loaded normally. Nzqwith_for_update should be the boolean value True, or a dictionary with options. A blank dictionary is ambiguous.T)Z refresh_staterZonly_load_propsZrequire_pk_colsrZis_user_refreshzCould not refresh instance '%s')rinstance_staterNO_STATEUnmappedInstanceError _expire_staterrrrM_from_argumentr;selectr,rZ load_on_identrLrr*)rrrrr rstmtrrrrefresh s:K   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` is not usually needed, assuming the transaction is isolated. .. seealso:: :ref:`session_expire` - introductory material :meth:`.Session.expire` :meth:`.Session.refresh` :meth:`_orm.Query.populate_existing` N)rJrOrQrrRrr rrr expire_allp s zSession.expire_all)rrrc CsPzt|}Wn0tjk r>}zt||W5d}~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` N)rrrrrr)rrrr rrrrexpire s 'zSession.expirer)r rrcCs\|||r||j|n:t|jjd|}|||D]\}}}}||q@dS)Nzrefresh-expire)_validate_persistent_expire_attributesrrmanagerrcascade_iterator_conditional_expire)rr rcascadedomst_dct_rrrr s  zSession._expire_state)r rrcCs>|jr||j|jjn ||jkr:|j|||dS)z5Expire a state if persistent, else expunge if pendingN)rLrQrrJrRrrZ_detach)rr rrrrr s   zSession._conditional_expirerc Cszt|}Wn0tjk r>}zt||W5d}~XYnX|j|jk r^tdt |t |j j d|}||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. Nz*Instance %s is not present in this SessionexpungecSsg|]\}}}}|qSrr)r rrrrrrrr  s z#Session.expunge..)rrrrr session_idrrrr/rrrrrH)rrr rrrrrr s  zSession.expungezIterable[InstanceState[Any]])statesrFrcCsv|D]Z}||jkr |j|q|j|rH|j||j|dq|jr|jj|dqtjj |||ddS)NrE) rrrJcontains_staterKrr+rVr4rW)rrrFr rrrrH s   zSession._expunge_stateszSet[InstanceState[Any]])rrc Cs|jjp d}|D]}t|}|}|dk r||}t|drL|jrZt|drlt dt ||j dkr~||_ n\|j |kr|j ||j}|dk st||jkr|j|d}n|j }||f|j|<||_ |j |} | dk r|| |kr| dk rtd|fd|_qtjdd|D|j |||dk rr||jD]}|||q`t||jD]}|j|qdS) 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|]}||jfVqdSrrr r rrr I sz/Session._register_persistent..)r,pending_to_persistentr)r_identity_key_from_stater( intersectionallow_partial_pks issupersetrror/rLrJrKr+r)r rMr<r\_orphaned_outside_of_sessionrVr4_commit_all_states_register_alteredrrr) rrrr rrZ instance_keyryorig_keyoldrrr_register_persistent sj                 zSession._register_persistentcCs8|jr4|D](}||jkr&d|jj|<q d|jj|<q dSNT)r+rr)rrr rrrr V s  zSession._register_alteredcCsn|jjp d}|D]X}|jr&d|jj|<|dk r6|}|j||j|dd|_|dk r|||qdSr)r,persistent_to_deletedr+rrrJrKr)rrrr rrrr_remove_newly_deleted^ s   zSession._remove_newly_deleted)r_warnrc Csb|r|jr|dzt|}Wn0tjk rR}zt||W5d}~XYnX||dS)aPlace an object into this :class:`_orm.Session`. Objects that are in the :term:`transient` state when passed to the :meth:`_orm.Session.add` method will move to the :term:`pending` state, until the next flush, at which point they will move to the :term:`persistent` state. Objects that are in the :term:`detached` state when passed to the :meth:`_orm.Session.add` method will move to the :term:`persistent` state directly. If the transaction used by the :class:`_orm.Session` is rolled back, objects which were transient when they were passed to :meth:`_orm.Session.add` will be moved back to the :term:`transient` state, and will no longer be present within this :class:`_orm.Session`. .. seealso:: :meth:`_orm.Session.add_all` :ref:`session_adding` - at :ref:`session_basics` z Session.add()N)r_flush_warningrrrrr_save_or_update_state)rrrr rrrrrt s  z Session.addzIterable[object]) instancesrcCs,|jr|d|D]}|j|ddqdS)a2Add the given collection of instances to this :class:`_orm.Session`. See the documentation for :meth:`_orm.Session.add` for a general behavioral description. .. seealso:: :meth:`_orm.Session.add` :ref:`session_adding` - at :ref:`session_basics` zSession.add_all()F)rN)rrr)rrrrrradd_all s zSession.add_allrcCsFd|_||t|}|jd||jdD]\}}}}||q*dS)NFz save-update)Zhalt_on)r _save_or_update_implr)r_contains_state)rr rrrrrrrrr s zSession._save_or_update_statec Csd|jr|dzt|}Wn0tjk rN}zt||W5d}~XYnX|j||dddS)aVMark an instance as deleted. The object is assumed to be either :term:`persistent` or :term:`detached` when passed; after the method is called, the object will remain in the :term:`persistent` state until the next flush proceeds. During this time, the object will also be a member of the :attr:`_orm.Session.deleted` collection. When the next flush proceeds, the object will move to the :term:`deleted` state, indicating a ``DELETE`` statement was emitted for its row within the current transaction. When the transaction is successfully committed, the deleted object is moved to the :term:`detached` state and is no longer present within this :class:`_orm.Session`. .. seealso:: :ref:`session_deleting` - at :ref:`session_basics` zSession.delete()NT)head)rrrrrrr _delete_implrrr rrrrdelete s zSession.delete)r rrrc Cs|jdkr&|r"tdt|ndS|||}||jkr@dS|j||r\||||rvt |j j d|}nd}||j|<|rt r|dk st|D]\}}}} |||dqdS)NInstance '%s' is not persistedrF)rLrrr/_before_attachrrJr _after_attachrrrrrr)r) rr rr to_attachZcascade_statesrrrrrrrr s.        zSession._delete_imploptionspopulate_existingrrrr_PKIdentityArgumentzOptional[Sequence[ORMOption]]z Optional[_O]) rrr$r%rrrrrc Cs|j||tj||||||d S)aReturn an instance based on the given primary key identifier, or ``None`` if not found. E.g.:: my_user = session.get(User, 5) some_object = session.get(VersionedFoo, (5, 10)) some_object = session.get( VersionedFoo, {"id": 5, "version_id": 10} ) .. versionadded:: 1.4 Added :meth:`_orm.Session.get`, which is moved from the now legacy :meth:`_orm.Query.get` method. :meth:`_orm.Session.get` is special in that it provides direct access to the identity map of the :class:`.Session`. If the given primary key identifier is present in the local identity map, the object is returned directly from this collection and no SQL is emitted, unless the object has been marked fully expired. If not present, a SELECT is performed in order to locate the object. :meth:`_orm.Session.get` also will perform a check if the object is present in the identity map and marked as expired - a SELECT is emitted to refresh the object as well as to ensure that the row is still present. If not, :class:`~sqlalchemy.orm.exc.ObjectDeletedError` is raised. :param entity: a mapped class or :class:`.Mapper` indicating the type of entity to be loaded. :param ident: A scalar, tuple, or dictionary representing the primary key. For a composite (e.g. multiple column) primary key, a tuple or dictionary should be passed. For a single-column primary key, the scalar calling form is typically the most expedient. If the primary key of a row is the value "5", the call looks like:: my_object = session.get(SomeClass, 5) The tuple form contains primary key values typically in the order in which they correspond to the mapped :class:`_schema.Table` object's primary key columns, or if the :paramref:`_orm.Mapper.primary_key` configuration parameter were used, in the order used for that parameter. For example, if the primary key of a row is represented by the integer digits "5, 10" the call would look like:: my_object = session.get(SomeClass, (5, 10)) The dictionary form should include as keys the mapped attribute names corresponding to each element of the primary key. If the mapped class has the attributes ``id``, ``version_id`` as the attributes which store the object's primary key value, the call would look like:: my_object = session.get(SomeClass, {"id": 5, "version_id": 10}) :param options: optional sequence of loader options which will be applied to the query, if one is emitted. :param populate_existing: causes the method to unconditionally emit a SQL query and refresh the object with the newly loaded data, regardless of whether or not the object is already present. :param with_for_update: optional boolean ``True`` indicating FOR UPDATE should be used, or may be a dictionary containing flags to indicate a more specific set of FOR UPDATE flags for the SELECT; flags should match the parameters of :meth:`_query.Query.with_for_update`. Supersedes the :paramref:`.Session.refresh.lockmode` parameter. :param execution_options: optional dictionary of execution options, which will be associated with the query execution if one is emitted. This dictionary can provide a subset of the options that are accepted by :meth:`_engine.Connection.execution_options`, and may also provide additional options understood only in an ORM context. .. versionadded:: 1.4.29 .. seealso:: :ref:`orm_queryguide_execution_options` - ORM-specific execution options :param bind_arguments: dictionary of additional arguments to determine the bind. May include "mapper", "bind", or other custom arguments. Contents of this dictionary are passed to the :meth:`.Session.get_bind` method. .. versionadded: 2.0.0rc1 :return: The object instance, or ``None``. r#) _get_implrZload_on_pk_identity) rrrr$r%rrrrrrrr srz Session.getr!c Cs0|j||||||||d} | dkr,td| S)a<Return exactly one instance based on the given primary key identifier, or raise an exception if not found. Raises ``sqlalchemy.orm.exc.NoResultFound`` if the query selects no rows. For a detailed documentation of the arguments see the method :meth:`.Session.get`. .. versionadded:: 2.0.22 :return: The object instance. .. seealso:: :meth:`.Session.get` - equivalent method that instead returns ``None`` if no row was found with the provided primary key r#Nz&No row was found when one was required)rrZ NoResultFound) rrrr$r%rrrrrrrrget_oneys! zSession.get_onezCallable[..., _O]z$Optional[Sequence[ExecutableOption]]) rr db_load_fnr$r%rrrrrc s tr,ttjkr,tjt} | t|} | dksB| jsPtd|tt } | snt j dgdt t | j krtdddd| j D| rH| j} | rt| }|rt |D]}|| |<qztfdd| jDWnFtk rF}z&tddd d| jD|W5d}~XYnX|s| js|dkr|j| ||| d }|dk rt|| jsdS|S|tjk sttjj}|r|d |i7}t | !t"}|dk rt#$||_%|r|j&|}||||||| d S) Nz(Expected mapped class or mapper, got: %r)defaultzoIncorrect number of values in identifier to formulate primary key for session.get(); primary key columns are %s,css|]}d|VqdSz'%s'Nr)r crrrrsz$Session._get_impl..c3s|]}|jVqdSrrLr proprrrrszIncorrect names of values in identifier to formulate primary key for session.get(); primary key attribute names are %s (synonym names are also accepted)css|]}d|jVqdSr,r.r/rrrrs)rrrZ_populate_existing)rrrr)'r#rrZ_composite_gettersrBZ is_mapperrrrrr<Zto_listrZ primary_keyrrZ _pk_synonymsrrrZ_identity_key_propsKeyErrorZalways_refreshrrr+ZPASSIVE_CLASS_MISMATCHr)rrrr;rZset_label_stylerNrMrZ_for_update_argr$)rrrr)r$r%rrrrgetterrZis_dictZ pk_synonymsZ correct_keyskrrrrrr1rr's           zSession._get_impl)loadr$)rr5r$rcCsl|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. :param instance: Instance to be merged. :param load: Boolean, when False, :meth:`.merge` switches into a "high performance" mode which causes it to forego emitting history events as well as all database access. This flag is used for cases such as transferring graphs of objects into a :class:`.Session` from a second level cache, or to transfer just-loaded objects into the :class:`.Session` owned by a worker thread or process without re-querying the database. The ``load=False`` use case adds the caveat that the given object has to be in a "clean" state, that is, has no pending changes to be flushed - even if the incoming object is detached from any :class:`.Session`. This is so that when the merge operation populates local attributes and cascades to related objects and collections, the values can be "stamped" onto the target object as is, without generating any history or attribute events, and without the need to reconcile the incoming data with any existing related objects or collections that might not be loaded. The resulting objects from ``load=False`` are always produced as "clean", so it is only appropriate that the given objects should be "clean" as well, else this suggests a mis-use of the method. :param options: optional sequence of loader options which will be applied to the :meth:`_orm.Session.get` method when the merge operation loads the existing version of the object from the database. .. versionadded:: 1.4.24 .. seealso:: :func:`.make_transient_to_detached` - provides for an alternative means of "merging" a single object into the :class:`.Session` zSession.merge()F)r5r$ _recursive_resolve_conflict_mapN) rrrr,r_mergerr instance_dict)rrr5r$r6r7rrrrmerge+s&>  z Session.merge)r$InstanceState[_O]rTzDict[Any, object]z#Dict[_IdentityKeyType[Any], object])r state_dictr$r5r6r7rc Cst|}||krtt||Sd}|j} | dkr||jkrLtdt||sZt d| |} t j | dkot | d p|jot | d } nd} | |jkrz|j| } Wqtk rd} YqXnd} | dkr`| r| |krtt|| } nd|s>|jrt d|j} t| } | | _|| d}n"| r`|j|j| d| d|d} | dkr|j} t| } t| } d}|| nt| } t| } | ||<| || <|| k rx|jdk r8|j|||jtj d }|j| | |jtj d }|t j!k r8|t j!k r8||kr8t"#d |t| |f|j$| _$|j%| _%| &||j'D]}|(|||| | |||qX|s| )| |j| j*j+,| d|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.r9)rr$rzVersion 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.).r)rr!rLrr<r\r/rrrr+Z NEVER_SETr(rr r rJr2rPZ class_manager new_instancerrrNrrr9rZversion_id_colZ_get_state_attr_by_columnr.ZPASSIVE_NO_INITIALIZEZPASSIVE_NO_RESULTrZStaleDataErrorZ load_pathrZ_copy_callablesZiterate_propertiesr: _commit_allrr,Z_sa_event_merge_wo_loadr5)rr r<r$r5r6r7rr>rLZkey_is_persistentZmergedZ merged_stateZ merged_dictZexisting_versionZmerged_versionr0rrrr8s                        zSession._mergecCs"|j|stdt|dS)Nz3Instance '%s' is not persistent within this Session)rJrrrr/rrrrr(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) rLrrr/rr rrZ insert_orderr!)rr rr"rrr _save_impl/s     zSession._save_impl)r rGrcCs|jdkrtdt||jrH|r6|js0dS|`ntdt||}|dkr\dS|||}|j|d|r|j |n |j ||r| ||n|r|j ||dS)NrzsInstance '%s' has been deleted. Use the make_transient() function to send this object back to the transient state.)rLrrr/rZ _attachedrr rrJrMrr!r,Zdeleted_to_persistent)rr rGrr"rrrrN>s4    zSession._update_implcCs$|jdkr||n ||dSr)rLr@rNrrrrrfs  zSession._save_or_update_impl)rrc Csfzt|}Wn0tjk r>}zt||W5d}~XYnX|||}d|_|rb|||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. NT)rrrrrr Z _load_pendingr!)rrr rr"rrrenable_relationship_loadingls7 z#Session.enable_relationship_loading)r rrcCsV||j|jkrdS|jrD|jtkrDtdt||j|jf|j||dS)NFz>Object '%s' is already attached to session '%s' (this is '%s')T) rrrrrrr/r,Z before_attachrr rrrrr s zSession._before_attachcCsT|j|_|jr|jdkr||_|j|||jrB|j||n|j||dSr) rrrPZ _strong_objr,Z after_attachrLZdetached_to_persistentZtransient_to_pendingrBrrrr!szSession._after_attachc CsJzt|}Wn0tjk r>}zt||W5d}~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. N)rrrrrrrrrr __contains__s zSession.__contains__zIterator[object]cCs tt|jt|jS)zWIterate over all pending or persistent instances within this Session. )iterrrrprJrrrr__iter__szSession.__iter__cCs||jkp|j|Sr)rrJrrrrrrszSession._contains_statezOptional[Sequence[Any]])objectsrcCs>|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. :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)r@rrrn_flush)rrFrrrrAs z Session.flush)methodrcCstd|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.)r<r\)rrHrrrrs zSession._flush_warningcCs|j o|j o|j Sr)rJZcheck_modifiedrrrrrrrn s  zSession._is_cleanzOptional[Sequence[object]]c Cs|j}|s&|js&|js&|jjdSt|}|jjrL|j||||j}t |j}t |j}t | |}|rt }|D]N}zt |}Wn0t jk r} zt || W5d} ~ XYnX||q|nd}t } |r||| |} n|| |} | D]h}t||} | o$|j} | rH| sH|jrH||gn&|j|| d}|sdtd| |q|r|| | } n | | } | D]"}|j|dd}|stdq|jsdS||_}zd|_z |W5d|_X|j |||!|sX|jjrXt"|jj}t#j$j%dd|jjD|jdt&'d||j(|||)Wn,t&*|j+dd W5QRXYnXdS) N)Zisdeletez*Failed to add object to the flush context!TFcSsg|]}||jfqSrrrrrrr lsz"Session._flush..)r9zAttribute 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_statesrrrJrRrXr8r,Z before_flushr differencerrrrrrrrr)Z _is_orphanZ has_identityr rHZregister_objectr)Zhas_workrr<rgrrZ after_flushZfinalize_flush_changesrrVr4r r<r\Zafter_flush_postexecrlrqrr)rrFdirtyZ flush_contextdeletednewZobjsetrr r processedprocZ is_orphanZis_persistent_orphanZ_regrgZlen_rrrrGs         zSession._flush)rFreturn_defaultsupdate_changed_onlypreserve_orderrc Cshdd|D}|s"t|ddd}dddd d }t||D]$\\}}} |j|| |d ||d d q>dS)a Perform a bulk save of the given list of objects. .. legacy:: This method is a legacy feature as of the 2.0 series of SQLAlchemy. For modern bulk INSERT and UPDATE, see the sections :ref:`orm_queryguide_bulk_insert` and :ref:`orm_queryguide_bulk_update`. For general INSERT and UPDATE of existing ORM mapped objects, prefer standard :term:`unit of work` data management patterns, introduced in the :ref:`unified_tutorial` at :ref:`tutorial_orm_data_manipulation`. SQLAlchemy 2.0 now uses :ref:`engine_insertmanyvalues` with modern dialects which solves previous issues of bulk INSERT slowness. :param objects: a sequence of mapped object instances. The mapped objects are persisted as is, and are **not** associated with the :class:`.Session` afterwards. For each object, whether the object is sent as an INSERT or an UPDATE is dependent on the same rules used by the :class:`.Session` in traditional operation; if the object has the :attr:`.InstanceState.key` attribute set, then the object is assumed to be "detached" and will result in an UPDATE. Otherwise, an INSERT is used. In the case of an UPDATE, statements are grouped based on which attributes have changed, and are thus to be the subject of each SET clause. If ``update_changed_only`` is False, then all attributes present within each object are applied to the UPDATE statement, which may help in allowing the statements to be grouped together into a larger executemany(), and will also reduce the overhead of checking history on attributes. :param return_defaults: when True, rows that are missing values which generate defaults, namely integer primary key defaults and sequences, will be inserted **one at a time**, so that the primary key value is available. In particular this will allow joined-inheritance and other multi-table mappings to insert correctly without the need to provide primary key values ahead of time; however, :paramref:`.Session.bulk_save_objects.return_defaults` **greatly reduces the performance gains** of the method overall. It is strongly advised to please use the standard :meth:`_orm.Session.add_all` approach. :param update_changed_only: when True, UPDATE statements are rendered based on those attributes in each state that have logged changes. When False, all attributes present are rendered into the SET clause with the exception of primary key attributes. :param preserve_order: when True, the order of inserts and updates matches exactly the order in which the objects are given. When False, common types of objects are grouped into inserts and updates, to allow for more batching opportunities. .. seealso:: :doc:`queryguide/dml` :meth:`.Session.bulk_insert_mappings` :meth:`.Session.bulk_update_mappings` css|]}t|VqdSr)rr)r rrrrrsz,Session.bulk_save_objects..cSst|j|jdk fSr)idrrLrrrrz+Session.bulk_save_objects..r.r;zTuple[Mapper[_O], bool]rcSs|j|jdk fSr)rrLrrrr grouping_keysz/Session.bulk_save_objects..grouping_keyTFisupdateisstatesrQrR render_nullsN)sortedrgroupby_bulk_save_mappings) rrFrQrRrSZ obj_statesrWrrYrrrrbulk_save_objectss(KzSession.bulk_save_objectsrzIterable[Dict[str, Any]])rmappingsrQr[rc Cs|j||dd|d|ddS)a= Perform a bulk insert of the given list of mapping dictionaries. .. legacy:: This method is a legacy feature as of the 2.0 series of SQLAlchemy. For modern bulk INSERT and UPDATE, see the sections :ref:`orm_queryguide_bulk_insert` and :ref:`orm_queryguide_bulk_update`. The 2.0 API shares implementation details with this method and adds new features as well. :param mapper: a mapped class, or the actual :class:`_orm.Mapper` object, representing the single kind of object represented within the mapping list. :param mappings: a sequence of dictionaries, each one containing the state of the mapped row to be inserted, in terms of the attribute names on the mapped class. If the mapping refers to multiple tables, such as a joined-inheritance mapping, each dictionary must contain all keys to be populated into all tables. :param return_defaults: when True, the INSERT process will be altered to ensure that newly generated primary key values will be fetched. The rationale for this parameter is typically to enable :ref:`Joined Table Inheritance ` mappings to be bulk inserted. .. note:: for backends that don't support RETURNING, the :paramref:`_orm.Session.bulk_insert_mappings.return_defaults` parameter can significantly decrease performance as INSERT statements can no longer be batched. See :ref:`engine_insertmanyvalues` for background on which backends are affected. :param render_nulls: When True, a value of ``None`` will result in a NULL value being included in the INSERT statement, rather than the column being omitted from the INSERT. This allows all the rows being INSERTed to have the identical set of columns which allows the full set of rows to be batched to the DBAPI. Normally, each column-set that contains a different combination of NULL values than the previous row must omit a different series of columns from the rendered INSERT statement, which means it must be emitted as a separate statement. By passing this flag, the full set of rows are guaranteed to be batchable into one batch; the cost however is that server-side defaults which are invoked by an omitted column will be skipped, so care must be taken to ensure that these are not necessary. .. warning:: When this flag is set, **server side default SQL values will not be invoked** for those columns that are inserted as NULL; the NULL value will be sent explicitly. Care must be taken to ensure that no server-side default functions need to be invoked for the operation as a whole. .. seealso:: :doc:`queryguide/dml` :meth:`.Session.bulk_save_objects` :meth:`.Session.bulk_update_mappings` FrXNr^)rrr`rQr[rrrbulk_insert_mappingssIzSession.bulk_insert_mappings)rr`rc Cs|j||dddddddS)aaPerform a bulk update of the given list of mapping dictionaries. .. legacy:: This method is a legacy feature as of the 2.0 series of SQLAlchemy. For modern bulk INSERT and UPDATE, see the sections :ref:`orm_queryguide_bulk_insert` and :ref:`orm_queryguide_bulk_update`. The 2.0 API shares implementation details with this method and adds new features as well. :param mapper: a mapped class, or the actual :class:`_orm.Mapper` object, representing the single kind of object represented within the mapping list. :param mappings: a sequence of dictionaries, each one containing the state of the mapped row to be updated, in terms of the attribute names on the mapped class. If the mapping refers to multiple tables, such as a joined-inheritance mapping, each dictionary may contain keys corresponding to all tables. All those keys which are present and are not part of the primary key are applied to the SET clause of the UPDATE statement; the primary key values, which are required, are applied to the WHERE clause. .. seealso:: :doc:`queryguide/dml` :meth:`.Session.bulk_insert_mappings` :meth:`.Session.bulk_save_objects` TFrXNra)rrr`rrrbulk_update_mappingsFs&zSession.bulk_update_mappingsz.)rOrJrrrrrLs  z Session.dirtycCstt|jS)zDThe set of all instances marked as 'deleted' within this ``Session``)r<rOrrrprrrrrM3szSession.deletedcCstt|jS)zAThe set of all instances marked as 'new' within this ``Session``.)r<rOrrrprrrrrN9sz Session.new)N)F)F)NN)N)N)N)N)N)N)N)N)N)N)N)N)N)N)F)N)NN)N)N)F)T)F)N)N)FTT)FF)T)frrrrZ _is_asynciorrJrrrrrr contextlibcontextmanagerrr`rbrrr<Zmemoized_propertyrrrcr_rrrlrir:r8r EMPTY_DICTrrrrrdrrrrrrrr7rr.Z PASSIVE_OFFrZnon_memoized_propertyrZ langhelpersZtag_method_for_warningsrZ SAWarningrrrrrrrrHrr rrrrrrrr(r'r:r8rr@rNrrAr r!rCrErrArrnrGr_rbrcr^rjrr3rJrLrMrNrrrrr{s@  *,       7&3 " "    F    &)$      ;y$- S# ,0094&\2'(A   "z m"S0$*L rc @seZdZUdZded<ed#dddddddddd d d d Zed$ddddd ddddd ddd Zd%edddddddddd d dd ZddddZd ddddZ d ddddZ d dd!d"Z 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+psycopg2://scott:tiger@localhost/') Session = sessionmaker(engine) with Session() as session: session.add(some_object) session.add(some_other_object) session.commit() Context manager use is optional; otherwise, the returned :class:`_orm.Session` object may be closed explicitly via the :meth:`_orm.Session.close` method. Using a ``try:/finally:`` block is optional, however will ensure that the close takes place even if there are database errors:: session = Session() try: session.add(some_object) session.add(some_other_object) session.commit() finally: session.close() :class:`.sessionmaker` acts as a factory for :class:`_orm.Session` objects in the same way as an :class:`_engine.Engine` acts as a factory for :class:`_engine.Connection` objects. In this way it also includes a :meth:`_orm.sessionmaker.begin` method, that provides a context manager which both begins and commits a transaction, as well as closes out the :class:`_orm.Session` when complete, rolling back the transaction if any errors occur:: Session = sessionmaker(engine) with Session.begin() as session: session.add(some_object) session.add(some_other_object) # commits transaction, closes session .. versionadded:: 1.4 When calling upon :class:`_orm.sessionmaker` to construct a :class:`_orm.Session`, keyword arguments may also be passed to the method; these arguments will override that of the globally configured parameters. Below we use a :class:`_orm.sessionmaker` bound to a certain :class:`_engine.Engine` to produce a :class:`_orm.Session` that is instead bound to a specific :class:`_engine.Connection` procured from that engine:: Session = sessionmaker(engine) # bind an individual session to a connection with engine.connect() as connection: with Session(bind=connection) as session: # work with session The class also includes a method :meth:`_orm.sessionmaker.configure`, which can be used to specify additional keyword arguments to the factory, which will take effect for subsequent :class:`.Session` objects generated. This is usually used to associate one or more :class:`_engine.Engine` objects with an existing :class:`.sessionmaker` factory before it is first used:: # application starts, sessionmaker does not have # an engine bound yet Session = sessionmaker() # ... later, when an engine URL is read from a configuration # file or other events allow the engine to be created engine = create_engine('sqlite:///foo.db') Session.configure(bind=engine) sess = Session() # work with session .. seealso:: :ref:`session_getting` - introductory text on creating sessions using :class:`.sessionmaker`. zType[_S]r.)rrUrrrrr)r9rrrUrrcKsdSrrrr9rrrUrrrrrrs zsessionmaker.__init__z'sessionmaker[Session]'rr9rrUrrcKsdSrrrorrrrs NT)rrrUrcKsD||d<||d<||d<|dk r(||d<||_t|j|fi|_dS)a<Construct a new :class:`.sessionmaker`. All arguments here except for ``class_`` correspond to arguments accepted by :class:`.Session` directly. See the :meth:`.Session.__init__` docstring for more details on parameters. :param bind: a :class:`_engine.Engine` or other :class:`.Connectable` with which newly created :class:`.Session` objects will be associated. :param class\_: class to use in order to create new :class:`.Session` objects. Defaults to :class:`.Session`. :param autoflush: The autoflush setting to use with newly created :class:`.Session` objects. .. seealso:: :ref:`session_flushing` - additional background on autoflush :param expire_on_commit=True: the :paramref:`_orm.Session.expire_on_commit` setting to use with newly created :class:`.Session` objects. :param info: optional dictionary of information that will be available via :attr:`.Session.info`. Note this dictionary is *updated*, not replaced, when the ``info`` parameter is specified to the specific :class:`.Session` construction operation. :param \**kw: all other keyword arguments are passed to the constructor of newly created :class:`.Session` objects. r9rrUNr)rrrrrnrrrrs)z%contextlib.AbstractContextManager[_S]rcCs|}|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)rrrrrrcszsessionmaker.beginr)local_kwrcKs\|jD]D\}}|dkrBd|krB|}||d||d<q |||q |jf|S)apProduce a new :class:`.Session` object using the configuration established in this :class:`.sessionmaker`. In Python, the ``__call__`` method is invoked on an object when it is "called" in the same way as a function:: Session = sessionmaker(some_engine) session = Session() # invokes sessionmaker.__call__() r)rrIcopyrrr)rrpr4vrrrrrs  zsessionmaker.__call__r)new_kwrcKs|j|dS)z(Re)configure the arguments for this sessionmaker. e.g.:: Session = sessionmaker() Session.configure(bind=create_engine('sqlite://')) N)rr)rrsrrr configures zsessionmaker.configurer-cCs,d|jj|jjddd|jDfS)Nz%s(class_=%r, %s)rcss|]\}}d||fVqdS)z%s=%rNr)r r4rrrrrr'sz(sessionmaker.__repr__..) __class__rrrrrIrrrr__repr__#s zsessionmaker.__repr__).).)N) rrrrrrrr{rcrrtrvrrrrr}Cs6 ^  3 rrcCstD] }|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)rrprd)rrrrr+s rrcCsNt|}t|}|r"||g|j|jr6|`|jr@|`|jrJ|`dS)aoAlter the state of the given instance so that it is :term:`transient`. .. note:: :func:`.make_transient` is a special-case function for advanced use cases only. The given mapped instance is assumed to be in the :term:`persistent` or :term:`detached` state. The function will remove its association with any :class:`.Session` as well as its :attr:`.InstanceState.identity`. The effect is that the object will behave as though it were newly constructed, except retaining any attribute / collection values that were loaded at the time of the call. The :attr:`.InstanceState.deleted` flag is also reset if this object had been deleted as a result of using :meth:`.Session.delete`. .. warning:: :func:`.make_transient` does **not** "unexpire" or otherwise eagerly load ORM-mapped attributes that are not currently loaded at the time the function is called. This includes attributes which: * were expired via :meth:`.Session.expire` * were expired as the natural effect of committing a session transaction, e.g. :meth:`.Session.commit` * are normally :term:`lazy loaded` but are not currently loaded * are "deferred" (see :ref:`orm_queryguide_column_deferral`) and are not yet loaded * were not present in the query which loaded this object, such as that which is common in joined table inheritance and other scenarios. After :func:`.make_transient` is called, unloaded attributes such as those above will normally resolve to the value ``None`` when accessed, or an empty collection for a collection-oriented attribute. As the object is transient and un-associated with any database identity, it will no longer retrieve these values. .. seealso:: :func:`.make_transient_to_detached` N) rrrrHZexpired_attributesrXZ callablesrLr)rr rSrrrr=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) rrrrLrrrrrr?rrZunloaded)rr rrrr~s    c CsLzt|}Wn0tjk r>}zt||W5d}~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. N)rrrrrr)rr rrrrrs )r __future__rrkenumrrr|typingrrrrrr r r r r rrrrrrrrrBrrrrrrrrr rVZ_typingr!r"r#r$r&baser'r(r)r*r+r,r-r.r/r0r1r2r3r4Z state_changesr5r6r7Z unitofworkr8r:rr;r<r=r>Z engine.utilr?eventr@rAZ inspectionrBrCrDrErFrGrHrIZsql.baserJrKZ sql.schemarLZsql.selectablerMrNrOZ util.typingrPrQrRrSrTrUZ interfacesrVrWrrXZ path_registryrYrZr[r\r]r^Z engine.baser_r`Zengine.interfacesrarbrcrdZ engine.resultrerfZ sql._typingrgrhrirjrkrlrmrnrorprqZ_TCCArrrsZsql.dmlrtZ sql.elementsruZ sql.rolesrvrwrxry__all__WeakValueDictionaryrrr&r-rZ_EntityBindKeyrrZrrrrrtuplerrrrrrZ MemoizedSlotsr~rr|r&r{rr}rrrrcounterrrrrrs                                                                                                                        2 /`, iA'