开发者

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

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


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.


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.


Straight from the documentation:

commit() is used to commit the current transaction. It always issues flush() beforehand to flush any remaining state to the database.


Although the above answers are correct, the most useful feature of flush is in applying the changes made to the table in the database back into the concerned object in the code. Here is an example, Suppose you register a user and you want to give back his id,

u = User(name,address,phone) #id is autogenerated 
session.add(u)
session.commit() #calls flush beforehand, but we need it after the commit
session.flush() #updates the objects of the session 
print(u.id) #id field of the User object updated after the flush

You need not query again to get his id!! Hope this helps


flush() will synchronize your database with the current state of object/objects held in the memory but it does not commit the transaction. So, if you get any exception after flush() is called, then the transaction will be rolled back. You can synchronize your database with small chunks of data using flush() instead of committing a large data at once using commit() and face the risk of getting an Out Of Memory exception.

commit() will make data stored in the database permanent. There is no way you can rollback your transaction once the commit() succeeds.

Source: https://stackoverflow.com/a/26976077/4115031

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜