Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does 'synchronize_session=False' do exactly in update functions for Sqlalchemy?and what is the best value for it?

We have the CRUD functions in our API which is using FastAPI and SQLAlchemy.
For update functions we have the below code:

def update_user(
    user_id: uuid.UUID,
    db: Session,
    update_model: UserUpdateModel,
) -> bool:
    query = (
        db.query(User)
        .filter(
            User.user_id == user_id,
        )
        .update(update_model, synchronize_session=False)
    )
    try:
        db.commit()
    except IntegrityError as e:
        if isinstance(e.orig, PG2UniqueViolation):
            raise UniqueViolation from e
    return bool(query)

What exactly does the 'synchronize_session=False' do here?
What is the best value for it? False or Fetch...?
Is it critical if we don't use it?

like image 995
Mitra Avatar asked Nov 30 '25 16:11

Mitra


1 Answers

By looking at the sqlalchemy doc you can find what synchronize_session does and how to use it properly

From the official doc:

With both the 1.x and 2.0 form of ORM-enabled updates and deletes, the following values for synchronize_session are supported:

  • False - don’t synchronize the session. This option is the most efficient and is reliable once the session is expired, which typically occurs after a commit(), or explicitly using expire_all(). Before the expiration, objects that were updated or deleted in the database may still remain in the session with stale values, which can lead to confusing results.

  • 'fetch' - Retrieves the primary key identity of affected rows by either performing a SELECT before the UPDATE or DELETE, or by using RETURNING if the database supports it, so that in-memory objects which are affected by the operation can be refreshed with new values (updates) or expunged from the Session (deletes). Note that this synchronization strategy is not available if the given update() or delete() construct specifies columns for UpdateBase.returning() explicitly.

  • 'evaluate' - Evaluate the WHERE criteria given in the UPDATE or DELETE statement in Python, to locate matching objects within the Session. This approach does not add any round trips and in the absence of RETURNING support is more efficient. For UPDATE or DELETE statements with complex criteria, the 'evaluate' strategy may not be able to evaluate the expression in Python and will raise an error. If this occurs, use the 'fetch' strategy for the operation instead.

like image 179
Bastien B Avatar answered Dec 02 '25 06:12

Bastien B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!