WordPress/WordPress-Coding-Standards

Using a transient should be considered a way of caching a direct database call

akirk opened this issue · 0 comments

Bug Description

Using a transient for caching a direct database call is not deemed acceptable but I believe it should be:

When using an external object cache, get_transient() is short-circuited to use wp_cache_get().

When not using an external object cache, it falls back to use get_option() (after ensuring that all options were loaded). And then get_option() either uses a hash lookup in all options, or wp_cache_get().

Thanks @apermo for the pointer and encouragement to file this!

Minimal Code Snippet

The issue happens when running this command:

./vendor/bin/phpcs -s --standard=WordPress transient.php

... over a file containing this code:

if ( ! get_transient( 'time' ) ) {
	$wpdb->get_var( 'SELECT current_time()' );
}

Error Code

WordPress.DB.DirectDatabaseQuery.NoCaching

Environment

Question Answer
PHP version 7.4
PHP_CodeSniffer version 3.10.1
WordPressCS version 3.1.0 (also tested with dev-develop 29488fe)
WordPressCS install type https://github.com/WordPress/WordPress-Coding-Standards?#composer-project-based-installation

Tested Against develop Branch?

  • I have verified the issue still exists in the develop branch of WordPressCS.