session.py 119 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002
  1. # orm/session.py
  2. # Copyright (C) 2005-2017 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: http://www.opensource.org/licenses/mit-license.php
  7. """Provides the Session class and related utilities."""
  8. import weakref
  9. from .. import util, sql, engine, exc as sa_exc
  10. from ..sql import util as sql_util, expression
  11. from . import (
  12. SessionExtension, attributes, exc, query,
  13. loading, identity
  14. )
  15. from ..inspection import inspect
  16. from .base import (
  17. object_mapper, class_mapper,
  18. _class_to_mapper, _state_mapper, object_state,
  19. _none_set, state_str, instance_str
  20. )
  21. import itertools
  22. from . import persistence
  23. from .unitofwork import UOWTransaction
  24. from . import state as statelib
  25. import sys
  26. __all__ = ['Session', 'SessionTransaction',
  27. 'SessionExtension', 'sessionmaker']
  28. _sessions = weakref.WeakValueDictionary()
  29. """Weak-referencing dictionary of :class:`.Session` objects.
  30. """
  31. def _state_session(state):
  32. """Given an :class:`.InstanceState`, return the :class:`.Session`
  33. associated, if any.
  34. """
  35. if state.session_id:
  36. try:
  37. return _sessions[state.session_id]
  38. except KeyError:
  39. pass
  40. return None
  41. class _SessionClassMethods(object):
  42. """Class-level methods for :class:`.Session`, :class:`.sessionmaker`."""
  43. @classmethod
  44. def close_all(cls):
  45. """Close *all* sessions in memory."""
  46. for sess in _sessions.values():
  47. sess.close()
  48. @classmethod
  49. @util.dependencies("sqlalchemy.orm.util")
  50. def identity_key(cls, orm_util, *args, **kwargs):
  51. """Return an identity key.
  52. This is an alias of :func:`.util.identity_key`.
  53. """
  54. return orm_util.identity_key(*args, **kwargs)
  55. @classmethod
  56. def object_session(cls, instance):
  57. """Return the :class:`.Session` to which an object belongs.
  58. This is an alias of :func:`.object_session`.
  59. """
  60. return object_session(instance)
  61. ACTIVE = util.symbol('ACTIVE')
  62. PREPARED = util.symbol('PREPARED')
  63. COMMITTED = util.symbol('COMMITTED')
  64. DEACTIVE = util.symbol('DEACTIVE')
  65. CLOSED = util.symbol('CLOSED')
  66. class SessionTransaction(object):
  67. """A :class:`.Session`-level transaction.
  68. :class:`.SessionTransaction` is a mostly behind-the-scenes object
  69. not normally referenced directly by application code. It coordinates
  70. among multiple :class:`.Connection` objects, maintaining a database
  71. transaction for each one individually, committing or rolling them
  72. back all at once. It also provides optional two-phase commit behavior
  73. which can augment this coordination operation.
  74. The :attr:`.Session.transaction` attribute of :class:`.Session`
  75. refers to the current :class:`.SessionTransaction` object in use, if any.
  76. The :attr:`.SessionTransaction.parent` attribute refers to the parent
  77. :class:`.SessionTransaction` in the stack of :class:`.SessionTransaction`
  78. objects. If this attribute is ``None``, then this is the top of the stack.
  79. If non-``None``, then this :class:`.SessionTransaction` refers either
  80. to a so-called "subtransaction" or a "nested" transaction. A
  81. "subtransaction" is a scoping concept that demarcates an inner portion
  82. of the outermost "real" transaction. A nested transaction, which
  83. is indicated when the :attr:`.SessionTransaction.nested`
  84. attribute is also True, indicates that this :class:`.SessionTransaction`
  85. corresponds to a SAVEPOINT.
  86. **Life Cycle**
  87. A :class:`.SessionTransaction` is associated with a :class:`.Session`
  88. in its default mode of ``autocommit=False`` immediately, associated
  89. with no database connections. As the :class:`.Session` is called upon
  90. to emit SQL on behalf of various :class:`.Engine` or :class:`.Connection`
  91. objects, a corresponding :class:`.Connection` and associated
  92. :class:`.Transaction` is added to a collection within the
  93. :class:`.SessionTransaction` object, becoming one of the
  94. connection/transaction pairs maintained by the
  95. :class:`.SessionTransaction`. The start of a :class:`.SessionTransaction`
  96. can be tracked using the :meth:`.SessionEvents.after_transaction_create`
  97. event.
  98. The lifespan of the :class:`.SessionTransaction` ends when the
  99. :meth:`.Session.commit`, :meth:`.Session.rollback` or
  100. :meth:`.Session.close` methods are called. At this point, the
  101. :class:`.SessionTransaction` removes its association with its parent
  102. :class:`.Session`. A :class:`.Session` that is in ``autocommit=False``
  103. mode will create a new :class:`.SessionTransaction` to replace it
  104. immediately, whereas a :class:`.Session` that's in ``autocommit=True``
  105. mode will remain without a :class:`.SessionTransaction` until the
  106. :meth:`.Session.begin` method is called. The end of a
  107. :class:`.SessionTransaction` can be tracked using the
  108. :meth:`.SessionEvents.after_transaction_end` event.
  109. **Nesting and Subtransactions**
  110. Another detail of :class:`.SessionTransaction` behavior is that it is
  111. capable of "nesting". This means that the :meth:`.Session.begin` method
  112. can be called while an existing :class:`.SessionTransaction` is already
  113. present, producing a new :class:`.SessionTransaction` that temporarily
  114. replaces the parent :class:`.SessionTransaction`. When a
  115. :class:`.SessionTransaction` is produced as nested, it assigns itself to
  116. the :attr:`.Session.transaction` attribute, and it additionally will assign
  117. the previous :class:`.SessionTransaction` to its :attr:`.Session.parent`
  118. attribute. The behavior is effectively a
  119. stack, where :attr:`.Session.transaction` refers to the current head of
  120. the stack, and the :attr:`.SessionTransaction.parent` attribute allows
  121. traversal up the stack until :attr:`.SessionTransaction.parent` is
  122. ``None``, indicating the top of the stack.
  123. When the scope of :class:`.SessionTransaction` is ended via
  124. :meth:`.Session.commit` or :meth:`.Session.rollback`, it restores its
  125. parent :class:`.SessionTransaction` back onto the
  126. :attr:`.Session.transaction` attribute.
  127. The purpose of this stack is to allow nesting of
  128. :meth:`.Session.rollback` or :meth:`.Session.commit` calls in context
  129. with various flavors of :meth:`.Session.begin`. This nesting behavior
  130. applies to when :meth:`.Session.begin_nested` is used to emit a
  131. SAVEPOINT transaction, and is also used to produce a so-called
  132. "subtransaction" which allows a block of code to use a
  133. begin/rollback/commit sequence regardless of whether or not its enclosing
  134. code block has begun a transaction. The :meth:`.flush` method, whether
  135. called explicitly or via autoflush, is the primary consumer of the
  136. "subtransaction" feature, in that it wishes to guarantee that it works
  137. within in a transaction block regardless of whether or not the
  138. :class:`.Session` is in transactional mode when the method is called.
  139. Note that the flush process that occurs within the "autoflush" feature
  140. as well as when the :meth:`.Session.flush` method is used **always**
  141. creates a :class:`.SessionTransaction` object. This object is normally
  142. a subtransaction, unless the :class:`.Session` is in autocommit mode
  143. and no transaction exists at all, in which case it's the outermost
  144. transaction. Any event-handling logic or other inspection logic
  145. needs to take into account whether a :class:`.SessionTransaction`
  146. is the outermost transaction, a subtransaction, or a "nested" / SAVEPOINT
  147. transaction.
  148. .. seealso::
  149. :meth:`.Session.rollback`
  150. :meth:`.Session.commit`
  151. :meth:`.Session.begin`
  152. :meth:`.Session.begin_nested`
  153. :attr:`.Session.is_active`
  154. :meth:`.SessionEvents.after_transaction_create`
  155. :meth:`.SessionEvents.after_transaction_end`
  156. :meth:`.SessionEvents.after_commit`
  157. :meth:`.SessionEvents.after_rollback`
  158. :meth:`.SessionEvents.after_soft_rollback`
  159. """
  160. _rollback_exception = None
  161. def __init__(self, session, parent=None, nested=False):
  162. self.session = session
  163. self._connections = {}
  164. self._parent = parent
  165. self.nested = nested
  166. self._state = ACTIVE
  167. if not parent and nested:
  168. raise sa_exc.InvalidRequestError(
  169. "Can't start a SAVEPOINT transaction when no existing "
  170. "transaction is in progress")
  171. if self.session._enable_transaction_accounting:
  172. self._take_snapshot()
  173. self.session.dispatch.after_transaction_create(self.session, self)
  174. @property
  175. def parent(self):
  176. """The parent :class:`.SessionTransaction` of this
  177. :class:`.SessionTransaction`.
  178. If this attribute is ``None``, indicates this
  179. :class:`.SessionTransaction` is at the top of the stack, and
  180. corresponds to a real "COMMIT"/"ROLLBACK"
  181. block. If non-``None``, then this is either a "subtransaction"
  182. or a "nested" / SAVEPOINT transaction. If the
  183. :attr:`.SessionTransaction.nested` attribute is ``True``, then
  184. this is a SAVEPOINT, and if ``False``, indicates this a subtransaction.
  185. .. versionadded:: 1.0.16 - use ._parent for previous versions
  186. """
  187. return self._parent
  188. nested = False
  189. """Indicates if this is a nested, or SAVEPOINT, transaction.
  190. When :attr:`.SessionTransaction.nested` is True, it is expected
  191. that :attr:`.SessionTransaction.parent` will be True as well.
  192. """
  193. @property
  194. def is_active(self):
  195. return self.session is not None and self._state is ACTIVE
  196. def _assert_active(self, prepared_ok=False,
  197. rollback_ok=False,
  198. deactive_ok=False,
  199. closed_msg="This transaction is closed"):
  200. if self._state is COMMITTED:
  201. raise sa_exc.InvalidRequestError(
  202. "This session is in 'committed' state; no further "
  203. "SQL can be emitted within this transaction."
  204. )
  205. elif self._state is PREPARED:
  206. if not prepared_ok:
  207. raise sa_exc.InvalidRequestError(
  208. "This session is in 'prepared' state; no further "
  209. "SQL can be emitted within this transaction."
  210. )
  211. elif self._state is DEACTIVE:
  212. if not deactive_ok and not rollback_ok:
  213. if self._rollback_exception:
  214. raise sa_exc.InvalidRequestError(
  215. "This Session's transaction has been rolled back "
  216. "due to a previous exception during flush."
  217. " To begin a new transaction with this Session, "
  218. "first issue Session.rollback()."
  219. " Original exception was: %s"
  220. % self._rollback_exception
  221. )
  222. elif not deactive_ok:
  223. raise sa_exc.InvalidRequestError(
  224. "This Session's transaction has been rolled back "
  225. "by a nested rollback() call. To begin a new "
  226. "transaction, issue Session.rollback() first."
  227. )
  228. elif self._state is CLOSED:
  229. raise sa_exc.ResourceClosedError(closed_msg)
  230. @property
  231. def _is_transaction_boundary(self):
  232. return self.nested or not self._parent
  233. def connection(self, bindkey, execution_options=None, **kwargs):
  234. self._assert_active()
  235. bind = self.session.get_bind(bindkey, **kwargs)
  236. return self._connection_for_bind(bind, execution_options)
  237. def _begin(self, nested=False):
  238. self._assert_active()
  239. return SessionTransaction(
  240. self.session, self, nested=nested)
  241. def _iterate_self_and_parents(self, upto=None):
  242. current = self
  243. result = ()
  244. while current:
  245. result += (current, )
  246. if current._parent is upto:
  247. break
  248. elif current._parent is None:
  249. raise sa_exc.InvalidRequestError(
  250. "Transaction %s is not on the active transaction list" % (
  251. upto))
  252. else:
  253. current = current._parent
  254. return result
  255. def _take_snapshot(self):
  256. if not self._is_transaction_boundary:
  257. self._new = self._parent._new
  258. self._deleted = self._parent._deleted
  259. self._dirty = self._parent._dirty
  260. self._key_switches = self._parent._key_switches
  261. return
  262. if not self.session._flushing:
  263. self.session.flush()
  264. self._new = weakref.WeakKeyDictionary()
  265. self._deleted = weakref.WeakKeyDictionary()
  266. self._dirty = weakref.WeakKeyDictionary()
  267. self._key_switches = weakref.WeakKeyDictionary()
  268. def _restore_snapshot(self, dirty_only=False):
  269. """Restore the restoration state taken before a transaction began.
  270. Corresponds to a rollback.
  271. """
  272. assert self._is_transaction_boundary
  273. self.session._expunge_states(
  274. set(self._new).union(self.session._new),
  275. to_transient=True)
  276. for s, (oldkey, newkey) in self._key_switches.items():
  277. self.session.identity_map.safe_discard(s)
  278. s.key = oldkey
  279. self.session.identity_map.replace(s)
  280. for s in set(self._deleted).union(self.session._deleted):
  281. self.session._update_impl(s, revert_deletion=True)
  282. assert not self.session._deleted
  283. for s in self.session.identity_map.all_states():
  284. if not dirty_only or s.modified or s in self._dirty:
  285. s._expire(s.dict, self.session.identity_map._modified)
  286. def _remove_snapshot(self):
  287. """Remove the restoration state taken before a transaction began.
  288. Corresponds to a commit.
  289. """
  290. assert self._is_transaction_boundary
  291. if not self.nested and self.session.expire_on_commit:
  292. for s in self.session.identity_map.all_states():
  293. s._expire(s.dict, self.session.identity_map._modified)
  294. statelib.InstanceState._detach_states(
  295. list(self._deleted), self.session)
  296. self._deleted.clear()
  297. elif self.nested:
  298. self._parent._new.update(self._new)
  299. self._parent._dirty.update(self._dirty)
  300. self._parent._deleted.update(self._deleted)
  301. self._parent._key_switches.update(self._key_switches)
  302. def _connection_for_bind(self, bind, execution_options):
  303. self._assert_active()
  304. if bind in self._connections:
  305. if execution_options:
  306. util.warn(
  307. "Connection is already established for the "
  308. "given bind; execution_options ignored")
  309. return self._connections[bind][0]
  310. if self._parent:
  311. conn = self._parent._connection_for_bind(bind, execution_options)
  312. if not self.nested:
  313. return conn
  314. else:
  315. if isinstance(bind, engine.Connection):
  316. conn = bind
  317. if conn.engine in self._connections:
  318. raise sa_exc.InvalidRequestError(
  319. "Session already has a Connection associated for the "
  320. "given Connection's Engine")
  321. else:
  322. conn = bind.contextual_connect()
  323. if execution_options:
  324. conn = conn.execution_options(**execution_options)
  325. if self.session.twophase and self._parent is None:
  326. transaction = conn.begin_twophase()
  327. elif self.nested:
  328. transaction = conn.begin_nested()
  329. else:
  330. transaction = conn.begin()
  331. self._connections[conn] = self._connections[conn.engine] = \
  332. (conn, transaction, conn is not bind)
  333. self.session.dispatch.after_begin(self.session, self, conn)
  334. return conn
  335. def prepare(self):
  336. if self._parent is not None or not self.session.twophase:
  337. raise sa_exc.InvalidRequestError(
  338. "'twophase' mode not enabled, or not root transaction; "
  339. "can't prepare.")
  340. self._prepare_impl()
  341. def _prepare_impl(self):
  342. self._assert_active()
  343. if self._parent is None or self.nested:
  344. self.session.dispatch.before_commit(self.session)
  345. stx = self.session.transaction
  346. if stx is not self:
  347. for subtransaction in stx._iterate_self_and_parents(upto=self):
  348. subtransaction.commit()
  349. if not self.session._flushing:
  350. for _flush_guard in range(100):
  351. if self.session._is_clean():
  352. break
  353. self.session.flush()
  354. else:
  355. raise exc.FlushError(
  356. "Over 100 subsequent flushes have occurred within "
  357. "session.commit() - is an after_flush() hook "
  358. "creating new objects?")
  359. if self._parent is None and self.session.twophase:
  360. try:
  361. for t in set(self._connections.values()):
  362. t[1].prepare()
  363. except:
  364. with util.safe_reraise():
  365. self.rollback()
  366. self._state = PREPARED
  367. def commit(self):
  368. self._assert_active(prepared_ok=True)
  369. if self._state is not PREPARED:
  370. self._prepare_impl()
  371. if self._parent is None or self.nested:
  372. for t in set(self._connections.values()):
  373. t[1].commit()
  374. self._state = COMMITTED
  375. self.session.dispatch.after_commit(self.session)
  376. if self.session._enable_transaction_accounting:
  377. self._remove_snapshot()
  378. self.close()
  379. return self._parent
  380. def rollback(self, _capture_exception=False):
  381. self._assert_active(prepared_ok=True, rollback_ok=True)
  382. stx = self.session.transaction
  383. if stx is not self:
  384. for subtransaction in stx._iterate_self_and_parents(upto=self):
  385. subtransaction.close()
  386. boundary = self
  387. rollback_err = None
  388. if self._state in (ACTIVE, PREPARED):
  389. for transaction in self._iterate_self_and_parents():
  390. if transaction._parent is None or transaction.nested:
  391. try:
  392. transaction._rollback_impl()
  393. except:
  394. rollback_err = sys.exc_info()
  395. transaction._state = DEACTIVE
  396. boundary = transaction
  397. break
  398. else:
  399. transaction._state = DEACTIVE
  400. sess = self.session
  401. if not rollback_err and sess._enable_transaction_accounting and \
  402. not sess._is_clean():
  403. # if items were added, deleted, or mutated
  404. # here, we need to re-restore the snapshot
  405. util.warn(
  406. "Session's state has been changed on "
  407. "a non-active transaction - this state "
  408. "will be discarded.")
  409. boundary._restore_snapshot(dirty_only=boundary.nested)
  410. self.close()
  411. if self._parent and _capture_exception:
  412. self._parent._rollback_exception = sys.exc_info()[1]
  413. if rollback_err:
  414. util.reraise(*rollback_err)
  415. sess.dispatch.after_soft_rollback(sess, self)
  416. return self._parent
  417. def _rollback_impl(self):
  418. try:
  419. for t in set(self._connections.values()):
  420. t[1].rollback()
  421. finally:
  422. if self.session._enable_transaction_accounting:
  423. self._restore_snapshot(dirty_only=self.nested)
  424. self.session.dispatch.after_rollback(self.session)
  425. def close(self, invalidate=False):
  426. self.session.transaction = self._parent
  427. if self._parent is None:
  428. for connection, transaction, autoclose in \
  429. set(self._connections.values()):
  430. if invalidate:
  431. connection.invalidate()
  432. if autoclose:
  433. connection.close()
  434. else:
  435. transaction.close()
  436. self._state = CLOSED
  437. self.session.dispatch.after_transaction_end(self.session, self)
  438. if self._parent is None:
  439. if not self.session.autocommit:
  440. self.session.begin()
  441. self.session = None
  442. self._connections = None
  443. def __enter__(self):
  444. return self
  445. def __exit__(self, type, value, traceback):
  446. self._assert_active(deactive_ok=True, prepared_ok=True)
  447. if self.session.transaction is None:
  448. return
  449. if type is None:
  450. try:
  451. self.commit()
  452. except:
  453. with util.safe_reraise():
  454. self.rollback()
  455. else:
  456. self.rollback()
  457. class Session(_SessionClassMethods):
  458. """Manages persistence operations for ORM-mapped objects.
  459. The Session's usage paradigm is described at :doc:`/orm/session`.
  460. """
  461. public_methods = (
  462. '__contains__', '__iter__', 'add', 'add_all', 'begin', 'begin_nested',
  463. 'close', 'commit', 'connection', 'delete', 'execute', 'expire',
  464. 'expire_all', 'expunge', 'expunge_all', 'flush', 'get_bind',
  465. 'is_modified', 'bulk_save_objects', 'bulk_insert_mappings',
  466. 'bulk_update_mappings',
  467. 'merge', 'query', 'refresh', 'rollback',
  468. 'scalar')
  469. def __init__(self, bind=None, autoflush=True, expire_on_commit=True,
  470. _enable_transaction_accounting=True,
  471. autocommit=False, twophase=False,
  472. weak_identity_map=True, binds=None, extension=None,
  473. info=None,
  474. query_cls=query.Query):
  475. r"""Construct a new Session.
  476. See also the :class:`.sessionmaker` function which is used to
  477. generate a :class:`.Session`-producing callable with a given
  478. set of arguments.
  479. :param autocommit:
  480. .. warning::
  481. The autocommit flag is **not for general use**, and if it is
  482. used, queries should only be invoked within the span of a
  483. :meth:`.Session.begin` / :meth:`.Session.commit` pair. Executing
  484. queries outside of a demarcated transaction is a legacy mode
  485. of usage, and can in some cases lead to concurrent connection
  486. checkouts.
  487. Defaults to ``False``. When ``True``, the
  488. :class:`.Session` does not keep a persistent transaction running,
  489. and will acquire connections from the engine on an as-needed basis,
  490. returning them immediately after their use. Flushes will begin and
  491. commit (or possibly rollback) their own transaction if no
  492. transaction is present. When using this mode, the
  493. :meth:`.Session.begin` method is used to explicitly start
  494. transactions.
  495. .. seealso::
  496. :ref:`session_autocommit`
  497. :param autoflush: When ``True``, all query operations will issue a
  498. :meth:`~.Session.flush` call to this ``Session`` before proceeding.
  499. This is a convenience feature so that :meth:`~.Session.flush` need
  500. not be called repeatedly in order for database queries to retrieve
  501. results. It's typical that ``autoflush`` is used in conjunction
  502. with ``autocommit=False``. In this scenario, explicit calls to
  503. :meth:`~.Session.flush` are rarely needed; you usually only need to
  504. call :meth:`~.Session.commit` (which flushes) to finalize changes.
  505. :param bind: An optional :class:`.Engine` or :class:`.Connection` to
  506. which this ``Session`` should be bound. When specified, all SQL
  507. operations performed by this session will execute via this
  508. connectable.
  509. :param binds: An optional dictionary which contains more granular
  510. "bind" information than the ``bind`` parameter provides. This
  511. dictionary can map individual :class`.Table`
  512. instances as well as :class:`~.Mapper` instances to individual
  513. :class:`.Engine` or :class:`.Connection` objects. Operations which
  514. proceed relative to a particular :class:`.Mapper` will consult this
  515. dictionary for the direct :class:`.Mapper` instance as
  516. well as the mapper's ``mapped_table`` attribute in order to locate
  517. a connectable to use. The full resolution is described in the
  518. :meth:`.Session.get_bind`.
  519. Usage looks like::
  520. Session = sessionmaker(binds={
  521. SomeMappedClass: create_engine('postgresql://engine1'),
  522. somemapper: create_engine('postgresql://engine2'),
  523. some_table: create_engine('postgresql://engine3'),
  524. })
  525. Also see the :meth:`.Session.bind_mapper`
  526. and :meth:`.Session.bind_table` methods.
  527. :param \class_: Specify an alternate class other than
  528. ``sqlalchemy.orm.session.Session`` which should be used by the
  529. returned class. This is the only argument that is local to the
  530. :class:`.sessionmaker` function, and is not sent directly to the
  531. constructor for ``Session``.
  532. :param _enable_transaction_accounting: Defaults to ``True``. A
  533. legacy-only flag which when ``False`` disables *all* 0.5-style
  534. object accounting on transaction boundaries, including auto-expiry
  535. of instances on rollback and commit, maintenance of the "new" and
  536. "deleted" lists upon rollback, and autoflush of pending changes
  537. upon :meth:`~.Session.begin`, all of which are interdependent.
  538. :param expire_on_commit: Defaults to ``True``. When ``True``, all
  539. instances will be fully expired after each :meth:`~.commit`,
  540. so that all attribute/object access subsequent to a completed
  541. transaction will load from the most recent database state.
  542. :param extension: An optional
  543. :class:`~.SessionExtension` instance, or a list
  544. of such instances, which will receive pre- and post- commit and
  545. flush events, as well as a post-rollback event. **Deprecated.**
  546. Please see :class:`.SessionEvents`.
  547. :param info: optional dictionary of arbitrary data to be associated
  548. with this :class:`.Session`. Is available via the
  549. :attr:`.Session.info` attribute. Note the dictionary is copied at
  550. construction time so that modifications to the per-
  551. :class:`.Session` dictionary will be local to that
  552. :class:`.Session`.
  553. .. versionadded:: 0.9.0
  554. :param query_cls: Class which should be used to create new Query
  555. objects, as returned by the :meth:`~.Session.query` method.
  556. Defaults to :class:`.Query`.
  557. :param twophase: When ``True``, all transactions will be started as
  558. a "two phase" transaction, i.e. using the "two phase" semantics
  559. of the database in use along with an XID. During a
  560. :meth:`~.commit`, after :meth:`~.flush` has been issued for all
  561. attached databases, the :meth:`~.TwoPhaseTransaction.prepare`
  562. method on each database's :class:`.TwoPhaseTransaction` will be
  563. called. This allows each database to roll back the entire
  564. transaction, before each transaction is committed.
  565. :param weak_identity_map: Defaults to ``True`` - when set to
  566. ``False``, objects placed in the :class:`.Session` will be
  567. strongly referenced until explicitly removed or the
  568. :class:`.Session` is closed. **Deprecated** - The strong
  569. reference identity map is legacy. See the
  570. recipe at :ref:`session_referencing_behavior` for
  571. an event-based approach to maintaining strong identity
  572. references.
  573. """
  574. if weak_identity_map:
  575. self._identity_cls = identity.WeakInstanceDict
  576. else:
  577. util.warn_deprecated(
  578. "weak_identity_map=False is deprecated. "
  579. "See the documentation on 'Session Referencing Behavior' "
  580. "for an event-based approach to maintaining strong identity "
  581. "references.")
  582. self._identity_cls = identity.StrongInstanceDict
  583. self.identity_map = self._identity_cls()
  584. self._new = {} # InstanceState->object, strong refs object
  585. self._deleted = {} # same
  586. self.bind = bind
  587. self.__binds = {}
  588. self._flushing = False
  589. self._warn_on_events = False
  590. self.transaction = None
  591. self.hash_key = _new_sessionid()
  592. self.autoflush = autoflush
  593. self.autocommit = autocommit
  594. self.expire_on_commit = expire_on_commit
  595. self._enable_transaction_accounting = _enable_transaction_accounting
  596. self.twophase = twophase
  597. self._query_cls = query_cls
  598. if info:
  599. self.info.update(info)
  600. if extension:
  601. for ext in util.to_list(extension):
  602. SessionExtension._adapt_listener(self, ext)
  603. if binds is not None:
  604. for key, bind in binds.items():
  605. self._add_bind(key, bind)
  606. if not self.autocommit:
  607. self.begin()
  608. _sessions[self.hash_key] = self
  609. connection_callable = None
  610. transaction = None
  611. """The current active or inactive :class:`.SessionTransaction`."""
  612. @util.memoized_property
  613. def info(self):
  614. """A user-modifiable dictionary.
  615. The initial value of this dictionary can be populated using the
  616. ``info`` argument to the :class:`.Session` constructor or
  617. :class:`.sessionmaker` constructor or factory methods. The dictionary
  618. here is always local to this :class:`.Session` and can be modified
  619. independently of all other :class:`.Session` objects.
  620. .. versionadded:: 0.9.0
  621. """
  622. return {}
  623. def begin(self, subtransactions=False, nested=False):
  624. """Begin a transaction on this :class:`.Session`.
  625. The :meth:`.Session.begin` method is only
  626. meaningful if this session is in **autocommit mode** prior to
  627. it being called; see :ref:`session_autocommit` for background
  628. on this setting.
  629. The method will raise an error if this :class:`.Session`
  630. is already inside of a transaction, unless
  631. :paramref:`.Session.begin.subtransactions` or
  632. :paramref:`.Session.begin.nested` are specified.
  633. :param subtransactions: if True, indicates that this
  634. :meth:`~.Session.begin` can create a subtransaction if a transaction
  635. is already in progress. For documentation on subtransactions, please
  636. see :ref:`session_subtransactions`.
  637. :param nested: if True, begins a SAVEPOINT transaction and is equivalent
  638. to calling :meth:`~.Session.begin_nested`. For documentation on
  639. SAVEPOINT transactions, please see :ref:`session_begin_nested`.
  640. :return: the :class:`.SessionTransaction` object. Note that
  641. :class:`.SessionTransaction`
  642. acts as a Python context manager, allowing :meth:`.Session.begin`
  643. to be used in a "with" block. See :ref:`session_autocommit` for
  644. an example.
  645. .. seealso::
  646. :ref:`session_autocommit`
  647. :meth:`.Session.begin_nested`
  648. """
  649. if self.transaction is not None:
  650. if subtransactions or nested:
  651. self.transaction = self.transaction._begin(
  652. nested=nested)
  653. else:
  654. raise sa_exc.InvalidRequestError(
  655. "A transaction is already begun. Use "
  656. "subtransactions=True to allow subtransactions.")
  657. else:
  658. self.transaction = SessionTransaction(
  659. self, nested=nested)
  660. return self.transaction # needed for __enter__/__exit__ hook
  661. def begin_nested(self):
  662. """Begin a "nested" transaction on this Session, e.g. SAVEPOINT.
  663. The target database(s) and associated drivers must support SQL
  664. SAVEPOINT for this method to function correctly.
  665. For documentation on SAVEPOINT
  666. transactions, please see :ref:`session_begin_nested`.
  667. :return: the :class:`.SessionTransaction` object. Note that
  668. :class:`.SessionTransaction` acts as a context manager, allowing
  669. :meth:`.Session.begin_nested` to be used in a "with" block.
  670. See :ref:`session_begin_nested` for a usage example.
  671. .. seealso::
  672. :ref:`session_begin_nested`
  673. :ref:`pysqlite_serializable` - special workarounds required
  674. with the SQLite driver in order for SAVEPOINT to work
  675. correctly.
  676. """
  677. return self.begin(nested=True)
  678. def rollback(self):
  679. """Rollback the current transaction in progress.
  680. If no transaction is in progress, this method is a pass-through.
  681. This method rolls back the current transaction or nested transaction
  682. regardless of subtransactions being in effect. All subtransactions up
  683. to the first real transaction are closed. Subtransactions occur when
  684. :meth:`.begin` is called multiple times.
  685. .. seealso::
  686. :ref:`session_rollback`
  687. """
  688. if self.transaction is None:
  689. pass
  690. else:
  691. self.transaction.rollback()
  692. def commit(self):
  693. """Flush pending changes and commit the current transaction.
  694. If no transaction is in progress, this method raises an
  695. :exc:`~sqlalchemy.exc.InvalidRequestError`.
  696. By default, the :class:`.Session` also expires all database
  697. loaded state on all ORM-managed attributes after transaction commit.
  698. This so that subsequent operations load the most recent
  699. data from the database. This behavior can be disabled using
  700. the ``expire_on_commit=False`` option to :class:`.sessionmaker` or
  701. the :class:`.Session` constructor.
  702. If a subtransaction is in effect (which occurs when begin() is called
  703. multiple times), the subtransaction will be closed, and the next call
  704. to ``commit()`` will operate on the enclosing transaction.
  705. When using the :class:`.Session` in its default mode of
  706. ``autocommit=False``, a new transaction will
  707. be begun immediately after the commit, but note that the newly begun
  708. transaction does *not* use any connection resources until the first
  709. SQL is actually emitted.
  710. .. seealso::
  711. :ref:`session_committing`
  712. """
  713. if self.transaction is None:
  714. if not self.autocommit:
  715. self.begin()
  716. else:
  717. raise sa_exc.InvalidRequestError("No transaction is begun.")
  718. self.transaction.commit()
  719. def prepare(self):
  720. """Prepare the current transaction in progress for two phase commit.
  721. If no transaction is in progress, this method raises an
  722. :exc:`~sqlalchemy.exc.InvalidRequestError`.
  723. Only root transactions of two phase sessions can be prepared. If the
  724. current transaction is not such, an
  725. :exc:`~sqlalchemy.exc.InvalidRequestError` is raised.
  726. """
  727. if self.transaction is None:
  728. if not self.autocommit:
  729. self.begin()
  730. else:
  731. raise sa_exc.InvalidRequestError("No transaction is begun.")
  732. self.transaction.prepare()
  733. def connection(self, mapper=None, clause=None,
  734. bind=None,
  735. close_with_result=False,
  736. execution_options=None,
  737. **kw):
  738. r"""Return a :class:`.Connection` object corresponding to this
  739. :class:`.Session` object's transactional state.
  740. If this :class:`.Session` is configured with ``autocommit=False``,
  741. either the :class:`.Connection` corresponding to the current
  742. transaction is returned, or if no transaction is in progress, a new
  743. one is begun and the :class:`.Connection` returned (note that no
  744. transactional state is established with the DBAPI until the first
  745. SQL statement is emitted).
  746. Alternatively, if this :class:`.Session` is configured with
  747. ``autocommit=True``, an ad-hoc :class:`.Connection` is returned
  748. using :meth:`.Engine.contextual_connect` on the underlying
  749. :class:`.Engine`.
  750. Ambiguity in multi-bind or unbound :class:`.Session` objects can be
  751. resolved through any of the optional keyword arguments. This
  752. ultimately makes usage of the :meth:`.get_bind` method for resolution.
  753. :param bind:
  754. Optional :class:`.Engine` to be used as the bind. If
  755. this engine is already involved in an ongoing transaction,
  756. that connection will be used. This argument takes precedence
  757. over ``mapper``, ``clause``.
  758. :param mapper:
  759. Optional :func:`.mapper` mapped class, used to identify
  760. the appropriate bind. This argument takes precedence over
  761. ``clause``.
  762. :param clause:
  763. A :class:`.ClauseElement` (i.e. :func:`~.sql.expression.select`,
  764. :func:`~.sql.expression.text`,
  765. etc.) which will be used to locate a bind, if a bind
  766. cannot otherwise be identified.
  767. :param close_with_result: Passed to :meth:`.Engine.connect`,
  768. indicating the :class:`.Connection` should be considered
  769. "single use", automatically closing when the first result set is
  770. closed. This flag only has an effect if this :class:`.Session` is
  771. configured with ``autocommit=True`` and does not already have a
  772. transaction in progress.
  773. :param execution_options: a dictionary of execution options that will
  774. be passed to :meth:`.Connection.execution_options`, **when the
  775. connection is first procured only**. If the connection is already
  776. present within the :class:`.Session`, a warning is emitted and
  777. the arguments are ignored.
  778. .. versionadded:: 0.9.9
  779. .. seealso::
  780. :ref:`session_transaction_isolation`
  781. :param \**kw:
  782. Additional keyword arguments are sent to :meth:`get_bind()`,
  783. allowing additional arguments to be passed to custom
  784. implementations of :meth:`get_bind`.
  785. """
  786. if bind is None:
  787. bind = self.get_bind(mapper, clause=clause, **kw)
  788. return self._connection_for_bind(bind,
  789. close_with_result=close_with_result,
  790. execution_options=execution_options)
  791. def _connection_for_bind(self, engine, execution_options=None, **kw):
  792. if self.transaction is not None:
  793. return self.transaction._connection_for_bind(
  794. engine, execution_options)
  795. else:
  796. conn = engine.contextual_connect(**kw)
  797. if execution_options:
  798. conn = conn.execution_options(**execution_options)
  799. return conn
  800. def execute(self, clause, params=None, mapper=None, bind=None, **kw):
  801. r"""Execute a SQL expression construct or string statement within
  802. the current transaction.
  803. Returns a :class:`.ResultProxy` representing
  804. results of the statement execution, in the same manner as that of an
  805. :class:`.Engine` or
  806. :class:`.Connection`.
  807. E.g.::
  808. result = session.execute(
  809. user_table.select().where(user_table.c.id == 5)
  810. )
  811. :meth:`~.Session.execute` accepts any executable clause construct,
  812. such as :func:`~.sql.expression.select`,
  813. :func:`~.sql.expression.insert`,
  814. :func:`~.sql.expression.update`,
  815. :func:`~.sql.expression.delete`, and
  816. :func:`~.sql.expression.text`. Plain SQL strings can be passed
  817. as well, which in the case of :meth:`.Session.execute` only
  818. will be interpreted the same as if it were passed via a
  819. :func:`~.expression.text` construct. That is, the following usage::
  820. result = session.execute(
  821. "SELECT * FROM user WHERE id=:param",
  822. {"param":5}
  823. )
  824. is equivalent to::
  825. from sqlalchemy import text
  826. result = session.execute(
  827. text("SELECT * FROM user WHERE id=:param"),
  828. {"param":5}
  829. )
  830. The second positional argument to :meth:`.Session.execute` is an
  831. optional parameter set. Similar to that of
  832. :meth:`.Connection.execute`, whether this is passed as a single
  833. dictionary, or a list of dictionaries, determines whether the DBAPI
  834. cursor's ``execute()`` or ``executemany()`` is used to execute the
  835. statement. An INSERT construct may be invoked for a single row::
  836. result = session.execute(
  837. users.insert(), {"id": 7, "name": "somename"})
  838. or for multiple rows::
  839. result = session.execute(users.insert(), [
  840. {"id": 7, "name": "somename7"},
  841. {"id": 8, "name": "somename8"},
  842. {"id": 9, "name": "somename9"}
  843. ])
  844. The statement is executed within the current transactional context of
  845. this :class:`.Session`. The :class:`.Connection` which is used
  846. to execute the statement can also be acquired directly by
  847. calling the :meth:`.Session.connection` method. Both methods use
  848. a rule-based resolution scheme in order to determine the
  849. :class:`.Connection`, which in the average case is derived directly
  850. from the "bind" of the :class:`.Session` itself, and in other cases
  851. can be based on the :func:`.mapper`
  852. and :class:`.Table` objects passed to the method; see the
  853. documentation for :meth:`.Session.get_bind` for a full description of
  854. this scheme.
  855. The :meth:`.Session.execute` method does *not* invoke autoflush.
  856. The :class:`.ResultProxy` returned by the :meth:`.Session.execute`
  857. method is returned with the "close_with_result" flag set to true;
  858. the significance of this flag is that if this :class:`.Session` is
  859. autocommitting and does not have a transaction-dedicated
  860. :class:`.Connection` available, a temporary :class:`.Connection` is
  861. established for the statement execution, which is closed (meaning,
  862. returned to the connection pool) when the :class:`.ResultProxy` has
  863. consumed all available data. This applies *only* when the
  864. :class:`.Session` is configured with autocommit=True and no
  865. transaction has been started.
  866. :param clause:
  867. An executable statement (i.e. an :class:`.Executable` expression
  868. such as :func:`.expression.select`) or string SQL statement
  869. to be executed.
  870. :param params:
  871. Optional dictionary, or list of dictionaries, containing
  872. bound parameter values. If a single dictionary, single-row
  873. execution occurs; if a list of dictionaries, an
  874. "executemany" will be invoked. The keys in each dictionary
  875. must correspond to parameter names present in the statement.
  876. :param mapper:
  877. Optional :func:`.mapper` or mapped class, used to identify
  878. the appropriate bind. This argument takes precedence over
  879. ``clause`` when locating a bind. See :meth:`.Session.get_bind`
  880. for more details.
  881. :param bind:
  882. Optional :class:`.Engine` to be used as the bind. If
  883. this engine is already involved in an ongoing transaction,
  884. that connection will be used. This argument takes
  885. precedence over ``mapper`` and ``clause`` when locating
  886. a bind.
  887. :param \**kw:
  888. Additional keyword arguments are sent to :meth:`.Session.get_bind()`
  889. to allow extensibility of "bind" schemes.
  890. .. seealso::
  891. :ref:`sqlexpression_toplevel` - Tutorial on using Core SQL
  892. constructs.
  893. :ref:`connections_toplevel` - Further information on direct
  894. statement execution.
  895. :meth:`.Connection.execute` - core level statement execution
  896. method, which is :meth:`.Session.execute` ultimately uses
  897. in order to execute the statement.
  898. """
  899. clause = expression._literal_as_text(clause)
  900. if bind is None:
  901. bind = self.get_bind(mapper, clause=clause, **kw)
  902. return self._connection_for_bind(
  903. bind, close_with_result=True).execute(clause, params or {})
  904. def scalar(self, clause, params=None, mapper=None, bind=None, **kw):
  905. """Like :meth:`~.Session.execute` but return a scalar result."""
  906. return self.execute(
  907. clause, params=params, mapper=mapper, bind=bind, **kw).scalar()
  908. def close(self):
  909. """Close this Session.
  910. This clears all items and ends any transaction in progress.
  911. If this session were created with ``autocommit=False``, a new
  912. transaction is immediately begun. Note that this new transaction does
  913. not use any connection resources until they are first needed.
  914. """
  915. self._close_impl(invalidate=False)
  916. def invalidate(self):
  917. """Close this Session, using connection invalidation.
  918. This is a variant of :meth:`.Session.close` that will additionally
  919. ensure that the :meth:`.Connection.invalidate` method will be called
  920. on all :class:`.Connection` objects. This can be called when
  921. the database is known to be in a state where the connections are
  922. no longer safe to be used.
  923. E.g.::
  924. try:
  925. sess = Session()
  926. sess.add(User())
  927. sess.commit()
  928. except gevent.Timeout:
  929. sess.invalidate()
  930. raise
  931. except:
  932. sess.rollback()
  933. raise
  934. This clears all items and ends any transaction in progress.
  935. If this session were created with ``autocommit=False``, a new
  936. transaction is immediately begun. Note that this new transaction does
  937. not use any connection resources until they are first needed.
  938. .. versionadded:: 0.9.9
  939. """
  940. self._close_impl(invalidate=True)
  941. def _close_impl(self, invalidate):
  942. self.expunge_all()
  943. if self.transaction is not None:
  944. for transaction in self.transaction._iterate_self_and_parents():
  945. transaction.close(invalidate)
  946. def expunge_all(self):
  947. """Remove all object instances from this ``Session``.
  948. This is equivalent to calling ``expunge(obj)`` on all objects in this
  949. ``Session``.
  950. """
  951. all_states = self.identity_map.all_states() + list(self._new)
  952. self.identity_map = self._identity_cls()
  953. self._new = {}
  954. self._deleted = {}
  955. statelib.InstanceState._detach_states(
  956. all_states, self
  957. )
  958. def _add_bind(self, key, bind):
  959. try:
  960. insp = inspect(key)
  961. except sa_exc.NoInspectionAvailable:
  962. if not isinstance(key, type):
  963. raise sa_exc.ArgumentError(
  964. "Not an acceptable bind target: %s" % key)
  965. else:
  966. self.__binds[key] = bind
  967. else:
  968. if insp.is_selectable:
  969. self.__binds[insp] = bind
  970. elif insp.is_mapper:
  971. self.__binds[insp.class_] = bind
  972. for selectable in insp._all_tables:
  973. self.__binds[selectable] = bind
  974. else:
  975. raise sa_exc.ArgumentError(
  976. "Not an acceptable bind target: %s" % key)
  977. def bind_mapper(self, mapper, bind):
  978. """Associate a :class:`.Mapper` with a "bind", e.g. a :class:`.Engine`
  979. or :class:`.Connection`.
  980. The given mapper is added to a lookup used by the
  981. :meth:`.Session.get_bind` method.
  982. """
  983. self._add_bind(mapper, bind)
  984. def bind_table(self, table, bind):
  985. """Associate a :class:`.Table` with a "bind", e.g. a :class:`.Engine`
  986. or :class:`.Connection`.
  987. The given mapper is added to a lookup used by the
  988. :meth:`.Session.get_bind` method.
  989. """
  990. self._add_bind(table, bind)
  991. def get_bind(self, mapper=None, clause=None):
  992. """Return a "bind" to which this :class:`.Session` is bound.
  993. The "bind" is usually an instance of :class:`.Engine`,
  994. except in the case where the :class:`.Session` has been
  995. explicitly bound directly to a :class:`.Connection`.
  996. For a multiply-bound or unbound :class:`.Session`, the
  997. ``mapper`` or ``clause`` arguments are used to determine the
  998. appropriate bind to return.
  999. Note that the "mapper" argument is usually present
  1000. when :meth:`.Session.get_bind` is called via an ORM
  1001. operation such as a :meth:`.Session.query`, each
  1002. individual INSERT/UPDATE/DELETE operation within a
  1003. :meth:`.Session.flush`, call, etc.
  1004. The order of resolution is:
  1005. 1. if mapper given and session.binds is present,
  1006. locate a bind based on mapper.
  1007. 2. if clause given and session.binds is present,
  1008. locate a bind based on :class:`.Table` objects
  1009. found in the given clause present in session.binds.
  1010. 3. if session.bind is present, return that.
  1011. 4. if clause given, attempt to return a bind
  1012. linked to the :class:`.MetaData` ultimately
  1013. associated with the clause.
  1014. 5. if mapper given, attempt to return a bind
  1015. linked to the :class:`.MetaData` ultimately
  1016. associated with the :class:`.Table` or other
  1017. selectable to which the mapper is mapped.
  1018. 6. No bind can be found, :exc:`~sqlalchemy.exc.UnboundExecutionError`
  1019. is raised.
  1020. :param mapper:
  1021. Optional :func:`.mapper` mapped class or instance of
  1022. :class:`.Mapper`. The bind can be derived from a :class:`.Mapper`
  1023. first by consulting the "binds" map associated with this
  1024. :class:`.Session`, and secondly by consulting the :class:`.MetaData`
  1025. associated with the :class:`.Table` to which the :class:`.Mapper`
  1026. is mapped for a bind.
  1027. :param clause:
  1028. A :class:`.ClauseElement` (i.e. :func:`~.sql.expression.select`,
  1029. :func:`~.sql.expression.text`,
  1030. etc.). If the ``mapper`` argument is not present or could not
  1031. produce a bind, the given expression construct will be searched
  1032. for a bound element, typically a :class:`.Table` associated with
  1033. bound :class:`.MetaData`.
  1034. """
  1035. if mapper is clause is None:
  1036. if self.bind:
  1037. return self.bind
  1038. else:
  1039. raise sa_exc.UnboundExecutionError(
  1040. "This session is not bound to a single Engine or "
  1041. "Connection, and no context was provided to locate "
  1042. "a binding.")
  1043. if mapper is not None:
  1044. try:
  1045. mapper = inspect(mapper)
  1046. except sa_exc.NoInspectionAvailable:
  1047. if isinstance(mapper, type):
  1048. raise exc.UnmappedClassError(mapper)
  1049. else:
  1050. raise
  1051. if self.__binds:
  1052. if mapper:
  1053. for cls in mapper.class_.__mro__:
  1054. if cls in self.__binds:
  1055. return self.__binds[cls]
  1056. if clause is None:
  1057. clause = mapper.mapped_table
  1058. if clause is not None:
  1059. for t in sql_util.find_tables(clause, include_crud=True):
  1060. if t in self.__binds:
  1061. return self.__binds[t]
  1062. if self.bind:
  1063. return self.bind
  1064. if isinstance(clause, sql.expression.ClauseElement) and clause.bind:
  1065. return clause.bind
  1066. if mapper and mapper.mapped_table.bind:
  1067. return mapper.mapped_table.bind
  1068. context = []
  1069. if mapper is not None:
  1070. context.append('mapper %s' % mapper)
  1071. if clause is not None:
  1072. context.append('SQL expression')
  1073. raise sa_exc.UnboundExecutionError(
  1074. "Could not locate a bind configured on %s or this Session" % (
  1075. ', '.join(context)))
  1076. def query(self, *entities, **kwargs):
  1077. """Return a new :class:`.Query` object corresponding to this
  1078. :class:`.Session`."""
  1079. return self._query_cls(entities, self, **kwargs)
  1080. @property
  1081. @util.contextmanager
  1082. def no_autoflush(self):
  1083. """Return a context manager that disables autoflush.
  1084. e.g.::
  1085. with session.no_autoflush:
  1086. some_object = SomeClass()
  1087. session.add(some_object)
  1088. # won't autoflush
  1089. some_object.related_thing = session.query(SomeRelated).first()
  1090. Operations that proceed within the ``with:`` block
  1091. will not be subject to flushes occurring upon query
  1092. access. This is useful when initializing a series
  1093. of objects which involve existing database queries,
  1094. where the uncompleted object should not yet be flushed.
  1095. .. versionadded:: 0.7.6
  1096. """
  1097. autoflush = self.autoflush
  1098. self.autoflush = False
  1099. try:
  1100. yield self
  1101. finally:
  1102. self.autoflush = autoflush
  1103. def _autoflush(self):
  1104. if self.autoflush and not self._flushing:
  1105. try:
  1106. self.flush()
  1107. except sa_exc.StatementError as e:
  1108. # note we are reraising StatementError as opposed to
  1109. # raising FlushError with "chaining" to remain compatible
  1110. # with code that catches StatementError, IntegrityError,
  1111. # etc.
  1112. e.add_detail(
  1113. "raised as a result of Query-invoked autoflush; "
  1114. "consider using a session.no_autoflush block if this "
  1115. "flush is occurring prematurely")
  1116. util.raise_from_cause(e)
  1117. def refresh(self, instance, attribute_names=None, lockmode=None):
  1118. """Expire and refresh the attributes on the given instance.
  1119. A query will be issued to the database and all attributes will be
  1120. refreshed with their current database value.
  1121. Lazy-loaded relational attributes will remain lazily loaded, so that
  1122. the instance-wide refresh operation will be followed immediately by
  1123. the lazy load of that attribute.
  1124. Eagerly-loaded relational attributes will eagerly load within the
  1125. single refresh operation.
  1126. Note that a highly isolated transaction will return the same values as
  1127. were previously read in that same transaction, regardless of changes
  1128. in database state outside of that transaction - usage of
  1129. :meth:`~Session.refresh` usually only makes sense if non-ORM SQL
  1130. statement were emitted in the ongoing transaction, or if autocommit
  1131. mode is turned on.
  1132. :param attribute_names: optional. An iterable collection of
  1133. string attribute names indicating a subset of attributes to
  1134. be refreshed.
  1135. :param lockmode: Passed to the :class:`~sqlalchemy.orm.query.Query`
  1136. as used by :meth:`~sqlalchemy.orm.query.Query.with_lockmode`.
  1137. .. seealso::
  1138. :ref:`session_expire` - introductory material
  1139. :meth:`.Session.expire`
  1140. :meth:`.Session.expire_all`
  1141. """
  1142. try:
  1143. state = attributes.instance_state(instance)
  1144. except exc.NO_STATE:
  1145. raise exc.UnmappedInstanceError(instance)
  1146. self._expire_state(state, attribute_names)
  1147. if loading.load_on_ident(
  1148. self.query(object_mapper(instance)),
  1149. state.key, refresh_state=state,
  1150. lockmode=lockmode,
  1151. only_load_props=attribute_names) is None:
  1152. raise sa_exc.InvalidRequestError(
  1153. "Could not refresh instance '%s'" %
  1154. instance_str(instance))
  1155. def expire_all(self):
  1156. """Expires all persistent instances within this Session.
  1157. When any attributes on a persistent instance is next accessed,
  1158. a query will be issued using the
  1159. :class:`.Session` object's current transactional context in order to
  1160. load all expired attributes for the given instance. Note that
  1161. a highly isolated transaction will return the same values as were
  1162. previously read in that same transaction, regardless of changes
  1163. in database state outside of that transaction.
  1164. To expire individual objects and individual attributes
  1165. on those objects, use :meth:`Session.expire`.
  1166. The :class:`.Session` object's default behavior is to
  1167. expire all state whenever the :meth:`Session.rollback`
  1168. or :meth:`Session.commit` methods are called, so that new
  1169. state can be loaded for the new transaction. For this reason,
  1170. calling :meth:`Session.expire_all` should not be needed when
  1171. autocommit is ``False``, assuming the transaction is isolated.
  1172. .. seealso::
  1173. :ref:`session_expire` - introductory material
  1174. :meth:`.Session.expire`
  1175. :meth:`.Session.refresh`
  1176. """
  1177. for state in self.identity_map.all_states():
  1178. state._expire(state.dict, self.identity_map._modified)
  1179. def expire(self, instance, attribute_names=None):
  1180. """Expire the attributes on an instance.
  1181. Marks the attributes of an instance as out of date. When an expired
  1182. attribute is next accessed, a query will be issued to the
  1183. :class:`.Session` object's current transactional context in order to
  1184. load all expired attributes for the given instance. Note that
  1185. a highly isolated transaction will return the same values as were
  1186. previously read in that same transaction, regardless of changes
  1187. in database state outside of that transaction.
  1188. To expire all objects in the :class:`.Session` simultaneously,
  1189. use :meth:`Session.expire_all`.
  1190. The :class:`.Session` object's default behavior is to
  1191. expire all state whenever the :meth:`Session.rollback`
  1192. or :meth:`Session.commit` methods are called, so that new
  1193. state can be loaded for the new transaction. For this reason,
  1194. calling :meth:`Session.expire` only makes sense for the specific
  1195. case that a non-ORM SQL statement was emitted in the current
  1196. transaction.
  1197. :param instance: The instance to be refreshed.
  1198. :param attribute_names: optional list of string attribute names
  1199. indicating a subset of attributes to be expired.
  1200. .. seealso::
  1201. :ref:`session_expire` - introductory material
  1202. :meth:`.Session.expire`
  1203. :meth:`.Session.refresh`
  1204. """
  1205. try:
  1206. state = attributes.instance_state(instance)
  1207. except exc.NO_STATE:
  1208. raise exc.UnmappedInstanceError(instance)
  1209. self._expire_state(state, attribute_names)
  1210. def _expire_state(self, state, attribute_names):
  1211. self._validate_persistent(state)
  1212. if attribute_names:
  1213. state._expire_attributes(state.dict, attribute_names)
  1214. else:
  1215. # pre-fetch the full cascade since the expire is going to
  1216. # remove associations
  1217. cascaded = list(state.manager.mapper.cascade_iterator(
  1218. 'refresh-expire', state))
  1219. self._conditional_expire(state)
  1220. for o, m, st_, dct_ in cascaded:
  1221. self._conditional_expire(st_)
  1222. def _conditional_expire(self, state):
  1223. """Expire a state if persistent, else expunge if pending"""
  1224. if state.key:
  1225. state._expire(state.dict, self.identity_map._modified)
  1226. elif state in self._new:
  1227. self._new.pop(state)
  1228. state._detach(self)
  1229. @util.deprecated("0.7", "The non-weak-referencing identity map "
  1230. "feature is no longer needed.")
  1231. def prune(self):
  1232. """Remove unreferenced instances cached in the identity map.
  1233. Note that this method is only meaningful if "weak_identity_map" is set
  1234. to False. The default weak identity map is self-pruning.
  1235. Removes any object in this Session's identity map that is not
  1236. referenced in user code, modified, new or scheduled for deletion.
  1237. Returns the number of objects pruned.
  1238. """
  1239. return self.identity_map.prune()
  1240. def expunge(self, instance):
  1241. """Remove the `instance` from this ``Session``.
  1242. This will free all internal references to the instance. Cascading
  1243. will be applied according to the *expunge* cascade rule.
  1244. """
  1245. try:
  1246. state = attributes.instance_state(instance)
  1247. except exc.NO_STATE:
  1248. raise exc.UnmappedInstanceError(instance)
  1249. if state.session_id is not self.hash_key:
  1250. raise sa_exc.InvalidRequestError(
  1251. "Instance %s is not present in this Session" %
  1252. state_str(state))
  1253. cascaded = list(state.manager.mapper.cascade_iterator(
  1254. 'expunge', state))
  1255. self._expunge_states(
  1256. [state] + [st_ for o, m, st_, dct_ in cascaded]
  1257. )
  1258. def _expunge_states(self, states, to_transient=False):
  1259. for state in states:
  1260. if state in self._new:
  1261. self._new.pop(state)
  1262. elif self.identity_map.contains_state(state):
  1263. self.identity_map.safe_discard(state)
  1264. self._deleted.pop(state, None)
  1265. elif self.transaction:
  1266. # state is "detached" from being deleted, but still present
  1267. # in the transaction snapshot
  1268. self.transaction._deleted.pop(state, None)
  1269. statelib.InstanceState._detach_states(
  1270. states, self, to_transient=to_transient)
  1271. def _register_newly_persistent(self, states):
  1272. pending_to_persistent = self.dispatch.pending_to_persistent or None
  1273. for state in states:
  1274. mapper = _state_mapper(state)
  1275. # prevent against last minute dereferences of the object
  1276. obj = state.obj()
  1277. if obj is not None:
  1278. instance_key = mapper._identity_key_from_state(state)
  1279. if _none_set.intersection(instance_key[1]) and \
  1280. not mapper.allow_partial_pks or \
  1281. _none_set.issuperset(instance_key[1]):
  1282. raise exc.FlushError(
  1283. "Instance %s has a NULL identity key. If this is an "
  1284. "auto-generated value, check that the database table "
  1285. "allows generation of new primary key values, and "
  1286. "that the mapped Column object is configured to "
  1287. "expect these generated values. Ensure also that "
  1288. "this flush() is not occurring at an inappropriate "
  1289. "time, such as within a load() event."
  1290. % state_str(state)
  1291. )
  1292. if state.key is None:
  1293. state.key = instance_key
  1294. elif state.key != instance_key:
  1295. # primary key switch. use safe_discard() in case another
  1296. # state has already replaced this one in the identity
  1297. # map (see test/orm/test_naturalpks.py ReversePKsTest)
  1298. self.identity_map.safe_discard(state)
  1299. if state in self.transaction._key_switches:
  1300. orig_key = self.transaction._key_switches[state][0]
  1301. else:
  1302. orig_key = state.key
  1303. self.transaction._key_switches[state] = (
  1304. orig_key, instance_key)
  1305. state.key = instance_key
  1306. self.identity_map.replace(state)
  1307. statelib.InstanceState._commit_all_states(
  1308. ((state, state.dict) for state in states),
  1309. self.identity_map
  1310. )
  1311. self._register_altered(states)
  1312. if pending_to_persistent is not None:
  1313. for state in states:
  1314. pending_to_persistent(self, state.obj())
  1315. # remove from new last, might be the last strong ref
  1316. for state in set(states).intersection(self._new):
  1317. self._new.pop(state)
  1318. def _register_altered(self, states):
  1319. if self._enable_transaction_accounting and self.transaction:
  1320. for state in states:
  1321. if state in self._new:
  1322. self.transaction._new[state] = True
  1323. else:
  1324. self.transaction._dirty[state] = True
  1325. def _remove_newly_deleted(self, states):
  1326. persistent_to_deleted = self.dispatch.persistent_to_deleted or None
  1327. for state in states:
  1328. if self._enable_transaction_accounting and self.transaction:
  1329. self.transaction._deleted[state] = True
  1330. if persistent_to_deleted is not None:
  1331. # get a strong reference before we pop out of
  1332. # self._deleted
  1333. obj = state.obj()
  1334. self.identity_map.safe_discard(state)
  1335. self._deleted.pop(state, None)
  1336. state._deleted = True
  1337. # can't call state._detach() here, because this state
  1338. # is still in the transaction snapshot and needs to be
  1339. # tracked as part of that
  1340. if persistent_to_deleted is not None:
  1341. persistent_to_deleted(self, obj)
  1342. def add(self, instance, _warn=True):
  1343. """Place an object in the ``Session``.
  1344. Its state will be persisted to the database on the next flush
  1345. operation.
  1346. Repeated calls to ``add()`` will be ignored. The opposite of ``add()``
  1347. is ``expunge()``.
  1348. """
  1349. if _warn and self._warn_on_events:
  1350. self._flush_warning("Session.add()")
  1351. try:
  1352. state = attributes.instance_state(instance)
  1353. except exc.NO_STATE:
  1354. raise exc.UnmappedInstanceError(instance)
  1355. self._save_or_update_state(state)
  1356. def add_all(self, instances):
  1357. """Add the given collection of instances to this ``Session``."""
  1358. if self._warn_on_events:
  1359. self._flush_warning("Session.add_all()")
  1360. for instance in instances:
  1361. self.add(instance, _warn=False)
  1362. def _save_or_update_state(self, state):
  1363. self._save_or_update_impl(state)
  1364. mapper = _state_mapper(state)
  1365. for o, m, st_, dct_ in mapper.cascade_iterator(
  1366. 'save-update',
  1367. state,
  1368. halt_on=self._contains_state):
  1369. self._save_or_update_impl(st_)
  1370. def delete(self, instance):
  1371. """Mark an instance as deleted.
  1372. The database delete operation occurs upon ``flush()``.
  1373. """
  1374. if self._warn_on_events:
  1375. self._flush_warning("Session.delete()")
  1376. try:
  1377. state = attributes.instance_state(instance)
  1378. except exc.NO_STATE:
  1379. raise exc.UnmappedInstanceError(instance)
  1380. self._delete_impl(state, instance, head=True)
  1381. def _delete_impl(self, state, obj, head):
  1382. if state.key is None:
  1383. if head:
  1384. raise sa_exc.InvalidRequestError(
  1385. "Instance '%s' is not persisted" %
  1386. state_str(state))
  1387. else:
  1388. return
  1389. to_attach = self._before_attach(state, obj)
  1390. if state in self._deleted:
  1391. return
  1392. self.identity_map.add(state)
  1393. if to_attach:
  1394. self._after_attach(state, obj)
  1395. if head:
  1396. # grab the cascades before adding the item to the deleted list
  1397. # so that autoflush does not delete the item
  1398. # the strong reference to the instance itself is significant here
  1399. cascade_states = list(state.manager.mapper.cascade_iterator(
  1400. 'delete', state))
  1401. self._deleted[state] = obj
  1402. if head:
  1403. for o, m, st_, dct_ in cascade_states:
  1404. self._delete_impl(st_, o, False)
  1405. def merge(self, instance, load=True):
  1406. """Copy the state of a given instance into a corresponding instance
  1407. within this :class:`.Session`.
  1408. :meth:`.Session.merge` examines the primary key attributes of the
  1409. source instance, and attempts to reconcile it with an instance of the
  1410. same primary key in the session. If not found locally, it attempts
  1411. to load the object from the database based on primary key, and if
  1412. none can be located, creates a new instance. The state of each
  1413. attribute on the source instance is then copied to the target
  1414. instance. The resulting target instance is then returned by the
  1415. method; the original source instance is left unmodified, and
  1416. un-associated with the :class:`.Session` if not already.
  1417. This operation cascades to associated instances if the association is
  1418. mapped with ``cascade="merge"``.
  1419. See :ref:`unitofwork_merging` for a detailed discussion of merging.
  1420. .. versionchanged:: 1.1 - :meth:`.Session.merge` will now reconcile
  1421. pending objects with overlapping primary keys in the same way
  1422. as persistent. See :ref:`change_3601` for discussion.
  1423. :param instance: Instance to be merged.
  1424. :param load: Boolean, when False, :meth:`.merge` switches into
  1425. a "high performance" mode which causes it to forego emitting history
  1426. events as well as all database access. This flag is used for
  1427. cases such as transferring graphs of objects into a :class:`.Session`
  1428. from a second level cache, or to transfer just-loaded objects
  1429. into the :class:`.Session` owned by a worker thread or process
  1430. without re-querying the database.
  1431. The ``load=False`` use case adds the caveat that the given
  1432. object has to be in a "clean" state, that is, has no pending changes
  1433. to be flushed - even if the incoming object is detached from any
  1434. :class:`.Session`. This is so that when
  1435. the merge operation populates local attributes and
  1436. cascades to related objects and
  1437. collections, the values can be "stamped" onto the
  1438. target object as is, without generating any history or attribute
  1439. events, and without the need to reconcile the incoming data with
  1440. any existing related objects or collections that might not
  1441. be loaded. The resulting objects from ``load=False`` are always
  1442. produced as "clean", so it is only appropriate that the given objects
  1443. should be "clean" as well, else this suggests a mis-use of the
  1444. method.
  1445. """
  1446. if self._warn_on_events:
  1447. self._flush_warning("Session.merge()")
  1448. _recursive = {}
  1449. _resolve_conflict_map = {}
  1450. if load:
  1451. # flush current contents if we expect to load data
  1452. self._autoflush()
  1453. object_mapper(instance) # verify mapped
  1454. autoflush = self.autoflush
  1455. try:
  1456. self.autoflush = False
  1457. return self._merge(
  1458. attributes.instance_state(instance),
  1459. attributes.instance_dict(instance),
  1460. load=load, _recursive=_recursive,
  1461. _resolve_conflict_map=_resolve_conflict_map)
  1462. finally:
  1463. self.autoflush = autoflush
  1464. def _merge(self, state, state_dict, load=True, _recursive=None,
  1465. _resolve_conflict_map=None):
  1466. mapper = _state_mapper(state)
  1467. if state in _recursive:
  1468. return _recursive[state]
  1469. new_instance = False
  1470. key = state.key
  1471. if key is None:
  1472. if not load:
  1473. raise sa_exc.InvalidRequestError(
  1474. "merge() with load=False option does not support "
  1475. "objects transient (i.e. unpersisted) objects. flush() "
  1476. "all changes on mapped instances before merging with "
  1477. "load=False.")
  1478. key = mapper._identity_key_from_state(state)
  1479. key_is_persistent = attributes.NEVER_SET not in key[1]
  1480. else:
  1481. key_is_persistent = True
  1482. if key in self.identity_map:
  1483. merged = self.identity_map[key]
  1484. elif key_is_persistent and key in _resolve_conflict_map:
  1485. merged = _resolve_conflict_map[key]
  1486. elif not load:
  1487. if state.modified:
  1488. raise sa_exc.InvalidRequestError(
  1489. "merge() with load=False option does not support "
  1490. "objects marked as 'dirty'. flush() all changes on "
  1491. "mapped instances before merging with load=False.")
  1492. merged = mapper.class_manager.new_instance()
  1493. merged_state = attributes.instance_state(merged)
  1494. merged_state.key = key
  1495. self._update_impl(merged_state)
  1496. new_instance = True
  1497. elif key_is_persistent and (
  1498. not _none_set.intersection(key[1]) or
  1499. (mapper.allow_partial_pks and
  1500. not _none_set.issuperset(key[1]))):
  1501. merged = self.query(mapper.class_).get(key[1])
  1502. else:
  1503. merged = None
  1504. if merged is None:
  1505. merged = mapper.class_manager.new_instance()
  1506. merged_state = attributes.instance_state(merged)
  1507. merged_dict = attributes.instance_dict(merged)
  1508. new_instance = True
  1509. self._save_or_update_state(merged_state)
  1510. else:
  1511. merged_state = attributes.instance_state(merged)
  1512. merged_dict = attributes.instance_dict(merged)
  1513. _recursive[state] = merged
  1514. _resolve_conflict_map[key] = merged
  1515. # check that we didn't just pull the exact same
  1516. # state out.
  1517. if state is not merged_state:
  1518. # version check if applicable
  1519. if mapper.version_id_col is not None:
  1520. existing_version = mapper._get_state_attr_by_column(
  1521. state,
  1522. state_dict,
  1523. mapper.version_id_col,
  1524. passive=attributes.PASSIVE_NO_INITIALIZE)
  1525. merged_version = mapper._get_state_attr_by_column(
  1526. merged_state,
  1527. merged_dict,
  1528. mapper.version_id_col,
  1529. passive=attributes.PASSIVE_NO_INITIALIZE)
  1530. if existing_version is not attributes.PASSIVE_NO_RESULT and \
  1531. merged_version is not attributes.PASSIVE_NO_RESULT and \
  1532. existing_version != merged_version:
  1533. raise exc.StaleDataError(
  1534. "Version id '%s' on merged state %s "
  1535. "does not match existing version '%s'. "
  1536. "Leave the version attribute unset when "
  1537. "merging to update the most recent version."
  1538. % (
  1539. existing_version,
  1540. state_str(merged_state),
  1541. merged_version
  1542. ))
  1543. merged_state.load_path = state.load_path
  1544. merged_state.load_options = state.load_options
  1545. # since we are copying load_options, we need to copy
  1546. # the callables_ that would have been generated by those
  1547. # load_options.
  1548. # assumes that the callables we put in state.callables_
  1549. # are not instance-specific (which they should not be)
  1550. merged_state._copy_callables(state)
  1551. for prop in mapper.iterate_properties:
  1552. prop.merge(self, state, state_dict,
  1553. merged_state, merged_dict,
  1554. load, _recursive, _resolve_conflict_map)
  1555. if not load:
  1556. # remove any history
  1557. merged_state._commit_all(merged_dict, self.identity_map)
  1558. if new_instance:
  1559. merged_state.manager.dispatch.load(merged_state, None)
  1560. return merged
  1561. def _validate_persistent(self, state):
  1562. if not self.identity_map.contains_state(state):
  1563. raise sa_exc.InvalidRequestError(
  1564. "Instance '%s' is not persistent within this Session" %
  1565. state_str(state))
  1566. def _save_impl(self, state):
  1567. if state.key is not None:
  1568. raise sa_exc.InvalidRequestError(
  1569. "Object '%s' already has an identity - "
  1570. "it can't be registered as pending" % state_str(state))
  1571. obj = state.obj()
  1572. to_attach = self._before_attach(state, obj)
  1573. if state not in self._new:
  1574. self._new[state] = obj
  1575. state.insert_order = len(self._new)
  1576. if to_attach:
  1577. self._after_attach(state, obj)
  1578. def _update_impl(self, state, revert_deletion=False):
  1579. if state.key is None:
  1580. raise sa_exc.InvalidRequestError(
  1581. "Instance '%s' is not persisted" %
  1582. state_str(state))
  1583. if state._deleted:
  1584. if revert_deletion:
  1585. if not state._attached:
  1586. return
  1587. del state._deleted
  1588. else:
  1589. raise sa_exc.InvalidRequestError(
  1590. "Instance '%s' has been deleted. "
  1591. "Use the make_transient() "
  1592. "function to send this object back "
  1593. "to the transient state." %
  1594. state_str(state)
  1595. )
  1596. obj = state.obj()
  1597. # check for late gc
  1598. if obj is None:
  1599. return
  1600. to_attach = self._before_attach(state, obj)
  1601. self._deleted.pop(state, None)
  1602. if revert_deletion:
  1603. self.identity_map.replace(state)
  1604. else:
  1605. self.identity_map.add(state)
  1606. if to_attach:
  1607. self._after_attach(state, obj)
  1608. elif revert_deletion:
  1609. self.dispatch.deleted_to_persistent(self, obj)
  1610. def _save_or_update_impl(self, state):
  1611. if state.key is None:
  1612. self._save_impl(state)
  1613. else:
  1614. self._update_impl(state)
  1615. def enable_relationship_loading(self, obj):
  1616. """Associate an object with this :class:`.Session` for related
  1617. object loading.
  1618. .. warning::
  1619. :meth:`.enable_relationship_loading` exists to serve special
  1620. use cases and is not recommended for general use.
  1621. Accesses of attributes mapped with :func:`.relationship`
  1622. will attempt to load a value from the database using this
  1623. :class:`.Session` as the source of connectivity. The values
  1624. will be loaded based on foreign key values present on this
  1625. object - it follows that this functionality
  1626. generally only works for many-to-one-relationships.
  1627. The object will be attached to this session, but will
  1628. **not** participate in any persistence operations; its state
  1629. for almost all purposes will remain either "transient" or
  1630. "detached", except for the case of relationship loading.
  1631. Also note that backrefs will often not work as expected.
  1632. Altering a relationship-bound attribute on the target object
  1633. may not fire off a backref event, if the effective value
  1634. is what was already loaded from a foreign-key-holding value.
  1635. The :meth:`.Session.enable_relationship_loading` method is
  1636. similar to the ``load_on_pending`` flag on :func:`.relationship`.
  1637. Unlike that flag, :meth:`.Session.enable_relationship_loading` allows
  1638. an object to remain transient while still being able to load
  1639. related items.
  1640. To make a transient object associated with a :class:`.Session`
  1641. via :meth:`.Session.enable_relationship_loading` pending, add
  1642. it to the :class:`.Session` using :meth:`.Session.add` normally.
  1643. :meth:`.Session.enable_relationship_loading` does not improve
  1644. behavior when the ORM is used normally - object references should be
  1645. constructed at the object level, not at the foreign key level, so
  1646. that they are present in an ordinary way before flush()
  1647. proceeds. This method is not intended for general use.
  1648. .. versionadded:: 0.8
  1649. .. seealso::
  1650. ``load_on_pending`` at :func:`.relationship` - this flag
  1651. allows per-relationship loading of many-to-ones on items that
  1652. are pending.
  1653. """
  1654. state = attributes.instance_state(obj)
  1655. to_attach = self._before_attach(state, obj)
  1656. state._load_pending = True
  1657. if to_attach:
  1658. self._after_attach(state, obj)
  1659. def _before_attach(self, state, obj):
  1660. if state.session_id == self.hash_key:
  1661. return False
  1662. if state.session_id and state.session_id in _sessions:
  1663. raise sa_exc.InvalidRequestError(
  1664. "Object '%s' is already attached to session '%s' "
  1665. "(this is '%s')" % (state_str(state),
  1666. state.session_id, self.hash_key))
  1667. self.dispatch.before_attach(self, obj)
  1668. return True
  1669. def _after_attach(self, state, obj):
  1670. state.session_id = self.hash_key
  1671. if state.modified and state._strong_obj is None:
  1672. state._strong_obj = obj
  1673. self.dispatch.after_attach(self, obj)
  1674. if state.key:
  1675. self.dispatch.detached_to_persistent(self, obj)
  1676. else:
  1677. self.dispatch.transient_to_pending(self, obj)
  1678. def __contains__(self, instance):
  1679. """Return True if the instance is associated with this session.
  1680. The instance may be pending or persistent within the Session for a
  1681. result of True.
  1682. """
  1683. try:
  1684. state = attributes.instance_state(instance)
  1685. except exc.NO_STATE:
  1686. raise exc.UnmappedInstanceError(instance)
  1687. return self._contains_state(state)
  1688. def __iter__(self):
  1689. """Iterate over all pending or persistent instances within this
  1690. Session.
  1691. """
  1692. return iter(
  1693. list(self._new.values()) + list(self.identity_map.values()))
  1694. def _contains_state(self, state):
  1695. return state in self._new or self.identity_map.contains_state(state)
  1696. def flush(self, objects=None):
  1697. """Flush all the object changes to the database.
  1698. Writes out all pending object creations, deletions and modifications
  1699. to the database as INSERTs, DELETEs, UPDATEs, etc. Operations are
  1700. automatically ordered by the Session's unit of work dependency
  1701. solver.
  1702. Database operations will be issued in the current transactional
  1703. context and do not affect the state of the transaction, unless an
  1704. error occurs, in which case the entire transaction is rolled back.
  1705. You may flush() as often as you like within a transaction to move
  1706. changes from Python to the database's transaction buffer.
  1707. For ``autocommit`` Sessions with no active manual transaction, flush()
  1708. will create a transaction on the fly that surrounds the entire set of
  1709. operations into the flush.
  1710. :param objects: Optional; restricts the flush operation to operate
  1711. only on elements that are in the given collection.
  1712. This feature is for an extremely narrow set of use cases where
  1713. particular objects may need to be operated upon before the
  1714. full flush() occurs. It is not intended for general use.
  1715. """
  1716. if self._flushing:
  1717. raise sa_exc.InvalidRequestError("Session is already flushing")
  1718. if self._is_clean():
  1719. return
  1720. try:
  1721. self._flushing = True
  1722. self._flush(objects)
  1723. finally:
  1724. self._flushing = False
  1725. def _flush_warning(self, method):
  1726. util.warn(
  1727. "Usage of the '%s' operation is not currently supported "
  1728. "within the execution stage of the flush process. "
  1729. "Results may not be consistent. Consider using alternative "
  1730. "event listeners or connection-level operations instead."
  1731. % method)
  1732. def _is_clean(self):
  1733. return not self.identity_map.check_modified() and \
  1734. not self._deleted and \
  1735. not self._new
  1736. def _flush(self, objects=None):
  1737. dirty = self._dirty_states
  1738. if not dirty and not self._deleted and not self._new:
  1739. self.identity_map._modified.clear()
  1740. return
  1741. flush_context = UOWTransaction(self)
  1742. if self.dispatch.before_flush:
  1743. self.dispatch.before_flush(self, flush_context, objects)
  1744. # re-establish "dirty states" in case the listeners
  1745. # added
  1746. dirty = self._dirty_states
  1747. deleted = set(self._deleted)
  1748. new = set(self._new)
  1749. dirty = set(dirty).difference(deleted)
  1750. # create the set of all objects we want to operate upon
  1751. if objects:
  1752. # specific list passed in
  1753. objset = set()
  1754. for o in objects:
  1755. try:
  1756. state = attributes.instance_state(o)
  1757. except exc.NO_STATE:
  1758. raise exc.UnmappedInstanceError(o)
  1759. objset.add(state)
  1760. else:
  1761. objset = None
  1762. # store objects whose fate has been decided
  1763. processed = set()
  1764. # put all saves/updates into the flush context. detect top-level
  1765. # orphans and throw them into deleted.
  1766. if objset:
  1767. proc = new.union(dirty).intersection(objset).difference(deleted)
  1768. else:
  1769. proc = new.union(dirty).difference(deleted)
  1770. for state in proc:
  1771. is_orphan = (
  1772. _state_mapper(state)._is_orphan(state) and state.has_identity)
  1773. _reg = flush_context.register_object(state, isdelete=is_orphan)
  1774. assert _reg, "Failed to add object to the flush context!"
  1775. processed.add(state)
  1776. # put all remaining deletes into the flush context.
  1777. if objset:
  1778. proc = deleted.intersection(objset).difference(processed)
  1779. else:
  1780. proc = deleted.difference(processed)
  1781. for state in proc:
  1782. _reg = flush_context.register_object(state, isdelete=True)
  1783. assert _reg, "Failed to add object to the flush context!"
  1784. if not flush_context.has_work:
  1785. return
  1786. flush_context.transaction = transaction = self.begin(
  1787. subtransactions=True)
  1788. try:
  1789. self._warn_on_events = True
  1790. try:
  1791. flush_context.execute()
  1792. finally:
  1793. self._warn_on_events = False
  1794. self.dispatch.after_flush(self, flush_context)
  1795. flush_context.finalize_flush_changes()
  1796. if not objects and self.identity_map._modified:
  1797. len_ = len(self.identity_map._modified)
  1798. statelib.InstanceState._commit_all_states(
  1799. [(state, state.dict) for state in
  1800. self.identity_map._modified],
  1801. instance_dict=self.identity_map)
  1802. util.warn("Attribute history events accumulated on %d "
  1803. "previously clean instances "
  1804. "within inner-flush event handlers have been "
  1805. "reset, and will not result in database updates. "
  1806. "Consider using set_committed_value() within "
  1807. "inner-flush event handlers to avoid this warning."
  1808. % len_)
  1809. # useful assertions:
  1810. # if not objects:
  1811. # assert not self.identity_map._modified
  1812. # else:
  1813. # assert self.identity_map._modified == \
  1814. # self.identity_map._modified.difference(objects)
  1815. self.dispatch.after_flush_postexec(self, flush_context)
  1816. transaction.commit()
  1817. except:
  1818. with util.safe_reraise():
  1819. transaction.rollback(_capture_exception=True)
  1820. def bulk_save_objects(
  1821. self, objects, return_defaults=False, update_changed_only=True):
  1822. """Perform a bulk save of the given list of objects.
  1823. The bulk save feature allows mapped objects to be used as the
  1824. source of simple INSERT and UPDATE operations which can be more easily
  1825. grouped together into higher performing "executemany"
  1826. operations; the extraction of data from the objects is also performed
  1827. using a lower-latency process that ignores whether or not attributes
  1828. have actually been modified in the case of UPDATEs, and also ignores
  1829. SQL expressions.
  1830. The objects as given are not added to the session and no additional
  1831. state is established on them, unless the ``return_defaults`` flag
  1832. is also set, in which case primary key attributes and server-side
  1833. default values will be populated.
  1834. .. versionadded:: 1.0.0
  1835. .. warning::
  1836. The bulk save feature allows for a lower-latency INSERT/UPDATE
  1837. of rows at the expense of most other unit-of-work features.
  1838. Features such as object management, relationship handling,
  1839. and SQL clause support are **silently omitted** in favor of raw
  1840. INSERT/UPDATES of records.
  1841. **Please read the list of caveats at** :ref:`bulk_operations`
  1842. **before using this method, and fully test and confirm the
  1843. functionality of all code developed using these systems.**
  1844. :param objects: a list of mapped object instances. The mapped
  1845. objects are persisted as is, and are **not** associated with the
  1846. :class:`.Session` afterwards.
  1847. For each object, whether the object is sent as an INSERT or an
  1848. UPDATE is dependent on the same rules used by the :class:`.Session`
  1849. in traditional operation; if the object has the
  1850. :attr:`.InstanceState.key`
  1851. attribute set, then the object is assumed to be "detached" and
  1852. will result in an UPDATE. Otherwise, an INSERT is used.
  1853. In the case of an UPDATE, statements are grouped based on which
  1854. attributes have changed, and are thus to be the subject of each
  1855. SET clause. If ``update_changed_only`` is False, then all
  1856. attributes present within each object are applied to the UPDATE
  1857. statement, which may help in allowing the statements to be grouped
  1858. together into a larger executemany(), and will also reduce the
  1859. overhead of checking history on attributes.
  1860. :param return_defaults: when True, rows that are missing values which
  1861. generate defaults, namely integer primary key defaults and sequences,
  1862. will be inserted **one at a time**, so that the primary key value
  1863. is available. In particular this will allow joined-inheritance
  1864. and other multi-table mappings to insert correctly without the need
  1865. to provide primary key values ahead of time; however,
  1866. :paramref:`.Session.bulk_save_objects.return_defaults` **greatly
  1867. reduces the performance gains** of the method overall.
  1868. :param update_changed_only: when True, UPDATE statements are rendered
  1869. based on those attributes in each state that have logged changes.
  1870. When False, all attributes present are rendered into the SET clause
  1871. with the exception of primary key attributes.
  1872. .. seealso::
  1873. :ref:`bulk_operations`
  1874. :meth:`.Session.bulk_insert_mappings`
  1875. :meth:`.Session.bulk_update_mappings`
  1876. """
  1877. for (mapper, isupdate), states in itertools.groupby(
  1878. (attributes.instance_state(obj) for obj in objects),
  1879. lambda state: (state.mapper, state.key is not None)
  1880. ):
  1881. self._bulk_save_mappings(
  1882. mapper, states, isupdate, True,
  1883. return_defaults, update_changed_only, False)
  1884. def bulk_insert_mappings(
  1885. self, mapper, mappings, return_defaults=False, render_nulls=False):
  1886. """Perform a bulk insert of the given list of mapping dictionaries.
  1887. The bulk insert feature allows plain Python dictionaries to be used as
  1888. the source of simple INSERT operations which can be more easily
  1889. grouped together into higher performing "executemany"
  1890. operations. Using dictionaries, there is no "history" or session
  1891. state management features in use, reducing latency when inserting
  1892. large numbers of simple rows.
  1893. The values within the dictionaries as given are typically passed
  1894. without modification into Core :meth:`.Insert` constructs, after
  1895. organizing the values within them across the tables to which
  1896. the given mapper is mapped.
  1897. .. versionadded:: 1.0.0
  1898. .. warning::
  1899. The bulk insert feature allows for a lower-latency INSERT
  1900. of rows at the expense of most other unit-of-work features.
  1901. Features such as object management, relationship handling,
  1902. and SQL clause support are **silently omitted** in favor of raw
  1903. INSERT of records.
  1904. **Please read the list of caveats at** :ref:`bulk_operations`
  1905. **before using this method, and fully test and confirm the
  1906. functionality of all code developed using these systems.**
  1907. :param mapper: a mapped class, or the actual :class:`.Mapper` object,
  1908. representing the single kind of object represented within the mapping
  1909. list.
  1910. :param mappings: a list of dictionaries, each one containing the state
  1911. of the mapped row to be inserted, in terms of the attribute names
  1912. on the mapped class. If the mapping refers to multiple tables,
  1913. such as a joined-inheritance mapping, each dictionary must contain
  1914. all keys to be populated into all tables.
  1915. :param return_defaults: when True, rows that are missing values which
  1916. generate defaults, namely integer primary key defaults and sequences,
  1917. will be inserted **one at a time**, so that the primary key value
  1918. is available. In particular this will allow joined-inheritance
  1919. and other multi-table mappings to insert correctly without the need
  1920. to provide primary
  1921. key values ahead of time; however,
  1922. :paramref:`.Session.bulk_insert_mappings.return_defaults`
  1923. **greatly reduces the performance gains** of the method overall.
  1924. If the rows
  1925. to be inserted only refer to a single table, then there is no
  1926. reason this flag should be set as the returned default information
  1927. is not used.
  1928. :param render_nulls: When True, a value of ``None`` will result
  1929. in a NULL value being included in the INSERT statement, rather
  1930. than the column being omitted from the INSERT. This allows all
  1931. the rows being INSERTed to have the identical set of columns which
  1932. allows the full set of rows to be batched to the DBAPI. Normally,
  1933. each column-set that contains a different combination of NULL values
  1934. than the previous row must omit a different series of columns from
  1935. the rendered INSERT statement, which means it must be emitted as a
  1936. separate statement. By passing this flag, the full set of rows
  1937. are guaranteed to be batchable into one batch; the cost however is
  1938. that server-side defaults which are invoked by an omitted column will
  1939. be skipped, so care must be taken to ensure that these are not
  1940. necessary.
  1941. .. warning::
  1942. When this flag is set, **server side default SQL values will
  1943. not be invoked** for those columns that are inserted as NULL;
  1944. the NULL value will be sent explicitly. Care must be taken
  1945. to ensure that no server-side default functions need to be
  1946. invoked for the operation as a whole.
  1947. .. versionadded:: 1.1
  1948. .. seealso::
  1949. :ref:`bulk_operations`
  1950. :meth:`.Session.bulk_save_objects`
  1951. :meth:`.Session.bulk_update_mappings`
  1952. """
  1953. self._bulk_save_mappings(
  1954. mapper, mappings, False, False,
  1955. return_defaults, False, render_nulls)
  1956. def bulk_update_mappings(self, mapper, mappings):
  1957. """Perform a bulk update of the given list of mapping dictionaries.
  1958. The bulk update feature allows plain Python dictionaries to be used as
  1959. the source of simple UPDATE operations which can be more easily
  1960. grouped together into higher performing "executemany"
  1961. operations. Using dictionaries, there is no "history" or session
  1962. state management features in use, reducing latency when updating
  1963. large numbers of simple rows.
  1964. .. versionadded:: 1.0.0
  1965. .. warning::
  1966. The bulk update feature allows for a lower-latency UPDATE
  1967. of rows at the expense of most other unit-of-work features.
  1968. Features such as object management, relationship handling,
  1969. and SQL clause support are **silently omitted** in favor of raw
  1970. UPDATES of records.
  1971. **Please read the list of caveats at** :ref:`bulk_operations`
  1972. **before using this method, and fully test and confirm the
  1973. functionality of all code developed using these systems.**
  1974. :param mapper: a mapped class, or the actual :class:`.Mapper` object,
  1975. representing the single kind of object represented within the mapping
  1976. list.
  1977. :param mappings: a list of dictionaries, each one containing the state
  1978. of the mapped row to be updated, in terms of the attribute names
  1979. on the mapped class. If the mapping refers to multiple tables,
  1980. such as a joined-inheritance mapping, each dictionary may contain
  1981. keys corresponding to all tables. All those keys which are present
  1982. and are not part of the primary key are applied to the SET clause
  1983. of the UPDATE statement; the primary key values, which are required,
  1984. are applied to the WHERE clause.
  1985. .. seealso::
  1986. :ref:`bulk_operations`
  1987. :meth:`.Session.bulk_insert_mappings`
  1988. :meth:`.Session.bulk_save_objects`
  1989. """
  1990. self._bulk_save_mappings(
  1991. mapper, mappings, True, False, False, False, False)
  1992. def _bulk_save_mappings(
  1993. self, mapper, mappings, isupdate, isstates,
  1994. return_defaults, update_changed_only, render_nulls):
  1995. mapper = _class_to_mapper(mapper)
  1996. self._flushing = True
  1997. transaction = self.begin(
  1998. subtransactions=True)
  1999. try:
  2000. if isupdate:
  2001. persistence._bulk_update(
  2002. mapper, mappings, transaction,
  2003. isstates, update_changed_only)
  2004. else:
  2005. persistence._bulk_insert(
  2006. mapper, mappings, transaction,
  2007. isstates, return_defaults, render_nulls)
  2008. transaction.commit()
  2009. except:
  2010. with util.safe_reraise():
  2011. transaction.rollback(_capture_exception=True)
  2012. finally:
  2013. self._flushing = False
  2014. def is_modified(self, instance, include_collections=True,
  2015. passive=True):
  2016. r"""Return ``True`` if the given instance has locally
  2017. modified attributes.
  2018. This method retrieves the history for each instrumented
  2019. attribute on the instance and performs a comparison of the current
  2020. value to its previously committed value, if any.
  2021. It is in effect a more expensive and accurate
  2022. version of checking for the given instance in the
  2023. :attr:`.Session.dirty` collection; a full test for
  2024. each attribute's net "dirty" status is performed.
  2025. E.g.::
  2026. return session.is_modified(someobject)
  2027. .. versionchanged:: 0.8
  2028. When using SQLAlchemy 0.7 and earlier, the ``passive``
  2029. flag should **always** be explicitly set to ``True``,
  2030. else SQL loads/autoflushes may proceed which can affect
  2031. the modified state itself:
  2032. ``session.is_modified(someobject, passive=True)``\ .
  2033. In 0.8 and above, the behavior is corrected and
  2034. this flag is ignored.
  2035. A few caveats to this method apply:
  2036. * Instances present in the :attr:`.Session.dirty` collection may
  2037. report ``False`` when tested with this method. This is because
  2038. the object may have received change events via attribute mutation,
  2039. thus placing it in :attr:`.Session.dirty`, but ultimately the state
  2040. is the same as that loaded from the database, resulting in no net
  2041. change here.
  2042. * Scalar attributes may not have recorded the previously set
  2043. value when a new value was applied, if the attribute was not loaded,
  2044. or was expired, at the time the new value was received - in these
  2045. cases, the attribute is assumed to have a change, even if there is
  2046. ultimately no net change against its database value. SQLAlchemy in
  2047. most cases does not need the "old" value when a set event occurs, so
  2048. it skips the expense of a SQL call if the old value isn't present,
  2049. based on the assumption that an UPDATE of the scalar value is
  2050. usually needed, and in those few cases where it isn't, is less
  2051. expensive on average than issuing a defensive SELECT.
  2052. The "old" value is fetched unconditionally upon set only if the
  2053. attribute container has the ``active_history`` flag set to ``True``.
  2054. This flag is set typically for primary key attributes and scalar
  2055. object references that are not a simple many-to-one. To set this
  2056. flag for any arbitrary mapped column, use the ``active_history``
  2057. argument with :func:`.column_property`.
  2058. :param instance: mapped instance to be tested for pending changes.
  2059. :param include_collections: Indicates if multivalued collections
  2060. should be included in the operation. Setting this to ``False`` is a
  2061. way to detect only local-column based properties (i.e. scalar columns
  2062. or many-to-one foreign keys) that would result in an UPDATE for this
  2063. instance upon flush.
  2064. :param passive:
  2065. .. versionchanged:: 0.8
  2066. Ignored for backwards compatibility.
  2067. When using SQLAlchemy 0.7 and earlier, this flag should always
  2068. be set to ``True``.
  2069. """
  2070. state = object_state(instance)
  2071. if not state.modified:
  2072. return False
  2073. dict_ = state.dict
  2074. for attr in state.manager.attributes:
  2075. if \
  2076. (
  2077. not include_collections and
  2078. hasattr(attr.impl, 'get_collection')
  2079. ) or not hasattr(attr.impl, 'get_history'):
  2080. continue
  2081. (added, unchanged, deleted) = \
  2082. attr.impl.get_history(state, dict_,
  2083. passive=attributes.NO_CHANGE)
  2084. if added or deleted:
  2085. return True
  2086. else:
  2087. return False
  2088. @property
  2089. def is_active(self):
  2090. """True if this :class:`.Session` is in "transaction mode" and
  2091. is not in "partial rollback" state.
  2092. The :class:`.Session` in its default mode of ``autocommit=False``
  2093. is essentially always in "transaction mode", in that a
  2094. :class:`.SessionTransaction` is associated with it as soon as
  2095. it is instantiated. This :class:`.SessionTransaction` is immediately
  2096. replaced with a new one as soon as it is ended, due to a rollback,
  2097. commit, or close operation.
  2098. "Transaction mode" does *not* indicate whether
  2099. or not actual database connection resources are in use; the
  2100. :class:`.SessionTransaction` object coordinates among zero or more
  2101. actual database transactions, and starts out with none, accumulating
  2102. individual DBAPI connections as different data sources are used
  2103. within its scope. The best way to track when a particular
  2104. :class:`.Session` has actually begun to use DBAPI resources is to
  2105. implement a listener using the :meth:`.SessionEvents.after_begin`
  2106. method, which will deliver both the :class:`.Session` as well as the
  2107. target :class:`.Connection` to a user-defined event listener.
  2108. The "partial rollback" state refers to when an "inner" transaction,
  2109. typically used during a flush, encounters an error and emits a
  2110. rollback of the DBAPI connection. At this point, the
  2111. :class:`.Session` is in "partial rollback" and awaits for the user to
  2112. call :meth:`.Session.rollback`, in order to close out the
  2113. transaction stack. It is in this "partial rollback" period that the
  2114. :attr:`.is_active` flag returns False. After the call to
  2115. :meth:`.Session.rollback`, the :class:`.SessionTransaction` is
  2116. replaced with a new one and :attr:`.is_active` returns ``True`` again.
  2117. When a :class:`.Session` is used in ``autocommit=True`` mode, the
  2118. :class:`.SessionTransaction` is only instantiated within the scope
  2119. of a flush call, or when :meth:`.Session.begin` is called. So
  2120. :attr:`.is_active` will always be ``False`` outside of a flush or
  2121. :meth:`.Session.begin` block in this mode, and will be ``True``
  2122. within the :meth:`.Session.begin` block as long as it doesn't enter
  2123. "partial rollback" state.
  2124. From all the above, it follows that the only purpose to this flag is
  2125. for application frameworks that wish to detect is a "rollback" is
  2126. necessary within a generic error handling routine, for
  2127. :class:`.Session` objects that would otherwise be in
  2128. "partial rollback" mode. In a typical integration case, this is also
  2129. not necessary as it is standard practice to emit
  2130. :meth:`.Session.rollback` unconditionally within the outermost
  2131. exception catch.
  2132. To track the transactional state of a :class:`.Session` fully,
  2133. use event listeners, primarily the :meth:`.SessionEvents.after_begin`,
  2134. :meth:`.SessionEvents.after_commit`,
  2135. :meth:`.SessionEvents.after_rollback` and related events.
  2136. """
  2137. return self.transaction and self.transaction.is_active
  2138. identity_map = None
  2139. """A mapping of object identities to objects themselves.
  2140. Iterating through ``Session.identity_map.values()`` provides
  2141. access to the full set of persistent objects (i.e., those
  2142. that have row identity) currently in the session.
  2143. .. seealso::
  2144. :func:`.identity_key` - helper function to produce the keys used
  2145. in this dictionary.
  2146. """
  2147. @property
  2148. def _dirty_states(self):
  2149. """The set of all persistent states considered dirty.
  2150. This method returns all states that were modified including
  2151. those that were possibly deleted.
  2152. """
  2153. return self.identity_map._dirty_states()
  2154. @property
  2155. def dirty(self):
  2156. """The set of all persistent instances considered dirty.
  2157. E.g.::
  2158. some_mapped_object in session.dirty
  2159. Instances are considered dirty when they were modified but not
  2160. deleted.
  2161. Note that this 'dirty' calculation is 'optimistic'; most
  2162. attribute-setting or collection modification operations will
  2163. mark an instance as 'dirty' and place it in this set, even if
  2164. there is no net change to the attribute's value. At flush
  2165. time, the value of each attribute is compared to its
  2166. previously saved value, and if there's no net change, no SQL
  2167. operation will occur (this is a more expensive operation so
  2168. it's only done at flush time).
  2169. To check if an instance has actionable net changes to its
  2170. attributes, use the :meth:`.Session.is_modified` method.
  2171. """
  2172. return util.IdentitySet(
  2173. [state.obj()
  2174. for state in self._dirty_states
  2175. if state not in self._deleted])
  2176. @property
  2177. def deleted(self):
  2178. "The set of all instances marked as 'deleted' within this ``Session``"
  2179. return util.IdentitySet(list(self._deleted.values()))
  2180. @property
  2181. def new(self):
  2182. "The set of all instances marked as 'new' within this ``Session``."
  2183. return util.IdentitySet(list(self._new.values()))
  2184. class sessionmaker(_SessionClassMethods):
  2185. """A configurable :class:`.Session` factory.
  2186. The :class:`.sessionmaker` factory generates new
  2187. :class:`.Session` objects when called, creating them given
  2188. the configurational arguments established here.
  2189. e.g.::
  2190. # global scope
  2191. Session = sessionmaker(autoflush=False)
  2192. # later, in a local scope, create and use a session:
  2193. sess = Session()
  2194. Any keyword arguments sent to the constructor itself will override the
  2195. "configured" keywords::
  2196. Session = sessionmaker()
  2197. # bind an individual session to a connection
  2198. sess = Session(bind=connection)
  2199. The class also includes a method :meth:`.configure`, which can
  2200. be used to specify additional keyword arguments to the factory, which
  2201. will take effect for subsequent :class:`.Session` objects generated.
  2202. This is usually used to associate one or more :class:`.Engine` objects
  2203. with an existing :class:`.sessionmaker` factory before it is first
  2204. used::
  2205. # application starts
  2206. Session = sessionmaker()
  2207. # ... later
  2208. engine = create_engine('sqlite:///foo.db')
  2209. Session.configure(bind=engine)
  2210. sess = Session()
  2211. .. seealso:
  2212. :ref:`session_getting` - introductory text on creating
  2213. sessions using :class:`.sessionmaker`.
  2214. """
  2215. def __init__(self, bind=None, class_=Session, autoflush=True,
  2216. autocommit=False,
  2217. expire_on_commit=True,
  2218. info=None, **kw):
  2219. r"""Construct a new :class:`.sessionmaker`.
  2220. All arguments here except for ``class_`` correspond to arguments
  2221. accepted by :class:`.Session` directly. See the
  2222. :meth:`.Session.__init__` docstring for more details on parameters.
  2223. :param bind: a :class:`.Engine` or other :class:`.Connectable` with
  2224. which newly created :class:`.Session` objects will be associated.
  2225. :param class_: class to use in order to create new :class:`.Session`
  2226. objects. Defaults to :class:`.Session`.
  2227. :param autoflush: The autoflush setting to use with newly created
  2228. :class:`.Session` objects.
  2229. :param autocommit: The autocommit setting to use with newly created
  2230. :class:`.Session` objects.
  2231. :param expire_on_commit=True: the expire_on_commit setting to use
  2232. with newly created :class:`.Session` objects.
  2233. :param info: optional dictionary of information that will be available
  2234. via :attr:`.Session.info`. Note this dictionary is *updated*, not
  2235. replaced, when the ``info`` parameter is specified to the specific
  2236. :class:`.Session` construction operation.
  2237. .. versionadded:: 0.9.0
  2238. :param \**kw: all other keyword arguments are passed to the
  2239. constructor of newly created :class:`.Session` objects.
  2240. """
  2241. kw['bind'] = bind
  2242. kw['autoflush'] = autoflush
  2243. kw['autocommit'] = autocommit
  2244. kw['expire_on_commit'] = expire_on_commit
  2245. if info is not None:
  2246. kw['info'] = info
  2247. self.kw = kw
  2248. # make our own subclass of the given class, so that
  2249. # events can be associated with it specifically.
  2250. self.class_ = type(class_.__name__, (class_,), {})
  2251. def __call__(self, **local_kw):
  2252. """Produce a new :class:`.Session` object using the configuration
  2253. established in this :class:`.sessionmaker`.
  2254. In Python, the ``__call__`` method is invoked on an object when
  2255. it is "called" in the same way as a function::
  2256. Session = sessionmaker()
  2257. session = Session() # invokes sessionmaker.__call__()
  2258. """
  2259. for k, v in self.kw.items():
  2260. if k == 'info' and 'info' in local_kw:
  2261. d = v.copy()
  2262. d.update(local_kw['info'])
  2263. local_kw['info'] = d
  2264. else:
  2265. local_kw.setdefault(k, v)
  2266. return self.class_(**local_kw)
  2267. def configure(self, **new_kw):
  2268. """(Re)configure the arguments for this sessionmaker.
  2269. e.g.::
  2270. Session = sessionmaker()
  2271. Session.configure(bind=create_engine('sqlite://'))
  2272. """
  2273. self.kw.update(new_kw)
  2274. def __repr__(self):
  2275. return "%s(class_=%r,%s)" % (
  2276. self.__class__.__name__,
  2277. self.class_.__name__,
  2278. ", ".join("%s=%r" % (k, v) for k, v in self.kw.items())
  2279. )
  2280. def make_transient(instance):
  2281. """Alter the state of the given instance so that it is :term:`transient`.
  2282. .. note::
  2283. :func:`.make_transient` is a special-case function for
  2284. advanced use cases only.
  2285. The given mapped instance is assumed to be in the :term:`persistent` or
  2286. :term:`detached` state. The function will remove its association with any
  2287. :class:`.Session` as well as its :attr:`.InstanceState.identity`. The
  2288. effect is that the object will behave as though it were newly constructed,
  2289. except retaining any attribute / collection values that were loaded at the
  2290. time of the call. The :attr:`.InstanceState.deleted` flag is also reset
  2291. if this object had been deleted as a result of using
  2292. :meth:`.Session.delete`.
  2293. .. warning::
  2294. :func:`.make_transient` does **not** "unexpire" or otherwise eagerly
  2295. load ORM-mapped attributes that are not currently loaded at the time
  2296. the function is called. This includes attributes which:
  2297. * were expired via :meth:`.Session.expire`
  2298. * were expired as the natural effect of committing a session
  2299. transaction, e.g. :meth:`.Session.commit`
  2300. * are normally :term:`lazy loaded` but are not currently loaded
  2301. * are "deferred" via :ref:`deferred` and are not yet loaded
  2302. * were not present in the query which loaded this object, such as that
  2303. which is common in joined table inheritance and other scenarios.
  2304. After :func:`.make_transient` is called, unloaded attributes such
  2305. as those above will normally resolve to the value ``None`` when
  2306. accessed, or an empty collection for a collection-oriented attribute.
  2307. As the object is transient and un-associated with any database
  2308. identity, it will no longer retrieve these values.
  2309. .. seealso::
  2310. :func:`.make_transient_to_detached`
  2311. """
  2312. state = attributes.instance_state(instance)
  2313. s = _state_session(state)
  2314. if s:
  2315. s._expunge_states([state])
  2316. # remove expired state
  2317. state.expired_attributes.clear()
  2318. # remove deferred callables
  2319. if state.callables:
  2320. del state.callables
  2321. if state.key:
  2322. del state.key
  2323. if state._deleted:
  2324. del state._deleted
  2325. def make_transient_to_detached(instance):
  2326. """Make the given transient instance :term:`detached`.
  2327. .. note::
  2328. :func:`.make_transient_to_detached` is a special-case function for
  2329. advanced use cases only.
  2330. All attribute history on the given instance
  2331. will be reset as though the instance were freshly loaded
  2332. from a query. Missing attributes will be marked as expired.
  2333. The primary key attributes of the object, which are required, will be made
  2334. into the "key" of the instance.
  2335. The object can then be added to a session, or merged
  2336. possibly with the load=False flag, at which point it will look
  2337. as if it were loaded that way, without emitting SQL.
  2338. This is a special use case function that differs from a normal
  2339. call to :meth:`.Session.merge` in that a given persistent state
  2340. can be manufactured without any SQL calls.
  2341. .. versionadded:: 0.9.5
  2342. .. seealso::
  2343. :func:`.make_transient`
  2344. """
  2345. state = attributes.instance_state(instance)
  2346. if state.session_id or state.key:
  2347. raise sa_exc.InvalidRequestError(
  2348. "Given object must be transient")
  2349. state.key = state.mapper._identity_key_from_state(state)
  2350. if state._deleted:
  2351. del state._deleted
  2352. state._commit_all(state.dict)
  2353. state._expire_attributes(state.dict, state.unloaded)
  2354. def object_session(instance):
  2355. """Return the :class:`.Session` to which the given instance belongs.
  2356. This is essentially the same as the :attr:`.InstanceState.session`
  2357. accessor. See that attribute for details.
  2358. """
  2359. try:
  2360. state = attributes.instance_state(instance)
  2361. except exc.NO_STATE:
  2362. raise exc.UnmappedInstanceError(instance)
  2363. else:
  2364. return _state_session(state)
  2365. _new_sessionid = util.counter()