Search code examples
pythonsqlalchemyblaze

Build sqlalchemy query from string


How can I convert a sql where clause string to a sqlalchemy query? I'm assuming I already know the table.

I'm building an Angular webapp which hits a Flask API for data. Flask is using sqlalchemy to query the db. jQuery-QueryBuilder fromSQL (http://querybuilder.js.org/plugins.html#import-export) exports filters as raw SQL which I want to pass back to the api, parse, and query.

For example:

where_str = "name LIKE '%BOB%' AND fruit != 'pineapple'"

would get converted to:

session.query(Table).filter(Table.name.like('%BOB%')).filter(Table.fruit != 'pineapple)

Tagging blaze because odo might be what I need.


Solution

  • You can try to execute session.query(Table).filter(where_str). It worked for me on SQLAlchemy v0.5.8. You can also build the whole SQL statement string and use the Connection.execute() method to execute it. Either way, passing SQL statements as strings directly from the webpage to the application can be very dangerous.