Stages of applying object changes to database in SQLAlchemy

In SQLAlchemy, the process of transitioning changes from Python objects to the database involves several stages. Here's an overview of these stages:

  1. Python Object Level: This is the initial stage where you work with your Python objects and make changes to their attributes. SQLAlchemy ORM objects are Python classes representing database tables.

  2. Pending State (Dirty Objects): After modifying attributes of SQLAlchemy objects, they enter the pending state or become "dirty" objects. This means that SQLAlchemy tracks the changes made to these objects.

  3. Session Flush: When you call session.flush(), SQLAlchemy examines all the dirty objects within the session and generates SQL statements for the changes. These statements are stored in the database's transaction buffer but not yet executed.

  4. Database Transaction Buffer: The SQL statements generated during the flush are stored in a buffer within the database connection. They are not committed to the actual database tables yet.

  5. Database Transaction Commit: When you call session.commit(), SQLAlchemy issues a database transaction commit command. At this point, the changes are finally written to the database tables.

  6. Persistent State (Clean Objects): After the changes are successfully committed to the database, the SQLAlchemy objects are now in a "persistent" state. They are synchronized with the corresponding rows in the database.

  7. Session Expunge or Close: If you expunge an object from the session or close the session, the object returns to a "detached" state. It's no longer associated with a session, and any further changes won't be automatically synchronized with the database.

  8. Rollback: If you call session.rollback(), all changes made in the session since the last flush or commit are discarded, and the objects return to their previous state.

These stages illustrate the typical flow of changes from Python objects to the database and back. It's important to note that SQLAlchemy's unit of work (session) manages this process and allows you to control when changes are flushed to the database and when transactions are committed.

Learn about the Web | 30DaysOfUdacity