Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between session.commit() and session.flush()?

Tags:

Does anybody know what the main difference between session.commit() and session.flush() in SQLAlchemy is?

like image 356
ashiaka Avatar asked Sep 19 '11 13:09

ashiaka


People also ask

What is Session flush ()?

Flushing the session forces Hibernate to synchronize the in-memory state of the Session with the database (i.e. to write changes to the database). By default, Hibernate will flush changes automatically for you: before some query executions. when a transaction is committed.

What is difference between flush and commit in hibernate?

Hibernate: Difference commit() vs flush(). flush(): Flushing is the process of synchronizing the underlying persistent store with persistable state held in memory.it will update or insert into your tables in the running transaction, but it may not commit those changes. Commit(): Commit will make the database commit.

What is Session commit?

Sessions or session handling is a way to make the data available across various pages of a web application. The session_ commit() function saves all the session data and closes it. It is an alias of session_write_close().

What is DB Session commit ()?

Conceptually db. session. commit() is basically 2 steps in one: Flushing - push changes from SQLAlchemy's in-memory representation to the database transaction buffer. Commit - persist changes from your database's transaction buffer into the database, ie inserting / updating / deleting.


2 Answers

Here are some relevant quotes from the documentation.

flush:

When the Session is used with its default configuration, the flush step is nearly always done transparently. Specifically, the flush occurs before any individual Query is issued, as well as within the commit() call before the transaction is committed.

commit:

commit() is used to commit the current transaction. It always issues flush() beforehand to flush any remaining state to the database; this is independent of the “autoflush” setting. If no transaction is present, it raises an error. Note that the default behavior of the Session is that a “transaction” is always present; this behavior can be disabled by setting autocommit=True. In autocommit mode, a transaction can be initiated by calling the begin() method.

like image 195
NPE Avatar answered Oct 05 '22 20:10

NPE


The easiest way I know how to explain what these do is to just show you, using echo=True:

>>> session.flush() BEGIN (implicit) INSERT INTO users (username, password) VALUES (?, ?) ('alice', None) >>> session.commit() COMMIT >>>  

flush() causes the data to be sent to the database. commit() causes a COMMIT, which tells the database to keep the data that was just sent. As others have stated, commit() will also cause a flush() to occur, if it's needed.

like image 28
SingleNegationElimination Avatar answered Oct 05 '22 18:10

SingleNegationElimination