[SalesForce] System.QueryException: sObject type ‘OpportunityLineItem’ is not supported

We get this script exception (in managed package) emailed from a customer instance.

Apex script unhandled trigger exception by user/organization:
XXXXX/YYYYY

pkg1.ProductOppStockCheck: execution of BeforeUpdate

caused by: System.QueryException: sObject type 'OpportunityLineItem'
is not supported.

It seems below line is causing this exception.

    List<OpportunityLineItem> oppLineItemList = [SELECT Id, OpportunityId, Quantity FROM OpportunityLineItem WHERE OpportunityId IN :oppList AND PricebookEntry.Product2.pkg1__Is_Flagged__c = TRUE];

But this error doesn't seem to occur in Dev. or our testing Enterprise edition orgs.

Any reason why OpportunityLineItem is not supported in a Enterprise Ed. org.?
Any thoughts, suggestions to find root cause are welcome.
Thanks.

Best Answer

Please check your class declaration : 'with/without sharing'.

Here is a similar issue -> https://developer.salesforce.com/forums/?id=906F000000090ZPIAY.

Below is an explanation by the person having the issue who got it resolved later on:

This error is occuring in a managed package, and affect multiple instances, including EE editions, developer editions, and sandboxes.

I was told by someone on twitter that unless explicitly noted that classes operate With Sharing by default when called from a trigger. In this case, I have a trigger that calls a helper class that has no sharing declaration. It's acting like it's With Sharing, since standard users that trip the trigger cause this SOQL error but Sys Admins that trip the trigger have no issue.

I swear that this is a change in default behavior. I thought that triggers and helper classes with no sharing declaration were in system context and without sharing by default. I think this is not the case though now, since when I changed the managed package class to Without Sharing, the problem was resolved.

This apex syntax around sharing needs a makeover. In my opinion, With Sharing or Without Sharing should be required on all classes since it's cryptic what no sharing declaration actually means.

Hope this helps.