Avoid extra DB query per menu item

Created on 3 December 2021, over 2 years ago
Updated 18 August 2023, 10 months ago

Problem/Motivation

The translatable_menu_link_uri_iterate_menu() function loads MenuLinkContent entities by their UUID, which actually triggers a database query for every content link displayed on a page, even if the entity was already loaded by ID.

Steps to reproduce

  • Install Translatable menu link uri module.
  • Install Web Profiler sub-module of the Devel project.
  • Create a menu and add multiple content links there.
  • Put a block with this menu to the page.
  • Visit the page with the menu block visible.
  • Check the database log for queries like the following:
SELECT "base_table"."revision_id" AS "revision_id", "base_table"."id" AS "id" 
FROM "menu_link_content" "base_table" 
INNER JOIN "menu_link_content" "menu_link_content" ON "menu_link_content"."id" = "base_table"."id" 
INNER JOIN "menu_link_content_data" "menu_link_content_data" ON "menu_link_content_data"."id" = "base_table"."id" 
WHERE ("menu_link_content"."uuid" IN (:db_condition_placeholder_0)) 
AND ("menu_link_content_data"."default_langcode" IN (:db_condition_placeholder_1))

Proposed resolution

Not yet, see remaining tasks.

Remaining tasks

It's up to module maintainer to choose the approach here. Possible options are:

  • The \Drupal\menu_link_content\Plugin\Menu\MenuLinkContent::getEntity() does a very nice job of loading all the items by ID at once and it's better to re-use the method. However, this method is not open to public. Please check ✨ Set MenuLinkContent getEntity to public visibility Fixed .
  • Alternative approach would be to explore the MenuLinkContent definition, find entity ID saved there at $this-pluginDefinition['metadata']['entity_id'] and try to load the entity by ID. This way entity storage is able to take it from the static cache and it eliminates the extra query too. It could also collect entity IDs from all the menu items and then load them at once by IDs. However, this adds dependency on some internals of the Menu Link Content module and backward compatibility doesn't seem to be guaranteed for such things.

User interface changes

No.

API changes

No.

Data model changes

No.

πŸ› Bug report
Status

Needs review

Version

2.0

Component

Code

Created by

πŸ‡²πŸ‡ͺMontenegro Dmitriy.trt

Live updates comments and jobs are added and updated live.
  • Needs tests

    The change is currently missing an automated test that fails when run with the original code, and succeeds when the bug has been fixed.

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.69.0 2024