from sqlalchemy import event, create_engine
import pandas as pd
engine = create_engine('your_database_url')
# Define your query
query = "SELECT * FROM your_table"
# Define the event handler function
@event.listens_for(engine, "after_execute")
def after_execute(conn, clauseelement, multiparams, params, results):
print("Query executed!")
# Now execute your query
df = pd.read_sql(query, con=engine)
from sqlalchemy.engine import Engine
@event.listens_for(Engine, "after_execute")
def after_execute(conn, clauseelement, multiparams, params, results):
print("Query executed!")
Got it! You want to:
- Load a SQL query from a
.sql file.
- Execute the query with
pd.read_sql().
- Use an event listener to print the SQL filename whenever the query is executed.
Because pd.read_sql() executes the query internally, the event (after_execute) won't carry info about the filename by default. You need to connect the filename with the query execution context somehow.
Here's a pattern to do that using SQLAlchemy events and passing the filename as a comment in the SQL string (or tracking it some other way):
Example approach: Tag the SQL query with a comment involving the filename
from sqlalchemy import event, create_engine
import pandas as pd
engine = create_engine('your_database_url')
# Let's define a function to read a .sql file and tag it with a comment
def load_sql_with_filename(sql_path):
with open(sql_path, 'r') as f:
sql = f.read()
# Add a comment containing the filename that will be visible in the event
sql_tagged = f"-- filename: {sql_path}\n{sql}"
return sql_tagged
# Event listener that extracts filename from the query comment
@event.listens_for(engine, "after_execute")
def after_execute(conn, clauseelement, multiparams, params, results):
# clauseelement is usually the SQL text or SQLAlchemy clause
# For textual queries, it's a TextClause, from which we can get the text
sql_text = str(clauseelement)
filename_line = None
for line in sql_text.splitlines():
if line.strip().startswith('-- filename:'):
filename_line = line.strip()
break
if filename_line:
print(f"Executed SQL file: {filename_line[len('-- filename:'):].strip()}")
# Usage:
sql_file_path = 'my_query.sql'
query = load_sql_with_filename(sql_file_path)
df = pd.read_sql(query, con=engine)
Explanation:
- We read the
.sql file into a string.
- Prepend a comment line like
-- filename: my_query.sql to the SQL query string.
- The
after_execute listener receives the SQL query string after execution.
- The listener tries to find the filename comment and print it.
Important notes:
- This works well if your DB dialect supports comments this way (most do).
- If your SQL text gets modified by the DBAPI or driver, this approach might not be 100% reliable.
- An alternative would be wrapping query execution in a function that prints the filename before/after calling
pd.read_sql(), but that does not use the event system.
If you want I can help you with the alternative approach or adapting this for your setup!