title: SQLAlchemy prevent “nesting” pattern
body: <p>I am now using SQLAlchemy(async/core), PostgreSQL and FastAPI.</p>
  <p>I made a <code>@contextlib.contextmanager</code>.</p>
  <pre><code>    @contextlib.contextmanager
      def transaction_begin(self) -&gt; typing.Generator:
          if not self.engine_connection.in_transaction():
              with self.engine_connection.begin():
                  yield self.engine_connection
          else:
              yield self.engine_connection
  </code></pre>
  <p>It worked fine, but today I encountered an <code>AttributeError: __enter__</code>. It works somewhere in FastAPI router functions, it doesn't somewhere:</p>
  <pre><code>Traceback (most recent call last):
    File &quot;/var/www/myproj/app/auth/routers.py&quot;, line 161, in get_refresh_token
      await CRUDModel(conn).insert(stmt)
    File &quot;/var/www/myproj/app/core/crud.py&quot;, line 61, in insert
      with self.transaction_begin():
    File &quot;/home/me/.pyenv/versions/3.10.5/lib/python3.10/contextlib.py&quot;, line 135, in __enter__
      return next(self.gen)
    File &quot;/var/www/myproj/app/core/crud.py&quot;, line 26, in transaction_begin
      with self.engine_connection.begin():
  AttributeError: __enter__
  </code></pre>
  <p>To solve the issue, I might rewrite the contextlib like this because PostgreSQL always implicit begins:</p>
  <pre><code>    @contextlib.contextmanager
      def transaction_begin(self) -&gt; typing.Generator:
          # BEGIN (implicit) by PostgreSQL
          yield self.engine_connection
  </code></pre>
  <p>Actually, my <code>contextmanager</code> code is from here :
  <a href="https://docs.sqlalchemy.org/en/14/core/connections.html#migrating-from-the-nesting-pattern" rel="nofollow noreferrer">https://docs.sqlalchemy.org/en/14/core/connections.html#migrating-from-the-nesting-pattern</a></p>
  <p>I would like to know that it is okay to get engine_connection without <code>BEGIN</code> if I use PostgreSQL. Otherwise, do I have to explicit begin transaction if not in transaction?</p>
  <p>Thank you.</p>