DEV Community

Cover image for SQLAlchemy Object Lifecycle

SQLAlchemy Object Lifecycle

Mahmoud EL-kariouny
Software developer
・2 min read

Object Lifecycle Recall

We can insert new records into the database using SQLAlchemy by running.

  • person = Person(name='Amr')

  • db.session.add(person)

  • db.session.commit()

which will build a transaction for inserting in a person instance in our model/table, and persist it to the database upon calling commit().


It isn't until we execute db.session() that we commit anything to the database.

Every time we want to interact with the database we start a connection and end a connection when all of the interactions are done.

Within that interaction session, We wound up creating transactions that we commit to the database every time that we want to commit work to the database.

So an important thing to keep in mind:

  • Proposed database changes are not immediately committed to the database once they're defined.

  • Changes go through stages in order to provide the ability to "undo" a mistake.

  • before committing it to a database.

There are 4 stages:

1- Transient.

2- Pending.

3- flush.

4- Committed.

What is Flush:

A flush is an event that takes pending and translates them into SQL commands, ready to be committed to the database.

On INSERTS, a flush allows (future) primary key values to existing.

Not the same as a commit.

Nothing is persisted in the database yet when a flush happens.

We still need to manually call commit for the commit to occur.

A flush takes pending changes and translates them into commands ready to be committed. It occurs:

when you call Query. Or

on db.session.commit()

A commit leads to persisted changes on the database + lets the db.session start with a new transaction.

When a statement has been flushed already, SQLAlchemy knows not to do the work again of translating actions to SQL statements.

Explain the four stages:

1- Transient: an object exists, it was defined.

user1 = User(name='Amr')

... But not attached to a session (yet).

2- Pending: an object was attached to a session.

... "Undo" becomes available via db.session.rollback().

... Waits for a flush to happen.

3- Flushed: about ready to be committed to the database, translating actions into SQL

... Command statements for the engine.

4- Committed: manually called for a change to persist to the database (permanently);

... session's transaction is cleared for a new set of changes.


Within a session, we create transactions every time we want to commit work to the database.

Proposed changes are not immediately committed to the database and instead, go through stages to allow for updos.

The ability to undo is allowed via db.session.rollback().

The main blog.

Discussion (0)