Skip to content

Optimize switch_blog hook #60174

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: trunk
Choose a base branch
from

Conversation

superdav42
Copy link
Contributor

switch_blog is triggered in a multisite install when iterating over many sites. With large network this will result in the hook being triggerd hundreds or thousands of times during a single request, this results in the $wpdb->tables array being filled with duplicate table names. This optimization only modifies prefixed table and stops filling the array with duplicates.

How to test the changes in this Pull Request:

  1. Install on a multisite install
  2. Use some features that use the custom tables like tax rate classes or products

Changelog entry

  • Automatically create a changelog entry from the details below.

  • This Pull Request does not require a changelog entry. (Comment required below)

Changelog Entry Details

Significance

  • Patch
  • Minor
  • Major

Type

  • Fix - Fixes an existing bug
  • Add - Adds functionality
  • Update - Update existing functionality
  • Dev - Development related task
  • Tweak - A minor adjustment to the codebase
  • Performance - Address performance issues
  • Enhancement - Improvement to existing functionality

Message

Optimize switch_blog hook

Changelog Entry Comment

Comment

`switch_blog` is triggered in a multisite install when iterating over
many sites. With large network this will result in the hook being triggerd
hundreds or thousands of times during a single request, this results in the
`$wpdb->tables` array being filled with duplicate table names. This optimization
only modifies prefixed table and stops filling the array with duplicates.
@github-actions github-actions bot added type: community contribution plugin: woocommerce Issues related to the WooCommerce Core plugin. labels Aug 2, 2025
Copy link
Contributor

coderabbitai bot commented Aug 2, 2025

📝 Walkthrough

Walkthrough

A new changelog entry was added for WooCommerce, documenting a patch focused on optimizing the switch_blog hook. In the WooCommerce core class, a private constant array now centralizes custom table names, and the logic for updating $wpdb table properties on blog switches was refactored for improved maintainability.

Changes

Cohort / File(s) Change Summary
Changelog Addition
plugins/woocommerce/changelog/60174-improve-switch-blog
Added a changelog entry describing a patch-level performance optimization to the switch_blog hook in WooCommerce. No code changes are present in this file.
WooCommerce Core Table Handling Refactor
plugins/woocommerce/includes/class-woocommerce.php
Introduced a private constant array DEFINED_TABLES for WooCommerce custom table names. Refactored define_tables() to iterate over this constant instead of a local array. Modified wpdb_table_fix() to directly assign $wpdb properties from DEFINED_TABLES without appending to $wpdb->tables and added an explicit global $wpdb declaration.

Sequence Diagram(s)

sequenceDiagram
    participant WordPress
    participant WooCommerce
    participant $wpdb

    WordPress->>WooCommerce: Fires switch_blog hook
    WooCommerce->>WooCommerce: wpdb_table_fix() (updated)
    WooCommerce->>$wpdb: Directly assign custom table properties from DEFINED_TABLES
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9705728 and 2729827.

📒 Files selected for processing (1)
  • plugins/woocommerce/includes/class-woocommerce.php (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • plugins/woocommerce/includes/class-woocommerce.php
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 32cbb10 and 9705728.

📒 Files selected for processing (2)
  • plugins/woocommerce/changelog/60174-improve-switch-blog (1 hunks)
  • plugins/woocommerce/includes/class-woocommerce.php (4 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{php,js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/code-quality.mdc)

**/*.{php,js,jsx,ts,tsx}: Guard against unexpected inputs
Sanitize and validate any potentially dangerous inputs
Ensure code is backwards compatible
Write code that is readable and intuitive
Ensure code has unit or E2E tests where applicable

Files:

  • plugins/woocommerce/includes/class-woocommerce.php
**/*.{php,js,ts,jsx,tsx}

⚙️ CodeRabbit Configuration File

**/*.{php,js,ts,jsx,tsx}: Don't trust that extension developers will follow the best practices, make sure the code:

  • Guards against unexpected inputs.
  • Sanitizes and validates any potentially dangerous inputs.
  • Is backwards compatible.
  • Is readable and intuitive.
  • Has unit or E2E tests where applicable.

Files:

  • plugins/woocommerce/includes/class-woocommerce.php
🧠 Learnings (7)
📓 Common learnings
Learnt from: NeosinneR
PR: woocommerce/woocommerce#60129
File: plugins/woocommerce/includes/wc-coupon-functions.php:145-154
Timestamp: 2025-07-31T11:18:02.478Z
Learning: In WooCommerce codebase, when table names are hardcoded (like `$wpdb->prefix . 'wc_order_coupon_lookup'`), the preference is to maintain consistency with existing patterns throughout the codebase rather than making isolated security improvements when the risk is minimal (since $wpdb->prefix is controlled by WordPress and table names are hardcoded constants).
Learnt from: jorgeatorres
PR: woocommerce/woocommerce#59675
File: .github/workflows/release-bump-as-requirement.yml:48-65
Timestamp: 2025-07-15T15:39:21.856Z
Learning: In WooCommerce core repository, changelog entries for all PRs live in `plugins/woocommerce/changelog/` directory and are processed during releases, not at the repository root level.
Learnt from: samueljseay
PR: woocommerce/woocommerce#58716
File: plugins/woocommerce/client/blocks/assets/js/blocks/mini-cart/iapi-frontend.ts:83-101
Timestamp: 2025-06-17T07:07:53.443Z
Learning: In WooCommerce blocks, when porting existing code patterns that have known issues (like parseInt truncating decimal money values), maintain consistency with existing implementation rather than making isolated fixes. The preference is for systematic refactoring approaches (like broader Dinero adoption) over piecemeal changes.
Learnt from: gigitux
PR: woocommerce/woocommerce#58846
File: plugins/woocommerce/client/blocks/tests/e2e/tests/all-products/all-products.block_theme.spec.ts:41-52
Timestamp: 2025-06-16T09:20:22.981Z
Learning: In WooCommerce E2E tests, the database is reset to the initial state for each test, so there's no need to manually restore global template changes (like clearing the header template) as the test infrastructure handles cleanup automatically.
Learnt from: prettyboymp
PR: woocommerce/woocommerce#59048
File: .github/workflows/cherry-pick-milestoned-prs.yml:60-83
Timestamp: 2025-06-26T12:45:40.709Z
Learning: WooCommerce uses WordPress versioning conventions where minor versions in X.Y.Z format are constrained to 0-9 (Y cannot exceed 9). This means version increment logic should reset minor to 0 and increment major when minor reaches 9, rather than allowing two-digit minor versions like 9.10 or 9.11.
📚 Learning: in woocommerce core repository, changelog entries for all prs live in `plugins/woocommerce/changelog...
Learnt from: jorgeatorres
PR: woocommerce/woocommerce#59675
File: .github/workflows/release-bump-as-requirement.yml:48-65
Timestamp: 2025-07-15T15:39:21.856Z
Learning: In WooCommerce core repository, changelog entries for all PRs live in `plugins/woocommerce/changelog/` directory and are processed during releases, not at the repository root level.

Applied to files:

  • plugins/woocommerce/changelog/60174-improve-switch-blog
  • plugins/woocommerce/includes/class-woocommerce.php
📚 Learning: the displaystyleswitcher component in plugins/woocommerce/client/blocks/assets/js/blocks/product-fil...
Learnt from: dinhtungdu
PR: woocommerce/woocommerce#59900
File: plugins/woocommerce/client/blocks/assets/js/blocks/product-filters/inner-blocks/attribute-filter/inspector.tsx:0-0
Timestamp: 2025-07-24T05:37:00.907Z
Learning: The DisplayStyleSwitcher component in plugins/woocommerce/client/blocks/assets/js/blocks/product-filters/components/display-style-switcher/index.tsx has been updated so that its onChange prop accepts only a string type (not string | number | undefined), eliminating the need for type assertions when using this component.

Applied to files:

  • plugins/woocommerce/changelog/60174-improve-switch-blog
📚 Learning: in woocommerce codebase, when table names are hardcoded (like `$wpdb->prefix . 'wc_order_coupon_look...
Learnt from: NeosinneR
PR: woocommerce/woocommerce#60129
File: plugins/woocommerce/includes/wc-coupon-functions.php:145-154
Timestamp: 2025-07-31T11:18:02.478Z
Learning: In WooCommerce codebase, when table names are hardcoded (like `$wpdb->prefix . 'wc_order_coupon_lookup'`), the preference is to maintain consistency with existing patterns throughout the codebase rather than making isolated security improvements when the risk is minimal (since $wpdb->prefix is controlled by WordPress and table names are hardcoded constants).

Applied to files:

  • plugins/woocommerce/includes/class-woocommerce.php
📚 Learning: in woocommerce e2e tests, the database is reset to the initial state for each test, so there's no ne...
Learnt from: gigitux
PR: woocommerce/woocommerce#58846
File: plugins/woocommerce/client/blocks/tests/e2e/tests/all-products/all-products.block_theme.spec.ts:41-52
Timestamp: 2025-06-16T09:20:22.981Z
Learning: In WooCommerce E2E tests, the database is reset to the initial state for each test, so there's no need to manually restore global template changes (like clearing the header template) as the test infrastructure handles cleanup automatically.

Applied to files:

  • plugins/woocommerce/includes/class-woocommerce.php
📚 Learning: action scheduler is bundled into woocommerce and always available, so there's no need to add fallbac...
Learnt from: senadir
PR: woocommerce/woocommerce#59325
File: plugins/woocommerce/includes/wc-formatting-functions.php:1211-1226
Timestamp: 2025-07-01T16:24:23.871Z
Learning: Action Scheduler is bundled into WooCommerce and always available, so there's no need to add fallback logic to WordPress cron functions when using Action Scheduler functions like as_schedule_single_action() and as_unschedule_all_actions() in WooCommerce code.

Applied to files:

  • plugins/woocommerce/includes/class-woocommerce.php
📚 Learning: in woocommerce's wc_delete_product_transients function, the context check includes both $is_admin_pa...
Learnt from: mreishus
PR: woocommerce/woocommerce#58817
File: plugins/woocommerce/includes/wc-product-functions.php:140-140
Timestamp: 2025-06-13T23:52:46.221Z
Learning: In WooCommerce's wc_delete_product_transients function, the context check includes both $is_admin_page (for regular admin screens) and $is_privileged_ajax (for AJAX requests from users with edit_products capability), ensuring that legitimate admin AJAX operations like product imports/exports can still delete transients.

Applied to files:

  • plugins/woocommerce/includes/class-woocommerce.php
🔇 Additional comments (4)
plugins/woocommerce/includes/class-woocommerce.php (3)

146-152: LGTM! Good centralization of table definitions.

The DEFINED_TABLES constant provides a clean, maintainable approach to centralize WooCommerce custom table names in a single location. This improves code organization and makes it easier to manage table definitions.


500-503: LGTM! Clean refactor using the centralized constant.

The method now properly uses the DEFINED_TABLES constant instead of a hardcoded array, improving maintainability while preserving the same functionality.


1127-1132: Excellent optimization! This prevents duplicate entries in $wpdb->tables.

The simplified implementation only updates $wpdb properties without adding to the $wpdb->tables array, which is exactly what's needed to prevent duplicates in multisite environments. This directly addresses the performance issue described in the PR objectives where the switch_blog hook was filling the array with duplicates.

plugins/woocommerce/changelog/60174-improve-switch-blog (1)

1-4: LGTM! Proper changelog format and accurate description.

The changelog entry follows the correct WooCommerce format and accurately describes the performance optimization for the switch_blog hook. The patch significance and performance type are appropriate for this change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
plugin: woocommerce Issues related to the WooCommerce Core plugin. type: community contribution
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant