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)
| 1895 | return self._transaction |
| 1896 | |
| 1897 | def begin(self, nested: bool = False) -> SessionTransaction: |
| 1898 | """Begin a transaction, or nested transaction, |
| 1899 | on this :class:`.Session`, if one is not already begun. |
| 1900 | |
| 1901 | The :class:`_orm.Session` object features **autobegin** behavior, |
| 1902 | so that normally it is not necessary to call the |
| 1903 | :meth:`_orm.Session.begin` |
| 1904 | method explicitly. However, it may be used in order to control |
| 1905 | the scope of when the transactional state is begun. |
| 1906 | |
| 1907 | When used to begin the outermost transaction, an error is raised |
| 1908 | if this :class:`.Session` is already inside of a transaction. |
| 1909 | |
| 1910 | :param nested: if True, begins a SAVEPOINT transaction and is |
| 1911 | equivalent to calling :meth:`~.Session.begin_nested`. For |
| 1912 | documentation on SAVEPOINT transactions, please see |
| 1913 | :ref:`session_begin_nested`. |
| 1914 | |
| 1915 | :return: the :class:`.SessionTransaction` object. Note that |
| 1916 | :class:`.SessionTransaction` |
| 1917 | acts as a Python context manager, allowing :meth:`.Session.begin` |
| 1918 | to be used in a "with" block. See :ref:`session_explicit_begin` for |
| 1919 | an example. |
| 1920 | |
| 1921 | .. seealso:: |
| 1922 | |
| 1923 | :ref:`session_autobegin` |
| 1924 | |
| 1925 | :ref:`unitofwork_transaction` |
| 1926 | |
| 1927 | :meth:`.Session.begin_nested` |
| 1928 | |
| 1929 | |
| 1930 | """ |
| 1931 | |
| 1932 | trans = self._transaction |
| 1933 | if trans is None: |
| 1934 | trans = self._autobegin_t(begin=True) |
| 1935 | |
| 1936 | if not nested: |
| 1937 | return trans |
| 1938 | |
| 1939 | assert trans is not None |
| 1940 | |
| 1941 | if nested: |
| 1942 | trans = trans._begin(nested=nested) |
| 1943 | assert self._transaction is trans |
| 1944 | self._nested_transaction = trans |
| 1945 | else: |
| 1946 | raise sa_exc.InvalidRequestError( |
| 1947 | "A transaction is already begun on this Session." |
| 1948 | ) |
| 1949 | |
| 1950 | return trans # needed for __enter__/__exit__ hook |
| 1951 | |
| 1952 | def begin_nested(self) -> SessionTransaction: |
| 1953 | """Begin a "nested" transaction on this Session, e.g. SAVEPOINT. |