1

Ultimately I'm trying to use pandas read_sql which takes in a raw SQL query.

I'm trying to convert something like;

sql = str(session.query(Post).filter(Post.user_id=1))

That generates something like

select * from Post where user_id = %(user_id_1)

Is there any way to generate that query with the parameter already interpolated?

2
  • You could try passing that SQL string directly to read_sql_query along with params={"user_id_1": 1}. That would help you avoid the messiness of injecting literal values into the SQL command text. Commented Dec 6, 2020 at 23:03
  • Yep, that's what I'm doing now. It just seems like there should be a way to automatically do this with SQLAlchemy Commented Dec 7, 2020 at 3:02

1 Answer 1

1

As you have found, if we str() an ORM query we get the SQL command text with parameter placeholders using the paramstyle for our dialect:

qry = session.query(Parent).filter(Parent.id == 1)
sql = str(qry)
print(sql)
"""console output:
SELECT parent.id AS parent_id, parent.lastname AS parent_lastname, parent.firstname AS parent_firstname 
FROM parent 
WHERE parent.id = %(id_1)s
"""

If we want to have the parameter values embedded in the SQL statement then we need to .compile() it:

sql_literal = qry.statement.compile(
    compile_kwargs={"literal_binds": True},
)
print(sql_literal)
"""console output:
SELECT parent.id, parent.lastname, parent.firstname 
FROM parent 
WHERE parent.id = 1
"""

(Standard disclaimers regarding SQL Injection apply.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.