MCPcopy
hub / github.com/sqlalchemy/sqlalchemy / begin

Method begin

lib/sqlalchemy/orm/session.py:1938–1991  ·  view source on GitHub ↗

Begin a transaction, or nested transaction, on this :class:`.Session`, if one is not already begun. The :class:`_orm.Session` object features **autobegin** behavior, so that normally it is not necessary to call the :meth:`_orm.Session.begin` method explicitly

(self, nested: bool = False)

Source from the content-addressed store, hash-verified

1936 return self._transaction
1937
1938 def begin(self, nested: bool = False) -> SessionTransaction:
1939 """Begin a transaction, or nested transaction,
1940 on this :class:`.Session`, if one is not already begun.
1941
1942 The :class:`_orm.Session` object features **autobegin** behavior,
1943 so that normally it is not necessary to call the
1944 :meth:`_orm.Session.begin`
1945 method explicitly. However, it may be used in order to control
1946 the scope of when the transactional state is begun.
1947
1948 When used to begin the outermost transaction, an error is raised
1949 if this :class:`.Session` is already inside of a transaction.
1950
1951 :param nested: if True, begins a SAVEPOINT transaction and is
1952 equivalent to calling :meth:`~.Session.begin_nested`. For
1953 documentation on SAVEPOINT transactions, please see
1954 :ref:`session_begin_nested`.
1955
1956 :return: the :class:`.SessionTransaction` object. Note that
1957 :class:`.SessionTransaction`
1958 acts as a Python context manager, allowing :meth:`.Session.begin`
1959 to be used in a "with" block. See :ref:`session_explicit_begin` for
1960 an example.
1961
1962 .. seealso::
1963
1964 :ref:`session_autobegin`
1965
1966 :ref:`unitofwork_transaction`
1967
1968 :meth:`.Session.begin_nested`
1969
1970
1971 """
1972
1973 trans = self._transaction
1974 if trans is None:
1975 trans = self._autobegin_t(begin=True)
1976
1977 if not nested:
1978 return trans
1979
1980 assert trans is not None
1981
1982 if nested:
1983 trans = trans._begin(nested=nested)
1984 assert self._transaction is trans
1985 self._nested_transaction = trans
1986 else:
1987 raise sa_exc.InvalidRequestError(
1988 "A transaction is already begun on this Session."
1989 )
1990
1991 return trans # needed for __enter__/__exit__ hook
1992
1993 def begin_nested(self) -> SessionTransaction:
1994 """Begin a "nested" transaction on this Session, e.g. SAVEPOINT.

Calls 2

_autobegin_tMethod · 0.95
_beginMethod · 0.80