session.py 159 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440
  1. # orm/session.py
  2. # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. """Provides the Session class and related utilities."""
  8. import itertools
  9. import sys
  10. import weakref
  11. from . import attributes
  12. from . import context
  13. from . import exc
  14. from . import identity
  15. from . import loading
  16. from . import persistence
  17. from . import query
  18. from . import state as statelib
  19. from .base import _class_to_mapper
  20. from .base import _none_set
  21. from .base import _state_mapper
  22. from .base import instance_str
  23. from .base import object_mapper
  24. from .base import object_state
  25. from .base import state_str
  26. from .unitofwork import UOWTransaction
  27. from .. import engine
  28. from .. import exc as sa_exc
  29. from .. import sql
  30. from .. import util
  31. from ..engine.util import TransactionalContext
  32. from ..inspection import inspect
  33. from ..sql import coercions
  34. from ..sql import dml
  35. from ..sql import roles
  36. from ..sql import visitors
  37. from ..sql.base import CompileState
  38. from ..sql.selectable import LABEL_STYLE_TABLENAME_PLUS_COL
  39. __all__ = [
  40. "Session",
  41. "SessionTransaction",
  42. "sessionmaker",
  43. "ORMExecuteState",
  44. "close_all_sessions",
  45. "make_transient",
  46. "make_transient_to_detached",
  47. "object_session",
  48. ]
  49. _sessions = weakref.WeakValueDictionary()
  50. """Weak-referencing dictionary of :class:`.Session` objects.
  51. """
  52. statelib._sessions = _sessions
  53. def _state_session(state):
  54. """Given an :class:`.InstanceState`, return the :class:`.Session`
  55. associated, if any.
  56. """
  57. return state.session
  58. class _SessionClassMethods(object):
  59. """Class-level methods for :class:`.Session`, :class:`.sessionmaker`."""
  60. @classmethod
  61. @util.deprecated(
  62. "1.3",
  63. "The :meth:`.Session.close_all` method is deprecated and will be "
  64. "removed in a future release. Please refer to "
  65. ":func:`.session.close_all_sessions`.",
  66. )
  67. def close_all(cls):
  68. """Close *all* sessions in memory."""
  69. close_all_sessions()
  70. @classmethod
  71. @util.preload_module("sqlalchemy.orm.util")
  72. def identity_key(cls, *args, **kwargs):
  73. """Return an identity key.
  74. This is an alias of :func:`.util.identity_key`.
  75. """
  76. return util.preloaded.orm_util.identity_key(*args, **kwargs)
  77. @classmethod
  78. def object_session(cls, instance):
  79. """Return the :class:`.Session` to which an object belongs.
  80. This is an alias of :func:`.object_session`.
  81. """
  82. return object_session(instance)
  83. ACTIVE = util.symbol("ACTIVE")
  84. PREPARED = util.symbol("PREPARED")
  85. COMMITTED = util.symbol("COMMITTED")
  86. DEACTIVE = util.symbol("DEACTIVE")
  87. CLOSED = util.symbol("CLOSED")
  88. class ORMExecuteState(util.MemoizedSlots):
  89. """Represents a call to the :meth:`_orm.Session.execute` method, as passed
  90. to the :meth:`.SessionEvents.do_orm_execute` event hook.
  91. .. versionadded:: 1.4
  92. .. seealso::
  93. :ref:`session_execute_events` - top level documentation on how
  94. to use :meth:`_orm.SessionEvents.do_orm_execute`
  95. """
  96. __slots__ = (
  97. "session",
  98. "statement",
  99. "parameters",
  100. "execution_options",
  101. "local_execution_options",
  102. "bind_arguments",
  103. "_compile_state_cls",
  104. "_starting_event_idx",
  105. "_events_todo",
  106. "_update_execution_options",
  107. )
  108. def __init__(
  109. self,
  110. session,
  111. statement,
  112. parameters,
  113. execution_options,
  114. bind_arguments,
  115. compile_state_cls,
  116. events_todo,
  117. ):
  118. self.session = session
  119. self.statement = statement
  120. self.parameters = parameters
  121. self.local_execution_options = execution_options
  122. self.execution_options = statement._execution_options.union(
  123. execution_options
  124. )
  125. self.bind_arguments = bind_arguments
  126. self._compile_state_cls = compile_state_cls
  127. self._events_todo = list(events_todo)
  128. def _remaining_events(self):
  129. return self._events_todo[self._starting_event_idx + 1 :]
  130. def invoke_statement(
  131. self,
  132. statement=None,
  133. params=None,
  134. execution_options=None,
  135. bind_arguments=None,
  136. ):
  137. """Execute the statement represented by this
  138. :class:`.ORMExecuteState`, without re-invoking events that have
  139. already proceeded.
  140. This method essentially performs a re-entrant execution of the current
  141. statement for which the :meth:`.SessionEvents.do_orm_execute` event is
  142. being currently invoked. The use case for this is for event handlers
  143. that want to override how the ultimate
  144. :class:`_engine.Result` object is returned, such as for schemes that
  145. retrieve results from an offline cache or which concatenate results
  146. from multiple executions.
  147. When the :class:`_engine.Result` object is returned by the actual
  148. handler function within :meth:`_orm.SessionEvents.do_orm_execute` and
  149. is propagated to the calling
  150. :meth:`_orm.Session.execute` method, the remainder of the
  151. :meth:`_orm.Session.execute` method is preempted and the
  152. :class:`_engine.Result` object is returned to the caller of
  153. :meth:`_orm.Session.execute` immediately.
  154. :param statement: optional statement to be invoked, in place of the
  155. statement currently represented by :attr:`.ORMExecuteState.statement`.
  156. :param params: optional dictionary of parameters which will be merged
  157. into the existing :attr:`.ORMExecuteState.parameters` of this
  158. :class:`.ORMExecuteState`.
  159. :param execution_options: optional dictionary of execution options
  160. will be merged into the existing
  161. :attr:`.ORMExecuteState.execution_options` of this
  162. :class:`.ORMExecuteState`.
  163. :param bind_arguments: optional dictionary of bind_arguments
  164. which will be merged amongst the current
  165. :attr:`.ORMExecuteState.bind_arguments`
  166. of this :class:`.ORMExecuteState`.
  167. :return: a :class:`_engine.Result` object with ORM-level results.
  168. .. seealso::
  169. :ref:`do_orm_execute_re_executing` - background and examples on the
  170. appropriate usage of :meth:`_orm.ORMExecuteState.invoke_statement`.
  171. """
  172. if statement is None:
  173. statement = self.statement
  174. _bind_arguments = dict(self.bind_arguments)
  175. if bind_arguments:
  176. _bind_arguments.update(bind_arguments)
  177. _bind_arguments["_sa_skip_events"] = True
  178. if params:
  179. _params = dict(self.parameters)
  180. _params.update(params)
  181. else:
  182. _params = self.parameters
  183. _execution_options = self.local_execution_options
  184. if execution_options:
  185. _execution_options = _execution_options.union(execution_options)
  186. return self.session.execute(
  187. statement,
  188. _params,
  189. _execution_options,
  190. _bind_arguments,
  191. _parent_execute_state=self,
  192. )
  193. @property
  194. def bind_mapper(self):
  195. """Return the :class:`_orm.Mapper` that is the primary "bind" mapper.
  196. For an :class:`_orm.ORMExecuteState` object invoking an ORM
  197. statement, that is, the :attr:`_orm.ORMExecuteState.is_orm_statement`
  198. attribute is ``True``, this attribute will return the
  199. :class:`_orm.Mapper` that is considered to be the "primary" mapper
  200. of the statement. The term "bind mapper" refers to the fact that
  201. a :class:`_orm.Session` object may be "bound" to multiple
  202. :class:`_engine.Engine` objects keyed to mapped classes, and the
  203. "bind mapper" determines which of those :class:`_engine.Engine` objects
  204. would be selected.
  205. For a statement that is invoked against a single mapped class,
  206. :attr:`_orm.ORMExecuteState.bind_mapper` is intended to be a reliable
  207. way of getting this mapper.
  208. .. versionadded:: 1.4.0b2
  209. .. seealso::
  210. :attr:`_orm.ORMExecuteState.all_mappers`
  211. """
  212. return self.bind_arguments.get("mapper", None)
  213. @property
  214. def all_mappers(self):
  215. """Return a sequence of all :class:`_orm.Mapper` objects that are
  216. involved at the top level of this statement.
  217. By "top level" we mean those :class:`_orm.Mapper` objects that would
  218. be represented in the result set rows for a :func:`_sql.select`
  219. query, or for a :func:`_dml.update` or :func:`_dml.delete` query,
  220. the mapper that is the main subject of the UPDATE or DELETE.
  221. .. versionadded:: 1.4.0b2
  222. .. seealso::
  223. :attr:`_orm.ORMExecuteState.bind_mapper`
  224. """
  225. if not self.is_orm_statement:
  226. return []
  227. elif self.is_select:
  228. result = []
  229. seen = set()
  230. for d in self.statement.column_descriptions:
  231. ent = d["entity"]
  232. if ent:
  233. insp = inspect(ent, raiseerr=False)
  234. if insp and insp.mapper and insp.mapper not in seen:
  235. seen.add(insp.mapper)
  236. result.append(insp.mapper)
  237. return result
  238. elif self.is_update or self.is_delete:
  239. return [self.bind_mapper]
  240. else:
  241. return []
  242. @property
  243. def is_orm_statement(self):
  244. """return True if the operation is an ORM statement.
  245. This indicates that the select(), update(), or delete() being
  246. invoked contains ORM entities as subjects. For a statement
  247. that does not have ORM entities and instead refers only to
  248. :class:`.Table` metadata, it is invoked as a Core SQL statement
  249. and no ORM-level automation takes place.
  250. """
  251. return self._compile_state_cls is not None
  252. @property
  253. def is_select(self):
  254. """return True if this is a SELECT operation."""
  255. return self.statement.is_select
  256. @property
  257. def is_insert(self):
  258. """return True if this is an INSERT operation."""
  259. return self.statement.is_dml and self.statement.is_insert
  260. @property
  261. def is_update(self):
  262. """return True if this is an UPDATE operation."""
  263. return self.statement.is_dml and self.statement.is_update
  264. @property
  265. def is_delete(self):
  266. """return True if this is a DELETE operation."""
  267. return self.statement.is_dml and self.statement.is_delete
  268. @property
  269. def _is_crud(self):
  270. return isinstance(self.statement, (dml.Update, dml.Delete))
  271. def update_execution_options(self, **opts):
  272. # TODO: no coverage
  273. self.local_execution_options = self.local_execution_options.union(opts)
  274. def _orm_compile_options(self):
  275. if not self.is_select:
  276. return None
  277. try:
  278. opts = self.statement._compile_options
  279. except AttributeError:
  280. return None
  281. if opts.isinstance(context.ORMCompileState.default_compile_options):
  282. return opts
  283. else:
  284. return None
  285. @property
  286. def lazy_loaded_from(self):
  287. """An :class:`.InstanceState` that is using this statement execution
  288. for a lazy load operation.
  289. The primary rationale for this attribute is to support the horizontal
  290. sharding extension, where it is available within specific query
  291. execution time hooks created by this extension. To that end, the
  292. attribute is only intended to be meaningful at **query execution
  293. time**, and importantly not any time prior to that, including query
  294. compilation time.
  295. """
  296. return self.load_options._lazy_loaded_from
  297. @property
  298. def loader_strategy_path(self):
  299. """Return the :class:`.PathRegistry` for the current load path.
  300. This object represents the "path" in a query along relationships
  301. when a particular object or collection is being loaded.
  302. """
  303. opts = self._orm_compile_options()
  304. if opts is not None:
  305. return opts._current_path
  306. else:
  307. return None
  308. @property
  309. def is_column_load(self):
  310. """Return True if the operation is refreshing column-oriented
  311. attributes on an existing ORM object.
  312. This occurs during operations such as :meth:`_orm.Session.refresh`,
  313. as well as when an attribute deferred by :func:`_orm.defer` is
  314. being loaded, or an attribute that was expired either directly
  315. by :meth:`_orm.Session.expire` or via a commit operation is being
  316. loaded.
  317. Handlers will very likely not want to add any options to queries
  318. when such an operation is occurring as the query should be a straight
  319. primary key fetch which should not have any additional WHERE criteria,
  320. and loader options travelling with the instance
  321. will have already been added to the query.
  322. .. versionadded:: 1.4.0b2
  323. .. seealso::
  324. :attr:`_orm.ORMExecuteState.is_relationship_load`
  325. """
  326. opts = self._orm_compile_options()
  327. return opts is not None and opts._for_refresh_state
  328. @property
  329. def is_relationship_load(self):
  330. """Return True if this load is loading objects on behalf of a
  331. relationship.
  332. This means, the loader in effect is either a LazyLoader,
  333. SelectInLoader, SubqueryLoader, or similar, and the entire
  334. SELECT statement being emitted is on behalf of a relationship
  335. load.
  336. Handlers will very likely not want to add any options to queries
  337. when such an operation is occurring, as loader options are already
  338. capable of being propagated to relationship loaders and should
  339. be already present.
  340. .. seealso::
  341. :attr:`_orm.ORMExecuteState.is_column_load`
  342. """
  343. opts = self._orm_compile_options()
  344. if opts is None:
  345. return False
  346. path = self.loader_strategy_path
  347. return path is not None and not path.is_root
  348. @property
  349. def load_options(self):
  350. """Return the load_options that will be used for this execution."""
  351. if not self.is_select:
  352. raise sa_exc.InvalidRequestError(
  353. "This ORM execution is not against a SELECT statement "
  354. "so there are no load options."
  355. )
  356. return self.execution_options.get(
  357. "_sa_orm_load_options", context.QueryContext.default_load_options
  358. )
  359. @property
  360. def update_delete_options(self):
  361. """Return the update_delete_options that will be used for this
  362. execution."""
  363. if not self._is_crud:
  364. raise sa_exc.InvalidRequestError(
  365. "This ORM execution is not against an UPDATE or DELETE "
  366. "statement so there are no update options."
  367. )
  368. return self.execution_options.get(
  369. "_sa_orm_update_options",
  370. persistence.BulkUDCompileState.default_update_options,
  371. )
  372. @property
  373. def user_defined_options(self):
  374. """The sequence of :class:`.UserDefinedOptions` that have been
  375. associated with the statement being invoked.
  376. """
  377. return [
  378. opt
  379. for opt in self.statement._with_options
  380. if not opt._is_compile_state and not opt._is_legacy_option
  381. ]
  382. class SessionTransaction(TransactionalContext):
  383. """A :class:`.Session`-level transaction.
  384. :class:`.SessionTransaction` is produced from the
  385. :meth:`_orm.Session.begin`
  386. and :meth:`_orm.Session.begin_nested` methods. It's largely an internal
  387. object that in modern use provides a context manager for session
  388. transactions.
  389. Documentation on interacting with :class:`_orm.SessionTransaction` is
  390. at: :ref:`unitofwork_transaction`.
  391. .. versionchanged:: 1.4 The scoping and API methods to work with the
  392. :class:`_orm.SessionTransaction` object directly have been simplified.
  393. .. seealso::
  394. :ref:`unitofwork_transaction`
  395. :meth:`.Session.begin`
  396. :meth:`.Session.begin_nested`
  397. :meth:`.Session.rollback`
  398. :meth:`.Session.commit`
  399. :meth:`.Session.in_transaction`
  400. :meth:`.Session.in_nested_transaction`
  401. :meth:`.Session.get_transaction`
  402. :meth:`.Session.get_nested_transaction`
  403. """
  404. _rollback_exception = None
  405. def __init__(
  406. self,
  407. session,
  408. parent=None,
  409. nested=False,
  410. autobegin=False,
  411. ):
  412. TransactionalContext._trans_ctx_check(session)
  413. self.session = session
  414. self._connections = {}
  415. self._parent = parent
  416. self.nested = nested
  417. if nested:
  418. self._previous_nested_transaction = session._nested_transaction
  419. self._state = ACTIVE
  420. if not parent and nested:
  421. raise sa_exc.InvalidRequestError(
  422. "Can't start a SAVEPOINT transaction when no existing "
  423. "transaction is in progress"
  424. )
  425. self._take_snapshot(autobegin=autobegin)
  426. # make sure transaction is assigned before we call the
  427. # dispatch
  428. self.session._transaction = self
  429. self.session.dispatch.after_transaction_create(self.session, self)
  430. @property
  431. def parent(self):
  432. """The parent :class:`.SessionTransaction` of this
  433. :class:`.SessionTransaction`.
  434. If this attribute is ``None``, indicates this
  435. :class:`.SessionTransaction` is at the top of the stack, and
  436. corresponds to a real "COMMIT"/"ROLLBACK"
  437. block. If non-``None``, then this is either a "subtransaction"
  438. or a "nested" / SAVEPOINT transaction. If the
  439. :attr:`.SessionTransaction.nested` attribute is ``True``, then
  440. this is a SAVEPOINT, and if ``False``, indicates this a subtransaction.
  441. .. versionadded:: 1.0.16 - use ._parent for previous versions
  442. """
  443. return self._parent
  444. nested = False
  445. """Indicates if this is a nested, or SAVEPOINT, transaction.
  446. When :attr:`.SessionTransaction.nested` is True, it is expected
  447. that :attr:`.SessionTransaction.parent` will be True as well.
  448. """
  449. @property
  450. def is_active(self):
  451. return self.session is not None and self._state is ACTIVE
  452. def _assert_active(
  453. self,
  454. prepared_ok=False,
  455. rollback_ok=False,
  456. deactive_ok=False,
  457. closed_msg="This transaction is closed",
  458. ):
  459. if self._state is COMMITTED:
  460. raise sa_exc.InvalidRequestError(
  461. "This session is in 'committed' state; no further "
  462. "SQL can be emitted within this transaction."
  463. )
  464. elif self._state is PREPARED:
  465. if not prepared_ok:
  466. raise sa_exc.InvalidRequestError(
  467. "This session is in 'prepared' state; no further "
  468. "SQL can be emitted within this transaction."
  469. )
  470. elif self._state is DEACTIVE:
  471. if not deactive_ok and not rollback_ok:
  472. if self._rollback_exception:
  473. raise sa_exc.PendingRollbackError(
  474. "This Session's transaction has been rolled back "
  475. "due to a previous exception during flush."
  476. " To begin a new transaction with this Session, "
  477. "first issue Session.rollback()."
  478. " Original exception was: %s"
  479. % self._rollback_exception,
  480. code="7s2a",
  481. )
  482. elif not deactive_ok:
  483. raise sa_exc.InvalidRequestError(
  484. "This session is in 'inactive' state, due to the "
  485. "SQL transaction being rolled back; no further "
  486. "SQL can be emitted within this transaction."
  487. )
  488. elif self._state is CLOSED:
  489. raise sa_exc.ResourceClosedError(closed_msg)
  490. @property
  491. def _is_transaction_boundary(self):
  492. return self.nested or not self._parent
  493. def connection(self, bindkey, execution_options=None, **kwargs):
  494. self._assert_active()
  495. bind = self.session.get_bind(bindkey, **kwargs)
  496. return self._connection_for_bind(bind, execution_options)
  497. def _begin(self, nested=False):
  498. self._assert_active()
  499. return SessionTransaction(self.session, self, nested=nested)
  500. def _iterate_self_and_parents(self, upto=None):
  501. current = self
  502. result = ()
  503. while current:
  504. result += (current,)
  505. if current._parent is upto:
  506. break
  507. elif current._parent is None:
  508. raise sa_exc.InvalidRequestError(
  509. "Transaction %s is not on the active transaction list"
  510. % (upto)
  511. )
  512. else:
  513. current = current._parent
  514. return result
  515. def _take_snapshot(self, autobegin=False):
  516. if not self._is_transaction_boundary:
  517. self._new = self._parent._new
  518. self._deleted = self._parent._deleted
  519. self._dirty = self._parent._dirty
  520. self._key_switches = self._parent._key_switches
  521. return
  522. if not autobegin and not self.session._flushing:
  523. self.session.flush()
  524. self._new = weakref.WeakKeyDictionary()
  525. self._deleted = weakref.WeakKeyDictionary()
  526. self._dirty = weakref.WeakKeyDictionary()
  527. self._key_switches = weakref.WeakKeyDictionary()
  528. def _restore_snapshot(self, dirty_only=False):
  529. """Restore the restoration state taken before a transaction began.
  530. Corresponds to a rollback.
  531. """
  532. assert self._is_transaction_boundary
  533. to_expunge = set(self._new).union(self.session._new)
  534. self.session._expunge_states(to_expunge, to_transient=True)
  535. for s, (oldkey, newkey) in self._key_switches.items():
  536. # we probably can do this conditionally based on
  537. # if we expunged or not, but safe_discard does that anyway
  538. self.session.identity_map.safe_discard(s)
  539. # restore the old key
  540. s.key = oldkey
  541. # now restore the object, but only if we didn't expunge
  542. if s not in to_expunge:
  543. self.session.identity_map.replace(s)
  544. for s in set(self._deleted).union(self.session._deleted):
  545. self.session._update_impl(s, revert_deletion=True)
  546. assert not self.session._deleted
  547. for s in self.session.identity_map.all_states():
  548. if not dirty_only or s.modified or s in self._dirty:
  549. s._expire(s.dict, self.session.identity_map._modified)
  550. def _remove_snapshot(self):
  551. """Remove the restoration state taken before a transaction began.
  552. Corresponds to a commit.
  553. """
  554. assert self._is_transaction_boundary
  555. if not self.nested and self.session.expire_on_commit:
  556. for s in self.session.identity_map.all_states():
  557. s._expire(s.dict, self.session.identity_map._modified)
  558. statelib.InstanceState._detach_states(
  559. list(self._deleted), self.session
  560. )
  561. self._deleted.clear()
  562. elif self.nested:
  563. self._parent._new.update(self._new)
  564. self._parent._dirty.update(self._dirty)
  565. self._parent._deleted.update(self._deleted)
  566. self._parent._key_switches.update(self._key_switches)
  567. def _connection_for_bind(self, bind, execution_options):
  568. self._assert_active()
  569. if bind in self._connections:
  570. if execution_options:
  571. util.warn(
  572. "Connection is already established for the "
  573. "given bind; execution_options ignored"
  574. )
  575. return self._connections[bind][0]
  576. local_connect = False
  577. should_commit = True
  578. if self._parent:
  579. conn = self._parent._connection_for_bind(bind, execution_options)
  580. if not self.nested:
  581. return conn
  582. else:
  583. if isinstance(bind, engine.Connection):
  584. conn = bind
  585. if conn.engine in self._connections:
  586. raise sa_exc.InvalidRequestError(
  587. "Session already has a Connection associated for the "
  588. "given Connection's Engine"
  589. )
  590. else:
  591. conn = bind.connect()
  592. local_connect = True
  593. try:
  594. if execution_options:
  595. conn = conn.execution_options(**execution_options)
  596. if self.session.twophase and self._parent is None:
  597. transaction = conn.begin_twophase()
  598. elif self.nested:
  599. transaction = conn.begin_nested()
  600. elif conn.in_transaction():
  601. # if given a future connection already in a transaction, don't
  602. # commit that transaction unless it is a savepoint
  603. if conn.in_nested_transaction():
  604. transaction = conn.get_nested_transaction()
  605. else:
  606. transaction = conn.get_transaction()
  607. should_commit = False
  608. else:
  609. transaction = conn.begin()
  610. except:
  611. # connection will not not be associated with this Session;
  612. # close it immediately so that it isn't closed under GC
  613. if local_connect:
  614. conn.close()
  615. raise
  616. else:
  617. bind_is_connection = isinstance(bind, engine.Connection)
  618. self._connections[conn] = self._connections[conn.engine] = (
  619. conn,
  620. transaction,
  621. should_commit,
  622. not bind_is_connection,
  623. )
  624. self.session.dispatch.after_begin(self.session, self, conn)
  625. return conn
  626. def prepare(self):
  627. if self._parent is not None or not self.session.twophase:
  628. raise sa_exc.InvalidRequestError(
  629. "'twophase' mode not enabled, or not root transaction; "
  630. "can't prepare."
  631. )
  632. self._prepare_impl()
  633. def _prepare_impl(self):
  634. self._assert_active()
  635. if self._parent is None or self.nested:
  636. self.session.dispatch.before_commit(self.session)
  637. stx = self.session._transaction
  638. if stx is not self:
  639. for subtransaction in stx._iterate_self_and_parents(upto=self):
  640. subtransaction.commit()
  641. if not self.session._flushing:
  642. for _flush_guard in range(100):
  643. if self.session._is_clean():
  644. break
  645. self.session.flush()
  646. else:
  647. raise exc.FlushError(
  648. "Over 100 subsequent flushes have occurred within "
  649. "session.commit() - is an after_flush() hook "
  650. "creating new objects?"
  651. )
  652. if self._parent is None and self.session.twophase:
  653. try:
  654. for t in set(self._connections.values()):
  655. t[1].prepare()
  656. except:
  657. with util.safe_reraise():
  658. self.rollback()
  659. self._state = PREPARED
  660. def commit(self, _to_root=False):
  661. self._assert_active(prepared_ok=True)
  662. if self._state is not PREPARED:
  663. self._prepare_impl()
  664. if self._parent is None or self.nested:
  665. for conn, trans, should_commit, autoclose in set(
  666. self._connections.values()
  667. ):
  668. if should_commit:
  669. trans.commit()
  670. self._state = COMMITTED
  671. self.session.dispatch.after_commit(self.session)
  672. self._remove_snapshot()
  673. self.close()
  674. if _to_root and self._parent:
  675. return self._parent.commit(_to_root=True)
  676. return self._parent
  677. def rollback(self, _capture_exception=False, _to_root=False):
  678. self._assert_active(prepared_ok=True, rollback_ok=True)
  679. stx = self.session._transaction
  680. if stx is not self:
  681. for subtransaction in stx._iterate_self_and_parents(upto=self):
  682. subtransaction.close()
  683. boundary = self
  684. rollback_err = None
  685. if self._state in (ACTIVE, PREPARED):
  686. for transaction in self._iterate_self_and_parents():
  687. if transaction._parent is None or transaction.nested:
  688. try:
  689. for t in set(transaction._connections.values()):
  690. t[1].rollback()
  691. transaction._state = DEACTIVE
  692. self.session.dispatch.after_rollback(self.session)
  693. except:
  694. rollback_err = sys.exc_info()
  695. finally:
  696. transaction._state = DEACTIVE
  697. transaction._restore_snapshot(
  698. dirty_only=transaction.nested
  699. )
  700. boundary = transaction
  701. break
  702. else:
  703. transaction._state = DEACTIVE
  704. sess = self.session
  705. if not rollback_err and not sess._is_clean():
  706. # if items were added, deleted, or mutated
  707. # here, we need to re-restore the snapshot
  708. util.warn(
  709. "Session's state has been changed on "
  710. "a non-active transaction - this state "
  711. "will be discarded."
  712. )
  713. boundary._restore_snapshot(dirty_only=boundary.nested)
  714. self.close()
  715. if self._parent and _capture_exception:
  716. self._parent._rollback_exception = sys.exc_info()[1]
  717. if rollback_err:
  718. util.raise_(rollback_err[1], with_traceback=rollback_err[2])
  719. sess.dispatch.after_soft_rollback(sess, self)
  720. if _to_root and self._parent:
  721. return self._parent.rollback(_to_root=True)
  722. return self._parent
  723. def close(self, invalidate=False):
  724. if self.nested:
  725. self.session._nested_transaction = (
  726. self._previous_nested_transaction
  727. )
  728. self.session._transaction = self._parent
  729. if self._parent is None:
  730. for connection, transaction, should_commit, autoclose in set(
  731. self._connections.values()
  732. ):
  733. if invalidate:
  734. connection.invalidate()
  735. if should_commit and transaction.is_active:
  736. transaction.close()
  737. if autoclose:
  738. connection.close()
  739. self._state = CLOSED
  740. self.session.dispatch.after_transaction_end(self.session, self)
  741. self.session = None
  742. self._connections = None
  743. def _get_subject(self):
  744. return self.session
  745. def _transaction_is_active(self):
  746. return self._state is ACTIVE
  747. def _transaction_is_closed(self):
  748. return self._state is CLOSED
  749. def _rollback_can_be_called(self):
  750. return self._state not in (COMMITTED, CLOSED)
  751. class Session(_SessionClassMethods):
  752. """Manages persistence operations for ORM-mapped objects.
  753. The Session's usage paradigm is described at :doc:`/orm/session`.
  754. """
  755. _is_asyncio = False
  756. @util.deprecated_params(
  757. autocommit=(
  758. "2.0",
  759. "The :paramref:`.Session.autocommit` parameter is deprecated "
  760. "and will be removed in SQLAlchemy version 2.0. The "
  761. ':class:`_orm.Session` now features "autobegin" behavior '
  762. "such that the :meth:`.Session.begin` method may be called "
  763. "if a transaction has not yet been started yet. See the section "
  764. ":ref:`session_explicit_begin` for background.",
  765. ),
  766. )
  767. def __init__(
  768. self,
  769. bind=None,
  770. autoflush=True,
  771. future=False,
  772. expire_on_commit=True,
  773. autocommit=False,
  774. twophase=False,
  775. binds=None,
  776. enable_baked_queries=True,
  777. info=None,
  778. query_cls=None,
  779. ):
  780. r"""Construct a new Session.
  781. See also the :class:`.sessionmaker` function which is used to
  782. generate a :class:`.Session`-producing callable with a given
  783. set of arguments.
  784. :param autocommit:
  785. Defaults to ``False``. When ``True``, the
  786. :class:`.Session` does not automatically begin transactions for
  787. individual statement executions, will acquire connections from the
  788. engine on an as-needed basis, releasing to the connection pool
  789. after each statement. Flushes will begin and commit (or possibly
  790. rollback) their own transaction if no transaction is present.
  791. When using this mode, the
  792. :meth:`.Session.begin` method may be used to explicitly start
  793. transactions, but the usual "autobegin" behavior is not present.
  794. :param autoflush: When ``True``, all query operations will issue a
  795. :meth:`~.Session.flush` call to this ``Session`` before proceeding.
  796. This is a convenience feature so that :meth:`~.Session.flush` need
  797. not be called repeatedly in order for database queries to retrieve
  798. results. It's typical that ``autoflush`` is used in conjunction
  799. with ``autocommit=False``. In this scenario, explicit calls to
  800. :meth:`~.Session.flush` are rarely needed; you usually only need to
  801. call :meth:`~.Session.commit` (which flushes) to finalize changes.
  802. .. seealso::
  803. :ref:`session_flushing` - additional background on autoflush
  804. :param bind: An optional :class:`_engine.Engine` or
  805. :class:`_engine.Connection` to
  806. which this ``Session`` should be bound. When specified, all SQL
  807. operations performed by this session will execute via this
  808. connectable.
  809. :param binds: A dictionary which may specify any number of
  810. :class:`_engine.Engine` or :class:`_engine.Connection`
  811. objects as the source of
  812. connectivity for SQL operations on a per-entity basis. The keys
  813. of the dictionary consist of any series of mapped classes,
  814. arbitrary Python classes that are bases for mapped classes,
  815. :class:`_schema.Table` objects and :class:`_orm.Mapper` objects.
  816. The
  817. values of the dictionary are then instances of
  818. :class:`_engine.Engine`
  819. or less commonly :class:`_engine.Connection` objects.
  820. Operations which
  821. proceed relative to a particular mapped class will consult this
  822. dictionary for the closest matching entity in order to determine
  823. which :class:`_engine.Engine` should be used for a particular SQL
  824. operation. The complete heuristics for resolution are
  825. described at :meth:`.Session.get_bind`. Usage looks like::
  826. Session = sessionmaker(binds={
  827. SomeMappedClass: create_engine('postgresql://engine1'),
  828. SomeDeclarativeBase: create_engine('postgresql://engine2'),
  829. some_mapper: create_engine('postgresql://engine3'),
  830. some_table: create_engine('postgresql://engine4'),
  831. })
  832. .. seealso::
  833. :ref:`session_partitioning`
  834. :meth:`.Session.bind_mapper`
  835. :meth:`.Session.bind_table`
  836. :meth:`.Session.get_bind`
  837. :param \class_: Specify an alternate class other than
  838. ``sqlalchemy.orm.session.Session`` which should be used by the
  839. returned class. This is the only argument that is local to the
  840. :class:`.sessionmaker` function, and is not sent directly to the
  841. constructor for ``Session``.
  842. :param enable_baked_queries: defaults to ``True``. A flag consumed
  843. by the :mod:`sqlalchemy.ext.baked` extension to determine if
  844. "baked queries" should be cached, as is the normal operation
  845. of this extension. When set to ``False``, caching as used by
  846. this particular extension is disabled.
  847. .. versionchanged:: 1.4 The ``sqlalchemy.ext.baked`` extension is
  848. legacy and is not used by any of SQLAlchemy's internals. This
  849. flag therefore only affects applications that are making explicit
  850. use of this extension within their own code.
  851. :param expire_on_commit: Defaults to ``True``. When ``True``, all
  852. instances will be fully expired after each :meth:`~.commit`,
  853. so that all attribute/object access subsequent to a completed
  854. transaction will load from the most recent database state.
  855. .. seealso::
  856. :ref:`session_committing`
  857. :param future: if True, use 2.0 style transactional and engine
  858. behavior. Future mode includes the following behaviors:
  859. * The :class:`_orm.Session` will not use "bound" metadata in order
  860. to locate an :class:`_engine.Engine`; the engine or engines in use
  861. must be specified to the constructor of :class:`_orm.Session` or
  862. otherwise be configured against the :class:`_orm.sessionmaker`
  863. in use
  864. * The "subtransactions" feature of :meth:`_orm.Session.begin` is
  865. removed in version 2.0 and is disabled when the future flag is
  866. set.
  867. * The behavior of the :paramref:`_orm.relationship.cascade_backrefs`
  868. flag on a :func:`_orm.relationship` will always assume
  869. "False" behavior.
  870. .. versionadded:: 1.4
  871. .. seealso::
  872. :ref:`migration_20_toplevel`
  873. :param info: optional dictionary of arbitrary data to be associated
  874. with this :class:`.Session`. Is available via the
  875. :attr:`.Session.info` attribute. Note the dictionary is copied at
  876. construction time so that modifications to the per-
  877. :class:`.Session` dictionary will be local to that
  878. :class:`.Session`.
  879. :param query_cls: Class which should be used to create new Query
  880. objects, as returned by the :meth:`~.Session.query` method.
  881. Defaults to :class:`_query.Query`.
  882. :param twophase: When ``True``, all transactions will be started as
  883. a "two phase" transaction, i.e. using the "two phase" semantics
  884. of the database in use along with an XID. During a
  885. :meth:`~.commit`, after :meth:`~.flush` has been issued for all
  886. attached databases, the :meth:`~.TwoPhaseTransaction.prepare`
  887. method on each database's :class:`.TwoPhaseTransaction` will be
  888. called. This allows each database to roll back the entire
  889. transaction, before each transaction is committed.
  890. """
  891. self.identity_map = identity.WeakInstanceDict()
  892. self._new = {} # InstanceState->object, strong refs object
  893. self._deleted = {} # same
  894. self.bind = bind
  895. self.__binds = {}
  896. self._flushing = False
  897. self._warn_on_events = False
  898. self._transaction = None
  899. self._nested_transaction = None
  900. self.future = future
  901. self.hash_key = _new_sessionid()
  902. self.autoflush = autoflush
  903. self.expire_on_commit = expire_on_commit
  904. self.enable_baked_queries = enable_baked_queries
  905. if autocommit:
  906. if future:
  907. raise sa_exc.ArgumentError(
  908. "Cannot use autocommit mode with future=True."
  909. )
  910. self.autocommit = True
  911. else:
  912. self.autocommit = False
  913. self.twophase = twophase
  914. self._query_cls = query_cls if query_cls else query.Query
  915. if info:
  916. self.info.update(info)
  917. if binds is not None:
  918. for key, bind in binds.items():
  919. self._add_bind(key, bind)
  920. _sessions[self.hash_key] = self
  921. # used by sqlalchemy.engine.util.TransactionalContext
  922. _trans_context_manager = None
  923. connection_callable = None
  924. def __enter__(self):
  925. return self
  926. def __exit__(self, type_, value, traceback):
  927. self.close()
  928. @util.contextmanager
  929. def _maker_context_manager(self):
  930. with self:
  931. with self.begin():
  932. yield self
  933. @property
  934. @util.deprecated_20(
  935. ":attr:`_orm.Session.transaction`",
  936. alternative="For context manager use, use "
  937. ":meth:`_orm.Session.begin`. To access "
  938. "the current root transaction, use "
  939. ":meth:`_orm.Session.get_transaction`.",
  940. warn_on_attribute_access=True,
  941. )
  942. def transaction(self):
  943. """The current active or inactive :class:`.SessionTransaction`.
  944. May be None if no transaction has begun yet.
  945. .. versionchanged:: 1.4 the :attr:`.Session.transaction` attribute
  946. is now a read-only descriptor that also may return None if no
  947. transaction has begun yet.
  948. """
  949. return self._legacy_transaction()
  950. def _legacy_transaction(self):
  951. if not self.future:
  952. self._autobegin()
  953. return self._transaction
  954. def in_transaction(self):
  955. """Return True if this :class:`_orm.Session` has begun a transaction.
  956. .. versionadded:: 1.4
  957. .. seealso::
  958. :attr:`_orm.Session.is_active`
  959. """
  960. return self._transaction is not None
  961. def in_nested_transaction(self):
  962. """Return True if this :class:`_orm.Session` has begun a nested
  963. transaction, e.g. SAVEPOINT.
  964. .. versionadded:: 1.4
  965. """
  966. return self._nested_transaction is not None
  967. def get_transaction(self):
  968. """Return the current root transaction in progress, if any.
  969. .. versionadded:: 1.4
  970. """
  971. trans = self._transaction
  972. while trans is not None and trans._parent is not None:
  973. trans = trans._parent
  974. return trans
  975. def get_nested_transaction(self):
  976. """Return the current nested transaction in progress, if any.
  977. .. versionadded:: 1.4
  978. """
  979. return self._nested_transaction
  980. @util.memoized_property
  981. def info(self):
  982. """A user-modifiable dictionary.
  983. The initial value of this dictionary can be populated using the
  984. ``info`` argument to the :class:`.Session` constructor or
  985. :class:`.sessionmaker` constructor or factory methods. The dictionary
  986. here is always local to this :class:`.Session` and can be modified
  987. independently of all other :class:`.Session` objects.
  988. """
  989. return {}
  990. def _autobegin(self):
  991. if not self.autocommit and self._transaction is None:
  992. trans = SessionTransaction(self, autobegin=True)
  993. assert self._transaction is trans
  994. return True
  995. return False
  996. @util.deprecated_params(
  997. subtransactions=(
  998. "2.0",
  999. "The :paramref:`_orm.Session.begin.subtransactions` flag is "
  1000. "deprecated and "
  1001. "will be removed in SQLAlchemy version 2.0. See "
  1002. "the documentation at :ref:`session_subtransactions` for "
  1003. "background on a compatible alternative pattern.",
  1004. )
  1005. )
  1006. def begin(self, subtransactions=False, nested=False, _subtrans=False):
  1007. """Begin a transaction, or nested transaction,
  1008. on this :class:`.Session`, if one is not already begun.
  1009. The :class:`_orm.Session` object features **autobegin** behavior,
  1010. so that normally it is not necessary to call the
  1011. :meth:`_orm.Session.begin`
  1012. method explicitly. However, it may be used in order to control
  1013. the scope of when the transactional state is begun.
  1014. When used to begin the outermost transaction, an error is raised
  1015. if this :class:`.Session` is already inside of a transaction.
  1016. :param nested: if True, begins a SAVEPOINT transaction and is
  1017. equivalent to calling :meth:`~.Session.begin_nested`. For
  1018. documentation on SAVEPOINT transactions, please see
  1019. :ref:`session_begin_nested`.
  1020. :param subtransactions: if True, indicates that this
  1021. :meth:`~.Session.begin` can create a "subtransaction".
  1022. :return: the :class:`.SessionTransaction` object. Note that
  1023. :class:`.SessionTransaction`
  1024. acts as a Python context manager, allowing :meth:`.Session.begin`
  1025. to be used in a "with" block. See :ref:`session_autocommit` for
  1026. an example.
  1027. .. seealso::
  1028. :ref:`session_autobegin`
  1029. :ref:`unitofwork_transaction`
  1030. :meth:`.Session.begin_nested`
  1031. """
  1032. if subtransactions and self.future:
  1033. raise NotImplementedError(
  1034. "subtransactions are not implemented in future "
  1035. "Session objects."
  1036. )
  1037. if self._autobegin():
  1038. if not subtransactions and not nested and not _subtrans:
  1039. return self._transaction
  1040. if self._transaction is not None:
  1041. if subtransactions or _subtrans or nested:
  1042. trans = self._transaction._begin(nested=nested)
  1043. assert self._transaction is trans
  1044. if nested:
  1045. self._nested_transaction = trans
  1046. else:
  1047. raise sa_exc.InvalidRequestError(
  1048. "A transaction is already begun on this Session."
  1049. )
  1050. elif not self.autocommit:
  1051. # outermost transaction. must be a not nested and not
  1052. # a subtransaction
  1053. assert not nested and not _subtrans and not subtransactions
  1054. trans = SessionTransaction(self)
  1055. assert self._transaction is trans
  1056. else:
  1057. # legacy autocommit mode
  1058. assert not self.future
  1059. trans = SessionTransaction(self, nested=nested)
  1060. assert self._transaction is trans
  1061. return self._transaction # needed for __enter__/__exit__ hook
  1062. def begin_nested(self):
  1063. """Begin a "nested" transaction on this Session, e.g. SAVEPOINT.
  1064. The target database(s) and associated drivers must support SQL
  1065. SAVEPOINT for this method to function correctly.
  1066. For documentation on SAVEPOINT
  1067. transactions, please see :ref:`session_begin_nested`.
  1068. :return: the :class:`.SessionTransaction` object. Note that
  1069. :class:`.SessionTransaction` acts as a context manager, allowing
  1070. :meth:`.Session.begin_nested` to be used in a "with" block.
  1071. See :ref:`session_begin_nested` for a usage example.
  1072. .. seealso::
  1073. :ref:`session_begin_nested`
  1074. :ref:`pysqlite_serializable` - special workarounds required
  1075. with the SQLite driver in order for SAVEPOINT to work
  1076. correctly.
  1077. """
  1078. return self.begin(nested=True)
  1079. def rollback(self):
  1080. """Rollback the current transaction in progress.
  1081. If no transaction is in progress, this method is a pass-through.
  1082. In :term:`1.x-style` use, this method rolls back the topmost
  1083. database transaction if no nested transactions are in effect, or
  1084. to the current nested transaction if one is in effect.
  1085. When
  1086. :term:`2.0-style` use is in effect via the
  1087. :paramref:`_orm.Session.future` flag, the method always rolls back
  1088. the topmost database transaction, discarding any nested
  1089. transactions that may be in progress.
  1090. .. seealso::
  1091. :ref:`session_rollback`
  1092. :ref:`unitofwork_transaction`
  1093. """
  1094. if self._transaction is None:
  1095. pass
  1096. else:
  1097. self._transaction.rollback(_to_root=self.future)
  1098. def commit(self):
  1099. """Flush pending changes and commit the current transaction.
  1100. When the COMMIT operation is complete, all objects are fully
  1101. :term:`expired`, erasing their internal contents, which will be
  1102. automatically re-loaded when the objects are next accessed. In the
  1103. interim, these objects are in an expired state and will not function if
  1104. they are :term:`detached` from the :class:`.Session`. Additionally,
  1105. this re-load operation is not supported when using asyncio-oriented
  1106. APIs. The :paramref:`.Session.expire_on_commit` parameter may be used
  1107. to disable this behavior.
  1108. When there is no transaction in place for the :class:`.Session`,
  1109. indicating that no operations were invoked on this :class:`.Session`
  1110. since the previous call to :meth:`.Session.commit`, the method will
  1111. begin and commit an internal-only "logical" transaction, that does not
  1112. normally affect the database unless pending flush changes were
  1113. detected, but will still invoke event handlers and object expiration
  1114. rules.
  1115. If :term:`1.x-style` use is in effect and there are currently
  1116. SAVEPOINTs in progress via :meth:`_orm.Session.begin_nested`,
  1117. the operation will release the current SAVEPOINT but not commit
  1118. the outermost database transaction.
  1119. If :term:`2.0-style` use is in effect via the
  1120. :paramref:`_orm.Session.future` flag, the outermost database
  1121. transaction is committed unconditionally, automatically releasing any
  1122. SAVEPOINTs in effect.
  1123. When using legacy "autocommit" mode, this method is only
  1124. valid to call if a transaction is actually in progress, else
  1125. an error is raised. Similarly, when using legacy "subtransactions",
  1126. the method will instead close out the current "subtransaction",
  1127. rather than the actual database transaction, if a transaction
  1128. is in progress.
  1129. .. seealso::
  1130. :ref:`session_committing`
  1131. :ref:`unitofwork_transaction`
  1132. :ref:`asyncio_orm_avoid_lazyloads`
  1133. """
  1134. if self._transaction is None:
  1135. if not self._autobegin():
  1136. raise sa_exc.InvalidRequestError("No transaction is begun.")
  1137. self._transaction.commit(_to_root=self.future)
  1138. def prepare(self):
  1139. """Prepare the current transaction in progress for two phase commit.
  1140. If no transaction is in progress, this method raises an
  1141. :exc:`~sqlalchemy.exc.InvalidRequestError`.
  1142. Only root transactions of two phase sessions can be prepared. If the
  1143. current transaction is not such, an
  1144. :exc:`~sqlalchemy.exc.InvalidRequestError` is raised.
  1145. """
  1146. if self._transaction is None:
  1147. if not self._autobegin():
  1148. raise sa_exc.InvalidRequestError("No transaction is begun.")
  1149. self._transaction.prepare()
  1150. def connection(
  1151. self,
  1152. bind_arguments=None,
  1153. close_with_result=False,
  1154. execution_options=None,
  1155. **kw
  1156. ):
  1157. r"""Return a :class:`_engine.Connection` object corresponding to this
  1158. :class:`.Session` object's transactional state.
  1159. If this :class:`.Session` is configured with ``autocommit=False``,
  1160. either the :class:`_engine.Connection` corresponding to the current
  1161. transaction is returned, or if no transaction is in progress, a new
  1162. one is begun and the :class:`_engine.Connection`
  1163. returned (note that no
  1164. transactional state is established with the DBAPI until the first
  1165. SQL statement is emitted).
  1166. Alternatively, if this :class:`.Session` is configured with
  1167. ``autocommit=True``, an ad-hoc :class:`_engine.Connection` is returned
  1168. using :meth:`_engine.Engine.connect` on the underlying
  1169. :class:`_engine.Engine`.
  1170. Ambiguity in multi-bind or unbound :class:`.Session` objects can be
  1171. resolved through any of the optional keyword arguments. This
  1172. ultimately makes usage of the :meth:`.get_bind` method for resolution.
  1173. :param bind_arguments: dictionary of bind arguments. May include
  1174. "mapper", "bind", "clause", other custom arguments that are passed
  1175. to :meth:`.Session.get_bind`.
  1176. :param bind:
  1177. deprecated; use bind_arguments
  1178. :param mapper:
  1179. deprecated; use bind_arguments
  1180. :param clause:
  1181. deprecated; use bind_arguments
  1182. :param close_with_result: Passed to :meth:`_engine.Engine.connect`,
  1183. indicating the :class:`_engine.Connection` should be considered
  1184. "single use", automatically closing when the first result set is
  1185. closed. This flag only has an effect if this :class:`.Session` is
  1186. configured with ``autocommit=True`` and does not already have a
  1187. transaction in progress.
  1188. .. deprecated:: 1.4 this parameter is deprecated and will be removed
  1189. in SQLAlchemy 2.0
  1190. :param execution_options: a dictionary of execution options that will
  1191. be passed to :meth:`_engine.Connection.execution_options`, **when the
  1192. connection is first procured only**. If the connection is already
  1193. present within the :class:`.Session`, a warning is emitted and
  1194. the arguments are ignored.
  1195. .. seealso::
  1196. :ref:`session_transaction_isolation`
  1197. :param \**kw:
  1198. deprecated; use bind_arguments
  1199. """
  1200. if not bind_arguments:
  1201. bind_arguments = kw
  1202. bind = bind_arguments.pop("bind", None)
  1203. if bind is None:
  1204. bind = self.get_bind(**bind_arguments)
  1205. return self._connection_for_bind(
  1206. bind,
  1207. close_with_result=close_with_result,
  1208. execution_options=execution_options,
  1209. )
  1210. def _connection_for_bind(self, engine, execution_options=None, **kw):
  1211. TransactionalContext._trans_ctx_check(self)
  1212. if self._transaction is not None or self._autobegin():
  1213. return self._transaction._connection_for_bind(
  1214. engine, execution_options
  1215. )
  1216. assert self._transaction is None
  1217. assert self.autocommit
  1218. conn = engine.connect(**kw)
  1219. if execution_options:
  1220. conn = conn.execution_options(**execution_options)
  1221. return conn
  1222. def execute(
  1223. self,
  1224. statement,
  1225. params=None,
  1226. execution_options=util.EMPTY_DICT,
  1227. bind_arguments=None,
  1228. _parent_execute_state=None,
  1229. _add_event=None,
  1230. **kw
  1231. ):
  1232. r"""Execute a SQL expression construct.
  1233. Returns a :class:`_engine.Result` object representing
  1234. results of the statement execution.
  1235. E.g.::
  1236. from sqlalchemy import select
  1237. result = session.execute(
  1238. select(User).where(User.id == 5)
  1239. )
  1240. The API contract of :meth:`_orm.Session.execute` is similar to that
  1241. of :meth:`_future.Connection.execute`, the :term:`2.0 style` version
  1242. of :class:`_future.Connection`.
  1243. .. versionchanged:: 1.4 the :meth:`_orm.Session.execute` method is
  1244. now the primary point of ORM statement execution when using
  1245. :term:`2.0 style` ORM usage.
  1246. :param statement:
  1247. An executable statement (i.e. an :class:`.Executable` expression
  1248. such as :func:`_expression.select`).
  1249. :param params:
  1250. Optional dictionary, or list of dictionaries, containing
  1251. bound parameter values. If a single dictionary, single-row
  1252. execution occurs; if a list of dictionaries, an
  1253. "executemany" will be invoked. The keys in each dictionary
  1254. must correspond to parameter names present in the statement.
  1255. :param execution_options: optional dictionary of execution options,
  1256. which will be associated with the statement execution. This
  1257. dictionary can provide a subset of the options that are accepted
  1258. by :meth:`_engine.Connection.execution_options`, and may also
  1259. provide additional options understood only in an ORM context.
  1260. :param bind_arguments: dictionary of additional arguments to determine
  1261. the bind. May include "mapper", "bind", or other custom arguments.
  1262. Contents of this dictionary are passed to the
  1263. :meth:`.Session.get_bind` method.
  1264. :param mapper:
  1265. deprecated; use the bind_arguments dictionary
  1266. :param bind:
  1267. deprecated; use the bind_arguments dictionary
  1268. :param \**kw:
  1269. deprecated; use the bind_arguments dictionary
  1270. :return: a :class:`_engine.Result` object.
  1271. """
  1272. statement = coercions.expect(roles.StatementRole, statement)
  1273. if kw:
  1274. util.warn_deprecated_20(
  1275. "Passing bind arguments to Session.execute() as keyword "
  1276. "arguments is deprecated and will be removed SQLAlchemy 2.0. "
  1277. "Please use the bind_arguments parameter."
  1278. )
  1279. if not bind_arguments:
  1280. bind_arguments = kw
  1281. else:
  1282. bind_arguments.update(kw)
  1283. elif not bind_arguments:
  1284. bind_arguments = {}
  1285. else:
  1286. bind_arguments = dict(bind_arguments)
  1287. if (
  1288. statement._propagate_attrs.get("compile_state_plugin", None)
  1289. == "orm"
  1290. ):
  1291. # note that even without "future" mode, we need
  1292. compile_state_cls = CompileState._get_plugin_class_for_plugin(
  1293. statement, "orm"
  1294. )
  1295. else:
  1296. compile_state_cls = None
  1297. execution_options = util.coerce_to_immutabledict(execution_options)
  1298. if compile_state_cls is not None:
  1299. (
  1300. statement,
  1301. execution_options,
  1302. ) = compile_state_cls.orm_pre_session_exec(
  1303. self,
  1304. statement,
  1305. params,
  1306. execution_options,
  1307. bind_arguments,
  1308. _parent_execute_state is not None,
  1309. )
  1310. else:
  1311. bind_arguments.setdefault("clause", statement)
  1312. execution_options = execution_options.union(
  1313. {"future_result": True}
  1314. )
  1315. if _parent_execute_state:
  1316. events_todo = _parent_execute_state._remaining_events()
  1317. else:
  1318. events_todo = self.dispatch.do_orm_execute
  1319. if _add_event:
  1320. events_todo = list(events_todo) + [_add_event]
  1321. if events_todo:
  1322. orm_exec_state = ORMExecuteState(
  1323. self,
  1324. statement,
  1325. params,
  1326. execution_options,
  1327. bind_arguments,
  1328. compile_state_cls,
  1329. events_todo,
  1330. )
  1331. for idx, fn in enumerate(events_todo):
  1332. orm_exec_state._starting_event_idx = idx
  1333. result = fn(orm_exec_state)
  1334. if result:
  1335. return result
  1336. statement = orm_exec_state.statement
  1337. execution_options = orm_exec_state.local_execution_options
  1338. bind = self.get_bind(**bind_arguments)
  1339. if self.autocommit:
  1340. # legacy stuff, we can't use future_result w/ autocommit because
  1341. # we rely upon close_with_result, also legacy. it's all
  1342. # interrelated
  1343. conn = self._connection_for_bind(bind, close_with_result=True)
  1344. execution_options = execution_options.union(
  1345. dict(future_result=False)
  1346. )
  1347. else:
  1348. conn = self._connection_for_bind(bind)
  1349. result = conn._execute_20(statement, params or {}, execution_options)
  1350. if compile_state_cls:
  1351. result = compile_state_cls.orm_setup_cursor_result(
  1352. self,
  1353. statement,
  1354. params,
  1355. execution_options,
  1356. bind_arguments,
  1357. result,
  1358. )
  1359. return result
  1360. def scalar(
  1361. self,
  1362. statement,
  1363. params=None,
  1364. execution_options=util.EMPTY_DICT,
  1365. bind_arguments=None,
  1366. **kw
  1367. ):
  1368. """Execute a statement and return a scalar result.
  1369. Usage and parameters are the same as that of
  1370. :meth:`_orm.Session.execute`; the return result is a scalar Python
  1371. value.
  1372. """
  1373. return self.execute(
  1374. statement,
  1375. params=params,
  1376. execution_options=execution_options,
  1377. bind_arguments=bind_arguments,
  1378. **kw
  1379. ).scalar()
  1380. def scalars(
  1381. self,
  1382. statement,
  1383. params=None,
  1384. execution_options=util.EMPTY_DICT,
  1385. bind_arguments=None,
  1386. **kw
  1387. ):
  1388. """Execute a statement and return the results as scalars.
  1389. Usage and parameters are the same as that of
  1390. :meth:`_orm.Session.execute`; the return result is a
  1391. :class:`_result.ScalarResult` filtering object which
  1392. will return single elements rather than :class:`_row.Row` objects.
  1393. :return: a :class:`_result.ScalarResult` object
  1394. .. versionadded:: 1.4.24 Added :meth:`_orm.Session.scalars`
  1395. .. versionadded:: 1.4.26 Added :meth:`_orm.scoped_session.scalars`
  1396. """
  1397. return self.execute(
  1398. statement,
  1399. params=params,
  1400. execution_options=execution_options,
  1401. bind_arguments=bind_arguments,
  1402. **kw
  1403. ).scalars()
  1404. def close(self):
  1405. """Close out the transactional resources and ORM objects used by this
  1406. :class:`_orm.Session`.
  1407. This expunges all ORM objects associated with this
  1408. :class:`_orm.Session`, ends any transaction in progress and
  1409. :term:`releases` any :class:`_engine.Connection` objects which this
  1410. :class:`_orm.Session` itself has checked out from associated
  1411. :class:`_engine.Engine` objects. The operation then leaves the
  1412. :class:`_orm.Session` in a state which it may be used again.
  1413. .. tip::
  1414. The :meth:`_orm.Session.close` method **does not prevent the
  1415. Session from being used again**. The :class:`_orm.Session` itself
  1416. does not actually have a distinct "closed" state; it merely means
  1417. the :class:`_orm.Session` will release all database connections
  1418. and ORM objects.
  1419. .. versionchanged:: 1.4 The :meth:`.Session.close` method does not
  1420. immediately create a new :class:`.SessionTransaction` object;
  1421. instead, the new :class:`.SessionTransaction` is created only if
  1422. the :class:`.Session` is used again for a database operation.
  1423. .. seealso::
  1424. :ref:`session_closing` - detail on the semantics of
  1425. :meth:`_orm.Session.close`
  1426. """
  1427. self._close_impl(invalidate=False)
  1428. def invalidate(self):
  1429. """Close this Session, using connection invalidation.
  1430. This is a variant of :meth:`.Session.close` that will additionally
  1431. ensure that the :meth:`_engine.Connection.invalidate`
  1432. method will be called on each :class:`_engine.Connection` object
  1433. that is currently in use for a transaction (typically there is only
  1434. one connection unless the :class:`_orm.Session` is used with
  1435. multiple engines).
  1436. This can be called when the database is known to be in a state where
  1437. the connections are no longer safe to be used.
  1438. Below illustrates a scenario when using `gevent
  1439. <https://www.gevent.org/>`_, which can produce ``Timeout`` exceptions
  1440. that may mean the underlying connection should be discarded::
  1441. import gevent
  1442. try:
  1443. sess = Session()
  1444. sess.add(User())
  1445. sess.commit()
  1446. except gevent.Timeout:
  1447. sess.invalidate()
  1448. raise
  1449. except:
  1450. sess.rollback()
  1451. raise
  1452. The method additionally does everything that :meth:`_orm.Session.close`
  1453. does, including that all ORM objects are expunged.
  1454. """
  1455. self._close_impl(invalidate=True)
  1456. def _close_impl(self, invalidate):
  1457. self.expunge_all()
  1458. if self._transaction is not None:
  1459. for transaction in self._transaction._iterate_self_and_parents():
  1460. transaction.close(invalidate)
  1461. def expunge_all(self):
  1462. """Remove all object instances from this ``Session``.
  1463. This is equivalent to calling ``expunge(obj)`` on all objects in this
  1464. ``Session``.
  1465. """
  1466. all_states = self.identity_map.all_states() + list(self._new)
  1467. self.identity_map._kill()
  1468. self.identity_map = identity.WeakInstanceDict()
  1469. self._new = {}
  1470. self._deleted = {}
  1471. statelib.InstanceState._detach_states(all_states, self)
  1472. def _add_bind(self, key, bind):
  1473. try:
  1474. insp = inspect(key)
  1475. except sa_exc.NoInspectionAvailable as err:
  1476. if not isinstance(key, type):
  1477. util.raise_(
  1478. sa_exc.ArgumentError(
  1479. "Not an acceptable bind target: %s" % key
  1480. ),
  1481. replace_context=err,
  1482. )
  1483. else:
  1484. self.__binds[key] = bind
  1485. else:
  1486. if insp.is_selectable:
  1487. self.__binds[insp] = bind
  1488. elif insp.is_mapper:
  1489. self.__binds[insp.class_] = bind
  1490. for _selectable in insp._all_tables:
  1491. self.__binds[_selectable] = bind
  1492. else:
  1493. raise sa_exc.ArgumentError(
  1494. "Not an acceptable bind target: %s" % key
  1495. )
  1496. def bind_mapper(self, mapper, bind):
  1497. """Associate a :class:`_orm.Mapper` or arbitrary Python class with a
  1498. "bind", e.g. an :class:`_engine.Engine` or
  1499. :class:`_engine.Connection`.
  1500. The given entity is added to a lookup used by the
  1501. :meth:`.Session.get_bind` method.
  1502. :param mapper: a :class:`_orm.Mapper` object,
  1503. or an instance of a mapped
  1504. class, or any Python class that is the base of a set of mapped
  1505. classes.
  1506. :param bind: an :class:`_engine.Engine` or :class:`_engine.Connection`
  1507. object.
  1508. .. seealso::
  1509. :ref:`session_partitioning`
  1510. :paramref:`.Session.binds`
  1511. :meth:`.Session.bind_table`
  1512. """
  1513. self._add_bind(mapper, bind)
  1514. def bind_table(self, table, bind):
  1515. """Associate a :class:`_schema.Table` with a "bind", e.g. an
  1516. :class:`_engine.Engine`
  1517. or :class:`_engine.Connection`.
  1518. The given :class:`_schema.Table` is added to a lookup used by the
  1519. :meth:`.Session.get_bind` method.
  1520. :param table: a :class:`_schema.Table` object,
  1521. which is typically the target
  1522. of an ORM mapping, or is present within a selectable that is
  1523. mapped.
  1524. :param bind: an :class:`_engine.Engine` or :class:`_engine.Connection`
  1525. object.
  1526. .. seealso::
  1527. :ref:`session_partitioning`
  1528. :paramref:`.Session.binds`
  1529. :meth:`.Session.bind_mapper`
  1530. """
  1531. self._add_bind(table, bind)
  1532. def get_bind(
  1533. self,
  1534. mapper=None,
  1535. clause=None,
  1536. bind=None,
  1537. _sa_skip_events=None,
  1538. _sa_skip_for_implicit_returning=False,
  1539. ):
  1540. """Return a "bind" to which this :class:`.Session` is bound.
  1541. The "bind" is usually an instance of :class:`_engine.Engine`,
  1542. except in the case where the :class:`.Session` has been
  1543. explicitly bound directly to a :class:`_engine.Connection`.
  1544. For a multiply-bound or unbound :class:`.Session`, the
  1545. ``mapper`` or ``clause`` arguments are used to determine the
  1546. appropriate bind to return.
  1547. Note that the "mapper" argument is usually present
  1548. when :meth:`.Session.get_bind` is called via an ORM
  1549. operation such as a :meth:`.Session.query`, each
  1550. individual INSERT/UPDATE/DELETE operation within a
  1551. :meth:`.Session.flush`, call, etc.
  1552. The order of resolution is:
  1553. 1. if mapper given and :paramref:`.Session.binds` is present,
  1554. locate a bind based first on the mapper in use, then
  1555. on the mapped class in use, then on any base classes that are
  1556. present in the ``__mro__`` of the mapped class, from more specific
  1557. superclasses to more general.
  1558. 2. if clause given and ``Session.binds`` is present,
  1559. locate a bind based on :class:`_schema.Table` objects
  1560. found in the given clause present in ``Session.binds``.
  1561. 3. if ``Session.binds`` is present, return that.
  1562. 4. if clause given, attempt to return a bind
  1563. linked to the :class:`_schema.MetaData` ultimately
  1564. associated with the clause.
  1565. 5. if mapper given, attempt to return a bind
  1566. linked to the :class:`_schema.MetaData` ultimately
  1567. associated with the :class:`_schema.Table` or other
  1568. selectable to which the mapper is mapped.
  1569. 6. No bind can be found, :exc:`~sqlalchemy.exc.UnboundExecutionError`
  1570. is raised.
  1571. Note that the :meth:`.Session.get_bind` method can be overridden on
  1572. a user-defined subclass of :class:`.Session` to provide any kind
  1573. of bind resolution scheme. See the example at
  1574. :ref:`session_custom_partitioning`.
  1575. :param mapper:
  1576. Optional :func:`.mapper` mapped class or instance of
  1577. :class:`_orm.Mapper`. The bind can be derived from a
  1578. :class:`_orm.Mapper`
  1579. first by consulting the "binds" map associated with this
  1580. :class:`.Session`, and secondly by consulting the
  1581. :class:`_schema.MetaData`
  1582. associated with the :class:`_schema.Table` to which the
  1583. :class:`_orm.Mapper`
  1584. is mapped for a bind.
  1585. :param clause:
  1586. A :class:`_expression.ClauseElement` (i.e.
  1587. :func:`_expression.select`,
  1588. :func:`_expression.text`,
  1589. etc.). If the ``mapper`` argument is not present or could not
  1590. produce a bind, the given expression construct will be searched
  1591. for a bound element, typically a :class:`_schema.Table`
  1592. associated with
  1593. bound :class:`_schema.MetaData`.
  1594. .. seealso::
  1595. :ref:`session_partitioning`
  1596. :paramref:`.Session.binds`
  1597. :meth:`.Session.bind_mapper`
  1598. :meth:`.Session.bind_table`
  1599. """
  1600. # this function is documented as a subclassing hook, so we have
  1601. # to call this method even if the return is simple
  1602. if bind:
  1603. return bind
  1604. elif not self.__binds and self.bind:
  1605. # simplest and most common case, we have a bind and no
  1606. # per-mapper/table binds, we're done
  1607. return self.bind
  1608. # we don't have self.bind and either have self.__binds
  1609. # or we don't have self.__binds (which is legacy). Look at the
  1610. # mapper and the clause
  1611. if mapper is clause is None:
  1612. if self.bind:
  1613. return self.bind
  1614. else:
  1615. raise sa_exc.UnboundExecutionError(
  1616. "This session is not bound to a single Engine or "
  1617. "Connection, and no context was provided to locate "
  1618. "a binding."
  1619. )
  1620. # look more closely at the mapper.
  1621. if mapper is not None:
  1622. try:
  1623. mapper = inspect(mapper)
  1624. except sa_exc.NoInspectionAvailable as err:
  1625. if isinstance(mapper, type):
  1626. util.raise_(
  1627. exc.UnmappedClassError(mapper),
  1628. replace_context=err,
  1629. )
  1630. else:
  1631. raise
  1632. # match up the mapper or clause in the __binds
  1633. if self.__binds:
  1634. # matching mappers and selectables to entries in the
  1635. # binds dictionary; supported use case.
  1636. if mapper:
  1637. for cls in mapper.class_.__mro__:
  1638. if cls in self.__binds:
  1639. return self.__binds[cls]
  1640. if clause is None:
  1641. clause = mapper.persist_selectable
  1642. if clause is not None:
  1643. plugin_subject = clause._propagate_attrs.get(
  1644. "plugin_subject", None
  1645. )
  1646. if plugin_subject is not None:
  1647. for cls in plugin_subject.mapper.class_.__mro__:
  1648. if cls in self.__binds:
  1649. return self.__binds[cls]
  1650. for obj in visitors.iterate(clause):
  1651. if obj in self.__binds:
  1652. return self.__binds[obj]
  1653. # none of the __binds matched, but we have a fallback bind.
  1654. # return that
  1655. if self.bind:
  1656. return self.bind
  1657. # now we are in legacy territory. looking for "bind" on tables
  1658. # that are via bound metadata. this goes away in 2.0.
  1659. future_msg = ""
  1660. future_code = ""
  1661. if mapper and clause is None:
  1662. clause = mapper.persist_selectable
  1663. if clause is not None:
  1664. if clause.bind:
  1665. if self.future:
  1666. future_msg = (
  1667. " A bind was located via legacy bound metadata, but "
  1668. "since future=True is set on this Session, this "
  1669. "bind is ignored."
  1670. )
  1671. else:
  1672. util.warn_deprecated_20(
  1673. "This Session located a target engine via bound "
  1674. "metadata; as this functionality will be removed in "
  1675. "SQLAlchemy 2.0, an Engine object should be passed "
  1676. "to the Session() constructor directly."
  1677. )
  1678. return clause.bind
  1679. if mapper:
  1680. if mapper.persist_selectable.bind:
  1681. if self.future:
  1682. future_msg = (
  1683. " A bind was located via legacy bound metadata, but "
  1684. "since future=True is set on this Session, this "
  1685. "bind is ignored."
  1686. )
  1687. else:
  1688. util.warn_deprecated_20(
  1689. "This Session located a target engine via bound "
  1690. "metadata; as this functionality will be removed in "
  1691. "SQLAlchemy 2.0, an Engine object should be passed "
  1692. "to the Session() constructor directly."
  1693. )
  1694. return mapper.persist_selectable.bind
  1695. context = []
  1696. if mapper is not None:
  1697. context.append("mapper %s" % mapper)
  1698. if clause is not None:
  1699. context.append("SQL expression")
  1700. raise sa_exc.UnboundExecutionError(
  1701. "Could not locate a bind configured on %s or this Session.%s"
  1702. % (", ".join(context), future_msg),
  1703. code=future_code,
  1704. )
  1705. def query(self, *entities, **kwargs):
  1706. """Return a new :class:`_query.Query` object corresponding to this
  1707. :class:`_orm.Session`.
  1708. """
  1709. return self._query_cls(entities, self, **kwargs)
  1710. def _identity_lookup(
  1711. self,
  1712. mapper,
  1713. primary_key_identity,
  1714. identity_token=None,
  1715. passive=attributes.PASSIVE_OFF,
  1716. lazy_loaded_from=None,
  1717. ):
  1718. """Locate an object in the identity map.
  1719. Given a primary key identity, constructs an identity key and then
  1720. looks in the session's identity map. If present, the object may
  1721. be run through unexpiration rules (e.g. load unloaded attributes,
  1722. check if was deleted).
  1723. e.g.::
  1724. obj = session._identity_lookup(inspect(SomeClass), (1, ))
  1725. :param mapper: mapper in use
  1726. :param primary_key_identity: the primary key we are searching for, as
  1727. a tuple.
  1728. :param identity_token: identity token that should be used to create
  1729. the identity key. Used as is, however overriding subclasses can
  1730. repurpose this in order to interpret the value in a special way,
  1731. such as if None then look among multiple target tokens.
  1732. :param passive: passive load flag passed to
  1733. :func:`.loading.get_from_identity`, which impacts the behavior if
  1734. the object is found; the object may be validated and/or unexpired
  1735. if the flag allows for SQL to be emitted.
  1736. :param lazy_loaded_from: an :class:`.InstanceState` that is
  1737. specifically asking for this identity as a related identity. Used
  1738. for sharding schemes where there is a correspondence between an object
  1739. and a related object being lazy-loaded (or otherwise
  1740. relationship-loaded).
  1741. :return: None if the object is not found in the identity map, *or*
  1742. if the object was unexpired and found to have been deleted.
  1743. if passive flags disallow SQL and the object is expired, returns
  1744. PASSIVE_NO_RESULT. In all other cases the instance is returned.
  1745. .. versionchanged:: 1.4.0 - the :meth:`.Session._identity_lookup`
  1746. method was moved from :class:`_query.Query` to
  1747. :class:`.Session`, to avoid having to instantiate the
  1748. :class:`_query.Query` object.
  1749. """
  1750. key = mapper.identity_key_from_primary_key(
  1751. primary_key_identity, identity_token=identity_token
  1752. )
  1753. return loading.get_from_identity(self, mapper, key, passive)
  1754. @property
  1755. @util.contextmanager
  1756. def no_autoflush(self):
  1757. """Return a context manager that disables autoflush.
  1758. e.g.::
  1759. with session.no_autoflush:
  1760. some_object = SomeClass()
  1761. session.add(some_object)
  1762. # won't autoflush
  1763. some_object.related_thing = session.query(SomeRelated).first()
  1764. Operations that proceed within the ``with:`` block
  1765. will not be subject to flushes occurring upon query
  1766. access. This is useful when initializing a series
  1767. of objects which involve existing database queries,
  1768. where the uncompleted object should not yet be flushed.
  1769. """
  1770. autoflush = self.autoflush
  1771. self.autoflush = False
  1772. try:
  1773. yield self
  1774. finally:
  1775. self.autoflush = autoflush
  1776. def _autoflush(self):
  1777. if self.autoflush and not self._flushing:
  1778. try:
  1779. self.flush()
  1780. except sa_exc.StatementError as e:
  1781. # note we are reraising StatementError as opposed to
  1782. # raising FlushError with "chaining" to remain compatible
  1783. # with code that catches StatementError, IntegrityError,
  1784. # etc.
  1785. e.add_detail(
  1786. "raised as a result of Query-invoked autoflush; "
  1787. "consider using a session.no_autoflush block if this "
  1788. "flush is occurring prematurely"
  1789. )
  1790. util.raise_(e, with_traceback=sys.exc_info()[2])
  1791. def refresh(self, instance, attribute_names=None, with_for_update=None):
  1792. """Expire and refresh attributes on the given instance.
  1793. The selected attributes will first be expired as they would when using
  1794. :meth:`_orm.Session.expire`; then a SELECT statement will be issued to
  1795. the database to refresh column-oriented attributes with the current
  1796. value available in the current transaction.
  1797. :func:`_orm.relationship` oriented attributes will also be immediately
  1798. loaded if they were already eagerly loaded on the object, using the
  1799. same eager loading strategy that they were loaded with originally.
  1800. Unloaded relationship attributes will remain unloaded, as will
  1801. relationship attributes that were originally lazy loaded.
  1802. .. versionadded:: 1.4 - the :meth:`_orm.Session.refresh` method
  1803. can also refresh eagerly loaded attributes.
  1804. .. tip::
  1805. While the :meth:`_orm.Session.refresh` method is capable of
  1806. refreshing both column and relationship oriented attributes, its
  1807. primary focus is on refreshing of local column-oriented attributes
  1808. on a single instance. For more open ended "refresh" functionality,
  1809. including the ability to refresh the attributes on many objects at
  1810. once while having explicit control over relationship loader
  1811. strategies, use the
  1812. :ref:`populate existing <orm_queryguide_populate_existing>` feature
  1813. instead.
  1814. Note that a highly isolated transaction will return the same values as
  1815. were previously read in that same transaction, regardless of changes
  1816. in database state outside of that transaction. Refreshing
  1817. attributes usually only makes sense at the start of a transaction
  1818. where database rows have not yet been accessed.
  1819. :param attribute_names: optional. An iterable collection of
  1820. string attribute names indicating a subset of attributes to
  1821. be refreshed.
  1822. :param with_for_update: optional boolean ``True`` indicating FOR UPDATE
  1823. should be used, or may be a dictionary containing flags to
  1824. indicate a more specific set of FOR UPDATE flags for the SELECT;
  1825. flags should match the parameters of
  1826. :meth:`_query.Query.with_for_update`.
  1827. Supersedes the :paramref:`.Session.refresh.lockmode` parameter.
  1828. .. seealso::
  1829. :ref:`session_expire` - introductory material
  1830. :meth:`.Session.expire`
  1831. :meth:`.Session.expire_all`
  1832. :ref:`orm_queryguide_populate_existing` - allows any ORM query
  1833. to refresh objects as they would be loaded normally.
  1834. """
  1835. try:
  1836. state = attributes.instance_state(instance)
  1837. except exc.NO_STATE as err:
  1838. util.raise_(
  1839. exc.UnmappedInstanceError(instance),
  1840. replace_context=err,
  1841. )
  1842. self._expire_state(state, attribute_names)
  1843. if with_for_update == {}:
  1844. raise sa_exc.ArgumentError(
  1845. "with_for_update should be the boolean value "
  1846. "True, or a dictionary with options. "
  1847. "A blank dictionary is ambiguous."
  1848. )
  1849. with_for_update = query.ForUpdateArg._from_argument(with_for_update)
  1850. stmt = sql.select(object_mapper(instance))
  1851. if (
  1852. loading.load_on_ident(
  1853. self,
  1854. stmt,
  1855. state.key,
  1856. refresh_state=state,
  1857. with_for_update=with_for_update,
  1858. only_load_props=attribute_names,
  1859. )
  1860. is None
  1861. ):
  1862. raise sa_exc.InvalidRequestError(
  1863. "Could not refresh instance '%s'" % instance_str(instance)
  1864. )
  1865. def expire_all(self):
  1866. """Expires all persistent instances within this Session.
  1867. When any attributes on a persistent instance is next accessed,
  1868. a query will be issued using the
  1869. :class:`.Session` object's current transactional context in order to
  1870. load all expired attributes for the given instance. Note that
  1871. a highly isolated transaction will return the same values as were
  1872. previously read in that same transaction, regardless of changes
  1873. in database state outside of that transaction.
  1874. To expire individual objects and individual attributes
  1875. on those objects, use :meth:`Session.expire`.
  1876. The :class:`.Session` object's default behavior is to
  1877. expire all state whenever the :meth:`Session.rollback`
  1878. or :meth:`Session.commit` methods are called, so that new
  1879. state can be loaded for the new transaction. For this reason,
  1880. calling :meth:`Session.expire_all` should not be needed when
  1881. autocommit is ``False``, assuming the transaction is isolated.
  1882. .. seealso::
  1883. :ref:`session_expire` - introductory material
  1884. :meth:`.Session.expire`
  1885. :meth:`.Session.refresh`
  1886. :meth:`_orm.Query.populate_existing`
  1887. """
  1888. for state in self.identity_map.all_states():
  1889. state._expire(state.dict, self.identity_map._modified)
  1890. def expire(self, instance, attribute_names=None):
  1891. """Expire the attributes on an instance.
  1892. Marks the attributes of an instance as out of date. When an expired
  1893. attribute is next accessed, a query will be issued to the
  1894. :class:`.Session` object's current transactional context in order to
  1895. load all expired attributes for the given instance. Note that
  1896. a highly isolated transaction will return the same values as were
  1897. previously read in that same transaction, regardless of changes
  1898. in database state outside of that transaction.
  1899. To expire all objects in the :class:`.Session` simultaneously,
  1900. use :meth:`Session.expire_all`.
  1901. The :class:`.Session` object's default behavior is to
  1902. expire all state whenever the :meth:`Session.rollback`
  1903. or :meth:`Session.commit` methods are called, so that new
  1904. state can be loaded for the new transaction. For this reason,
  1905. calling :meth:`Session.expire` only makes sense for the specific
  1906. case that a non-ORM SQL statement was emitted in the current
  1907. transaction.
  1908. :param instance: The instance to be refreshed.
  1909. :param attribute_names: optional list of string attribute names
  1910. indicating a subset of attributes to be expired.
  1911. .. seealso::
  1912. :ref:`session_expire` - introductory material
  1913. :meth:`.Session.expire`
  1914. :meth:`.Session.refresh`
  1915. :meth:`_orm.Query.populate_existing`
  1916. """
  1917. try:
  1918. state = attributes.instance_state(instance)
  1919. except exc.NO_STATE as err:
  1920. util.raise_(
  1921. exc.UnmappedInstanceError(instance),
  1922. replace_context=err,
  1923. )
  1924. self._expire_state(state, attribute_names)
  1925. def _expire_state(self, state, attribute_names):
  1926. self._validate_persistent(state)
  1927. if attribute_names:
  1928. state._expire_attributes(state.dict, attribute_names)
  1929. else:
  1930. # pre-fetch the full cascade since the expire is going to
  1931. # remove associations
  1932. cascaded = list(
  1933. state.manager.mapper.cascade_iterator("refresh-expire", state)
  1934. )
  1935. self._conditional_expire(state)
  1936. for o, m, st_, dct_ in cascaded:
  1937. self._conditional_expire(st_)
  1938. def _conditional_expire(self, state, autoflush=None):
  1939. """Expire a state if persistent, else expunge if pending"""
  1940. if state.key:
  1941. state._expire(state.dict, self.identity_map._modified)
  1942. elif state in self._new:
  1943. self._new.pop(state)
  1944. state._detach(self)
  1945. def expunge(self, instance):
  1946. """Remove the `instance` from this ``Session``.
  1947. This will free all internal references to the instance. Cascading
  1948. will be applied according to the *expunge* cascade rule.
  1949. """
  1950. try:
  1951. state = attributes.instance_state(instance)
  1952. except exc.NO_STATE as err:
  1953. util.raise_(
  1954. exc.UnmappedInstanceError(instance),
  1955. replace_context=err,
  1956. )
  1957. if state.session_id is not self.hash_key:
  1958. raise sa_exc.InvalidRequestError(
  1959. "Instance %s is not present in this Session" % state_str(state)
  1960. )
  1961. cascaded = list(
  1962. state.manager.mapper.cascade_iterator("expunge", state)
  1963. )
  1964. self._expunge_states([state] + [st_ for o, m, st_, dct_ in cascaded])
  1965. def _expunge_states(self, states, to_transient=False):
  1966. for state in states:
  1967. if state in self._new:
  1968. self._new.pop(state)
  1969. elif self.identity_map.contains_state(state):
  1970. self.identity_map.safe_discard(state)
  1971. self._deleted.pop(state, None)
  1972. elif self._transaction:
  1973. # state is "detached" from being deleted, but still present
  1974. # in the transaction snapshot
  1975. self._transaction._deleted.pop(state, None)
  1976. statelib.InstanceState._detach_states(
  1977. states, self, to_transient=to_transient
  1978. )
  1979. def _register_persistent(self, states):
  1980. """Register all persistent objects from a flush.
  1981. This is used both for pending objects moving to the persistent
  1982. state as well as already persistent objects.
  1983. """
  1984. pending_to_persistent = self.dispatch.pending_to_persistent or None
  1985. for state in states:
  1986. mapper = _state_mapper(state)
  1987. # prevent against last minute dereferences of the object
  1988. obj = state.obj()
  1989. if obj is not None:
  1990. instance_key = mapper._identity_key_from_state(state)
  1991. if (
  1992. _none_set.intersection(instance_key[1])
  1993. and not mapper.allow_partial_pks
  1994. or _none_set.issuperset(instance_key[1])
  1995. ):
  1996. raise exc.FlushError(
  1997. "Instance %s has a NULL identity key. If this is an "
  1998. "auto-generated value, check that the database table "
  1999. "allows generation of new primary key values, and "
  2000. "that the mapped Column object is configured to "
  2001. "expect these generated values. Ensure also that "
  2002. "this flush() is not occurring at an inappropriate "
  2003. "time, such as within a load() event."
  2004. % state_str(state)
  2005. )
  2006. if state.key is None:
  2007. state.key = instance_key
  2008. elif state.key != instance_key:
  2009. # primary key switch. use safe_discard() in case another
  2010. # state has already replaced this one in the identity
  2011. # map (see test/orm/test_naturalpks.py ReversePKsTest)
  2012. self.identity_map.safe_discard(state)
  2013. if state in self._transaction._key_switches:
  2014. orig_key = self._transaction._key_switches[state][0]
  2015. else:
  2016. orig_key = state.key
  2017. self._transaction._key_switches[state] = (
  2018. orig_key,
  2019. instance_key,
  2020. )
  2021. state.key = instance_key
  2022. # there can be an existing state in the identity map
  2023. # that is replaced when the primary keys of two instances
  2024. # are swapped; see test/orm/test_naturalpks.py -> test_reverse
  2025. old = self.identity_map.replace(state)
  2026. if (
  2027. old is not None
  2028. and mapper._identity_key_from_state(old) == instance_key
  2029. and old.obj() is not None
  2030. ):
  2031. util.warn(
  2032. "Identity map already had an identity for %s, "
  2033. "replacing it with newly flushed object. Are there "
  2034. "load operations occurring inside of an event handler "
  2035. "within the flush?" % (instance_key,)
  2036. )
  2037. state._orphaned_outside_of_session = False
  2038. statelib.InstanceState._commit_all_states(
  2039. ((state, state.dict) for state in states), self.identity_map
  2040. )
  2041. self._register_altered(states)
  2042. if pending_to_persistent is not None:
  2043. for state in states.intersection(self._new):
  2044. pending_to_persistent(self, state)
  2045. # remove from new last, might be the last strong ref
  2046. for state in set(states).intersection(self._new):
  2047. self._new.pop(state)
  2048. def _register_altered(self, states):
  2049. if self._transaction:
  2050. for state in states:
  2051. if state in self._new:
  2052. self._transaction._new[state] = True
  2053. else:
  2054. self._transaction._dirty[state] = True
  2055. def _remove_newly_deleted(self, states):
  2056. persistent_to_deleted = self.dispatch.persistent_to_deleted or None
  2057. for state in states:
  2058. if self._transaction:
  2059. self._transaction._deleted[state] = True
  2060. if persistent_to_deleted is not None:
  2061. # get a strong reference before we pop out of
  2062. # self._deleted
  2063. obj = state.obj() # noqa
  2064. self.identity_map.safe_discard(state)
  2065. self._deleted.pop(state, None)
  2066. state._deleted = True
  2067. # can't call state._detach() here, because this state
  2068. # is still in the transaction snapshot and needs to be
  2069. # tracked as part of that
  2070. if persistent_to_deleted is not None:
  2071. persistent_to_deleted(self, state)
  2072. def add(self, instance, _warn=True):
  2073. """Place an object into this :class:`_orm.Session`.
  2074. Objects that are in the :term:`transient` state when passed to the
  2075. :meth:`_orm.Session.add` method will move to the
  2076. :term:`pending` state, until the next flush, at which point they
  2077. will move to the :term:`persistent` state.
  2078. Objects that are in the :term:`detached` state when passed to the
  2079. :meth:`_orm.Session.add` method will move to the :term:`persistent`
  2080. state directly.
  2081. If the transaction used by the :class:`_orm.Session` is rolled back,
  2082. objects which were transient when they were passed to
  2083. :meth:`_orm.Session.add` will be moved back to the
  2084. :term:`transient` state, and will no longer be present within this
  2085. :class:`_orm.Session`.
  2086. .. seealso::
  2087. :meth:`_orm.Session.add_all`
  2088. :ref:`session_adding` - at :ref:`session_basics`
  2089. """
  2090. if _warn and self._warn_on_events:
  2091. self._flush_warning("Session.add()")
  2092. try:
  2093. state = attributes.instance_state(instance)
  2094. except exc.NO_STATE as err:
  2095. util.raise_(
  2096. exc.UnmappedInstanceError(instance),
  2097. replace_context=err,
  2098. )
  2099. self._save_or_update_state(state)
  2100. def add_all(self, instances):
  2101. """Add the given collection of instances to this :class:`_orm.Session`.
  2102. See the documentation for :meth:`_orm.Session.add` for a general
  2103. behavioral description.
  2104. .. seealso::
  2105. :meth:`_orm.Session.add`
  2106. :ref:`session_adding` - at :ref:`session_basics`
  2107. """
  2108. if self._warn_on_events:
  2109. self._flush_warning("Session.add_all()")
  2110. for instance in instances:
  2111. self.add(instance, _warn=False)
  2112. def _save_or_update_state(self, state):
  2113. state._orphaned_outside_of_session = False
  2114. self._save_or_update_impl(state)
  2115. mapper = _state_mapper(state)
  2116. for o, m, st_, dct_ in mapper.cascade_iterator(
  2117. "save-update", state, halt_on=self._contains_state
  2118. ):
  2119. self._save_or_update_impl(st_)
  2120. def delete(self, instance):
  2121. """Mark an instance as deleted.
  2122. The object is assumed to be either :term:`persistent` or
  2123. :term:`detached` when passed; after the method is called, the
  2124. object will remain in the :term:`persistent` state until the next
  2125. flush proceeds. During this time, the object will also be a member
  2126. of the :attr:`_orm.Session.deleted` collection.
  2127. When the next flush proceeds, the object will move to the
  2128. :term:`deleted` state, indicating a ``DELETE`` statement was emitted
  2129. for its row within the current transaction. When the transaction
  2130. is successfully committed,
  2131. the deleted object is moved to the :term:`detached` state and is
  2132. no longer present within this :class:`_orm.Session`.
  2133. .. seealso::
  2134. :ref:`session_deleting` - at :ref:`session_basics`
  2135. """
  2136. if self._warn_on_events:
  2137. self._flush_warning("Session.delete()")
  2138. try:
  2139. state = attributes.instance_state(instance)
  2140. except exc.NO_STATE as err:
  2141. util.raise_(
  2142. exc.UnmappedInstanceError(instance),
  2143. replace_context=err,
  2144. )
  2145. self._delete_impl(state, instance, head=True)
  2146. def _delete_impl(self, state, obj, head):
  2147. if state.key is None:
  2148. if head:
  2149. raise sa_exc.InvalidRequestError(
  2150. "Instance '%s' is not persisted" % state_str(state)
  2151. )
  2152. else:
  2153. return
  2154. to_attach = self._before_attach(state, obj)
  2155. if state in self._deleted:
  2156. return
  2157. self.identity_map.add(state)
  2158. if to_attach:
  2159. self._after_attach(state, obj)
  2160. if head:
  2161. # grab the cascades before adding the item to the deleted list
  2162. # so that autoflush does not delete the item
  2163. # the strong reference to the instance itself is significant here
  2164. cascade_states = list(
  2165. state.manager.mapper.cascade_iterator("delete", state)
  2166. )
  2167. self._deleted[state] = obj
  2168. if head:
  2169. for o, m, st_, dct_ in cascade_states:
  2170. self._delete_impl(st_, o, False)
  2171. def get(
  2172. self,
  2173. entity,
  2174. ident,
  2175. options=None,
  2176. populate_existing=False,
  2177. with_for_update=None,
  2178. identity_token=None,
  2179. execution_options=None,
  2180. ):
  2181. """Return an instance based on the given primary key identifier,
  2182. or ``None`` if not found.
  2183. E.g.::
  2184. my_user = session.get(User, 5)
  2185. some_object = session.get(VersionedFoo, (5, 10))
  2186. some_object = session.get(
  2187. VersionedFoo,
  2188. {"id": 5, "version_id": 10}
  2189. )
  2190. .. versionadded:: 1.4 Added :meth:`_orm.Session.get`, which is moved
  2191. from the now deprecated :meth:`_orm.Query.get` method.
  2192. :meth:`_orm.Session.get` is special in that it provides direct
  2193. access to the identity map of the :class:`.Session`.
  2194. If the given primary key identifier is present
  2195. in the local identity map, the object is returned
  2196. directly from this collection and no SQL is emitted,
  2197. unless the object has been marked fully expired.
  2198. If not present,
  2199. a SELECT is performed in order to locate the object.
  2200. :meth:`_orm.Session.get` also will perform a check if
  2201. the object is present in the identity map and
  2202. marked as expired - a SELECT
  2203. is emitted to refresh the object as well as to
  2204. ensure that the row is still present.
  2205. If not, :class:`~sqlalchemy.orm.exc.ObjectDeletedError` is raised.
  2206. :param entity: a mapped class or :class:`.Mapper` indicating the
  2207. type of entity to be loaded.
  2208. :param ident: A scalar, tuple, or dictionary representing the
  2209. primary key. For a composite (e.g. multiple column) primary key,
  2210. a tuple or dictionary should be passed.
  2211. For a single-column primary key, the scalar calling form is typically
  2212. the most expedient. If the primary key of a row is the value "5",
  2213. the call looks like::
  2214. my_object = session.get(SomeClass, 5)
  2215. The tuple form contains primary key values typically in
  2216. the order in which they correspond to the mapped
  2217. :class:`_schema.Table`
  2218. object's primary key columns, or if the
  2219. :paramref:`_orm.Mapper.primary_key` configuration parameter were
  2220. used, in
  2221. the order used for that parameter. For example, if the primary key
  2222. of a row is represented by the integer
  2223. digits "5, 10" the call would look like::
  2224. my_object = session.get(SomeClass, (5, 10))
  2225. The dictionary form should include as keys the mapped attribute names
  2226. corresponding to each element of the primary key. If the mapped class
  2227. has the attributes ``id``, ``version_id`` as the attributes which
  2228. store the object's primary key value, the call would look like::
  2229. my_object = session.get(SomeClass, {"id": 5, "version_id": 10})
  2230. :param options: optional sequence of loader options which will be
  2231. applied to the query, if one is emitted.
  2232. :param populate_existing: causes the method to unconditionally emit
  2233. a SQL query and refresh the object with the newly loaded data,
  2234. regardless of whether or not the object is already present.
  2235. :param with_for_update: optional boolean ``True`` indicating FOR UPDATE
  2236. should be used, or may be a dictionary containing flags to
  2237. indicate a more specific set of FOR UPDATE flags for the SELECT;
  2238. flags should match the parameters of
  2239. :meth:`_query.Query.with_for_update`.
  2240. Supersedes the :paramref:`.Session.refresh.lockmode` parameter.
  2241. :param execution_options: optional dictionary of execution options,
  2242. which will be associated with the query execution if one is emitted.
  2243. This dictionary can provide a subset of the options that are
  2244. accepted by :meth:`_engine.Connection.execution_options`, and may
  2245. also provide additional options understood only in an ORM context.
  2246. .. versionadded:: 1.4.29
  2247. .. seealso::
  2248. :ref:`orm_queryguide_execution_options` - ORM-specific execution
  2249. options
  2250. :return: The object instance, or ``None``.
  2251. """
  2252. return self._get_impl(
  2253. entity,
  2254. ident,
  2255. loading.load_on_pk_identity,
  2256. options,
  2257. populate_existing=populate_existing,
  2258. with_for_update=with_for_update,
  2259. identity_token=identity_token,
  2260. execution_options=execution_options,
  2261. )
  2262. def _get_impl(
  2263. self,
  2264. entity,
  2265. primary_key_identity,
  2266. db_load_fn,
  2267. options=None,
  2268. populate_existing=False,
  2269. with_for_update=None,
  2270. identity_token=None,
  2271. execution_options=None,
  2272. ):
  2273. # convert composite types to individual args
  2274. if hasattr(primary_key_identity, "__composite_values__"):
  2275. primary_key_identity = primary_key_identity.__composite_values__()
  2276. mapper = inspect(entity)
  2277. if not mapper or not mapper.is_mapper:
  2278. raise sa_exc.ArgumentError(
  2279. "Expected mapped class or mapper, got: %r" % entity
  2280. )
  2281. is_dict = isinstance(primary_key_identity, dict)
  2282. if not is_dict:
  2283. primary_key_identity = util.to_list(
  2284. primary_key_identity, default=(None,)
  2285. )
  2286. if len(primary_key_identity) != len(mapper.primary_key):
  2287. raise sa_exc.InvalidRequestError(
  2288. "Incorrect number of values in identifier to formulate "
  2289. "primary key for session.get(); primary key columns "
  2290. "are %s" % ",".join("'%s'" % c for c in mapper.primary_key)
  2291. )
  2292. if is_dict:
  2293. pk_synonyms = mapper._pk_synonyms
  2294. if pk_synonyms:
  2295. correct_keys = set(pk_synonyms).intersection(
  2296. primary_key_identity
  2297. )
  2298. if correct_keys:
  2299. primary_key_identity = dict(primary_key_identity)
  2300. for k in correct_keys:
  2301. primary_key_identity[
  2302. pk_synonyms[k]
  2303. ] = primary_key_identity[k]
  2304. try:
  2305. primary_key_identity = list(
  2306. primary_key_identity[prop.key]
  2307. for prop in mapper._identity_key_props
  2308. )
  2309. except KeyError as err:
  2310. util.raise_(
  2311. sa_exc.InvalidRequestError(
  2312. "Incorrect names of values in identifier to formulate "
  2313. "primary key for session.get(); primary key attribute "
  2314. "names are %s (synonym names are also accepted)"
  2315. % ",".join(
  2316. "'%s'" % prop.key
  2317. for prop in mapper._identity_key_props
  2318. )
  2319. ),
  2320. replace_context=err,
  2321. )
  2322. if (
  2323. not populate_existing
  2324. and not mapper.always_refresh
  2325. and with_for_update is None
  2326. ):
  2327. instance = self._identity_lookup(
  2328. mapper, primary_key_identity, identity_token=identity_token
  2329. )
  2330. if instance is not None:
  2331. # reject calls for id in identity map but class
  2332. # mismatch.
  2333. if not issubclass(instance.__class__, mapper.class_):
  2334. return None
  2335. return instance
  2336. elif instance is attributes.PASSIVE_CLASS_MISMATCH:
  2337. return None
  2338. # set_label_style() not strictly necessary, however this will ensure
  2339. # that tablename_colname style is used which at the moment is
  2340. # asserted in a lot of unit tests :)
  2341. load_options = context.QueryContext.default_load_options
  2342. if populate_existing:
  2343. load_options += {"_populate_existing": populate_existing}
  2344. statement = sql.select(mapper).set_label_style(
  2345. LABEL_STYLE_TABLENAME_PLUS_COL
  2346. )
  2347. if with_for_update is not None:
  2348. statement._for_update_arg = query.ForUpdateArg._from_argument(
  2349. with_for_update
  2350. )
  2351. if options:
  2352. statement = statement.options(*options)
  2353. if execution_options:
  2354. statement = statement.execution_options(**execution_options)
  2355. return db_load_fn(
  2356. self,
  2357. statement,
  2358. primary_key_identity,
  2359. load_options=load_options,
  2360. )
  2361. def merge(self, instance, load=True, options=None):
  2362. """Copy the state of a given instance into a corresponding instance
  2363. within this :class:`.Session`.
  2364. :meth:`.Session.merge` examines the primary key attributes of the
  2365. source instance, and attempts to reconcile it with an instance of the
  2366. same primary key in the session. If not found locally, it attempts
  2367. to load the object from the database based on primary key, and if
  2368. none can be located, creates a new instance. The state of each
  2369. attribute on the source instance is then copied to the target
  2370. instance. The resulting target instance is then returned by the
  2371. method; the original source instance is left unmodified, and
  2372. un-associated with the :class:`.Session` if not already.
  2373. This operation cascades to associated instances if the association is
  2374. mapped with ``cascade="merge"``.
  2375. See :ref:`unitofwork_merging` for a detailed discussion of merging.
  2376. .. versionchanged:: 1.1 - :meth:`.Session.merge` will now reconcile
  2377. pending objects with overlapping primary keys in the same way
  2378. as persistent. See :ref:`change_3601` for discussion.
  2379. :param instance: Instance to be merged.
  2380. :param load: Boolean, when False, :meth:`.merge` switches into
  2381. a "high performance" mode which causes it to forego emitting history
  2382. events as well as all database access. This flag is used for
  2383. cases such as transferring graphs of objects into a :class:`.Session`
  2384. from a second level cache, or to transfer just-loaded objects
  2385. into the :class:`.Session` owned by a worker thread or process
  2386. without re-querying the database.
  2387. The ``load=False`` use case adds the caveat that the given
  2388. object has to be in a "clean" state, that is, has no pending changes
  2389. to be flushed - even if the incoming object is detached from any
  2390. :class:`.Session`. This is so that when
  2391. the merge operation populates local attributes and
  2392. cascades to related objects and
  2393. collections, the values can be "stamped" onto the
  2394. target object as is, without generating any history or attribute
  2395. events, and without the need to reconcile the incoming data with
  2396. any existing related objects or collections that might not
  2397. be loaded. The resulting objects from ``load=False`` are always
  2398. produced as "clean", so it is only appropriate that the given objects
  2399. should be "clean" as well, else this suggests a mis-use of the
  2400. method.
  2401. :param options: optional sequence of loader options which will be
  2402. applied to the :meth:`_orm.Session.get` method when the merge
  2403. operation loads the existing version of the object from the database.
  2404. .. versionadded:: 1.4.24
  2405. .. seealso::
  2406. :func:`.make_transient_to_detached` - provides for an alternative
  2407. means of "merging" a single object into the :class:`.Session`
  2408. """
  2409. if self._warn_on_events:
  2410. self._flush_warning("Session.merge()")
  2411. _recursive = {}
  2412. _resolve_conflict_map = {}
  2413. if load:
  2414. # flush current contents if we expect to load data
  2415. self._autoflush()
  2416. object_mapper(instance) # verify mapped
  2417. autoflush = self.autoflush
  2418. try:
  2419. self.autoflush = False
  2420. return self._merge(
  2421. attributes.instance_state(instance),
  2422. attributes.instance_dict(instance),
  2423. load=load,
  2424. options=options,
  2425. _recursive=_recursive,
  2426. _resolve_conflict_map=_resolve_conflict_map,
  2427. )
  2428. finally:
  2429. self.autoflush = autoflush
  2430. def _merge(
  2431. self,
  2432. state,
  2433. state_dict,
  2434. load=True,
  2435. options=None,
  2436. _recursive=None,
  2437. _resolve_conflict_map=None,
  2438. ):
  2439. mapper = _state_mapper(state)
  2440. if state in _recursive:
  2441. return _recursive[state]
  2442. new_instance = False
  2443. key = state.key
  2444. if key is None:
  2445. if state in self._new:
  2446. util.warn(
  2447. "Instance %s is already pending in this Session yet is "
  2448. "being merged again; this is probably not what you want "
  2449. "to do" % state_str(state)
  2450. )
  2451. if not load:
  2452. raise sa_exc.InvalidRequestError(
  2453. "merge() with load=False option does not support "
  2454. "objects transient (i.e. unpersisted) objects. flush() "
  2455. "all changes on mapped instances before merging with "
  2456. "load=False."
  2457. )
  2458. key = mapper._identity_key_from_state(state)
  2459. key_is_persistent = attributes.NEVER_SET not in key[1] and (
  2460. not _none_set.intersection(key[1])
  2461. or (
  2462. mapper.allow_partial_pks
  2463. and not _none_set.issuperset(key[1])
  2464. )
  2465. )
  2466. else:
  2467. key_is_persistent = True
  2468. if key in self.identity_map:
  2469. try:
  2470. merged = self.identity_map[key]
  2471. except KeyError:
  2472. # object was GC'ed right as we checked for it
  2473. merged = None
  2474. else:
  2475. merged = None
  2476. if merged is None:
  2477. if key_is_persistent and key in _resolve_conflict_map:
  2478. merged = _resolve_conflict_map[key]
  2479. elif not load:
  2480. if state.modified:
  2481. raise sa_exc.InvalidRequestError(
  2482. "merge() with load=False option does not support "
  2483. "objects marked as 'dirty'. flush() all changes on "
  2484. "mapped instances before merging with load=False."
  2485. )
  2486. merged = mapper.class_manager.new_instance()
  2487. merged_state = attributes.instance_state(merged)
  2488. merged_state.key = key
  2489. self._update_impl(merged_state)
  2490. new_instance = True
  2491. elif key_is_persistent:
  2492. merged = self.get(
  2493. mapper.class_,
  2494. key[1],
  2495. identity_token=key[2],
  2496. options=options,
  2497. )
  2498. if merged is None:
  2499. merged = mapper.class_manager.new_instance()
  2500. merged_state = attributes.instance_state(merged)
  2501. merged_dict = attributes.instance_dict(merged)
  2502. new_instance = True
  2503. self._save_or_update_state(merged_state)
  2504. else:
  2505. merged_state = attributes.instance_state(merged)
  2506. merged_dict = attributes.instance_dict(merged)
  2507. _recursive[state] = merged
  2508. _resolve_conflict_map[key] = merged
  2509. # check that we didn't just pull the exact same
  2510. # state out.
  2511. if state is not merged_state:
  2512. # version check if applicable
  2513. if mapper.version_id_col is not None:
  2514. existing_version = mapper._get_state_attr_by_column(
  2515. state,
  2516. state_dict,
  2517. mapper.version_id_col,
  2518. passive=attributes.PASSIVE_NO_INITIALIZE,
  2519. )
  2520. merged_version = mapper._get_state_attr_by_column(
  2521. merged_state,
  2522. merged_dict,
  2523. mapper.version_id_col,
  2524. passive=attributes.PASSIVE_NO_INITIALIZE,
  2525. )
  2526. if (
  2527. existing_version is not attributes.PASSIVE_NO_RESULT
  2528. and merged_version is not attributes.PASSIVE_NO_RESULT
  2529. and existing_version != merged_version
  2530. ):
  2531. raise exc.StaleDataError(
  2532. "Version id '%s' on merged state %s "
  2533. "does not match existing version '%s'. "
  2534. "Leave the version attribute unset when "
  2535. "merging to update the most recent version."
  2536. % (
  2537. existing_version,
  2538. state_str(merged_state),
  2539. merged_version,
  2540. )
  2541. )
  2542. merged_state.load_path = state.load_path
  2543. merged_state.load_options = state.load_options
  2544. # since we are copying load_options, we need to copy
  2545. # the callables_ that would have been generated by those
  2546. # load_options.
  2547. # assumes that the callables we put in state.callables_
  2548. # are not instance-specific (which they should not be)
  2549. merged_state._copy_callables(state)
  2550. for prop in mapper.iterate_properties:
  2551. prop.merge(
  2552. self,
  2553. state,
  2554. state_dict,
  2555. merged_state,
  2556. merged_dict,
  2557. load,
  2558. _recursive,
  2559. _resolve_conflict_map,
  2560. )
  2561. if not load:
  2562. # remove any history
  2563. merged_state._commit_all(merged_dict, self.identity_map)
  2564. merged_state.manager.dispatch._sa_event_merge_wo_load(
  2565. merged_state, None
  2566. )
  2567. if new_instance:
  2568. merged_state.manager.dispatch.load(merged_state, None)
  2569. return merged
  2570. def _validate_persistent(self, state):
  2571. if not self.identity_map.contains_state(state):
  2572. raise sa_exc.InvalidRequestError(
  2573. "Instance '%s' is not persistent within this Session"
  2574. % state_str(state)
  2575. )
  2576. def _save_impl(self, state):
  2577. if state.key is not None:
  2578. raise sa_exc.InvalidRequestError(
  2579. "Object '%s' already has an identity - "
  2580. "it can't be registered as pending" % state_str(state)
  2581. )
  2582. obj = state.obj()
  2583. to_attach = self._before_attach(state, obj)
  2584. if state not in self._new:
  2585. self._new[state] = obj
  2586. state.insert_order = len(self._new)
  2587. if to_attach:
  2588. self._after_attach(state, obj)
  2589. def _update_impl(self, state, revert_deletion=False):
  2590. if state.key is None:
  2591. raise sa_exc.InvalidRequestError(
  2592. "Instance '%s' is not persisted" % state_str(state)
  2593. )
  2594. if state._deleted:
  2595. if revert_deletion:
  2596. if not state._attached:
  2597. return
  2598. del state._deleted
  2599. else:
  2600. raise sa_exc.InvalidRequestError(
  2601. "Instance '%s' has been deleted. "
  2602. "Use the make_transient() "
  2603. "function to send this object back "
  2604. "to the transient state." % state_str(state)
  2605. )
  2606. obj = state.obj()
  2607. # check for late gc
  2608. if obj is None:
  2609. return
  2610. to_attach = self._before_attach(state, obj)
  2611. self._deleted.pop(state, None)
  2612. if revert_deletion:
  2613. self.identity_map.replace(state)
  2614. else:
  2615. self.identity_map.add(state)
  2616. if to_attach:
  2617. self._after_attach(state, obj)
  2618. elif revert_deletion:
  2619. self.dispatch.deleted_to_persistent(self, state)
  2620. def _save_or_update_impl(self, state):
  2621. if state.key is None:
  2622. self._save_impl(state)
  2623. else:
  2624. self._update_impl(state)
  2625. def enable_relationship_loading(self, obj):
  2626. """Associate an object with this :class:`.Session` for related
  2627. object loading.
  2628. .. warning::
  2629. :meth:`.enable_relationship_loading` exists to serve special
  2630. use cases and is not recommended for general use.
  2631. Accesses of attributes mapped with :func:`_orm.relationship`
  2632. will attempt to load a value from the database using this
  2633. :class:`.Session` as the source of connectivity. The values
  2634. will be loaded based on foreign key and primary key values
  2635. present on this object - if not present, then those relationships
  2636. will be unavailable.
  2637. The object will be attached to this session, but will
  2638. **not** participate in any persistence operations; its state
  2639. for almost all purposes will remain either "transient" or
  2640. "detached", except for the case of relationship loading.
  2641. Also note that backrefs will often not work as expected.
  2642. Altering a relationship-bound attribute on the target object
  2643. may not fire off a backref event, if the effective value
  2644. is what was already loaded from a foreign-key-holding value.
  2645. The :meth:`.Session.enable_relationship_loading` method is
  2646. similar to the ``load_on_pending`` flag on :func:`_orm.relationship`.
  2647. Unlike that flag, :meth:`.Session.enable_relationship_loading` allows
  2648. an object to remain transient while still being able to load
  2649. related items.
  2650. To make a transient object associated with a :class:`.Session`
  2651. via :meth:`.Session.enable_relationship_loading` pending, add
  2652. it to the :class:`.Session` using :meth:`.Session.add` normally.
  2653. If the object instead represents an existing identity in the database,
  2654. it should be merged using :meth:`.Session.merge`.
  2655. :meth:`.Session.enable_relationship_loading` does not improve
  2656. behavior when the ORM is used normally - object references should be
  2657. constructed at the object level, not at the foreign key level, so
  2658. that they are present in an ordinary way before flush()
  2659. proceeds. This method is not intended for general use.
  2660. .. seealso::
  2661. :paramref:`_orm.relationship.load_on_pending` - this flag
  2662. allows per-relationship loading of many-to-ones on items that
  2663. are pending.
  2664. :func:`.make_transient_to_detached` - allows for an object to
  2665. be added to a :class:`.Session` without SQL emitted, which then
  2666. will unexpire attributes on access.
  2667. """
  2668. try:
  2669. state = attributes.instance_state(obj)
  2670. except exc.NO_STATE as err:
  2671. util.raise_(
  2672. exc.UnmappedInstanceError(obj),
  2673. replace_context=err,
  2674. )
  2675. to_attach = self._before_attach(state, obj)
  2676. state._load_pending = True
  2677. if to_attach:
  2678. self._after_attach(state, obj)
  2679. def _before_attach(self, state, obj):
  2680. self._autobegin()
  2681. if state.session_id == self.hash_key:
  2682. return False
  2683. if state.session_id and state.session_id in _sessions:
  2684. raise sa_exc.InvalidRequestError(
  2685. "Object '%s' is already attached to session '%s' "
  2686. "(this is '%s')"
  2687. % (state_str(state), state.session_id, self.hash_key)
  2688. )
  2689. self.dispatch.before_attach(self, state)
  2690. return True
  2691. def _after_attach(self, state, obj):
  2692. state.session_id = self.hash_key
  2693. if state.modified and state._strong_obj is None:
  2694. state._strong_obj = obj
  2695. self.dispatch.after_attach(self, state)
  2696. if state.key:
  2697. self.dispatch.detached_to_persistent(self, state)
  2698. else:
  2699. self.dispatch.transient_to_pending(self, state)
  2700. def __contains__(self, instance):
  2701. """Return True if the instance is associated with this session.
  2702. The instance may be pending or persistent within the Session for a
  2703. result of True.
  2704. """
  2705. try:
  2706. state = attributes.instance_state(instance)
  2707. except exc.NO_STATE as err:
  2708. util.raise_(
  2709. exc.UnmappedInstanceError(instance),
  2710. replace_context=err,
  2711. )
  2712. return self._contains_state(state)
  2713. def __iter__(self):
  2714. """Iterate over all pending or persistent instances within this
  2715. Session.
  2716. """
  2717. return iter(
  2718. list(self._new.values()) + list(self.identity_map.values())
  2719. )
  2720. def _contains_state(self, state):
  2721. return state in self._new or self.identity_map.contains_state(state)
  2722. def flush(self, objects=None):
  2723. """Flush all the object changes to the database.
  2724. Writes out all pending object creations, deletions and modifications
  2725. to the database as INSERTs, DELETEs, UPDATEs, etc. Operations are
  2726. automatically ordered by the Session's unit of work dependency
  2727. solver.
  2728. Database operations will be issued in the current transactional
  2729. context and do not affect the state of the transaction, unless an
  2730. error occurs, in which case the entire transaction is rolled back.
  2731. You may flush() as often as you like within a transaction to move
  2732. changes from Python to the database's transaction buffer.
  2733. For ``autocommit`` Sessions with no active manual transaction, flush()
  2734. will create a transaction on the fly that surrounds the entire set of
  2735. operations into the flush.
  2736. :param objects: Optional; restricts the flush operation to operate
  2737. only on elements that are in the given collection.
  2738. This feature is for an extremely narrow set of use cases where
  2739. particular objects may need to be operated upon before the
  2740. full flush() occurs. It is not intended for general use.
  2741. """
  2742. if self._flushing:
  2743. raise sa_exc.InvalidRequestError("Session is already flushing")
  2744. if self._is_clean():
  2745. return
  2746. try:
  2747. self._flushing = True
  2748. self._flush(objects)
  2749. finally:
  2750. self._flushing = False
  2751. def _flush_warning(self, method):
  2752. util.warn(
  2753. "Usage of the '%s' operation is not currently supported "
  2754. "within the execution stage of the flush process. "
  2755. "Results may not be consistent. Consider using alternative "
  2756. "event listeners or connection-level operations instead." % method
  2757. )
  2758. def _is_clean(self):
  2759. return (
  2760. not self.identity_map.check_modified()
  2761. and not self._deleted
  2762. and not self._new
  2763. )
  2764. def _flush(self, objects=None):
  2765. dirty = self._dirty_states
  2766. if not dirty and not self._deleted and not self._new:
  2767. self.identity_map._modified.clear()
  2768. return
  2769. flush_context = UOWTransaction(self)
  2770. if self.dispatch.before_flush:
  2771. self.dispatch.before_flush(self, flush_context, objects)
  2772. # re-establish "dirty states" in case the listeners
  2773. # added
  2774. dirty = self._dirty_states
  2775. deleted = set(self._deleted)
  2776. new = set(self._new)
  2777. dirty = set(dirty).difference(deleted)
  2778. # create the set of all objects we want to operate upon
  2779. if objects:
  2780. # specific list passed in
  2781. objset = set()
  2782. for o in objects:
  2783. try:
  2784. state = attributes.instance_state(o)
  2785. except exc.NO_STATE as err:
  2786. util.raise_(
  2787. exc.UnmappedInstanceError(o),
  2788. replace_context=err,
  2789. )
  2790. objset.add(state)
  2791. else:
  2792. objset = None
  2793. # store objects whose fate has been decided
  2794. processed = set()
  2795. # put all saves/updates into the flush context. detect top-level
  2796. # orphans and throw them into deleted.
  2797. if objset:
  2798. proc = new.union(dirty).intersection(objset).difference(deleted)
  2799. else:
  2800. proc = new.union(dirty).difference(deleted)
  2801. for state in proc:
  2802. is_orphan = _state_mapper(state)._is_orphan(state)
  2803. is_persistent_orphan = is_orphan and state.has_identity
  2804. if (
  2805. is_orphan
  2806. and not is_persistent_orphan
  2807. and state._orphaned_outside_of_session
  2808. ):
  2809. self._expunge_states([state])
  2810. else:
  2811. _reg = flush_context.register_object(
  2812. state, isdelete=is_persistent_orphan
  2813. )
  2814. assert _reg, "Failed to add object to the flush context!"
  2815. processed.add(state)
  2816. # put all remaining deletes into the flush context.
  2817. if objset:
  2818. proc = deleted.intersection(objset).difference(processed)
  2819. else:
  2820. proc = deleted.difference(processed)
  2821. for state in proc:
  2822. _reg = flush_context.register_object(state, isdelete=True)
  2823. assert _reg, "Failed to add object to the flush context!"
  2824. if not flush_context.has_work:
  2825. return
  2826. flush_context.transaction = transaction = self.begin(_subtrans=True)
  2827. try:
  2828. self._warn_on_events = True
  2829. try:
  2830. flush_context.execute()
  2831. finally:
  2832. self._warn_on_events = False
  2833. self.dispatch.after_flush(self, flush_context)
  2834. flush_context.finalize_flush_changes()
  2835. if not objects and self.identity_map._modified:
  2836. len_ = len(self.identity_map._modified)
  2837. statelib.InstanceState._commit_all_states(
  2838. [
  2839. (state, state.dict)
  2840. for state in self.identity_map._modified
  2841. ],
  2842. instance_dict=self.identity_map,
  2843. )
  2844. util.warn(
  2845. "Attribute history events accumulated on %d "
  2846. "previously clean instances "
  2847. "within inner-flush event handlers have been "
  2848. "reset, and will not result in database updates. "
  2849. "Consider using set_committed_value() within "
  2850. "inner-flush event handlers to avoid this warning." % len_
  2851. )
  2852. # useful assertions:
  2853. # if not objects:
  2854. # assert not self.identity_map._modified
  2855. # else:
  2856. # assert self.identity_map._modified == \
  2857. # self.identity_map._modified.difference(objects)
  2858. self.dispatch.after_flush_postexec(self, flush_context)
  2859. transaction.commit()
  2860. except:
  2861. with util.safe_reraise():
  2862. transaction.rollback(_capture_exception=True)
  2863. def bulk_save_objects(
  2864. self,
  2865. objects,
  2866. return_defaults=False,
  2867. update_changed_only=True,
  2868. preserve_order=True,
  2869. ):
  2870. """Perform a bulk save of the given list of objects.
  2871. The bulk save feature allows mapped objects to be used as the
  2872. source of simple INSERT and UPDATE operations which can be more easily
  2873. grouped together into higher performing "executemany"
  2874. operations; the extraction of data from the objects is also performed
  2875. using a lower-latency process that ignores whether or not attributes
  2876. have actually been modified in the case of UPDATEs, and also ignores
  2877. SQL expressions.
  2878. The objects as given are not added to the session and no additional
  2879. state is established on them. If the
  2880. :paramref:`_orm.Session.bulk_save_objects.return_defaults` flag is set,
  2881. then server-generated primary key values will be assigned to the
  2882. returned objects, but **not server side defaults**; this is a
  2883. limitation in the implementation. If stateful objects are desired,
  2884. please use the standard :meth:`_orm.Session.add_all` approach or
  2885. as an alternative newer mass-insert features such as
  2886. :ref:`orm_dml_returning_objects`.
  2887. .. legacy::
  2888. The bulk save feature allows for a lower-latency INSERT/UPDATE
  2889. of rows at the expense of most other unit-of-work features.
  2890. Features such as object management, relationship handling,
  2891. and SQL clause support are silently omitted in favor of raw
  2892. INSERT/UPDATES of records.
  2893. In SQLAlchemy 2.0, improved versions of the bulk insert/update
  2894. methods are introduced, with clearer behavior and
  2895. documentation, new capabilities, and much better performance.
  2896. For 1.4 use, **please read the list of caveats at**
  2897. :ref:`bulk_operations_caveats` **before using this method, and
  2898. fully test and confirm the functionality of all code developed
  2899. using these systems.**
  2900. :param objects: a sequence of mapped object instances. The mapped
  2901. objects are persisted as is, and are **not** associated with the
  2902. :class:`.Session` afterwards.
  2903. For each object, whether the object is sent as an INSERT or an
  2904. UPDATE is dependent on the same rules used by the :class:`.Session`
  2905. in traditional operation; if the object has the
  2906. :attr:`.InstanceState.key`
  2907. attribute set, then the object is assumed to be "detached" and
  2908. will result in an UPDATE. Otherwise, an INSERT is used.
  2909. In the case of an UPDATE, statements are grouped based on which
  2910. attributes have changed, and are thus to be the subject of each
  2911. SET clause. If ``update_changed_only`` is False, then all
  2912. attributes present within each object are applied to the UPDATE
  2913. statement, which may help in allowing the statements to be grouped
  2914. together into a larger executemany(), and will also reduce the
  2915. overhead of checking history on attributes.
  2916. :param return_defaults: when True, rows that are missing values which
  2917. generate defaults, namely integer primary key defaults and sequences,
  2918. will be inserted **one at a time**, so that the primary key value
  2919. is available. In particular this will allow joined-inheritance
  2920. and other multi-table mappings to insert correctly without the need
  2921. to provide primary key values ahead of time; however,
  2922. :paramref:`.Session.bulk_save_objects.return_defaults` **greatly
  2923. reduces the performance gains** of the method overall. It is strongly
  2924. advised to please use the standard :meth:`_orm.Session.add_all`
  2925. approach.
  2926. :param update_changed_only: when True, UPDATE statements are rendered
  2927. based on those attributes in each state that have logged changes.
  2928. When False, all attributes present are rendered into the SET clause
  2929. with the exception of primary key attributes.
  2930. :param preserve_order: when True, the order of inserts and updates
  2931. matches exactly the order in which the objects are given. When
  2932. False, common types of objects are grouped into inserts
  2933. and updates, to allow for more batching opportunities.
  2934. .. versionadded:: 1.3
  2935. .. seealso::
  2936. :ref:`bulk_operations`
  2937. :meth:`.Session.bulk_insert_mappings`
  2938. :meth:`.Session.bulk_update_mappings`
  2939. """
  2940. obj_states = (attributes.instance_state(obj) for obj in objects)
  2941. if not preserve_order:
  2942. # the purpose of this sort is just so that common mappers
  2943. # and persistence states are grouped together, so that groupby
  2944. # will return a single group for a particular type of mapper.
  2945. # it's not trying to be deterministic beyond that.
  2946. obj_states = sorted(
  2947. obj_states,
  2948. key=lambda state: (id(state.mapper), state.key is not None),
  2949. )
  2950. def grouping_key(state):
  2951. return (state.mapper, state.key is not None)
  2952. for (mapper, isupdate), states in itertools.groupby(
  2953. obj_states, grouping_key
  2954. ):
  2955. self._bulk_save_mappings(
  2956. mapper,
  2957. states,
  2958. isupdate,
  2959. True,
  2960. return_defaults,
  2961. update_changed_only,
  2962. False,
  2963. )
  2964. def bulk_insert_mappings(
  2965. self, mapper, mappings, return_defaults=False, render_nulls=False
  2966. ):
  2967. """Perform a bulk insert of the given list of mapping dictionaries.
  2968. The bulk insert feature allows plain Python dictionaries to be used as
  2969. the source of simple INSERT operations which can be more easily
  2970. grouped together into higher performing "executemany"
  2971. operations. Using dictionaries, there is no "history" or session
  2972. state management features in use, reducing latency when inserting
  2973. large numbers of simple rows.
  2974. The values within the dictionaries as given are typically passed
  2975. without modification into Core :meth:`_expression.Insert` constructs,
  2976. after
  2977. organizing the values within them across the tables to which
  2978. the given mapper is mapped.
  2979. .. versionadded:: 1.0.0
  2980. .. legacy::
  2981. The bulk insert feature allows for a lower-latency INSERT
  2982. of rows at the expense of most other unit-of-work features.
  2983. Features such as object management, relationship handling,
  2984. and SQL clause support are silently omitted in favor of raw
  2985. INSERT of records.
  2986. In SQLAlchemy 2.0, improved versions of the bulk insert/update
  2987. methods are introduced, with clearer behavior and
  2988. documentation, new capabilities, and much better performance.
  2989. For 1.4 use, **please read the list of caveats at**
  2990. :ref:`bulk_operations_caveats` **before using this method, and
  2991. fully test and confirm the functionality of all code developed
  2992. using these systems.**
  2993. :param mapper: a mapped class, or the actual :class:`_orm.Mapper`
  2994. object,
  2995. representing the single kind of object represented within the mapping
  2996. list.
  2997. :param mappings: a sequence of dictionaries, each one containing the
  2998. state of the mapped row to be inserted, in terms of the attribute
  2999. names on the mapped class. If the mapping refers to multiple tables,
  3000. such as a joined-inheritance mapping, each dictionary must contain all
  3001. keys to be populated into all tables.
  3002. :param return_defaults: when True, rows that are missing values which
  3003. generate defaults, namely integer primary key defaults and sequences,
  3004. will be inserted **one at a time**, so that the primary key value
  3005. is available. In particular this will allow joined-inheritance
  3006. and other multi-table mappings to insert correctly without the need
  3007. to provide primary
  3008. key values ahead of time; however,
  3009. :paramref:`.Session.bulk_insert_mappings.return_defaults`
  3010. **greatly reduces the performance gains** of the method overall.
  3011. If the rows
  3012. to be inserted only refer to a single table, then there is no
  3013. reason this flag should be set as the returned default information
  3014. is not used.
  3015. :param render_nulls: When True, a value of ``None`` will result
  3016. in a NULL value being included in the INSERT statement, rather
  3017. than the column being omitted from the INSERT. This allows all
  3018. the rows being INSERTed to have the identical set of columns which
  3019. allows the full set of rows to be batched to the DBAPI. Normally,
  3020. each column-set that contains a different combination of NULL values
  3021. than the previous row must omit a different series of columns from
  3022. the rendered INSERT statement, which means it must be emitted as a
  3023. separate statement. By passing this flag, the full set of rows
  3024. are guaranteed to be batchable into one batch; the cost however is
  3025. that server-side defaults which are invoked by an omitted column will
  3026. be skipped, so care must be taken to ensure that these are not
  3027. necessary.
  3028. .. warning::
  3029. When this flag is set, **server side default SQL values will
  3030. not be invoked** for those columns that are inserted as NULL;
  3031. the NULL value will be sent explicitly. Care must be taken
  3032. to ensure that no server-side default functions need to be
  3033. invoked for the operation as a whole.
  3034. .. versionadded:: 1.1
  3035. .. seealso::
  3036. :ref:`bulk_operations`
  3037. :meth:`.Session.bulk_save_objects`
  3038. :meth:`.Session.bulk_update_mappings`
  3039. """
  3040. self._bulk_save_mappings(
  3041. mapper,
  3042. mappings,
  3043. False,
  3044. False,
  3045. return_defaults,
  3046. False,
  3047. render_nulls,
  3048. )
  3049. def bulk_update_mappings(self, mapper, mappings):
  3050. """Perform a bulk update of the given list of mapping dictionaries.
  3051. The bulk update feature allows plain Python dictionaries to be used as
  3052. the source of simple UPDATE operations which can be more easily
  3053. grouped together into higher performing "executemany"
  3054. operations. Using dictionaries, there is no "history" or session
  3055. state management features in use, reducing latency when updating
  3056. large numbers of simple rows.
  3057. .. versionadded:: 1.0.0
  3058. .. legacy::
  3059. The bulk update feature allows for a lower-latency UPDATE
  3060. of rows at the expense of most other unit-of-work features.
  3061. Features such as object management, relationship handling,
  3062. and SQL clause support are silently omitted in favor of raw
  3063. UPDATES of records.
  3064. In SQLAlchemy 2.0, improved versions of the bulk insert/update
  3065. methods are introduced, with clearer behavior and
  3066. documentation, new capabilities, and much better performance.
  3067. For 1.4 use, **please read the list of caveats at**
  3068. :ref:`bulk_operations_caveats` **before using this method, and
  3069. fully test and confirm the functionality of all code developed
  3070. using these systems.**
  3071. :param mapper: a mapped class, or the actual :class:`_orm.Mapper`
  3072. object,
  3073. representing the single kind of object represented within the mapping
  3074. list.
  3075. :param mappings: a sequence of dictionaries, each one containing the
  3076. state of the mapped row to be updated, in terms of the attribute names
  3077. on the mapped class. If the mapping refers to multiple tables, such
  3078. as a joined-inheritance mapping, each dictionary may contain keys
  3079. corresponding to all tables. All those keys which are present and
  3080. are not part of the primary key are applied to the SET clause of the
  3081. UPDATE statement; the primary key values, which are required, are
  3082. applied to the WHERE clause.
  3083. .. seealso::
  3084. :ref:`bulk_operations`
  3085. :meth:`.Session.bulk_insert_mappings`
  3086. :meth:`.Session.bulk_save_objects`
  3087. """
  3088. self._bulk_save_mappings(
  3089. mapper, mappings, True, False, False, False, False
  3090. )
  3091. def _bulk_save_mappings(
  3092. self,
  3093. mapper,
  3094. mappings,
  3095. isupdate,
  3096. isstates,
  3097. return_defaults,
  3098. update_changed_only,
  3099. render_nulls,
  3100. ):
  3101. mapper = _class_to_mapper(mapper)
  3102. self._flushing = True
  3103. transaction = self.begin(_subtrans=True)
  3104. try:
  3105. if isupdate:
  3106. persistence._bulk_update(
  3107. mapper,
  3108. mappings,
  3109. transaction,
  3110. isstates,
  3111. update_changed_only,
  3112. )
  3113. else:
  3114. persistence._bulk_insert(
  3115. mapper,
  3116. mappings,
  3117. transaction,
  3118. isstates,
  3119. return_defaults,
  3120. render_nulls,
  3121. )
  3122. transaction.commit()
  3123. except:
  3124. with util.safe_reraise():
  3125. transaction.rollback(_capture_exception=True)
  3126. finally:
  3127. self._flushing = False
  3128. def is_modified(self, instance, include_collections=True):
  3129. r"""Return ``True`` if the given instance has locally
  3130. modified attributes.
  3131. This method retrieves the history for each instrumented
  3132. attribute on the instance and performs a comparison of the current
  3133. value to its previously committed value, if any.
  3134. It is in effect a more expensive and accurate
  3135. version of checking for the given instance in the
  3136. :attr:`.Session.dirty` collection; a full test for
  3137. each attribute's net "dirty" status is performed.
  3138. E.g.::
  3139. return session.is_modified(someobject)
  3140. A few caveats to this method apply:
  3141. * Instances present in the :attr:`.Session.dirty` collection may
  3142. report ``False`` when tested with this method. This is because
  3143. the object may have received change events via attribute mutation,
  3144. thus placing it in :attr:`.Session.dirty`, but ultimately the state
  3145. is the same as that loaded from the database, resulting in no net
  3146. change here.
  3147. * Scalar attributes may not have recorded the previously set
  3148. value when a new value was applied, if the attribute was not loaded,
  3149. or was expired, at the time the new value was received - in these
  3150. cases, the attribute is assumed to have a change, even if there is
  3151. ultimately no net change against its database value. SQLAlchemy in
  3152. most cases does not need the "old" value when a set event occurs, so
  3153. it skips the expense of a SQL call if the old value isn't present,
  3154. based on the assumption that an UPDATE of the scalar value is
  3155. usually needed, and in those few cases where it isn't, is less
  3156. expensive on average than issuing a defensive SELECT.
  3157. The "old" value is fetched unconditionally upon set only if the
  3158. attribute container has the ``active_history`` flag set to ``True``.
  3159. This flag is set typically for primary key attributes and scalar
  3160. object references that are not a simple many-to-one. To set this
  3161. flag for any arbitrary mapped column, use the ``active_history``
  3162. argument with :func:`.column_property`.
  3163. :param instance: mapped instance to be tested for pending changes.
  3164. :param include_collections: Indicates if multivalued collections
  3165. should be included in the operation. Setting this to ``False`` is a
  3166. way to detect only local-column based properties (i.e. scalar columns
  3167. or many-to-one foreign keys) that would result in an UPDATE for this
  3168. instance upon flush.
  3169. """
  3170. state = object_state(instance)
  3171. if not state.modified:
  3172. return False
  3173. dict_ = state.dict
  3174. for attr in state.manager.attributes:
  3175. if (
  3176. not include_collections
  3177. and hasattr(attr.impl, "get_collection")
  3178. ) or not hasattr(attr.impl, "get_history"):
  3179. continue
  3180. (added, unchanged, deleted) = attr.impl.get_history(
  3181. state, dict_, passive=attributes.NO_CHANGE
  3182. )
  3183. if added or deleted:
  3184. return True
  3185. else:
  3186. return False
  3187. @property
  3188. def is_active(self):
  3189. """True if this :class:`.Session` not in "partial rollback" state.
  3190. .. versionchanged:: 1.4 The :class:`_orm.Session` no longer begins
  3191. a new transaction immediately, so this attribute will be False
  3192. when the :class:`_orm.Session` is first instantiated.
  3193. "partial rollback" state typically indicates that the flush process
  3194. of the :class:`_orm.Session` has failed, and that the
  3195. :meth:`_orm.Session.rollback` method must be emitted in order to
  3196. fully roll back the transaction.
  3197. If this :class:`_orm.Session` is not in a transaction at all, the
  3198. :class:`_orm.Session` will autobegin when it is first used, so in this
  3199. case :attr:`_orm.Session.is_active` will return True.
  3200. Otherwise, if this :class:`_orm.Session` is within a transaction,
  3201. and that transaction has not been rolled back internally, the
  3202. :attr:`_orm.Session.is_active` will also return True.
  3203. .. seealso::
  3204. :ref:`faq_session_rollback`
  3205. :meth:`_orm.Session.in_transaction`
  3206. """
  3207. if self.autocommit:
  3208. return (
  3209. self._transaction is not None and self._transaction.is_active
  3210. )
  3211. else:
  3212. return self._transaction is None or self._transaction.is_active
  3213. identity_map = None
  3214. """A mapping of object identities to objects themselves.
  3215. Iterating through ``Session.identity_map.values()`` provides
  3216. access to the full set of persistent objects (i.e., those
  3217. that have row identity) currently in the session.
  3218. .. seealso::
  3219. :func:`.identity_key` - helper function to produce the keys used
  3220. in this dictionary.
  3221. """
  3222. @property
  3223. def _dirty_states(self):
  3224. """The set of all persistent states considered dirty.
  3225. This method returns all states that were modified including
  3226. those that were possibly deleted.
  3227. """
  3228. return self.identity_map._dirty_states()
  3229. @property
  3230. def dirty(self):
  3231. """The set of all persistent instances considered dirty.
  3232. E.g.::
  3233. some_mapped_object in session.dirty
  3234. Instances are considered dirty when they were modified but not
  3235. deleted.
  3236. Note that this 'dirty' calculation is 'optimistic'; most
  3237. attribute-setting or collection modification operations will
  3238. mark an instance as 'dirty' and place it in this set, even if
  3239. there is no net change to the attribute's value. At flush
  3240. time, the value of each attribute is compared to its
  3241. previously saved value, and if there's no net change, no SQL
  3242. operation will occur (this is a more expensive operation so
  3243. it's only done at flush time).
  3244. To check if an instance has actionable net changes to its
  3245. attributes, use the :meth:`.Session.is_modified` method.
  3246. """
  3247. return util.IdentitySet(
  3248. [
  3249. state.obj()
  3250. for state in self._dirty_states
  3251. if state not in self._deleted
  3252. ]
  3253. )
  3254. @property
  3255. def deleted(self):
  3256. "The set of all instances marked as 'deleted' within this ``Session``"
  3257. return util.IdentitySet(list(self._deleted.values()))
  3258. @property
  3259. def new(self):
  3260. "The set of all instances marked as 'new' within this ``Session``."
  3261. return util.IdentitySet(list(self._new.values()))
  3262. class sessionmaker(_SessionClassMethods):
  3263. """A configurable :class:`.Session` factory.
  3264. The :class:`.sessionmaker` factory generates new
  3265. :class:`.Session` objects when called, creating them given
  3266. the configurational arguments established here.
  3267. e.g.::
  3268. from sqlalchemy import create_engine
  3269. from sqlalchemy.orm import sessionmaker
  3270. # an Engine, which the Session will use for connection
  3271. # resources
  3272. engine = create_engine('postgresql://scott:tiger@localhost/')
  3273. Session = sessionmaker(engine)
  3274. with Session() as session:
  3275. session.add(some_object)
  3276. session.add(some_other_object)
  3277. session.commit()
  3278. Context manager use is optional; otherwise, the returned
  3279. :class:`_orm.Session` object may be closed explicitly via the
  3280. :meth:`_orm.Session.close` method. Using a
  3281. ``try:/finally:`` block is optional, however will ensure that the close
  3282. takes place even if there are database errors::
  3283. session = Session()
  3284. try:
  3285. session.add(some_object)
  3286. session.add(some_other_object)
  3287. session.commit()
  3288. finally:
  3289. session.close()
  3290. :class:`.sessionmaker` acts as a factory for :class:`_orm.Session`
  3291. objects in the same way as an :class:`_engine.Engine` acts as a factory
  3292. for :class:`_engine.Connection` objects. In this way it also includes
  3293. a :meth:`_orm.sessionmaker.begin` method, that provides a context
  3294. manager which both begins and commits a transaction, as well as closes
  3295. out the :class:`_orm.Session` when complete, rolling back the transaction
  3296. if any errors occur::
  3297. Session = sessionmaker(engine)
  3298. with Session.begin() as session:
  3299. session.add(some_object)
  3300. session.add(some_other_object)
  3301. # commits transaction, closes session
  3302. .. versionadded:: 1.4
  3303. When calling upon :class:`_orm.sessionmaker` to construct a
  3304. :class:`_orm.Session`, keyword arguments may also be passed to the
  3305. method; these arguments will override that of the globally configured
  3306. parameters. Below we use a :class:`_orm.sessionmaker` bound to a certain
  3307. :class:`_engine.Engine` to produce a :class:`_orm.Session` that is instead
  3308. bound to a specific :class:`_engine.Connection` procured from that engine::
  3309. Session = sessionmaker(engine)
  3310. # bind an individual session to a connection
  3311. with engine.connect() as connection:
  3312. with Session(bind=connection) as session:
  3313. # work with session
  3314. The class also includes a method :meth:`_orm.sessionmaker.configure`, which
  3315. can be used to specify additional keyword arguments to the factory, which
  3316. will take effect for subsequent :class:`.Session` objects generated. This
  3317. is usually used to associate one or more :class:`_engine.Engine` objects
  3318. with an existing
  3319. :class:`.sessionmaker` factory before it is first used::
  3320. # application starts, sessionmaker does not have
  3321. # an engine bound yet
  3322. Session = sessionmaker()
  3323. # ... later, when an engine URL is read from a configuration
  3324. # file or other events allow the engine to be created
  3325. engine = create_engine('sqlite:///foo.db')
  3326. Session.configure(bind=engine)
  3327. sess = Session()
  3328. # work with session
  3329. .. seealso::
  3330. :ref:`session_getting` - introductory text on creating
  3331. sessions using :class:`.sessionmaker`.
  3332. """
  3333. def __init__(
  3334. self,
  3335. bind=None,
  3336. class_=Session,
  3337. autoflush=True,
  3338. autocommit=False,
  3339. expire_on_commit=True,
  3340. info=None,
  3341. **kw
  3342. ):
  3343. r"""Construct a new :class:`.sessionmaker`.
  3344. All arguments here except for ``class_`` correspond to arguments
  3345. accepted by :class:`.Session` directly. See the
  3346. :meth:`.Session.__init__` docstring for more details on parameters.
  3347. :param bind: a :class:`_engine.Engine` or other :class:`.Connectable`
  3348. with
  3349. which newly created :class:`.Session` objects will be associated.
  3350. :param class\_: class to use in order to create new :class:`.Session`
  3351. objects. Defaults to :class:`.Session`.
  3352. :param autoflush: The autoflush setting to use with newly created
  3353. :class:`.Session` objects.
  3354. :param autocommit: The autocommit setting to use with newly created
  3355. :class:`.Session` objects.
  3356. :param expire_on_commit=True: the
  3357. :paramref:`_orm.Session.expire_on_commit` setting to use
  3358. with newly created :class:`.Session` objects.
  3359. :param info: optional dictionary of information that will be available
  3360. via :attr:`.Session.info`. Note this dictionary is *updated*, not
  3361. replaced, when the ``info`` parameter is specified to the specific
  3362. :class:`.Session` construction operation.
  3363. :param \**kw: all other keyword arguments are passed to the
  3364. constructor of newly created :class:`.Session` objects.
  3365. """
  3366. kw["bind"] = bind
  3367. kw["autoflush"] = autoflush
  3368. kw["autocommit"] = autocommit
  3369. kw["expire_on_commit"] = expire_on_commit
  3370. if info is not None:
  3371. kw["info"] = info
  3372. self.kw = kw
  3373. # make our own subclass of the given class, so that
  3374. # events can be associated with it specifically.
  3375. self.class_ = type(class_.__name__, (class_,), {})
  3376. def begin(self):
  3377. """Produce a context manager that both provides a new
  3378. :class:`_orm.Session` as well as a transaction that commits.
  3379. e.g.::
  3380. Session = sessionmaker(some_engine)
  3381. with Session.begin() as session:
  3382. session.add(some_object)
  3383. # commits transaction, closes session
  3384. .. versionadded:: 1.4
  3385. """
  3386. session = self()
  3387. return session._maker_context_manager()
  3388. def __call__(self, **local_kw):
  3389. """Produce a new :class:`.Session` object using the configuration
  3390. established in this :class:`.sessionmaker`.
  3391. In Python, the ``__call__`` method is invoked on an object when
  3392. it is "called" in the same way as a function::
  3393. Session = sessionmaker()
  3394. session = Session() # invokes sessionmaker.__call__()
  3395. """
  3396. for k, v in self.kw.items():
  3397. if k == "info" and "info" in local_kw:
  3398. d = v.copy()
  3399. d.update(local_kw["info"])
  3400. local_kw["info"] = d
  3401. else:
  3402. local_kw.setdefault(k, v)
  3403. return self.class_(**local_kw)
  3404. def configure(self, **new_kw):
  3405. """(Re)configure the arguments for this sessionmaker.
  3406. e.g.::
  3407. Session = sessionmaker()
  3408. Session.configure(bind=create_engine('sqlite://'))
  3409. """
  3410. self.kw.update(new_kw)
  3411. def __repr__(self):
  3412. return "%s(class_=%r, %s)" % (
  3413. self.__class__.__name__,
  3414. self.class_.__name__,
  3415. ", ".join("%s=%r" % (k, v) for k, v in self.kw.items()),
  3416. )
  3417. def close_all_sessions():
  3418. """Close all sessions in memory.
  3419. This function consults a global registry of all :class:`.Session` objects
  3420. and calls :meth:`.Session.close` on them, which resets them to a clean
  3421. state.
  3422. This function is not for general use but may be useful for test suites
  3423. within the teardown scheme.
  3424. .. versionadded:: 1.3
  3425. """
  3426. for sess in _sessions.values():
  3427. sess.close()
  3428. def make_transient(instance):
  3429. """Alter the state of the given instance so that it is :term:`transient`.
  3430. .. note::
  3431. :func:`.make_transient` is a special-case function for
  3432. advanced use cases only.
  3433. The given mapped instance is assumed to be in the :term:`persistent` or
  3434. :term:`detached` state. The function will remove its association with any
  3435. :class:`.Session` as well as its :attr:`.InstanceState.identity`. The
  3436. effect is that the object will behave as though it were newly constructed,
  3437. except retaining any attribute / collection values that were loaded at the
  3438. time of the call. The :attr:`.InstanceState.deleted` flag is also reset
  3439. if this object had been deleted as a result of using
  3440. :meth:`.Session.delete`.
  3441. .. warning::
  3442. :func:`.make_transient` does **not** "unexpire" or otherwise eagerly
  3443. load ORM-mapped attributes that are not currently loaded at the time
  3444. the function is called. This includes attributes which:
  3445. * were expired via :meth:`.Session.expire`
  3446. * were expired as the natural effect of committing a session
  3447. transaction, e.g. :meth:`.Session.commit`
  3448. * are normally :term:`lazy loaded` but are not currently loaded
  3449. * are "deferred" via :ref:`deferred` and are not yet loaded
  3450. * were not present in the query which loaded this object, such as that
  3451. which is common in joined table inheritance and other scenarios.
  3452. After :func:`.make_transient` is called, unloaded attributes such
  3453. as those above will normally resolve to the value ``None`` when
  3454. accessed, or an empty collection for a collection-oriented attribute.
  3455. As the object is transient and un-associated with any database
  3456. identity, it will no longer retrieve these values.
  3457. .. seealso::
  3458. :func:`.make_transient_to_detached`
  3459. """
  3460. state = attributes.instance_state(instance)
  3461. s = _state_session(state)
  3462. if s:
  3463. s._expunge_states([state])
  3464. # remove expired state
  3465. state.expired_attributes.clear()
  3466. # remove deferred callables
  3467. if state.callables:
  3468. del state.callables
  3469. if state.key:
  3470. del state.key
  3471. if state._deleted:
  3472. del state._deleted
  3473. def make_transient_to_detached(instance):
  3474. """Make the given transient instance :term:`detached`.
  3475. .. note::
  3476. :func:`.make_transient_to_detached` is a special-case function for
  3477. advanced use cases only.
  3478. All attribute history on the given instance
  3479. will be reset as though the instance were freshly loaded
  3480. from a query. Missing attributes will be marked as expired.
  3481. The primary key attributes of the object, which are required, will be made
  3482. into the "key" of the instance.
  3483. The object can then be added to a session, or merged
  3484. possibly with the load=False flag, at which point it will look
  3485. as if it were loaded that way, without emitting SQL.
  3486. This is a special use case function that differs from a normal
  3487. call to :meth:`.Session.merge` in that a given persistent state
  3488. can be manufactured without any SQL calls.
  3489. .. seealso::
  3490. :func:`.make_transient`
  3491. :meth:`.Session.enable_relationship_loading`
  3492. """
  3493. state = attributes.instance_state(instance)
  3494. if state.session_id or state.key:
  3495. raise sa_exc.InvalidRequestError("Given object must be transient")
  3496. state.key = state.mapper._identity_key_from_state(state)
  3497. if state._deleted:
  3498. del state._deleted
  3499. state._commit_all(state.dict)
  3500. state._expire_attributes(state.dict, state.unloaded_expirable)
  3501. def object_session(instance):
  3502. """Return the :class:`.Session` to which the given instance belongs.
  3503. This is essentially the same as the :attr:`.InstanceState.session`
  3504. accessor. See that attribute for details.
  3505. """
  3506. try:
  3507. state = attributes.instance_state(instance)
  3508. except exc.NO_STATE as err:
  3509. util.raise_(
  3510. exc.UnmappedInstanceError(instance),
  3511. replace_context=err,
  3512. )
  3513. else:
  3514. return _state_session(state)
  3515. _new_sessionid = util.counter()