OEurix
OEurix

Reputation: 433

SQLAlchemy: Should I commit an update between two queries?

In a single session, if I want to:

// make a query on Foo table to get one instance
// update this instance
// commit() or not?
// make the same query on Foo table

Will I get the same result in these two queries? That's to say, is it necessary to commit the update before query on the table within a single session?

Thanks!

Upvotes: 0

Views: 1073

Answers (2)

Ammar Hoque
Ammar Hoque

Reputation: 136

It's not necessary to do both commits, as each transaction is visible to subsequent actions in the database (or queries).

You can just put the commit at the end, although I am not sure if multiple commits will affect runtime.

Upvotes: 1

peekay
peekay

Reputation: 2065

It is not necessary to commit prior to making the query again. As a general principle, updates within a transaction (session) will be visible to subsequent queries in that same transaction, even prior to a commit.

Having said that, doing the same exact query twice within a transaction might be "code smell". It's worth considering, since the updated object is already memory, is it really necessary to query the object again?

Also, depending on the database isolation level, the second query is not guaranteed to return the same result set as the first one. This can happen if another transaction modifies the data prior to the second query.

Upvotes: 3

Related Questions