Parentheses on Dynamic SOQL Unexpected Token ‘(‘

apexdatabasedynamicquerysoql

I still dont get to know why this dynamic query executed through Database.query() is throwing Unexpected Token Error on the parenthesis char. My code so far is this:

@AuraEnabled
    public static String getClinicalOrganizationalTableData(String paId, String contentType, String fileExtensions) {
        Id programApplicationId = Id.valueOf(paId);

        String cdQuery = 'SELECT Id, LinkedEntityId, ContentDocumentId, ContentDocument.Title FROM ContentDocumentLink WHERE LinkedEntityId IN :MIsMap.keySet() AND';
        String dynamicQueryFilter = ' ('; // This seems to be the problem
        List<String> extList = fileExtensions.split(',');
        Integer counter = 0;
        
        for(String ext: fileExtensions.split(',')) {
            dynamicQueryFilter += ( counter == extList.size() -1 ) ? 
                                    'ContentDocument.FileExtension = \'' + ext + '\')' : 
                                    'ContentDocument.FileExtension = \'' + ext + '\' OR ';
            counter++;
        }

        cdQuery += dynamicQueryFilter;

    Map<Id, MentoringInfo__c> MIsMap = new Map<Id, MentoringInfo__c>([SELECT Facility__c, MentorFacilityName__c, MentorName__c, Type__c, 
                                                                      MentorFacilityAddressF__c, OrganizationalAgreementStage__c, MentorEmailF__c
                                                                      FROM MentoringInfo__c 
                                                                      WHERE ProgramApplication__c = :programApplicationId
                                                                      AND NestedInfo__c = TRUE]);

     List<ContentDocumentLink> cdlList = Database.query(cdQuery);
        return cdQuery;
   }

fileExtensions is = 'mp4,wav,mkv'

Is there a way to make this work?
By the way, the resulting query in cdQuery is:

"SELECT Id, LinkedEntityId, ContentDocumentId, ContentDocument.Title
FROM ContentDocumentLink WHERE LinkedEntityId IN :MIsMap.keySet() AND
(ContentDocument.FileExtension = 'mp4' OR
ContentDocument.FileExtension = 'wav' OR ContentDocument.FileExtension
= 'mkv')"

Best Answer

The problem is that dynamic queries do not allow any dot reference. So MIsMap.keySet() isn't allowed. That said, you can create a reference outside the query to hold that value.

 Set<Id> infoIds = MIsMap.keySet();
 ...
 WHERE LinkedEntityId IN :infoIds
Related Topic