Commit 0b97ba29 authored by catch's avatar catch
Browse files

fix: #3634917 [random test failure] “cache_file_parsing” table does not exist...

fix: #3634917 [random test failure] “cache_file_parsing” table does not exist in functional tests on PostgreSQL and SQLite

By: joelpittet
By: mondrake
(cherry picked from commit e28908b6)
parent e8b0a407
Loading
Loading
Loading
Loading
Loading
+56 −32
Changes for core/lib/Drupal/Core/Cache/DatabaseBackend.php: 56 added lines, 32 removed lines.
Original line number Diff line number Diff line
@@ -200,21 +200,16 @@ public function set($cid, $data, $expire = Cache::PERMANENT, array $tags = []) {
   * {@inheritdoc}
   */
  public function setMultiple(array $items) {
    $try_again = FALSE;
    try {
      // The bin might not yet exist.
      // The bin table can be missing.
      $this->doSetMultiple($items);
    }
    catch (\Exception $e) {
      // If there was an exception, try to create the bins.
      if (!$try_again = $this->ensureBinExists()) {
        // If the exception happened for other reason than the missing bin
        // table, propagate the exception.
        throw $e;
      }
    }
    // Now that the bin has been created, try again if necessary.
    if ($try_again) {
    catch (\Exception) {
      // If the query fails, make the bin table and do the query again. It is
      // possible that another process made the table after the query failed.
      // If the query fails for a different cause, it fails again and the
      // exception goes to the caller.
      $this->ensureBinExists();
      $this->doSetMultiple($items);
    }
  }
@@ -305,22 +300,34 @@ public function delete($cid) {
  public function deleteMultiple(array $cids) {
    $cids = array_values(array_map([$this, 'normalizeCid'], $cids));
    try {
      // Delete in chunks when a large array is passed.
      $this->doDeleteMultiple($cids);
    }
    catch (\Exception) {
      // Make the cache table. The new table is empty. During core
      // installation, it is possible to clear a cache table before items are
      // in it, for example {cache_render} and {cache_data}. If the table is
      // already there, it is possible that another process made it after the
      // query failed. In this condition, do the query again.
      if (!$this->ensureBinExists()) {
        $this->doDeleteMultiple($cids);
      }
    }
  }

  /**
   * Deletes items from the cache bin table.
   *
   * @param string[] $cids
   *   An array of normalized cache IDs.
   */
  protected function doDeleteMultiple(array $cids): void {
    // Delete the items in groups of 1000. This keeps each query small.
    foreach (array_chunk($cids, 1000) as $cids_chunk) {
      $this->connection->delete($this->bin)
        ->condition('cid', $cids_chunk, 'IN')
        ->execute();
    }
  }
    catch (\Exception $e) {
      // Create the cache table, which will be empty. This fixes cases during
      // core install where a cache table is cleared before it is set
      // with {cache_render} and {cache_data}.
      if (!$this->ensureBinExists()) {
        $this->catchException($e);
      }
    }
  }

  /**
   * {@inheritdoc}
@@ -329,12 +336,14 @@ public function deleteAll() {
    try {
      $this->connection->truncate($this->bin)->execute();
    }
    catch (\Exception $e) {
      // Create the cache table, which will be empty. This fixes cases during
      // core install where a cache table is cleared before it is set
      // with {cache_render} and {cache_data}.
    catch (\Exception) {
      // Make the cache table. The new table is empty. During core
      // installation, it is possible to clear a cache table before items are
      // in it, for example {cache_render} and {cache_data}. If the table is
      // already there, it is possible that another process made it after the
      // query failed. In this condition, do the query again.
      if (!$this->ensureBinExists()) {
        $this->catchException($e);
        $this->connection->truncate($this->bin)->execute();
      }
    }
  }
@@ -352,7 +361,26 @@ public function invalidate($cid) {
  public function invalidateMultiple(array $cids) {
    $cids = array_values(array_map([$this, 'normalizeCid'], $cids));
    try {
      // Update in chunks when a large array is passed.
      $this->doInvalidateMultiple($cids);
    }
    catch (\Exception) {
      // If the table is missing, there are no items to invalidate. If the
      // table is there, it is possible that another process made it after the
      // query failed. In this condition, do the query again.
      if ($this->connection->schema()->tableExists($this->bin)) {
        $this->doInvalidateMultiple($cids);
      }
    }
  }

  /**
   * Marks items in the cache bin table as invalid.
   *
   * @param string[] $cids
   *   An array of normalized cache IDs.
   */
  protected function doInvalidateMultiple(array $cids): void {
    // Update the items in groups of 1000. This keeps each query small.
    $requestTime = $this->time->getRequestTime();
    foreach (array_chunk($cids, 1000) as $cids_chunk) {
      $this->connection->update($this->bin)
@@ -361,10 +389,6 @@ public function invalidateMultiple(array $cids) {
        ->execute();
    }
  }
    catch (\Exception $e) {
      $this->catchException($e);
    }
  }

  /**
   * {@inheritdoc}
+46
Changes for core/tests/Drupal/KernelTests/Core/Cache/DatabaseBackendTest.php: 46 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -6,8 +6,11 @@

use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Cache\DatabaseBackend;
use Drupal\Core\Database\Event\StatementExecutionFailureEvent;
use Drupal\Core\Database\Event\StatementExecutionStartEvent;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses;
use PHPUnit\Framework\Attributes\TestWith;

/**
 * Unit test of the database backend using the generic cache unit test base.
@@ -103,6 +106,49 @@ public function testGarbageCollection(): void {
    $this->assertFalse($backend->get('test0'));
  }

  /**
   * Tests write operations when another process makes the bin table.
   *
   * The other process makes the table after the first query fails.
   *
   * @param string $method
   *   The name of the cache backend method to call.
   */
  #[TestWith(['setMultiple'])]
  #[TestWith(['invalidateMultiple'])]
  #[TestWith(['deleteMultiple'])]
  #[TestWith(['deleteAll'])]
  public function testBinCreatedAfterQueryFailure(string $method): void {
    $backend = $this->createCacheBackend('created_concurrently');
    $connection = $this->container->get('database');
    $table = 'cache_created_concurrently';
    $this->assertFalse($connection->schema()->tableExists($table));

    // Make the table after the first query fails and before the backend
    // catches the exception. Another process can do this.
    $created = FALSE;
    $connection->enableEvents([
      StatementExecutionStartEvent::class,
      StatementExecutionFailureEvent::class,
    ]);
    $this->container->get('event_dispatcher')->addListener(StatementExecutionFailureEvent::class, function () use ($backend, $connection, $table, &$created): void {
      if (!$created) {
        $created = TRUE;
        $connection->schema()->createTable($table, $backend->schemaDefinition());
      }
    });

    match ($method) {
      'setMultiple' => $backend->setMultiple(['test' => ['data' => 'value']]),
      'deleteAll' => $backend->deleteAll(),
      default => $backend->$method(['test']),
    };
    $this->assertTrue($created);
    if ($method === 'setMultiple') {
      $this->assertSame('value', $backend->get('test')->data);
    }
  }

  /**
   * Gets the number of rows in the test cache bin database table.
   *