[Python] How to run a statement outside of transaction in alembic migration with psycopg3?

Discussão em 'Python' iniciado por Stack, Agosto 12, 2025.

  1. Stack

    Stack Membro Participativo

    I don't know if I'm doing it wrong, missing something, or is unsupported, a bug, or something else.

    From what I understand, the correct way is:

    with op.get_context().autocommit_block():
    op.execute("REINDEX INDEX CONCURRENTLY idx_something")


    But when using psycopg3, I get an AssertionError:

    @contextmanager
    def autocommit_block(self) -> Iterator[None]:
    # ...
    _in_connection_transaction = self._in_connection_transaction()

    if self.impl.transactional_ddl and self.as_sql:
    self.impl.emit_commit()

    elif _in_connection_transaction:
    > assert self._transaction is not None
    E AssertionError

    .venv/lib/python3.10/site-packages/alembic/runtime/migration.py:330: AssertionError


    I tried other ways including acquiring a raw connection, but could not get it to work. I also tried setting transaction per migration to true along with other things.

    psycopg: 3.2.9 alembic: 1.16.4 sqlalchemy: 2.0.42

    I see a similar question asked here, but it's just saying to do what I did and it isn't working, so I'm guessing it might be related to psycopg3.

    Continue reading...

Compartilhe esta Página