Database query metadata missing for Views queries altered for cache key generation

Created on 20 October 2021, about 3 years ago
Updated 23 June 2023, over 1 year ago

Problem/Motivation

When altering database queries generated by views (via hook_query_alter() or hook_query_TAG_alter()), you can generally access the view via the query’s 'view' metadata key.
However, the default cache plugins also include the generated SQL queries in their cache key for results, and therefore have to pre-execute the queries (both normal and count query) themselves, too. In the code doing that (\Drupal\views\Plugin\views\cache\CachePluginBase::generateResultsKey()), the view is not added to the metadata.

In cases where the view is needed for making alterations to the query, this could lead to either errors (when the code doesn’t check whether the view is actually present in the metadata before using it) or cacheability problems (cache key lacking some variation that the actually executed database query has).

Steps to reproduce

  1. Create a view with ID foo on normal SQL data (e.g., “Content“) and a page display.
  2. Set/Leave caching to “Tag-based”.
  3. In a custom module, implement hook_query_views_alter() and output whether or not there is anything in $query->getMetaData('view').
  4. Clear the cache so the hook gets found.
  5. Go to the view’s page twice. You will see the view is present on the first request for a particular page, but not on subsequent requests.

Proposed resolution

Add $query->addMetaData('view', $this->view); right before $query->preExecute(); in \Drupal\views\Plugin\views\cache\CachePluginBase::generateResultsKey().

Remaining tasks

Answer the question in #5
Review the test

User interface changes

None.

API changes

None.

Data model changes

None.

Release notes snippet

None needed, I’m pretty certain.

🐛 Bug report
Status

Needs work

Version

11.0 🔥

Component
Views 

Last updated about 6 hours ago

Created by

🇦🇹Austria drunken monkey Vienna, Austria

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024