L iIUdZddlmZddlZddlmZddlZddlZddlZddlm 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_maZaej0rddQl'mbZbddRl'mcZcddSl'mdZdddTl'meZeddUlfmgZgddVlfmhZhddWlimjZjddXlkmlZlddYl$mmZmd8dZlBmnZnd8d[lBmoZod8d\lBmpZpd8d]lqmrZrd8d^lqmsZsd8d_ltmuZud8d`ltmvZvd8daltmwZwd8dbltmxZxd8dclymzZzd8ddlJm{Z{d8del|m}Z}d8dfl|m~Z~d8dgl|mZd8dhl|mZd8dil|mZd8djl|mZd8dkl|mZd8dll|mZd8dml|mZd8dnl|mZd8dol|mZd8dplVmZd8dqlVmZd8drlmZd8dslmZd8dtl[mZd8dul[mZedve wZgdxZej&Zdyedz< ee&_ee ee d{ffZe ee fZeee(d|fZeee d}d~efZedZe`dZGddeaZddZGddZGdde>Zee\ZZZZZZGddeEjPZGddeZGdde=eIZGddeZGddeeLZeddwZGddee eZddZddZddZddZeEjhZy)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_option)is_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)Result)Row) RowMapping) Transaction)TwoPhaseTransaction)_CoreAnyExecuteParams)_CoreSingleExecuteParams)_ExecuteOptions)CoreExecuteOptionsParameter) ScalarResult)_InstanceLevelDispatch)_ColumnsClauseArgument) _InfoType)_T0)_T1)_T2)_T3)_T4)_T5)_T6)_T7)_TypedColumnClauseArgument) Executable)ExecutableOption) ClauseElement)TypedColumnsClauseRole)ForUpdateParameter)TypedReturnsRows_T)bound)SessionSessionTransaction 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,eZdZdZ d ddZy)_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. Nc yN)selfmapperinstancekws \/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py__call__z!_ConnectionCallableProto.__call__s NN)rOptional[Mapper[Any]]rzOptional[object]rrreturnr=)__name__ __module__ __qualname____doc__rrrrrrs: )-%)%#   rrc|jS)z[Given an :class:`.InstanceState`, return the :class:`.Session` associated, if any. sessionr s r_state_sessionrs ==rceZdZdZeej ddd dZeejd d dddd d dZ ed d Z y)_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`.cty)zClose *all* sessions in memory.N)r})clss r close_allz_SessionClassMethods.close_alls  rzsqlalchemy.orm.utilNrrowidentity_tokenc^tjjj|||||S)zZReturn an identity key. This is an alias of :func:`.util.identity_key`. r)r< preloadedorm_util identity_key)rclass_identrrrs rrz!_SessionClassMethods.identity_keys5 ~~&&33  ) 4  rct|S)zxReturn the :class:`.Session` to which an object belongs. This is an alias of :func:`.object_session`. )r)rrs rrz#_SessionClassMethods.object_sessionsh''rrNoner) rzOptional[Type[Any]]rUnion[Any, Tuple[Any, ...]]r Optional[Any]rz%Optional[Union[Row[Any], RowMapping]]rrrz_IdentityKeyType[Any]robjectrOptional[Session]) rrrr classmethodr< deprecatedrpreload_modulerrrrrrrsLT__  /   T./'+-1 #'59(, # +   3  &   0 ,((rrc$eZdZdZdZdZdZdZdZy)SessionTransactionStaterr9N) rrrACTIVEPREPARED COMMITTEDDEACTIVECLOSEDPROVISIONING_CONNECTIONrrrrrs! FHIH Frrc6eZdZUdZdZded< ded< ded< d ed < d ed < d ed < ded<ded<ded<ded< d.dZd/dZ d0 d1dZe d2dZ e d3dZ e d4dZ e d4dZ e d4dZe d4dZe d4d Ze d4d!Ze d4d"Ze d4d#Zd5d$Z d6d%Ze d7d&Ze d8d'Ze d4d(Ze d4d)Ze d9d*Ze d:d+Ze d;d,Ze d 2-1)* ""'+*DOO($6?5J5J(/8651$k(/;3F$882256J2K1LM !$F }A /(,,<'=$$++K8NN#345"t$4dooFGt$4f=>ooG!99 !3!9!9:K!L ||--  0*"& .  rc>|jjdd}|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)rmps r bind_mapperzORMExecuteState.bind_mappers!4%)$7$7$;$;Hd$K rc|jsgSt|jttfrg}t }|jj D]l}|d}|s t|d}|s|js(|j|vs7|j|j|j|jn|S|jjr|jr |jgSgS)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)raiseerr) is_orm_statement isinstancerrGr0setcolumn_descriptionsrBraddris_dmlr)rresultseendentinsps r all_mapperszORMExecuteState.all_mapperss&$$I (? @F5D^^77 3k"37D  40G- dkk2  3M ^^ " "t'7'7$$% %Irc|jduS)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)rrs rrz ORMExecuteState.is_orm_statement's&&d22rc6t|jtS)zreturn True if the parameters are a multi-element list of dictionaries with more than one dictionary. .. versionadded:: 2.0 )rrrrs rrzORMExecuteState.is_executemany4s$//400rc.|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_selectrs rrzORMExecuteState.is_select>s~~'''rc.|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_statementrs rr z!ORMExecuteState.is_from_statementJs~~///rc^|jjxr|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_insertrs rr zORMExecuteState.is_insert[#~~$$A)A)AArc^|jjxr|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_updaters rrzORMExecuteState.is_updategr rc^|jjxr|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_deleters rrzORMExecuteState.is_deletesr rcjt|jtjtjfSr)rrrEUpdateDeleters r_is_crudzORMExecuteState._is_cruds $..3::szz*BCCrc D|jj||_y)z3Update the local execution options with new values.N)rrroptss rupdate_execution_optionsz(ORMExecuteState.update_execution_optionss'+'C'C'I'I$'O$rc|jsy |jj}|+|j t j jr|Sy#t$rYywxYwr)rr_compile_optionsAttributeErrorrrr1default_compile_optionsrs r_orm_compile_optionsz$ORMExecuteState._orm_compile_optionssb~~ >>22D    # # ; ;! K  sA AAc.|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_options_lazy_loaded_fromrs rlazy_loaded_fromz ORMExecuteState.lazy_loaded_froms  222rc@|j}| |jSy)zReturn the :class:`.PathRegistry` for the current load path. This object represents the "path" in a query along relationships when a particular object or collection is being loaded. N)r _current_pathrs rloader_strategy_pathz$ORMExecuteState.loader_strategy_paths'((*  %% %rcF|j}|duxr |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)r_for_refresh_staters ris_column_loadzORMExecuteState.is_column_loads(0((*4;D$;$;;rcf|j}|y|j}|duxr |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)rr%is_root)rrpaths ris_relationship_loadz$ORMExecuteState.is_relationship_loads<(((* <((44 $44rc|jstjd|jj dt j j}|S)z=Return the load_options that will be used for this execution.zRThis ORM execution is not against a SELECT statement so there are no load options._sa_orm_load_options)rrrrrr QueryContextdefault_load_options)rlos rr zORMExecuteState.load_optionssV~~,,0   " " & & "G$8$8$M$M   rc|jstjd|jj dt j j}|S)zNReturn the update_delete_options that will be used for this execution.z_This ORM execution is not against an UPDATE or DELETE statement so there are no update options._sa_orm_update_options)rrrrrrBulkUDCompileStatedefault_update_options)ruos rupdate_delete_optionsz%ORMExecuteState.update_delete_optionssW}},,<   " " & & $  / / F F   rc|jjDcgc]}t|r|js|c}Scc}wr)r _with_optionsr%_is_compile_stateropts r_non_compile_orm_optionsz(ORMExecuteState._non_compile_orm_optionss>~~33 S!#*?*?    s <cj|jjDcgc]}t|r|c}Scc}w)zzThe sequence of :class:`.UserDefinedOptions` that have been associated with the statement being invoked. )rr9r&r;s ruser_defined_optionsz$ORMExecuteState.user_defined_options&s6~~33 %c*    s0)rryrrqrrrrbrrrrr%List[_InstanceLevelDispatch[Session]])rr@)NNNN) rzOptional[Executable]rrrz$Optional[OrmExecuteOptionsParameter]rOptional[_BindArguments]r Result[Any])rr)rzSequence[Mapper[Any]]rbool)rrrr)rzwOptional[Union[context.ORMCompileState.default_compile_options, Type[context.ORMCompileState.default_compile_options]]])rOptional[InstanceState[Any]])rzOptional[PathRegistry])rzaUnion[context.QueryContext.default_load_options, Type[context.QueryContext.default_load_options]])rzUnion[bulk_persistence.BulkUDCompileState.default_update_options, Type[bulk_persistence.BulkUDCompileState.default_update_options]])rzSequence[ORMOption])rzSequence[UserDefinedOption])rrrr __slots____annotations__rrrpropertyrrrrrr r rrrrrr"r%r(r,r r7r=r?rrrr|r|s  I+0/%'& -, #"8788...4 . + . ' .;.;.4A +/26BF37 h 'h 0h @ h 1 h  h T8""H 3 311 ( (00  B B B B B BDDP , 3 3  <<4552 , .      rr|c&eZdZdZdZ dZ dZ dZy)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_NESTEDSUBTRANSACTIONrrrrJrJ3s)I/ EHLFN6rrJcDeZdZUdZdZded<ded<ded<d ed <d ed <d ed<d ed<d ed<ded<ded< dZded< d- d.dZ d/dZe d0dZ e d1dZ e d1dZ e jej fej$ d- d2dZe jej fej$d3d4dZ d- d5dZd6d Zd3d7d!Zd6d"Ze jej fej$ d8d#Zd6d$Ze jej fej6d6d%Ze jej ej6fej:d3d9d&Ze jej ej>ej6fej: d: d;d'Z e jejBej:d3drzaA :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]] _connectionsryrOptional[SessionTransaction]_parentr_statez5weakref.WeakKeyDictionary[InstanceState[Any], object]_new_deleted_dirtyz>weakref.WeakKeyDictionary[InstanceState[Any], Tuple[Any, Any]] _key_switchesrJoriginFrDnestedcPtj|||_i|_||_|t j ux|_}||_|jtjurtjd|r)|stjd|j|_n|t j ur|J|Jt"j$|_|j)||j_|jj,j/|j|y)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_checkrrQrSrJrMrZrY _close_state_SessionCloseStaterrr_nested_transaction_previous_nested_transactionrNrrrT_take_snapshot _transactiondispatchafter_transaction_create)rrrYparentrZs rrzSessionTransaction.__init__s --g6  %)A)N)NNN f   #5#<#< <,,;  001 180K0KD - />> >% %%> !>-44  %) ! 66t||TJrc|tjurE|jr$tjd|jdtj d|tj urtjd|tjurtj ddtj d|jjd ) 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: 7s2a)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 permittediscezThis session is in 'z?' state; no further SQL can be emitted within this transaction.) rrrPrPendingRollbackErrorrrResourceClosedErrorrnamelower)roperation_namer!s r_raise_for_prerequisite_statez0SessionTransaction._raise_for_prerequisite_states +44 4''110150H0H/I K  00> -44 4,,-IJ J -EE E,,/  ,,&uzz'7'7'9&:;FF rc|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. )rSrs rrezSessionTransaction.parents||rcZ|jduxr|jtjuSr)rrTrrrs r is_activezSessionTransaction.is_actives- LL $ > 6=== rc8|jxs |j Sr)rZrSrs r_is_transaction_boundaryz+SessionTransaction._is_transaction_boundarys{{.$,,..rc `|jj|fi|}|j||Sr)rget_bind_connection_for_bind)rbindkeyrkwargsbinds r connectionzSessionTransaction.connections3%t||$$W77((/@AArczt|j|rtj|Stj|Sr)rzrrJrMrN)rrZs r_beginzSessionTransaction._beginsE" LL)55   .<<   rc|}d}|rJ||fz }|j|ur |S|jtjd|z|j}|rJ|S)Nrz4Transaction %s is not on the active transaction list)rSrr)ruptocurrentrs r_iterate_self_and_parentsz,SessionTransaction._iterate_self_and_parentsst13 wj F$& (00J "// rcJ|jsU|j}|J|j|_|j|_|j|_|j |_y|j tjtjfv}|s0|jjs|jjtj|_tj|_tj|_tj|_yr)rtrSrUrVrWrXrYrJrLrKr _flushingflushweakrefWeakKeyDictionary)rreis_begins rraz!SessionTransaction._take_snapshot0s,,\\F% %% DI"OODM --DK!'!5!5D  ;; $ * * $ . .#   6 6 LL   --/ 113 //1 $668rc|jsJt|jj|jj}|jj |d|j jD]^\}\}}|jjj|||_ ||vs:|jjj|`t|jj|jjD]}|jj|d!|jjrJ|jjjD]Y}|r|js||j vs |j#|j$|jjj&[y)zmRestore the restoration state taken before a transaction began. Corresponds to a rollback. T to_transient)revert_deletionN)rtrrUrr_expunge_statesrXitems identity_map safe_discardkeyreplacerV _update_impl all_statesmodifiedrW_expirer _modified)r dirty_only to_expungesoldkeynewkeys r_restore_snapshotz$SessionTransaction._restore_snapshotFsn ,,,,^))$,,*;*;<  $$Zd$C#'#5#5#;#;#= 5 A LL % % 2 21 5AE " ))11!4 5T]]#))$,,*?*?@ ?A LL % %a % > ?<<((((**557 GAqDKK/? !&&$,,";";"E"EF Grc<|jsJ|js|jjr|jjj D]<}|j |j|jjj>tjjt|j|j|jjy|jr|j}|J|j j#|j |j$j#|j$|jj#|j|j&j#|j&yy)zjRemove the restoration state taken before a transaction began. Corresponds to a commit. N)rtrZrexpire_on_commitrrrrrstatelibr4_detach_statesrrVclearrSrUrrWrX)rrres r_remove_snapshotz#SessionTransaction._remove_snapshotfs# ,,,,{{t||<<\\..99; G !&&$,,";";"E"EF G  " " 1 1T]]#T\\  MM   ! [[\\F% %% KK  tyy ) MM  - OO " "4== 1  ' '(:(: ; rc||jvr)|rtjd|j|dStj|_d}d} |j r?|j j||}|jsr|tj|_St|tjr/|}|j|jvr'tjd|j}d} |r|j d i|}|j"j$r|j |j'}n|jr|j)}n|j+r|j"j,}|dk(r0|j/rd}nd}|rtjd |d |d vr9|j/r|j1}n|j3}|dk(r0d}n-|dk(r|j)}nJ||j5}t|tj}|||| fx|j|<|j|j<|j"j6j9|j"|||tj|_S#|r|j;xYw#tj|_wxYw) 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)rrr)rQr<warnrrrTrSrwrZrrr:r=rrconnectrrtwophasebegin_twophase begin_nestedin_transactionjoin_transaction_modein_nested_transaction _get_required_nested_transaction_get_required_transactionbeginrc after_beginclose) rrzr local_connect should_commitconn transactionrbind_is_connections rrwz'SessionTransaction._connection_for_bind~s 4$$ $  <$$T*1- --EE   X 9||||88+{{d288DKadF$5$56D{{d&7&77$88@  <<>D$(MC $1411F4EFD<<((T\\-A #'"5"5"7K[["&"3"3"5K((*,0LL,N,N),0GG5574F14C1( II!L $9"; << #4<<+@+@,,!  rc||j |jr/|jjj |j|jj }|J||ur'|j |D]}|j|jjs[tdD]8}|jjrn1|jj:tjd|j]|jjrG t|j j#D]}t%d|dj'! t.j0|_y#t)j*5|j-dddn #1swYnxYwYTxYw)NrdzrOver 100 subsequent flushes have occurred within session.commit() - is an after_flush() hook creating new objects?r_r)rSrZrrc before_commitrbrcommitrrange _is_cleanrr FlushErrorrrrQvaluesrrr< safe_reraiserollbackrrrT)rstxsubtransaction _flush_guardts rrz SessionTransaction._prepare_implso << 4;; LL ! ! / / =ll'' d?"%"?"?T"?"J (%%' (||%% %c  <<))+ ""$  nn, << DLL$9$9 $T..5578@A.!5==?@ .66  $&&($MMO$$$s%!AE==F;F-$ F;-F6 2F;c|jtjur8|jtj5|j ddd|j |j rt|jjD]\}}}}|s |jtj|_|jjj|j|j|jtj 5|j#ddd|r*|j r|j jdyyy#1swYxYw#1swYCxYw)NT_to_root)rTrr _expect_staterrSrZrrQrrrrrc after_commitrrr)rrrtransr autocloses rrzSessionTransaction.commits- ;;5>> >##$;$D$DE %""$ % << 4;;9<!!((*: #5e]I!LLN  # 2;;DK LL ! ! . .t|| <  ! ! #    7 > > ?  JJL   LL    .%8% % %  sE& E3&E03E<c|jj}|J||ur'|j|D]}|j|}d}|jt j t jfvr|jD]}|j |jr t|jjD]}|djt j|_|jjj!|jt j|_|j'|j|}nt j|_|j} |sA| j)s1t+j,d|j'|j|j/t j05|jddd|jr(|r&t#j$d|j_|r|dr|dj5|d| jj7| ||r*|jr|jjdyyy#t#j$}YxYw#t j|_|j'|jwxYw#1swYxYw)Nrr)rz\Session's state has been changed on a non-active transaction - this state will be discarded.r9Tr)rrbrrrTrrrrSrZrrQrrrrcafter_rollbacksysexc_inforrr<rrrrPwith_tracebackafter_soft_rollback) r_capture_exceptionrrrboundary rollback_errrrsesss rrzSessionTransaction.rollback3sll'' d?"%"?"?T"?"J '$$& ' ;; # * * # , ,   $==? J &&.+2D2D !$[%=%=%D%D%F!G,AaDMMO,.E-M-M * --< > ?  JJL  <<./2||~a/@DLL , LOq/00aA A ))$5  LL ! !4 ! 0%8G6'*||~ -D-M-M *#55'2'9'96(  s%"A?JK!J(%J++3K!K*c|jr|j|j_|j|j_t |jjD]c\}}}}|r|j|j|r|jr|j|sG|jT|jetj|_|j}|jj!||yr)rZr`rr_rSrbrrQr invalidaterrrrrrTrcafter_transaction_end)rrr{rrrrs rrzSessionTransaction.closexs ;;11 LL ,%)LL !AD    $ $ &B  # =J ]Idll2%%'!6!6!!#T\\1  " #.44 || ++D$7rc|jSrrrs r _get_subjectzSessionTransaction._get_subjects ||rc:|jtjuSr)rTrrrs r_transaction_is_activez)SessionTransaction._transaction_is_active{{5<<<;1 ;1;1z!\   7 > >88>==6rrzceZdZdZdZdZy)r^rr9rN)rrrrrCLOSE_IS_RESETrrrr^r^s F FNrr^c. eZdZUdZdZded<ded< ded<ded <d ed <d ed <ded<ded<ded<ded<ded<ded<ded<ded<ded<ded<ded<ded< dd!d!d!d!dd d!d d dd"ejd# dd$Zd Z d%ed&<d Z d'ed(<dd)Z dd*Z e jdd+Zdd,Zdd-Zdd.Zdd/Zej*dd0Zddd1Zddd2Zdd3Zdd4Zdd5Zdd6Z d dd7Z d dd8Ze dej@d d d d9d: dd;Z!e dej@d d d d9d: dd<Z! dej@d d d dd: dd=Z!e dej@d d d d> dd?Z"e dej@d d d d> dd@Z" dej@d d d d> ddAZ"e dej@d dB ddCZ#e dej@d dB ddDZ# dej@d dB ddEZ#e dej@d dB ddFZ$e dej@d dB ddGZ$ dej@d dB ddHZ$ddIZ%ddJZ&ddKZ'dddLZ(ddMZ)ddNZ* ddOZ+ddPZ, dd d d ddQ ddRZ-eddSZ.e ddTZ.e ddUZ.e ddVZ.e ddWZ.e ddXZ.e ddYZ.e ddZZ.e dd[Z.e dd\Z. dd]Z.d e/j`d ej@d f dd^Z1ejde jdd_Z3ejhjkd`e6jnddaZ8 d ddbZ9ddcZ: d dddZ; ddeZ< d ddfZ=ddgZ> d ddhZ?ddiZ@ddjZA ddkZBdddlZCddmZDddnZEddoZF ddpZGd dd d ej@d dq ddrZHd dd d ej@d dq ddsZId dd d ej@d dq ddtZJd!d du ddvZKd dw ddxZLddyZMddzZN d dd{ZOdd|ZPdd}ZQdd~ZRddZSddZTddZUddZVdddZWddZXddZYdddZZ d ddZ[ d ddZ\ ddZ] ddZ^ d ddZ_e`ddZae`ddZbe`ddZce`ddZde`ddZey )rya 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]rcr2rzDict[InstanceState[Any], Any]rUrVz#Optional[Union[Engine, Connection]]rzz#Dict[_SessionBindKey, _SessionBind]_Session__bindsrDr_warn_on_eventsrRrbr_rhash_key autoflushrenable_baked_queriesrJoinTransactionModerzType[Query[Any]] _query_clsr^r]NTr) rfuturer autobeginrbindsrinfo query_cls autocommitrclose_resets_onlyc 6| rtjdtj|_|stjdi|_i|_||_i|_d|_ d|_ d|_ d|_ t|_||_||_||_||_| dt&j(fvrt*j,|_nt*j0|_| r+| t2j4vrtjd| d| |_||_| r| nt:j<|_| r|j@jC| |*|jED]\}}|jG|||tH|j<y)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.FNTz.invalid selection for join_transaction_mode: "")%r ArgumentErrorrWeakInstanceDictrrUrVrzrrrrbr__new_sessionidrrrrrrJNO_ARGr^rr]rr__args__rrrr3rrrr _add_bindr)rrzrrrrrrrrrrrrrs rrzSession.__init__sn &&8 %557&&5      $ #' &( "" 0$8! v}} 5 5 2 A AD  2 9 9D  !%&//0&&)*!- &;"  '0)ekk  II  T "  "[[] * TsD) *$( $-- rzOptional[TransactionalContext]_trans_context_managerz"Optional[_ConnectionCallableProto]connection_callablec|Srrrs r __enter__zSession.__enter__ s rc$|jyr)r)rtype_value tracebacks r__exit__zSession.__exit__s  rc#K|5|j5|ddddddy#1swYxYw#1swYyxYwwrrrs r_maker_context_managerzSession._maker_context_managersE           s(A8,8 A5 8AAc|jduS)zReturn True if this :class:`_orm.Session` has begun a transaction. .. versionadded:: 1.4 .. seealso:: :attr:`_orm.Session.is_active` N)rbrs rrzSession.in_transactions  ,,rc|jduS)zReturn True if this :class:`_orm.Session` has begun a nested transaction, e.g. SAVEPOINT. .. versionadded:: 1.4 Nr_rs rrzSession.in_nested_transaction&s''t33rcp|j}|'|j|j}| |j|S)zaReturn the current root transaction in progress, if any. .. versionadded:: 1.4 )rbrSrrs rget_transactionzSession.get_transaction/s= !!EMM$=MMEEMM$= rc|jS)zcReturn the current nested transaction in progress, if any. .. versionadded:: 1.4 rrs rget_nested_transactionzSession.get_nested_transaction:s'''rciS)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. rrs rrz Session.infoCs  rc|ja|s!|jstjdt ||rt j nt j}|j|usJ|S|jS)Nz]Autobegin is disabled on this Session; please call session.begin() to start a new transaction)rbrrrrzrJrLrK)rrrs r _autobegin_tzSession._autobegin_tPs    $00A'-221;; E$$- --L   rc|j}||jd}|s|S|J|r+|j|}|j|usJ||_|St j d)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` TrrZz/A transaction is already begun on this Session.)rbrr}r_rr)rrZrs rrz Session.begindsF!! =%%D%1E    LLL/E$$- --',D $  ,,A rc&|jdS)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`. Tr rrs rrzSession.begin_nesteds0zzz&&rcV|jy|jjdy)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` NTr)rbrrs rrzSession.rollbacks*    $     & & & 5rcd|j}||j}|jdy)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` NTr)rbrrrs rrzSession.commits1@!! =%%'E d #rc`|j}||j}|jy)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)rbrrrs rrzSession.prepares+!! =%%'E rc|r'|jdd}|#|jdi|}n|j}|j||S)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` rzNrr)poprvrw)rrrrzs rr{zSession.connections[F !%%fd3D|$t}}6~6==?D(( /)  rc tj||j}||j}|j ||Sr)r?r\rbrrw)rr:rrrs rrwzSession._connection_for_bind1sD --d3!! =%%'E))&2CDDr.)rrr _add_event_scalar_resultcyrrrrrrrrr)r*s rrzSession._execute_internal>srcyrrr,s rrzSession._execute_internalKsrc Ttjtj|}|si}n t |}|j j dddk(r8tj|d}tr0t|tjsJd}|jd|tj|}|r|j!} n'|j"j$} |rt'| |gz} | r||j)|||||d\}}t+||||||| } t-| D].\} } | | _| | } | s|r| j1cS| cS| j2}| j4}||j)|||||d\}}|j6di|}|j9|}|r0|s.trt;t<|}|j1||xsi|S|r|j?|||xsi|||}n|jA||xsi|}|r|j1S|S)Ncompile_state_pluginormclauseTFr&r)!rDexpectrF StatementRoler_propagate_attrsrrK_get_plugin_class_for_pluginrrrAbstractORMCompileState setdefaultr<coerce_to_immutabledictrrcdo_orm_executerorm_pre_session_execr| enumeraterscalarrrrvrwrraorm_execute_statementexecute)rrrrrrr)r*rrorm_exec_stateidxfn fn_resultrzrrs rrzSession._execute_internalXs$$U%8%8)D N!.1N  & & * *+A4 H !- I I5! !%w'F'F!%   % %h : 889JK /AACK--66K";/:,>  ,&::%" %-!!N%[1 )R58235n3E %(//11(( )'00I . F F   ("66!  !t}}.~.((. "36?;;6zSession.executesrcyrrrEs rr>zSession.executesrc0|j||||||S)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. rCrrEs rr>zSession.executes/x%%  /)"7! &  r)rrc yrrrrrrrrs rr<zSession.scalar8 src yrrrJs rr<zSession.scalarC src 2|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)rrr*rHrJs rr<zSession.scalarN s9"&t%%   0)     rc yrrrJs rscalarszSession.scalarsh src yrrrJs rrNzSession.scalarss s rc N|j|f|||dd|jS)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*)rrNrJs rrNzSession.scalars~ s@:&t%%  /)     ') rc(|jdy)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_implrs rrz Session.close sN E*rc*|jddy)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_resetNrSrs rresetz Session.reset s. ED9rc(|jdy)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. TrRNrSrs rrzSession.invalidate sD D)rc|s1|jtjurtj|_|j |j 1|j j D]}|j|yyr)r]r^rr expunge_allrbrr)rrrVrs rrTzSession._close_impl spD--1C1J1JJ 2 9 9D      (#00JJL . !!*- . )rc&|jjt|jz}|jj t j |_i|_i|_tjj||y)zRemove all object instances from this ``Session``. This is equivalent to calling ``expunge(obj)`` on all objects in this ``Session``. N) rrrrU_killrrrVrr4r)rrs rrZzSession.expunge_all sl&&113d499oE  !$557  --j$?rc t|}trt|tsJt|tr||j |<yt |r:||j |j<|jD]}||j |<ytjd|z#tj$rB}t|tstjd|z|||j |<Yd}~yd}~wwxYw)Nz!Not an acceptable bind target: %s) rBrrrCrHrr#r _all_tablesrrNoInspectionAvailabletype)rrrzr _selectableerrs rrzSession._add_bind" s 3fnyyyy 22!   #*6?  $  << +22::1Cdll*#||C001>-@@F!!'!8!8! s BErcyrr)rryrzr|r~rr_Session__ent6s rrz Session.queryI s GJrc yrr) rryrzr|r~rrr_Session__ent7s rrz Session.queryU s LOrcyrrrentitiesrys rrz Session.queryd src*|j||fi|S)aReturn a new :class:`_query.Query` object corresponding to this :class:`_orm.Session`. Note that the :class:`_query.Query` object is legacy as of SQLAlchemy 2.0; the :func:`_sql.select` construct is now used to construct ORM queries. .. seealso:: :ref:`unified_tutorial` :ref:`queryguide_toplevel` :ref:`query_api_toplevel` - legacy API doc )rrs rrz Session.queryi s(tx888rc\|j||}tj||||} | S)ayLocate an object in the identity map. Given a primary key identity, constructs an identity key and then looks in the session's identity map. If present, the object may be run through unexpiration rules (e.g. load unloaded attributes, check if was deleted). e.g.:: obj = session._identity_lookup(inspect(SomeClass), (1,)) :param mapper: mapper in use :param primary_key_identity: the primary key we are searching for, as a tuple. :param identity_token: identity token that should be used to create the identity key. Used as is, however overriding subclasses can repurpose this in order to interpret the value in a special way, such as if None then look among multiple target tokens. :param passive: passive load flag passed to :func:`.loading.get_from_identity`, which impacts the behavior if the object is found; the object may be validated and/or unexpired if the flag allows for SQL to be emitted. :param lazy_loaded_from: an :class:`.InstanceState` that is specifically asking for this identity as a related identity. Used for sharding schemes where there is a correspondence between an object and a related object being lazy-loaded (or otherwise relationship-loaded). :return: None if the object is not found in the identity map, *or* if the object was unexpired and found to have been deleted. if passive flags disallow SQL and the object is expired, returns PASSIVE_NO_RESULT. In all other cases the instance is returned. .. versionchanged:: 1.4.0 - the :meth:`.Session._identity_lookup` method was moved from :class:`_query.Query` to :class:`.Session`, to avoid having to instantiate the :class:`_query.Query` object. )r)identity_key_from_primary_keyrget_from_identity) rrprimary_key_identityrpassiver"rrr return_values r_identity_lookupzSession._identity_lookup s=f22 3  00vsGL rc#bK|j}d|_ |||_y#||_wxYww)agReturn a context manager that disables autoflush. e.g.:: with session.no_autoflush: some_object = SomeClass() session.add(some_object) # won't autoflush some_object.related_thing = session.query(SomeRelated).first() Operations that proceed within the ``with:`` block will not be subject to flushes occurring upon query access. This is useful when initializing a series of objects which involve existing database queries, where the uncompleted object should not yet be flushed. FN)r)rrs r no_autoflushzSession.no_autoflush s0*NN  'J&DNYDNs/#/ ,/zThis warning originated from the Session 'autoflush' process, which was invoked automatically in response to a user-initiated operation. Consider using ``no_autoflush`` context manager if this warning happened while initializing objects.c|jr|js |jyyy#tj$r<}|j d|j tjdd}~wwxYw)Nzraised as a result of Query-invoked autoflush; consider using a session.no_autoflush block if this flush is occurring prematurelyr9) rrrrStatementError add_detailrrr)res r _autoflushzSession._autoflush so >>$.. : #1>(( :  5 &&s||~a'899 :s-A<7A77A<c  tj|}|j |||j |ik(rtjdtj|}tjt|}tj|||j |||ddd !tj"dt%|zy#tj$r}tj||d}~wwxYw)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) refresh_statewith_for_updateonly_load_propsrequire_pk_colsris_user_refreshzCould not refresh instance '%s')rinstance_staterNO_STATEUnmappedInstanceError _expire_staterrrrM_from_argumentr;selectr,r load_on_identrrr*)rrattribute_namesrr!rbstmts rrefreshzSession.refresh sV ?--h7E 5/2  b &&3  '55oFJJ}X'>?  ! ! # / / $" $   ,,1L4JJ ! 1|| ?++H53 > ?sCC?$C::C?c|jjD]2}|j|j|jj4y)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)rrrrrrr!s r expire_allzSession.expire_allf sC@&&113 CE MM%**d&7&7&A&A B Crc tj|}|j ||y#tj$r}tj||d}~wwxYw)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!rbs rexpirezSession.expire sSN ?--h7E 5/2|| ?++H53 > ?s*AAAc|j||r|j|j|yt|jj j d|}|j||D]\}}}}|j|y)Nzrefresh-expire)_validate_persistent_expire_attributesrrmanagerrcascade_iterator_conditional_expire)rr!rcascadedomst_dct_s rrzSession._expire_state s !!%(   $ $UZZ A $$556FNH  $ $U +#+ .1c4((- .rc|jr1|j|j|jjy||j vr-|j j ||j|yy)z5Expire a state if persistent, else expunge if pendingN)rrrrrrUr'_detach)rr!rs rrzSession._conditional_expire sV 99 MM%**d&7&7&A&A B dii  IIMM% MM$  rc  tj|}|j |j ur!tjdt|zt|jjjd|}|j|g|Dcgc] \}}}}| c}}}}zy#tj$r}tj||d}~wwxYwcc}}}}w)zRemove the `instance` from this ``Session``. This will free all internal references to the instance. Cascading will be applied according to the *expunge* cascade rule. Nz*Instance %s is not present in this Sessionexpunge)rrrrr session_idrrrr/rrrrr) rrr!rbrrrrrs rrzSession.expunge s ?--h7E   4== 0,, ?(MsB.C.CCCc|D]}||jvr|jj|-|jj|r8|jj ||j j|d|j s|j j j|dtjj|||y)Nr) rUr'rcontains_staterrVrbrr4r)rstatesrr!s rrzSession._expunge_states s z/Session._register_persistent..? s 5UeUZZ 5s)rcpending_to_persistentr)rs_identity_key_from_stater( intersectionallow_partial_pks issupersetrrr/rrrrbrXrr<r_orphaned_outside_of_sessionrr4_commit_all_states_register_alteredrUrr') rrrr!rrs instance_keyrorig_keyolds r_register_persistentzSession._register_persistent s7!% C C Kt: ;E"5)F))+C%>>uE **<?;"44 ++LO<..?$E*+  99$ ,EIYY,.%%2259 --E ,,, 3 33#(#6#6u#=a#@#(99 $2E''.!-EI ''//6O77< L -II0<> 6;2u: ;x 11 5f 5t7H7H  v& ,,,TYY7 3%dE2 3[--dii8 !E IIMM%  !rc|jrI|D]C}||jvrd|jj|<+d|jj|<EyyNT)rbrUrW)rrr!s rrzSession._register_alteredL sW    ;DII%48D%%**516:D%%,,U3  ; rcH|jjxsd}|D]}|jrd|jj|<||j }|j j ||jj|dd|_|{|||yr)rcpersistent_to_deletedrbrVrsrrr')rrrr!rss r_remove_newly_deletedzSession._remove_newly_deletedT s!% C C Kt 3E  48!!**51$0iik    * *5 1 MM  eT *!EN%0%dE2! 3rc|r|jr|jd tj|}|j|y#tj $r}t j ||d}~wwxYw)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)rr_warnr!rbs rrz Session.addj sk2 T))    0 ?--h7E ""5)|| ?++H53 > ?sAA6A11A6cr|jr|jd|D]}|j|dy)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)r instancesrs radd_allzSession.add_all s;       3 4! ,H HHXUH + ,rcd|_|j|t|}|jd||jD]\}}}}|j|y)NFz save-update)halt_on)r_save_or_update_implr)r_contains_state)rr!rrrrrs rrzSession._save_or_update_state sf-2* !!%(u%%66 5$*>*> 7  +OAq#t  % %c * +rc|jr|jd tj|}|j||dy#tj $r}t j ||d}~wwxYw)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!rbs rdeletezSession.delete sq*       2 3 ?--h7E %5|| ?++H53 > ?sA A7A22A7c|j$|r!tjdt|zy|j ||}||j vry|j j||r|j|||r0t|jjjd|}nd}||j |<|r*tr|J|D]\}}}} |j||dyy)NInstance '%s' is not persistedrF)rrrr/_before_attachrVrr _after_attachrrrrrr) rr!rsr to_attachcascade_statesrrrrs rrzSession._delete_impl s 99 004y7GG''s3 DMM !  e$    uc * " $$55hFN"N" e %111#1 11c4!!#q%0 1 roptionspopulate_existingrrrrc R|j||tj|||||| 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_implrload_on_pk_identity) rrrrrrrrrs rrz Session.get s<^~~    ' '/+)/)  rc f|j||||||||} | tjd| S)a+Return exactly one instance based on the given primary key identifier, or raise an exception if not found. Raises :class:`_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 rz&No row was found when one was required)rr NoResultFound) rrrrrrrrrrs rget_onezSession.get_onelsU@88  /+)/)    &&8 rc tr?ttjvr$tjt} | t |} | | j st jd|ztt} | stjdgtt| jk7r8t jddjd| jDz| rf| j } | r9t#| j%}|rt|D] }|| |< t'fd| j(D|sS| j,sG|E|j/| ||| }|t|| j0sy|S|t2j4usJt6j8j:}|r|d |iz }t=j>| jAtB}|tEjF||_$|r|jJ|}||||||| S#t*$r>}t jddjd| j(Dz|d}~wwxYw) 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,c3&K|] }d|z ywz'%s'Nr)rcs rrz$Session._get_impl..s#K1FQJ#Ksc3<K|]}|jywrr)rproprs rrz$Session._get_impl..s",)2,szIncorrect names of values in identifier to formulate primary key for session.get(); primary key attribute names are %s (synonym names are also accepted)c3:K|]}d|jzywrr)rrs rrz$Session._get_impl..s! )s)rrr_populate_existing)r rrr)&r$r`r_composite_gettersrB is_mapperrrrrr<to_listr primary_keyrrq _pk_synonymsrrr_identity_key_propsKeyErroralways_refreshrrr+PASSIVE_CLASS_MISMATCHrr/r0r;rset_label_stylerNrMr_for_update_argr)rrr db_load_fnrrrrrrgetterris_dict pk_synonyms correct_keyskrbrr rs ` rrzSession._get_impls 3 4)*223&88)*F$**>#? '.v >!1!1&&:VC 148#'<<$tf$  # $F,>,>(? ?,,88#K8J8J#KKL   --K";/<<(   +/0D+E()03-[^<  '+, & : :,($""))',,$-"3- -H#"(FMM:#7#N#NN NN ++@@  13DE ELJJv&66 *   &(4(C(C)I % ) ))73I   %)/)  i 00Ehh$*$>$> s I J  9JJ )loadrcF|jr|jdi}i}|r|jt||j} d|_|j t j|t j|||||||_S#||_wxYw)a Copy the state of a given instance into a corresponding instance within this :class:`.Session`. :meth:`.Session.merge` examines the primary key attributes of the source instance, and attempts to reconcile it with an instance of the same primary key in the session. If not found locally, it attempts to load the object from the database based on primary key, and if none can be located, creates a new instance. The state of each attribute on the source instance is then copied to the target instance. The resulting target instance is then returned by the method; the original source instance is left unmodified, and un-associated with the :class:`.Session` if not already. This operation cascades to associated instances if the association is mapped with ``cascade="merge"``. See :ref:`unitofwork_merging` for a detailed discussion of merging. :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)rr _recursive_resolve_conflict_map) rrrr,r_mergerr instance_dict)rrrrrrrs rmergez Session.merges|       1 279 EG  OO hNN  '"DN;;))(3((2%&; 'DNYDNs AB B )rc t|}||vrtt||Sd}|j} | ||jvr!t j dt|z|stjd|j|} tj| dvxrBtj| d xs'|jxrtj | d } nd} |j"j%| } | | r| |vrtt|| } n|sk|j&rtjd|j(j+} t-j.| } | | _|j1| d}n'| r%|j%|j2| d| d|} | X|j(j+} t-j.| } t-j4| } d}|j7| n*t-j.| } t-j4| } | ||<| || <|| ur|j8|j;|||j8t<j> }|j;| | |j8t<j> }|tj@ur?|tj@ur-||k7r(tCjDd |d t| d |d |jF| _#|jH| _$| jK||jLD]}|jO|||| | ||||sB| jQ| |j"| jRjTjW| d|r&| jRjTjY| 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)rrrz Version id 'z' on merged state z" does not match existing version 'zT'. Leave the version attribute unset when merging to update the most recent version.)-r)rr"rrUr<rr/rrrr+ NEVER_SETr(rrrrrr class_manager new_instancerrrrrrversion_id_col_get_state_attr_by_columnr.PASSIVE_NO_INITIALIZEPASSIVE_NO_RESULTrStaleDataError load_pathr _copy_callablesiterate_propertiesr _commit_allrrc_sa_event_merge_wo_loadr)rr! state_dictrrrrrrrkey_is_persistentmerged merged_state merged_dictexisting_versionmerged_versionrs rrzSession._mergets+51 J Ju-. . ii ; ! './ 00" 11%8C 4 > >cG!!**3q622,,9%00Q88 !% ""&&s+ > S,A%Ab"7"<=>> 44K  --::<)88@ #&  !!,/# "MMF#&q6# " >))668F%44V  //6,,EE"# 7rc:|j!tjdt|z|j }|j ||}||j vr)||j |<t|j |_|r|j||yy)NzGObject '%s' already has an identity - it can't be registered as pending) rrrr/rsrrUr insert_orderr)rr!rsrs r _save_implzSession._save_impls 99 ,,46?6FG  iik''s3  !"DIIe !$TYYE     uc * rc8|j!tjdt|z|jr3|r|j sy|`n!tjdt|z|j }|y|j||}|jj|d|r|jj|n|jj||r|j||y|r|jj||yy)NrzsInstance '%s' has been deleted. Use the make_transient() function to send this object back to the transient state.)rrrr/rV _attachedrsrr'rrrrrcdeleted_to_persistent)rr!rrsrs rrzSession._update_impl)s 99 ,,09U3CC  >>N00.1:%0@Aiik ; ''s3  %&     % %e ,    ! !% (    uc *  MM / /e <rcb|j|j|y|j|yr)rr1rrs rrzSession._save_or_update_implQs& 99  OOE "   e $rc tj|}|j ||}d|_|r|j||yy#tj$r}tj||d}~wwxYw)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 _load_pendingr)rrsr!rbrs renable_relationship_loadingz#Session.enable_relationship_loadingWsun :--c2E''s3 "    uc *  || :++C0c 9 :sAA4A//A4c D|j|j|jk(ry|jrN|jtvr>e//7 #E  ""4/ 99 MM 0 0u = MM . .tU ;rc tj|}|j |S#tj$r}tj||d}~wwxYw)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)rrrrrrrs r __contains__zSession.__contains__sS ?--h7E##E**|| ?++H53 > ?s(AAActt|jjt|jjzS)zWIterate over all pending or persistent instances within this Session. )iterrrUrrrs r__iter__zSession.__iter__s?  !!# $tD,=,=,D,D,F'G G  rcX||jvxs|jj|Sr)rUrrrs rrzSession._contains_states' !LT%6%6%E%Ee%LLrc|jrtjd|jry d|_|j |d|_y#d|_wxYw)aFlush all the object changes to the database. Writes out all pending object creations, deletions and modifications to the database as INSERTs, DELETEs, UPDATEs, etc. Operations are automatically ordered by the Session's unit of work dependency solver. Database operations will be issued in the current transactional context and do not affect the state of the transaction, unless an error occurs, in which case the entire transaction is rolled back. You may flush() as often as you like within a transaction to move changes from Python to the database's transaction buffer. :param objects: Optional; restricts the flush operation to operate only on elements that are in the given collection. This feature is for an extremely narrow set of use cases where particular objects may need to be operated upon before the full flush() occurs. It is not intended for general use. zSession is already flushingNTF)rrrr_flush)robjectss rrz Session.flushsQ. >>,,-JK K >>   #!DN KK "DNUDNs A Ac4tjd|zy)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)rmethods rrzSession._flush_warnings!  FIO O rct|jj xr|j xr |j Sr)rcheck_modifiedrVrUrs rrzSession._is_cleans9!!002 2 MM! II  rcF|j}|s=|js1|js%|jjj yt |}|jjr)|jj||||j}t|j}t|j}t|j|}|r9t}|D])} tj|}|j!|+nd}t} |r0|j#|j%|j|} n |j#|j|} | D]|}t'|j)|} | xr |j*} | r!| s|j,r|j/|gP|j1|| }|sJd| j!|~|r!|j%|j| } n|j| } | D]}|j1|d}|rJd|j2sy|j5j7x|_} d|_ |j=d|_|jj?|||jA|s|jjrtC|jj}tDjFjI|jjDcgc]}||jJfc}|jtMjNd|z|jjQ|||jSy#tj$r} tj|| d} ~ wwxYw#d|_wxYwcc}w#tMjT5|jWddddYy#1swYYyxYwxYw)N)isdeletez*Failed to add object to the flush context!TF)rzAttribute history events accumulated on %d previously clean instances within inner-flush event handlers have been reset, and will not result in database updates. Consider using set_committed_value() within inner-flush event handlers to avoid this warning.r), _dirty_statesrVrUrrrr8rc before_flushr differencerrrrrrrrr) _is_orphan has_identityrrregister_objecthas_workrr}rrr> after_flushfinalize_flush_changesrrr4rrr<rafter_flush_postexecrrr)rrIdirty flush_contextdeletednewobjsetrr!rb processedproc is_orphanis_persistent_orphan_regrlen_s rrHzSession._flushs""T]]499    ' ' - - / &t, == % % MM & &t]G D&&Edmm$$))nE %%g. UF "@&55a8E 5!  "FE  99U#008CCGLD99U#..w7D %E%e,77>I#,#C1C1C ,66$$eW-$44$85IIIt e$! %& ''/::9ED%%i0D FE 000FD EE E4 F%% 262C2C2E2L2L2NN !K+ >#'D  -%%'',$ MM % %dM :  0 0 2t00::4,,667&&99&*%6%6%@%@! +#'"3"3 : H KO O MM . .t] C    m||@33A6C?@h(-$4 >""$ >$$$= > > >sh,N>O OBO 1OAO O 1OO  OO P 6P P P P P c d|D}|st|d} d d}tj||D] \\}}} |j|| |d||d"y) 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` c3FK|]}tj|ywr)rr)rrss rrz,Session.bulk_save_objects..sHj//4Hs!cHt|j|jdufSr)idrrr s rz+Session.bulk_save_objects..s2ell#3UYYd5J"Krrc6|j|jdufSr)rrr s r grouping_keyz/Session.bulk_save_objects..grouping_keysLL%))4"78 8rTFisupdateisstatesreturn_defaultsupdate_changed_only render_nullsN)r!InstanceState[_O]rzTuple[Mapper[_O], bool])sortedrgroupby_bulk_save_mappings) rrIrprqpreserve_order obj_statesrlrrnrs rbulk_save_objectszSession.bulk_save_objectsusVIH   KJ  9$ 9 $ 9 +4*;*;  +  & VX  $ $! /$7" %  rc 4|j||dd|d|y)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` FrmNrv)rrmappingsrprrs rbulk_insert_mappingszSession.bulk_insert_mappingss-R    + %% ! rc 4|j||dddddy)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` TFrmNr{)rrr|s rbulk_update_mappingszSession.bulk_update_mappings1s-L    ! % ! rct|}d|_|jj} |rt j |||||nt j |||||||jd|_y#tj5|jddddn #1swYnxYwYHxYw#d|_wxYw)NT)rorq)rorprrrPF) r'rrr}r _bulk_update _bulk_insertrr<rr) rrr|rnrorprqrrrs rrvzSession._bulk_save_mappingsas"&)'')002  # --%(; !--%$3!-     #DN  >""$ >$$$= > > >#DNs0ABCB4+ C4B= 9CC CcLt|}|jsy|j}|jjD]g}|st |j dst |j ds2|j j||tj\}}}|s|sgyy)aD Return ``True`` if the given instance has locally modified attributes. This method retrieves the history for each instrumented attribute on the instance and performs a comparison of the current value to its previously flushed or committed value, if any. It is in effect a more expensive and accurate version of checking for the given instance in the :attr:`.Session.dirty` collection; a full test for each attribute's net "dirty" status is performed. E.g.:: return session.is_modified(someobject) A few caveats to this method apply: * Instances present in the :attr:`.Session.dirty` collection may report ``False`` when tested with this method. This is because the object may have received change events via attribute mutation, thus placing it in :attr:`.Session.dirty`, but ultimately the state is the same as that loaded from the database, resulting in no net change here. * Scalar attributes may not have recorded the previously set value when a new value was applied, if the attribute was not loaded, or was expired, at the time the new value was received - in these cases, the attribute is assumed to have a change, even if there is ultimately no net change against its database value. SQLAlchemy in most cases does not need the "old" value when a set event occurs, so it skips the expense of a SQL call if the old value isn't present, based on the assumption that an UPDATE of the scalar value is usually needed, and in those few cases where it isn't, is less expensive on average than issuing a defensive SELECT. The "old" value is fetched unconditionally upon set only if the attribute container has the ``active_history`` flag set to ``True``. This flag is set typically for primary key attributes and scalar object references that are not a simple many-to-one. To set this flag for any arbitrary mapped column, use the ``active_history`` argument with :func:`.column_property`. :param instance: mapped instance to be tested for pending changes. :param include_collections: Indicates if multivalued collections should be included in the operation. Setting this to ``False`` is a way to detect only local-column based properties (i.e. scalar columns or many-to-one foreign keys) that would result in an UPDATE for this instance upon flush. Fget_collection get_historyrT) r-rrrrhasattrimplrr.r) rrinclude_collectionsr!dict_attradded unchangedr]s r is_modifiedzSession.is_modifiedsjX&~~ MM,, D'DII'78TYY 6*.))*?*?uk&;&;+@+ 'UIw rcN|jduxs|jjS)a4True if this :class:`.Session` not in "partial rollback" state. .. versionchanged:: 1.4 The :class:`_orm.Session` no longer begins a new transaction immediately, so this attribute will be False when the :class:`_orm.Session` is first instantiated. "partial rollback" state typically indicates that the flush process of the :class:`_orm.Session` has failed, and that the :meth:`_orm.Session.rollback` method must be emitted in order to fully roll back the transaction. If this :class:`_orm.Session` is not in a transaction at all, the :class:`_orm.Session` will autobegin when it is first used, so in this case :attr:`_orm.Session.is_active` will return True. Otherwise, if this :class:`_orm.Session` is within a transaction, and that transaction has not been rolled back internally, the :attr:`_orm.Session.is_active` will also return True. .. seealso:: :ref:`faq_session_rollback` :meth:`_orm.Session.in_transaction` N)rbrrrs rrrzSession.is_actives&8  D(GD,=,=,G,GGrc6|jjS)zThe set of all persistent states considered dirty. This method returns all states that were modified including those that were possibly deleted. )rrQrs rrQzSession._dirty_statess  ..00rct|jDcgc] }||jvr|j"c}Scc}w)aZThe set of all persistent instances considered dirty. E.g.:: some_mapped_object in session.dirty Instances are considered dirty when they were modified but not deleted. Note that this 'dirty' calculation is 'optimistic'; most attribute-setting or collection modification operations will mark an instance as 'dirty' and place it in this set, even if there is no net change to the attribute's value. At flush time, the value of each attribute is compared to its previously saved value, and if there's no net change, no SQL operation will occur (this is a more expensive operation so it's only done at flush time). To check if an instance has actionable net changes to its attributes, use the :meth:`.Session.is_modified` method. )rOrQrVrsrs rr[z Session.dirtysF0"//  -     s%Acntjt|jj S)zDThe set of all instances marked as 'deleted' within this ``Session``)r<rOrrVrrs rr]zSession.deleteds'T]]%9%9%; <==rcntjt|jj S)zAThe set of all instances marked as 'new' within this ``Session``.)r<rOrrUrrs rr^z Session.new$s'TYY%5%5%7 899rr)rzOptional[_SessionBind]rrDr Literal[True]rrDrrDrrDrz-Optional[Dict[_SessionBindKey, _SessionBind]]rrDrOptional[_InfoType]rzOptional[Type[Query[Any]]]rzLiteral[False]rrrzUnion[bool, _NoArg])r_Srr)r rrrrrrr)rrrz Iterator[_S]rCr)rrgr)rrDrrzr)rrzrr)rrArrrr=)r:rrrrrrr=)rrqr"Optional[_CoreSingleExecuteParams]rrUrrArrr)rr*rrr)rrqrrrrUrrArrr)rr*rDrrB)rrqrrrrUrrArrr)rr*rDrr)rzTypedReturnsRows[_T]rrrrUrrArrr)rrz Result[_T])rrqrrrrUrrArrr)rrrB) rTypedReturnsRows[Tuple[_T]]rrrrUrrArrrz Optional[_T]) rrqrrrrUrrArrrr) rrrrrrUrrArrrzScalarResult[_T]) rrqrrrrUrrArrrzScalarResult[Any])rrDrVrDrr)r_SessionBindKeyrzrrr)r_EntityBindKey[_O]rzrrr)rfrHrzrrr)rzOptional[_EntityBindKey[_O]]r1zOptional[ClauseElement]rzrrOptional[bool]rhrDrrrzUnion[Engine, Connection])ruz_EntityType[_O]rz Query[_O])rwzTypedColumnsClauseRole[_T]rzRowReturningQuery[Tuple[_T]])ry _TCCA[_T0]rz _TCCA[_T1]rz"RowReturningQuery[Tuple[_T0, _T1]])ryrrzrr| _TCCA[_T2]rz'RowReturningQuery[Tuple[_T0, _T1, _T2]]) ryrrzrr|rr~ _TCCA[_T3]rz,RowReturningQuery[Tuple[_T0, _T1, _T2, _T3]]) ryrrzrr|rr~rr _TCCA[_T4]rz1RowReturningQuery[Tuple[_T0, _T1, _T2, _T3, _T4]])ryrrzrr|rr~rrrr _TCCA[_T5]rz6RowReturningQuery[Tuple[_T0, _T1, _T2, _T3, _T4, _T5]])ryrrzrr|rr~rrrrrr _TCCA[_T6]rz;RowReturningQuery[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6]])ryrrzrr|rr~rrrrrrrrz _TCCA[_T7]rz@RowReturningQuery[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6, _T7]])rz_ColumnsClauseArgument[Any]ryrrz Query[Any])rrrrrrrr.r"rErrUrrArz)Union[Optional[_O], LoaderCallableStatus])rzIterator[Session])rrrOptional[Iterable[str]]rrurr)rrrrrr)r!InstanceState[Any]rrrr)r!rrrrrrrrr)rIterable[InstanceState[Any]]rrDrr)rzSet[InstanceState[Any]]rr)rrrr)T)rrrrDrr)rIterable[object]rr)r!rrr)r!rrsrrrDrr)rrr_PKIdentityArgumentrOptional[Sequence[ORMOption]]rrDrrurrrrUrrAr Optional[_O])rrrrrrrrDrrurrrrUrrArr")rrrrr zCallable[..., _O]rz$Optional[Sequence[ExecutableOption]]rrDrrurrrrUrrArr)rr"rrDrrrr")r!rsr'rTrrrrDrzDict[Any, object]rz#Dict[_IdentityKeyType[Any], object]rr")r!rrrDrr)rsrrr)r!rrsrrrD)r!rrsrrr)rrrrD)rzIterator[object])r!rrrD)rIzOptional[Sequence[Any]]rr)rKrrr)rIzOptional[Sequence[object]]rr)FTT) rIrrprDrqrDrwrDrrr) rrr|Iterable[Dict[str, Any]]rprDrrrDrr)rrr|rrr)rrr|zr<rNrrWrrTrZrrrgrvrr. PASSIVE_OFFrnon_memoized_propertyr langhelperstag_method_for_warningsr SAWarningrrrrrrrrrrrrrrrrrrrrrrr1rrr8rrrBrErrrrrHryr}rrvrrHrrrQr[r]r^rrrryrysK!!  ('++ -- 00O..55MON..  $$(,k( $!%?C%)$(04%*5L17k($k( k(  k(  k(k(k(=k(#k("k(.k(#k( 3k(/k(\ >B:A>B;B -4 (   !(5n'46*$$L&48CG. 0. A.   . fDH E EA E E  E6:  9=37/3$((+  3  6  1  - " &    37  9=37/3$("  0  6  1  - "     37A 9=37/3$($AA0A 6 A 1 A -A"AA AF37  9=37/3$( ' 0  6  1  - "    37  9=37/3$(  0  6  1  - "    37C 9=37/3$(C C 0C 6 C 1 C  -C "C  C J6: 9=37 .3 6  1  6: 9=37 3 6  1  6: 9=37   3 6  1     437 9=37 .0 6  1  37 9=37   0 6  1      37$ 9=37 $$0$ 6 $ 1 $$ $L'+R:2"*H.@ 2%(%0<% %<$<04] +/'+*.05] ,] ( ] % ] ( ] *.] ]  #] ~?? +2+ %++1 1*41 +116 6*46>H6 066;;; ;  ; 6 ;;@@@ @  @  @ ;@@EEE E  E  EE @EE J J J J  J  J J J E J J O O O O  O  O O O O J O O4@C 949@C9 94#*669=8<3799:9 9  9 7 96919 39v ' '4 -- 7  ::&48.2 ww1w, w  wr!CHLP+3+31H+3 +3Z.!.1.  .&FJ  '  4B    N,JO 2 BF  "Q!f;323 3,!*F,(+6>%1'%1.4%1<@%1 %1X26"'.2(,8<37y "y #y / y  y ,y &y 6y 1y  y @26"'.2(,8<370"0#0 / 0  0,0&06010 0p9="'.2(,8<37} "} 2} & } 6 }  } ,} &} 6} 1}  } F15 U'U' U' / U' U'x26 ] ]"] / ]  ]&] C] ]~ + BG&='&=:>&= &=P% ?+B" < + M #D  u>t!&$(# g!gg" g  g  gZ!&" Q Q +Q  Q  Q  Q f. !. -E. . `'#'#O'#  '#  '#'#"'#'# '#T=AJJ59J JXHH:11  >>> ::rryrceZdZUdZded<e ddddd ddZe ddddd ddZ ded d dd  dd Zdd Zdd Z ddZ ddZ y)r{a A configurable :class:`.Session` factory. The :class:`.sessionmaker` factory generates new :class:`.Session` objects when called, creating them given the configurational arguments established here. e.g.:: from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker # an Engine, which the Session will use for connection # resources engine = create_engine("postgresql+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`. Type[_S]r.)rrrc yrrrrzrrrrrs rrzsessionmaker.__init__s rc yrr)rrzrrrrs rrzsessionmaker.__init__s rNT)rrrrc x||d<||d<||d<|||d<||_t|j|fi|_y)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. rzrrNr)rr`rrrs rrzsessionmaker.__init__sPR6 #;!1   BvJ6??VIr: rc0|}|jS)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)rrs rrzsessionmaker.begins&&--//rc |jjD]J\}}|dk(r.d|vr*|j}|j|d||d<9|j ||L|j di|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__() rr)rrcopyrr7r)rlocal_kwrvrs rrzsessionmaker.__call__s{GGMMO *DAqF{v1FFH&)*#$ ##Aq)  *t{{&X&&rc :|jj|y)z(Re)configure the arguments for this sessionmaker. e.g.:: Session = sessionmaker() Session.configure(bind=create_engine("sqlite://")) N)rr)rnew_kws r configurezsessionmaker.configures vrc |jjd|jjddjd|jj DdS)Nz(class_=rkc30K|]\}}|d|yw)=Nr)rrrs rrz(sessionmaker.__repr__..sC41aA&Csr) __class__rrrqrrrs r__repr__zsessionmaker.__repr__sB NN # # KK IIC477==?C C  r).) rzrrrrrDrrDrrrr) rz'sessionmaker[Session]'rzrrrDrrDrrrrr)rz%contextlib.AbstractContextManager[_S])rrrr)rrrr)rr) rrrrrGrrryrrrrrrrr{r{.s?\|  (+  !$$'  $        "      (+ !$$'  % $     "    (,1;#!%$(1;$1; 1;  1;  1;"1;1;f0,'(  rr{cVtjD]}|jy)aOClose all sessions in memory. This function consults a global registry of all :class:`.Session` objects and calls :meth:`.Session.close` on them, which resets them to a clean state. This function is not for general use but may be useful for test suites within the teardown scheme. .. versionadded:: 1.3 N)rrr)rs rr}r}s%  " rctj|}t|}|r|j|g|jj |j r|`|jr|`|jr|`yy)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) rrrrexpired_attributesr callablesrrV)rr!rs rr~r~(sq^  % %h /EuA 5'" ""$  O yy I ~~ Nrcftj|}|js |jrt j d|j j||_|jr|`|j|j|j|j|jy)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) rrrrrrrrrVr%rrunloaded)rr!s rrris:  % %h /E 599(()IJJ 55e engine.utilr?eventr@rA inspectionrBrCrDrErFrGrHrIsql.baserJrK sql.schemarLsql.selectablerMrNrO util.typingrPrQrRrSrTrU interfacesrVrWrrX path_registryrYrZr[r\r] engine.baser^r_engine.interfacesr`rarbrc engine.resultrdre sql._typingrfrgrhrirjrkrlrmrnrorp_TCCArqrr sql.elementsrs sql.rolesrtrurvrw__all__WeakValueDictionaryrrGrrr_EntityBindKeyrrrrrrrtuplerrrrrr MemoizedSlotsr|rJrzr^ryrr{r}r~rrcounterrrrrrs8"  #'"+"&"$! ',-&. $#);!" $)&3%-+(#)19<3?,.4'!!!!!!!!A%+,231 T  G! 4CsCx01c3htBx-.S =-DE+, x*/(/(d / JOJF)Xv/F h d((h V7t70Y 6';Y 6x {5:"K{5:|k T#e 'e P$>B$9N % r