[SalesForce] Need to run soql as admin in apex controller
I need to run an SOQL command, as admin just like system.runAs(u) in controller.
Is there a way to do this.
Best Answer
To run a query as "an administrator", use the "without sharing" keyword within a class:
public without sharing class Utility {
public static Account[] queryAccounts() {
return [SELECT Id, Name, Industry FROM Account LIMIT 100];
}
}
While you are still running the query as the current user, the current user's sharing is ignored, which means that the query will execute as if the user were an administrator.
Also note that within triggers, the code runs by default "without sharing", so it is generally not necessary to run "as administrator" unless you're using utility classes (such as the example here).
With Spring 19' update there is a new setting in the "App Permission -> Content -> Query All Files: Allows View All Data users to SOQL query all files in the org".
This is not enabled by default for the admin user but you can at least enable it in a Profile/Permissions Set.
More importantly, I scheduled a quick flow to test this and I can see through debug logs that the scheduled flow was executed by the Automated Process User as opposed to the user who scheduled it.
Best Answer
To run a query as "an administrator", use the "without sharing" keyword within a class:
While you are still running the query as the current user, the current user's sharing is ignored, which means that the query will execute as if the user were an administrator.
Also note that within triggers, the code runs by default "without sharing", so it is generally not necessary to run "as administrator" unless you're using utility classes (such as the example here).