Skip to content

Commit

Permalink
Co-authored-by: SundusShahbaz <SundusShahbaz@users.noreply.github.com>
Browse files Browse the repository at this point in the history
  • Loading branch information
rob-baillie-ortoo committed Mar 3, 2022
1 parent 513d3d9 commit bff4b34
Showing 1 changed file with 30 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,26 @@
/**
* Provides the ability to cache the results of particular SOQL statements in the Org Wide Platform Cache.
*
* Should only be used for queries that reference data that does not generally change.
*
* If used, it is recommended that triggers are added to those objects, or code added to the UI that updates the objects
* referenced in the SOQL that invalidate the cache.
*/
public inherited sharing class OrgCachedSoqlExecutor
{
private final static string SOQL_PARTITION_NAME = 'soql';
private final static String SOQL_PARTITION_NAME = 'soql';
private final static Integer CACHE_LIFESPAN_SECONDS = 43200;

/**
* Perform the given query, first checking if the Org Platform Cache Partition contains results for that SOQL.
* If so, the cached versions are returned.
* If not, the query is executed against the database and the result cached.
* If, for any reason, a cache read or write cannot be performed, the method will continue without an exception.
* Errors can be seen in the System.debug log.
*
* @param String The SOQL to return the results for
* @return List<Sobject> The records that match
*/
public List<Sobject> query( String soql )
{
String key = generateKey( soql );
Expand All @@ -24,7 +43,7 @@ public inherited sharing class OrgCachedSoqlExecutor

try
{
Cache.Org.put( key, returnValues, 43200, Cache.Visibility.NAMESPACE, false ); // immutable results
Cache.Org.put( key, returnValues, CACHE_LIFESPAN_SECONDS, Cache.Visibility.NAMESPACE, false ); // immutable results
}
catch ( Exception e )
{
Expand All @@ -36,11 +55,19 @@ public inherited sharing class OrgCachedSoqlExecutor
return returnValues;
}

/**
* Clears the cached results for the given SOQL that are held in the Org Platform Cache Partition
*
* @param String The SOQL to clear the cache for
*/
public void clearCacheFor( String soql )
{
Cache.Org.remove( generateKey( soql ) );
}

/**
* Clears the cached results all cached SOQL
*/
// TODO: how do we get this to just try to remove things that are in this partition?
public void clearAllCache()
{
Expand All @@ -55,7 +82,7 @@ public inherited sharing class OrgCachedSoqlExecutor
}
}

public String generateKey( String soql )
private String generateKey( String soql )
{
String subkey = EncodingUtil.convertToHex( Crypto.generateDigest( 'SHA1', Blob.valueOf( soql ) ) );
return qualifiedKey( subkey );
Expand Down

0 comments on commit bff4b34

Please sign in to comment.