session.py 160 KB

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