You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4263 lines
152KB

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