Change record status: 
Project: 
Introduced in branch: 
11.4.x
Description: 

Drupal\Core\Database\Query\SelectInterface and Drupal\Core\Entity\Query\QueryInterface now extend Drupal\Core\Cache\RefinableCacheableDependencyInterface. This means that cacheable metadata can be added and retrieved from database select objects and entity query objects.

For any entity type whose entity queries are implemented by Drupal\Core\Entity\Query\Sql\Query (so any content entity type, generally), the returned values from getCacheContexts(), getCacheMaxAge, and getCacheTags() are merged with the values for the corresponding methods on the SelectInterface object that is a class property. Any cacheable metadata added to such a SelectInterface object in hook_query_alter() or hook_query_TAG_aler() implementations will be merged to the QueryInterface object.

Example in Drupal\node\Hook\NodeHooks1::queryNodeAccessAlter():

  #[Hook('query_node_access_alter')]
  public function queryNodeAccessAlter(AlterableInterface $query): void {
    ...
    // Bubble the 'user.node_grants:$op' cache context to the current render
    // context.
    $contexts = ['user.node_grants:' . $op];
    if ($query instanceof SelectInterface) {
      $query->addCacheContexts($contexts);
    }
    ...
  }

Note that any classes that implementSelectInterface, but do not extend Drupal\Core\Database\Query\Select or Drupal\Core\Database\Query\SelectExtender, or any classes that implement QueryInterface , but do not extend Drupal\Core\Entity\Query\QueryBase, will need to implement the methods in RefinableCacheableDependencyInterface and CacheableDependencyInterface.

Impacts: 
Module developers