Search code examples
pythoneventssqlalchemy

sqlalchemy: get rows affected by bulk delete


I need to get all rows that were affected by a bulk delete like that:

Session.query(SomeClass).filter_by(foo='bar').delete()

I found the possibility to subscribe to bulk delete events but can't figure out how I can use this event to actually get the information I need.


Solution

  • Okay, found the answer \☺/ You can re-execute the select statement that was used to select the rows for bulk deletion. Unfortunately you can't query the ORM objects, but you can get a list of all the deleted rows with the old column values as tuples:

    def after_bulk_delete(session, query, query_context, result):
        affected_table = query_context.statement.froms[0]
        affected_rows = query_context.statement.execute().fetchall() 
    
    sqlalchemy.event.listen(Session, "after_bulk_delete", after_bulk_delete)