Skip to content
Advertisement

difference between autobegin and Session.begin

In the following code snippet a commit is executed once the with block is exited.

JavaScript

As per the docs https://docs.sqlalchemy.org/en/20/orm/session_api.html#sqlalchemy.orm.Session.begin

The Session object features autobegin behavior, so that normally it is not necessary to call the Session.begin() method explicitly

Running without begin, like so does not commit even though the docs mention autobegin is not needed.

JavaScript

The docs for Session.begin does not mention anything about commits, what am I not understanding with here?

Advertisement

Answer

The SQLAlchemy 2.0 tutorial explains the two approaches for managing transactions: “commit as you go” and “begin once”.

Commit as you go

“Commit as you go” takes advantage of SQLAlchemy’s “autobegin” behaviour which ensures that a transaction is implicitly started whenever we perform an operation that might change the database (and hence might need to be rolled back). In this mode

  • we don’t need to explicitly begin a transaction, but
  • we do need to explicitly commit changes if we want to keep them.

Core:

JavaScript

ORM:

JavaScript

Note that if we forget to .commit() then the changes are automatically rolled back:

JavaScript

Begin once

We also have the option to call .begin() ourselves. In this case we don’t have to remember to explicitly commit the changes; they will automatically be committed when the context manager exits (provided that no errors occurred).

The long-winded way to use “begin once” is to invoke .begin() in its own context manager:

Core:

JavaScript

ORM:

JavaScript

However, we can use shortcuts to make the code more compact

JavaScript

and with Core we can make the code even shorter by using engine.begin() instead of engine.connect()

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement