Search code examples
salesforceapex-codesoql

Issue with building my SOQL query string


I have a SOQL query,

I want to check the fields in the query for FSL (field level security) before building the query string, and if they aren't readable, dont add them to the string. This might not be the very best approach, but it's somewhere for me to start. The following works fine.

String soql = 'SELECT Id, MAX(Name) personName, MAX(From_Date__c) fromDate, MAX(Status__c) status' 
String end  = ' FROM The_Object__c WHERE Id = :Id'

soql += end

SObject r = Database.query(soql);

So to check the field before adding it to the string... Somthing like this perhaps: (which doesnt work)

String extra_soql = ', SUM(Revenue__c) revenue ';

if (!Schema.sObjectType.The_Object__c.fields.Revenue__c.isAccessible()){ 

    REMOVE THE SOQL SOMEHOW? OR PASS AN EMPTY STRING TO THE QUERY?

    extra_soql = ''; <-- DOESNT WORK
    extra_soql = ' '; <-- DOESNT WORK
    extra_soql = NULL; <-- DOESNT WORK

    NOT SURE WHAT TO DO IN HERE
}

soql += extra_soql
soql += end

SObject r = Database.query(soql);

Any suggestions or advice would be greatly appreciated.


Solution

  • If you can't access the Revenue__c field due to field level security you can just skip appending it to the dynamic SOQL query. You might like to set a boolean that can be used at a later stage to indicate the Revenue isn't available.

    String soql = 'SELECT Id, MAX(Name) personName, MAX(From_Date__c) fromDate, MAX(Status__c) status';
    
    boolean revenueAvailable = Schema.sObjectType.The_Object__c.fields.Revenue__c.isAccessible();
    if(revenueAvailable) { 
        soql += ', SUM(Revenue__c) revenue';
    }
    
    soql += ' FROM The_Object__c WHERE Id = :Id';
    
    SObject r = Database.query(soql);