Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy - Is there a way to see what is currently in the session?

I'm curious if there's a way to show what is currently in the session?

Or perhaps a way to check if the session is empty or not so that I can do something like the below.

if db.session:
    db.session.commit()

This way it will only commit if there's actually something in the session waiting to be committed.

like image 432
Chockomonkey Avatar asked Aug 10 '15 20:08

Chockomonkey


People also ask

What is all () in SQLAlchemy?

add a mapped entity to the list of result columns to be returned. method sqlalchemy.orm.Query. all() Return the results represented by this Query as a list. This results in an execution of the underlying SQL statement.

Is SQLAlchemy worth learning?

SQLAlchemy is the ORM of choice for working with relational databases in python. The reason why SQLAlchemy is so popular is because it is very simple to implement, helps you develop your code quicker and doesn't require knowledge of SQL to get started.

What is Session in SQLAlchemy?

A session object is the handle to database. Session class is defined using sessionmaker() – a configurable session factory method which is bound to the engine object created earlier. from sqlalchemy. orm import sessionmaker Session = sessionmaker(bind = engine)

Does commit close the Session SQLAlchemy?

commit() will then COMMIT the actual database transaction or transactions, if any, that are in place. Finally, all objects within the Session are expired as the transaction is closed out.


1 Answers

There are following properties to check session state:

  • Session.new - for objects, which will be added to database.
  • Session.dirty - for objects, which will be updated.
  • Session.deleted - for objects, which will be deleted from database.

These three properties can be used to check session state:

if not db.session.new and not db.session.dirty and not db.session.deleted:
    # do smth

However it is safe to call session.commit() even if there is no changes in session. If you don't do something special, you don't need to explicitly check session state before commit.


Also there is a private method called Session._is_clean(), which is used to check if there are any changes to be flushed to database. It's implemented like this:

def _is_clean(self):
    return not self.identity_map.check_modified() and \
        not self._deleted and \
        not self._new
like image 87
Yaroslav Admin Avatar answered Sep 18 '22 20:09

Yaroslav Admin