DatabaseBackend.php 20.2 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Definition of Drupal\Core\Cache\DatabaseBackend.
6 7
 */

8
namespace Drupal\Core\Cache;
9

10
use Drupal\Component\Utility\Crypt;
11
use Drupal\Core\Database\Connection;
12
use Drupal\Core\Database\SchemaObjectExistsException;
13 14 15 16 17 18

/**
 * Defines a default cache implementation.
 *
 * This is Drupal's default cache implementation. It uses the database to store
 * cached data. Each cache bin corresponds to a database table by the same name.
19 20
 *
 * @ingroup cache
21 22 23 24 25 26 27 28
 */
class DatabaseBackend implements CacheBackendInterface {

  /**
   * @var string
   */
  protected $bin;

29 30 31 32 33 34 35 36

  /**
   * The database connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $connection;

37
  /**
38 39
   * Constructs a DatabaseBackend object.
   *
40 41
   * @param \Drupal\Core\Database\Connection $connection
   *   The database connection.
42 43
   * @param string $bin
   *   The cache bin for which the object is created.
44
   */
45
  public function __construct(Connection $connection, $bin) {
46 47 48
    // All cache tables should be prefixed with 'cache_'.
    $bin = 'cache_' . $bin;

49
    $this->bin = $bin;
50
    $this->connection = $connection;
51 52 53
  }

  /**
54
   * Implements Drupal\Core\Cache\CacheBackendInterface::get().
55
   */
56
  public function get($cid, $allow_invalid = FALSE) {
57
    $cids = array($cid);
58
    $cache = $this->getMultiple($cids, $allow_invalid);
59 60 61 62
    return reset($cache);
  }

  /**
63
   * Implements Drupal\Core\Cache\CacheBackendInterface::getMultiple().
64
   */
65
  public function getMultiple(&$cids, $allow_invalid = FALSE) {
66 67 68 69
    $cid_mapping = array();
    foreach ($cids as $cid) {
      $cid_mapping[$this->normalizeCid($cid)] = $cid;
    }
70 71 72 73 74 75 76
    // When serving cached pages, the overhead of using ::select() was found
    // to add around 30% overhead to the request. Since $this->bin is a
    // variable, this means the call to ::query() here uses a concatenated
    // string. This is highly discouraged under any other circumstances, and
    // is used here only due to the performance overhead we would incur
    // otherwise. When serving an uncached page, the overhead of using
    // ::select() is a much smaller proportion of the request.
77 78
    $result = array();
    try {
79
      $result = $this->connection->query('SELECT cid, data, created, expire, serialized, tags, checksum_invalidations, checksum_deletions FROM {' . $this->connection->escapeTable($this->bin) . '} WHERE cid IN (:cids)', array(':cids' => array_keys($cid_mapping)));
80 81 82 83
    }
    catch (\Exception $e) {
      // Nothing to do.
    }
84 85
    $cache = array();
    foreach ($result as $item) {
86 87
      // Map the cache ID back to the original.
      $item->cid = $cid_mapping[$item->cid];
88 89 90
      $item = $this->prepareItem($item, $allow_invalid);
      if ($item) {
        $cache[$item->cid] = $item;
91 92
      }
    }
93 94
    $cids = array_diff($cids, array_keys($cache));
    return $cache;
95 96 97 98 99 100 101 102
  }

  /**
   * Prepares a cached item.
   *
   * Checks that items are either permanent or did not expire, and unserializes
   * data as appropriate.
   *
103
   * @param object $cache
104
   *   An item loaded from cache_get() or cache_get_multiple().
105 106
   * @param bool $allow_invalid
   *   If FALSE, the method returns FALSE if the cache item is not valid.
107
   *
108 109 110
   * @return mixed|false
   *   The item with data unserialized as appropriate and a property indicating
   *   whether the item is valid, or FALSE if there is no valid item to load.
111
   */
112
  protected function prepareItem($cache, $allow_invalid) {
113 114 115 116
    if (!isset($cache->data)) {
      return FALSE;
    }

117 118 119 120 121 122 123 124 125 126
    $cache->tags = $cache->tags ? explode(' ', $cache->tags) : array();

    $checksum = $this->checksumTags($cache->tags);

    // Check if deleteTags() has been called with any of the entry's tags.
    if ($cache->checksum_deletions != $checksum['deletions']) {
      return FALSE;
    }

    // Check expire time.
127
    $cache->valid = $cache->expire == Cache::PERMANENT || $cache->expire >= REQUEST_TIME;
128 129 130 131 132 133 134 135

    // Check if invalidateTags() has been called with any of the entry's tags.
    if ($cache->checksum_invalidations != $checksum['invalidations']) {
      $cache->valid = FALSE;
    }

    if (!$allow_invalid && !$cache->valid) {
      return FALSE;
136 137
    }

138
    // Unserialize and return the cached data.
139 140 141 142 143 144 145 146
    if ($cache->serialized) {
      $cache->data = unserialize($cache->data);
    }

    return $cache;
  }

  /**
147
   * Implements Drupal\Core\Cache\CacheBackendInterface::set().
148
   */
149
  public function set($cid, $data, $expire = Cache::PERMANENT, array $tags = array()) {
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
    $try_again = FALSE;
    try {
      // The bin might not yet exist.
      $this->doSet($cid, $data, $expire, $tags);
    }
    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) {
      $this->doSet($cid, $data, $expire, $tags);
    }
  }

  /**
   * Actually set the cache.
   */
  protected function doSet($cid, $data, $expire, $tags) {
173
    $flat_tags = $this->flattenTags($tags);
174
    $deleted_tags = &drupal_static('Drupal\Core\Cache\DatabaseBackend::deletedTags', array());
175 176 177 178
    $invalidated_tags = &drupal_static('Drupal\Core\Cache\DatabaseBackend::invalidatedTags', array());
    // Remove tags that were already deleted or invalidated during this request
    // from the static caches so that another deletion or invalidation can
    // occur.
179 180 181 182
    foreach ($flat_tags as $tag) {
      if (isset($deleted_tags[$tag])) {
        unset($deleted_tags[$tag]);
      }
183 184 185
      if (isset($invalidated_tags[$tag])) {
        unset($invalidated_tags[$tag]);
      }
186
    }
187 188 189
    $checksum = $this->checksumTags($flat_tags);
    $fields = array(
      'serialized' => 0,
190
      'created' => round(microtime(TRUE), 3),
191 192 193 194 195 196 197 198
      'expire' => $expire,
      'tags' => implode(' ', $flat_tags),
      'checksum_invalidations' => $checksum['invalidations'],
      'checksum_deletions' => $checksum['deletions'],
    );
    if (!is_string($data)) {
      $fields['data'] = serialize($data);
      $fields['serialized'] = 1;
199
    }
200 201 202
    else {
      $fields['data'] = $data;
      $fields['serialized'] = 0;
203
    }
204

205
    $this->connection->merge($this->bin)
206
      ->key('cid', $this->normalizeCid($cid))
207 208
      ->fields($fields)
      ->execute();
209 210
  }

211 212 213 214 215 216 217 218 219 220 221 222
  /**
   * {@inheritdoc}
   */
  public function setMultiple(array $items) {
    $deleted_tags = &drupal_static('Drupal\Core\Cache\DatabaseBackend::deletedTags', array());
    $invalidated_tags = &drupal_static('Drupal\Core\Cache\DatabaseBackend::invalidatedTags', array());

    // Use a transaction so that the database can write the changes in a single
    // commit.
    $transaction = $this->connection->startTransaction();

    try {
223
      // Delete all items first so we can do one insert. Rather than multiple
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
      // merge queries.
      $this->deleteMultiple(array_keys($items));

      $query = $this->connection
        ->insert($this->bin)
        ->fields(array('cid', 'data', 'expire', 'created', 'serialized', 'tags', 'checksum_invalidations', 'checksum_deletions'));

      foreach ($items as $cid => $item) {
        $item += array(
          'expire' => CacheBackendInterface::CACHE_PERMANENT,
          'tags' => array(),
        );

        $flat_tags = $this->flattenTags($item['tags']);

        // Remove tags that were already deleted or invalidated during this
        // request from the static caches so that another deletion or
        // invalidation can occur.
        foreach ($flat_tags as $tag) {
          if (isset($deleted_tags[$tag])) {
            unset($deleted_tags[$tag]);
          }
          if (isset($invalidated_tags[$tag])) {
            unset($invalidated_tags[$tag]);
          }
        }

        $checksum = $this->checksumTags($flat_tags);

        $fields = array(
          'cid' => $cid,
          'expire' => $item['expire'],
256
          'created' => round(microtime(TRUE), 3),
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
          'tags' => implode(' ', $flat_tags),
          'checksum_invalidations' => $checksum['invalidations'],
          'checksum_deletions' => $checksum['deletions'],
        );

        if (!is_string($item['data'])) {
          $fields['data'] = serialize($item['data']);
          $fields['serialized'] = 1;
        }
        else {
          $fields['data'] = $item['data'];
          $fields['serialized'] = 0;
        }

        $query->values($fields);
      }

      $query->execute();
    }
    catch (\Exception $e) {
      $transaction->rollback();
      // @todo Log something here or just re throw?
      throw $e;
    }
  }

283
  /**
284
   * Implements Drupal\Core\Cache\CacheBackendInterface::delete().
285
   */
286
  public function delete($cid) {
287
    $this->deleteMultiple(array($cid));
288 289 290
  }

  /**
291
   * Implements Drupal\Core\Cache\CacheBackendInterface::deleteMultiple().
292
   */
293
  public function deleteMultiple(array $cids) {
294
    $cids = array_values(array_map(array($this, 'normalizeCid'), $cids));
295 296
    try {
      // Delete in chunks when a large array is passed.
297
      foreach (array_chunk($cids, 1000) as $cids_chunk) {
298
        $this->connection->delete($this->bin)
299
          ->condition('cid', $cids_chunk, 'IN')
300 301 302 303
          ->execute();
      }
    }
    catch (\Exception $e) {
304 305
      // Create the cache table, which will be empty. This fixes cases during
      // core install where a cache table is cleared before it is set
306
      // with {cache_render} and {cache_data}.
307 308 309
      if (!$this->ensureBinExists()) {
        $this->catchException($e);
      }
310 311 312 313
    }
  }

  /**
314 315 316
   * Implements Drupal\Core\Cache\CacheBackendInterface::deleteTags().
   */
  public function deleteTags(array $tags) {
317
    $tag_cache = &drupal_static('Drupal\Core\Cache\CacheBackendInterface::tagCache', array());
318
    $deleted_tags = &drupal_static('Drupal\Core\Cache\DatabaseBackend::deletedTags', array());
319
    foreach ($this->flattenTags($tags) as $tag) {
320 321 322 323 324
      // Only delete tags once per request unless they are written again.
      if (isset($deleted_tags[$tag])) {
        continue;
      }
      $deleted_tags[$tag] = TRUE;
325
      unset($tag_cache[$tag]);
326
      try {
327
        $this->connection->merge('cachetags')
328 329
          ->insertFields(array('deletions' => 1))
          ->expression('deletions', 'deletions + 1')
330
          ->key('tag', $tag)
331 332 333
          ->execute();
      }
      catch (\Exception $e) {
334
        $this->catchException($e, 'cachetags');
335
      }
336 337 338 339 340
    }
  }

  /**
   * Implements Drupal\Core\Cache\CacheBackendInterface::deleteAll().
341
   */
342
  public function deleteAll() {
343 344 345 346
    try {
      $this->connection->truncate($this->bin)->execute();
    }
    catch (\Exception $e) {
347 348
      // Create the cache table, which will be empty. This fixes cases during
      // core install where a cache table is cleared before it is set
349
      // with {cache_render} and {cache_data}.
350 351 352
      if (!$this->ensureBinExists()) {
        $this->catchException($e);
      }
353
    }
354 355 356
  }

  /**
357
   * Implements Drupal\Core\Cache\CacheBackendInterface::invalidate().
358
   */
359 360
  public function invalidate($cid) {
    $this->invalidateMultiple(array($cid));
361 362
  }

363
  /**
364
   * Implements Drupal\Core\Cache\CacheBackendInterface::invalidateMultiple().
365 366
   */
  public function invalidateMultiple(array $cids) {
367
    $cids = array_values(array_map(array($this, 'normalizeCid'), $cids));
368 369
    try {
      // Update in chunks when a large array is passed.
370
      foreach (array_chunk($cids, 1000) as $cids_chunk) {
371 372
        $this->connection->update($this->bin)
          ->fields(array('expire' => REQUEST_TIME - 1))
373
          ->condition('cid', $cids_chunk, 'IN')
374 375 376 377 378
          ->execute();
      }
    }
    catch (\Exception $e) {
      $this->catchException($e);
379 380 381 382 383 384 385
    }
  }

  /**
   * Implements Drupal\Core\Cache\CacheBackendInterface::invalidateTags().
   */
  public function invalidateTags(array $tags) {
386
    try {
387
      $tag_cache = &drupal_static('Drupal\Core\Cache\CacheBackendInterface::tagCache', array());
388
      $invalidated_tags = &drupal_static('Drupal\Core\Cache\DatabaseBackend::invalidatedTags', array());
389
      foreach ($this->flattenTags($tags) as $tag) {
390 391 392 393 394
        // Only invalidate tags once per request unless they are written again.
        if (isset($invalidated_tags[$tag])) {
          continue;
        }
        $invalidated_tags[$tag] = TRUE;
395
        unset($tag_cache[$tag]);
396
        $this->connection->merge('cachetags')
397 398
          ->insertFields(array('invalidations' => 1))
          ->expression('invalidations', 'invalidations + 1')
399
          ->key('tag', $tag)
400 401 402 403
          ->execute();
      }
    }
    catch (\Exception $e) {
404
      $this->catchException($e, 'cachetags');
405 406 407 408 409
    }
  }

  /**
   * Implements Drupal\Core\Cache\CacheBackendInterface::invalidateAll().
410
   */
411
  public function invalidateAll() {
412 413 414 415 416 417 418 419
    try {
      $this->connection->update($this->bin)
        ->fields(array('expire' => REQUEST_TIME - 1))
        ->execute();
    }
    catch (\Exception $e) {
      $this->catchException($e);
    }
420 421 422
  }

  /**
423 424 425
   * Implements Drupal\Core\Cache\CacheBackendInterface::garbageCollection().
   */
  public function garbageCollection() {
426
    try {
427
      $this->connection->delete($this->bin)
428
        ->condition('expire', Cache::PERMANENT, '<>')
429 430 431 432 433 434 435 436
        ->condition('expire', REQUEST_TIME, '<')
        ->execute();
    }
    catch (\Exception $e) {
      // If the table does not exist, it surely does not have garbage in it.
      // If the table exists, the next garbage collection will clean up.
      // There is nothing to do.
    }
437 438 439 440
  }

  /**
   * 'Flattens' a tags array into an array of strings.
441 442 443 444
   *
   * @param array $tags
   *   Associative array of tags to flatten.
   *
445
   * @return array
446
   *   An indexed array of flattened tag identifiers.
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
   */
  protected function flattenTags(array $tags) {
    if (isset($tags[0])) {
      return $tags;
    }

    $flat_tags = array();
    foreach ($tags as $namespace => $values) {
      if (is_array($values)) {
        foreach ($values as $value) {
          $flat_tags[] = "$namespace:$value";
        }
      }
      else {
        $flat_tags[] = "$namespace:$values";
      }
    }
    return $flat_tags;
  }

  /**
   * Returns the sum total of validations for a given set of tags.
   *
   * @param array $tags
471
   *   Array of flat tags.
472
   *
473
   * @return int
474
   *   Sum of all invalidations.
475
   *
476
   * @see \Drupal\Core\Cache\DatabaseBackend::flattenTags()
477
   */
478 479
  protected function checksumTags($flat_tags) {
    $tag_cache = &drupal_static('Drupal\Core\Cache\CacheBackendInterface::tagCache', array());
480

481 482 483 484
    $checksum = array(
      'invalidations' => 0,
      'deletions' => 0,
    );
485

486
    $query_tags = array_diff($flat_tags, array_keys($tag_cache));
487
    if ($query_tags) {
488
      $db_tags = $this->connection->query('SELECT tag, invalidations, deletions FROM {cachetags} WHERE tag IN (:tags)', array(':tags' => $query_tags))->fetchAllAssoc('tag', \PDO::FETCH_ASSOC);
489 490 491 492
      $tag_cache += $db_tags;

      // Fill static cache with empty objects for tags not found in the database.
      $tag_cache += array_fill_keys(array_diff($query_tags, array_keys($db_tags)), $checksum);
493
    }
494 495 496 497 498 499

    foreach ($flat_tags as $tag) {
      $checksum['invalidations'] += $tag_cache[$tag]['invalidations'];
      $checksum['deletions'] += $tag_cache[$tag]['deletions'];
    }

500 501 502
    return $checksum;
  }

503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
  /**
   * {@inheritdoc}
   */
  public function removeBin() {
    try {
      $this->connection->schema()->dropTable($this->bin);
    }
    catch (\Exception $e) {
      $this->catchException($e);
    }
  }

  /**
   * Check if the cache bin exists and create it if not.
   */
  protected function ensureBinExists() {
    try {
      $database_schema = $this->connection->schema();
      if (!$database_schema->tableExists($this->bin)) {
        $schema_definition = $this->schemaDefinition();
        $database_schema->createTable($this->bin, $schema_definition['bin']);
        // If the bin doesn't exist, the cache tags table may also not exist.
525 526
        if (!$database_schema->tableExists('cachetags')) {
          $database_schema->createTable('cachetags', $schema_definition['cachetags']);
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
        }
        return TRUE;
      }
    }
    // If another process has already created the cache table, attempting to
    // recreate it will throw an exception. In this case just catch the
    // exception and do nothing.
    catch (SchemaObjectExistsException $e) {
      return TRUE;
    }
    return FALSE;
  }

  /**
   * Act on an exception when cache might be stale.
   *
543
   * If the {cachetags} table does not yet exist, that's fine but if the table
544 545 546 547 548 549
   * exists and yet the query failed, then the cache is stale and the
   * exception needs to propagate.
   *
   * @param $e
   *   The exception.
   * @param string|null $table_name
550
   *   The table name, defaults to $this->bin. Can be cachetags.
551 552 553 554 555 556 557
   */
  protected function catchException(\Exception $e, $table_name = NULL) {
    if ($this->connection->schema()->tableExists($table_name ?: $this->bin)) {
      throw $e;
    }
  }

558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
  /**
   * Ensures that cache IDs have a maximum length of 255 characters.
   *
   * @param string $cid
   *   The passed in cache ID.
   *
   * @return string
   *   A cache ID that is at most 255 characters long.
   */
  protected function normalizeCid($cid) {
    // Nothing to do if the ID length is 255 characters or less.
    if (strlen($cid) <= 255) {
      return $cid;
    }
    // Return a string that uses as much as possible of the original cache ID
    // with the hash appended.
    $hash = Crypt::hashBase64($cid);
    return substr($cid, 0, 255 - strlen($hash)) . $hash;
  }

578
  /**
579
   * Defines the schema for the {cache_*} bin and {cachetags} tables.
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
   */
  public function schemaDefinition() {
    $schema['bin'] = array(
      'description' => 'Storage for the cache API.',
      'fields' => array(
        'cid' => array(
          'description' => 'Primary Key: Unique cache ID.',
          'type' => 'varchar',
          'length' => 255,
          'not null' => TRUE,
          'default' => '',
        ),
        'data' => array(
          'description' => 'A collection of data to cache.',
          'type' => 'blob',
          'not null' => FALSE,
          'size' => 'big',
        ),
        'expire' => array(
          'description' => 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.',
          'type' => 'int',
          'not null' => TRUE,
          'default' => 0,
        ),
        'created' => array(
605 606 607 608
          'description' => 'A timestamp with millisecond precision indicating when the cache entry was created.',
          'type' => 'numeric',
          'precision' => 14,
          'scale' => 3,
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
          'not null' => TRUE,
          'default' => 0,
        ),
        'serialized' => array(
          'description' => 'A flag to indicate whether content is serialized (1) or not (0).',
          'type' => 'int',
          'size' => 'small',
          'not null' => TRUE,
          'default' => 0,
        ),
        'tags' => array(
          'description' => 'Space-separated list of cache tags for this entry.',
          'type' => 'text',
          'size' => 'big',
          'not null' => FALSE,
        ),
        'checksum_invalidations' => array(
          'description' => 'The tag invalidation sum when this entry was saved.',
          'type' => 'int',
          'not null' => TRUE,
          'default' => 0,
        ),
        'checksum_deletions' => array(
          'description' => 'The tag deletion sum when this entry was saved.',
          'type' => 'int',
          'not null' => TRUE,
          'default' => 0,
        ),
      ),
      'indexes' => array(
        'expire' => array('expire'),
      ),
      'primary key' => array('cid'),
    );
643
    $schema['cachetags'] = array(
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
      'description' => 'Cache table for tracking cache tags related to the cache bin.',
      'fields' => array(
        'tag' => array(
          'description' => 'Namespace-prefixed tag string.',
          'type' => 'varchar',
          'length' => 255,
          'not null' => TRUE,
          'default' => '',
        ),
        'invalidations' => array(
          'description' => 'Number incremented when the tag is invalidated.',
          'type' => 'int',
          'not null' => TRUE,
          'default' => 0,
        ),
        'deletions' => array(
          'description' => 'Number incremented when the tag is deleted.',
          'type' => 'int',
          'not null' => TRUE,
          'default' => 0,
        ),
      ),
      'primary key' => array('tag'),
    );
    return $schema;
  }
670
}