+ Start a Discussion

Dynamic query from page parameters error

I'm trying to construct a dynamic query where the where clause comes in the page parameters. Not wanting to subject myself to possible SOQL-injection, I am using the escapeSingleQuotes method. However, this is causing an error when running the query: 


System.QueryException: line 1:76 no viable alternative at character '\'


Do I have something wrong or is this expected behavior? If it is expected, how would one go about solving this?


Edited code:


private List<sObject> getQuery(){
    string qry  = ApexPages.currentPage().getParameters().get('q');
    string objectName = ApexPages.currentPage().getParameters().get('object_name');
    string whereClause = ApexPages.currentPage().getParameters().get('where_clause');  

    string queryString = 'select Id, Name from ' + string.escapeSingleQuotes(objectName) + ' where name like \'%'+ string.escapeSingleQuotes(qry) + '%\'';
    if (whereClause.trim().length() != 0) {
	queryString +=  ' AND ' + string.escapeSingleQuotes(whereClause);
    return Database.query(queryString);

If  the where_Clause parameter is Status__c='Open', the query becomes the following and I get the error.


select Id, Name from MyObject__c where name like '%ABC%' AND Status__c=\'Open\'



Hi rscott,


   The method escapeSingleQuotes is used for the query parameter value rather than clause itself.


If you are passing the correct where clause, like the one you have just passed, the escapesinglequotes is surely going place the backslash in front of every singlequote it encounters (which is not right). In this case you can directly append the parameter "where_clause" in queryString


Hence the place where escapesinglequots has to be used is in the parameter value rather than entire where clause.






escapeSingleQuotes is being used on the query parameter. The value of that parameter is: Status__c='Open'


The issue is that just taking that value and putting it in the dynamic SOQL statement opens me up to SOQL injection. And using escapeSingleQuotes on that value causes an error when trying to execute it.


Maybe the answer is that I just can't pass that through the queryString.