I have been running this custom query which works against Postgres db and Python:
from sqlalchemy import text, bindparam
sql = text("""
select t.column1, t.column2
from table1 t
where t.column3 = :which_column"""
)
sql_params = {'which_column': variable}
sql_query = sql.bindparams(bindparam('which_column'))
sql_response = session.execute(sql_query, sql_params)
However, when trying to use this query including ‘order by’ and ‘ASC’ or ‘DESC’ as new parameters, it fails:
sql = text("""
select t.column1, t.column2
from table1 t
where t.column3 = :which_column
order by :order_by :sort""")
sql_params = {'which_column': variable,
'order_by': variable2,
'sort': variable3} }
sql_query = sql.bindparams(bindparam('which_column'),
bindparam('order_by'),
bindparam('sort'))
Error negotiating with database: (psycopg2.ProgrammingError) syntax error at or near "'asc'"
The problem is that the ‘order_by’ and ‘sort’ parameters are inserted into single quotes.
e.g.: order by ‘column1’ ‘asc’
My attempts using literal_column() and literal from sqlalchemy docs don’t work in this context.