Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I want to execute some raw SQL and take advantage of SQLAlchemy's SQL injection prevention.

My code is similar to this bit:

import sqlalchemy
from sqlalchemy.sql import text

DB_URI = '...'
engine = sqlalchemy.create_engine(DB_URI)

sql = text("SELECT * FROM some_table WHERE userid = :userid")
res = engine.execute(sql, userid=12345)
# do something with the result... 

The problem is that userid in some_table is of type varchar. All I want to do is to tell SQLAlchemy to convert 12345 to a string before executing the statement. I know how I could do the conversion both in Python and in SQL. But I remember that I once used a explicit type definition in SQLAlchemy, I just can't find it anymore. Can someone point me to the right direction? (My actual question involves postgresql arrays of BIGINTs vs. INTs, but I tried to keep it simple.)

Thanks for any help!

share|improve this question

From what I see, there are two kind of "duh" ways to do it if I am not missing anything -

1st Way

userid=12345 # defining here
sql = text("SELECT * FROM some_table WHERE userid = '"+userid+"'")
res = engine.execute(sql)

2nd Way

sql = text("SELECT * FROM some_table WHERE userid = :userid")
res = engine.execute(sql, userid=str(12345))
share|improve this answer
    
Yeah - I knew both of these... (There is also the way of explicitly type casting in SQL). But my issue is that I have an postgresql array of integers that I want to compare against an array of BIGINTs. I know there are types in sqlalchemy and I seem to remember that there is a way of explicitly setting a type for a text() command. (btw. 1st way is a bad idea because of userid="';DROP TABLE some_table; --") – asPlankBridge Nov 30 at 9:05
    
can you please edit the question to include these details? Its very hard to narrow down a solution and we will only end up guessing stuff – Vivek Kalyanarangan Nov 30 at 10:39

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.