0

I am fairly new to salesforce. I am getting the soql sosl injection error in the below method while doing query. How to resolve this error?

 public static Days_Unavailable__c getAvlRecordById(String avlId){
            String query = QUERY_PART1 + ' where Id = \'' + avlId + '\' and Event_Status__c!=NULL ';
            
            selector.checkRead(QUERY_PART1_FIELDS);
            List<Days_Unavailable__c> avlList = Database.query(query);
            
            if(avlList != null && avlList.size() > 0 ){
                return avlList.get(0);
            }else{
                return null;    
            }
            
        }

I set the 'QUERY_PART1' and 'QUERY_PART1_FIELDS' as:

    final static String QUERY_PART1 = 'select Id, Weekly_Recurrence__c, Recurrence_Weekdays__c, Recurrence_End_Date__c, Start_Date__c, Candidate_Management__r.name, Candidate_Management__r.Placement__r.name, Candidate_Management__r.Placement__r.Company__r.name,End_Date__c, Event_Status__c, EventReason__c, Contact__c from Days_Unavailable__c';
    final static String QUERY_PART1_FIELDS = 'Id, Start_Date__c, Candidate_Management__r.name, Candidate_Management__r.Placement__r.name, Candidate_Management__r.Placement__r.Company__r.name,End_Date__c, Event_Status__c, EventReason__c, Contact__c';
1
  • Can you try this while executing query. List<Days_Unavailable__c> avlList = Database.query(String.escapeSingleQuotes(query)); Sep 16, 2022 at 7:25

1 Answer 1

4

You have two options:

  • Use a merge variable. Simple, compact, easy to read.

    String query = QUERY_PART1 + ' where Id = :avlId and Event_Status__c!=NULL ';
    
  • Escape the input.

    String query = QUERY_PART1 + ' where Id = \'' + String.escapeSingleQuotes(avlId) +
        '\' and Event_Status__c!=NULL ';
    

I also recommend very strongly you use complete words in all your variable names. Abbreviations are horrendous for readability.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .