Skip to content

Options: Invalidate object cache when update_option() DB write fails #9481

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 2 commits into
base: trunk
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/wp-includes/option.php
Original file line number Diff line number Diff line change
Expand Up @@ -963,6 +963,19 @@ function update_option( $option, $value, $autoload = null ) {

$result = $wpdb->update( $wpdb->options, $update_args, array( 'option_name' => $option ) );
if ( ! $result ) {
if ( ! wp_installing() ) {
$alloptions = wp_load_alloptions( true );

if ( isset( $alloptions[ $option ] ) ) {
unset( $alloptions[ $option ] );
wp_cache_set( 'alloptions', $alloptions, 'options' );
} else {
wp_cache_delete( 'alloptions', 'options' );
}

wp_cache_delete( $option, 'options' );
}

return false;
}

Expand Down
37 changes: 37 additions & 0 deletions tests/phpunit/tests/option/updateOption.php
Original file line number Diff line number Diff line change
Expand Up @@ -225,4 +225,41 @@ public function test_update_option_array_with_object() {
public function __return_foo() {
return 'foo';
}

/**
* @ticket 26402
*
* @covers ::update_option
*/
public function test_should_invalidate_cache_when_db_update_fails() {
global $wpdb;

$option_name = 'test_option_update_fail';
$option_value = 'initial';

add_option( $option_name, $option_value );
$this->assertSame( $option_value, get_option( $option_name ) );

$wpdb->delete( $wpdb->options, array( 'option_name' => $option_name ) );

tests_add_filter(
'query',
function ( $query ) use ( $wpdb ) {
if ( stripos( $query, "update `$wpdb->options`" ) === 0 ) {
return false; // Simulate DB update failure.
}
return $query;
}
);

$result = update_option( $option_name, 'new_value' );

$this->assertFalse( $result, 'Expected update_option() to fail when DB update fails.' );
$this->assertFalse( wp_cache_get( $option_name, 'options' ) );

// Verify alloptions cache no longer contains the option.
$alloptions = wp_cache_get( 'alloptions', 'options' );
$this->assertIsArray( $alloptions );
$this->assertArrayNotHasKey( $option_name, $alloptions );
}
}
Loading