postgresqlpython-3.xeventssqlalchemyflask-sqlalchemy

How to make SQLAlchemy issue additional SQL after flushing the current session?


I have some SQL that I'd like SQLAlchemy to issue after it flushes the current session.

So I'm trying to write a Python function that will do the following "at the end of this specific SQLAlchemy session, 1) flush the session, 2) then send this extra SQL to the database as well, 3) then finally commit the session", but only if I call it within that particular session.

I don't want it on all sessions globally, so if I didn't call the function within this session, then don't execute the SQL.

I know SQLAlchemy has a built-in events system, and I played around with it, but I can't figure out how to register an event listener for only the current session, and not all sessions globally. I read the docs, but I'm still not getting it.

I am aware of database triggers, but they won't work for this particular scenario.

I'm using Flask-SQLAlchemy, which uses scoped sessions.


Solution

  • Not sure why it does not work for you. Sample code below runs as expected:

    class Stuff(Base):
        __tablename__ = "stuff"
        id = Column(Integer, primary_key=True)
        name = Column(String)
    
    
    Base.metadata.create_all(engine)
    session = Session()
    
    from sqlalchemy import event
    @event.listens_for(session, "after_flush")
    def _handle_event(session, context):
        print(">> --- after_flush started ---")
        rows = session.execute("SELECT 1 AS XXX").fetchall()
        print(rows)
        print(">> --- after_flush finished ---")
    
    
    # create test data
    s1 = Stuff(name="uno")
    session.add(s1)
    print("--- before calling commit ---")
    session.commit()
    print("--- after  calling commit ---")