SQL Alchemy Core Events

Hi friends,

I am new to SQLAlchemy and I am using that to modify the query using events. I need to modify the SQL statement before executing. I know I can do that in “before_cursor_execute” core event in SQLAlchemy. But for that, I need the table name which the query is using right that time and I have to handle all (select, insert, update and delete) query in a single event. How can I get the table name in “before_cursor_execute” method? Please help.

@event.listens_for(engine,'before_cursor_execute', retval=True)
def before_cursor_execute(conn, cursor, statement, parameters, context, executemany):
    code for modify the query. Here i need the table name for checking what modification have to 
    return statement, parameters

I’m not an expert but as far as I know before_cursor_execute gives you the string statement. You should probably go for before_execute which will give you the SQL Alchemy sql expression (the thing resulting from, for instance, select([table1.field]).
Otherwise you should parse the SQL string in before_cursor_execute and get the list yourself (not very easy if you want to consider all possible cases).

1 Like