summaryrefslogtreecommitdiffstatshomepage
path: root/core/lib/Drupal/Core/Cache/DatabaseBackend.php
blob: d5c9150dd389564cab4866408f5c608d093e691f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
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
256
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
<?php

namespace Drupal\Core\Cache;

use Drupal\Component\Serialization\ObjectAwareSerializationInterface;
use Drupal\Component\Assertion\Inspector;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Component\Utility\Crypt;
use Drupal\Core\Database\Connection;
use Drupal\Core\Database\DatabaseException;

/**
 * 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.
 *
 * @ingroup cache
 */
class DatabaseBackend implements CacheBackendInterface {

  /**
   * The default maximum number of rows that this cache bin table can store.
   *
   * This maximum is introduced to ensure that the database is not filled with
   * hundred of thousand of cache entries with gigabytes in size.
   *
   * Read about how to change it in the @link cache Cache API topic. @endlink
   */
  const DEFAULT_MAX_ROWS = 5000;

  /**
   * Indicates that an infinite number of rows is allowed for the cache backend.
   */
  const MAXIMUM_NONE = -1;

  /**
   * The chunk size for inserting cache entities.
   */
  const MAX_ITEMS_PER_CACHE_SET = 100;

  /**
   * The maximum number of rows that this cache bin table is allowed to store.
   *
   * @var int
   *
   * @see ::MAXIMUM_NONE
   */
  protected $maxRows;

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


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

  /**
   * The cache tags checksum provider.
   *
   * @var \Drupal\Core\Cache\CacheTagsChecksumInterface
   */
  protected $checksumProvider;

  /**
   * Constructs a DatabaseBackend object.
   *
   * @param \Drupal\Core\Database\Connection $connection
   *   The database connection.
   * @param \Drupal\Core\Cache\CacheTagsChecksumInterface $checksum_provider
   *   The cache tags checksum provider.
   * @param string $bin
   *   The cache bin for which the object is created.
   * @param \Drupal\Component\Serialization\ObjectAwareSerializationInterface|int|string|null $serializer
   *   (optional) The serializer to use.
   * @param \Drupal\Component\Datetime\TimeInterface|int|string|null $time
   *   The time service.
   * @param int $max_rows
   *   (optional) The maximum number of rows that are allowed in this cache bin
   *   table.
   */
  public function __construct(
    Connection $connection,
    CacheTagsChecksumInterface $checksum_provider,
    $bin,
    protected ObjectAwareSerializationInterface $serializer,
    protected TimeInterface $time,
    $max_rows = NULL,
  ) {
    // All cache tables should be prefixed with 'cache_'.
    $bin = 'cache_' . $bin;

    $this->bin = $bin;
    $this->connection = $connection;
    $this->checksumProvider = $checksum_provider;
    $this->maxRows = $max_rows ?? static::DEFAULT_MAX_ROWS;
  }

  /**
   * {@inheritdoc}
   */
  public function get($cid, $allow_invalid = FALSE) {
    $cids = [$cid];
    $cache = $this->getMultiple($cids, $allow_invalid);
    return reset($cache);
  }

  /**
   * {@inheritdoc}
   */
  public function getMultiple(&$cids, $allow_invalid = FALSE) {
    $cid_mapping = [];
    foreach ($cids as $cid) {
      $cid_mapping[$this->normalizeCid($cid)] = $cid;
    }
    // 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.
    $result = [];
    try {
      $result = $this->connection->query('SELECT [cid], [data], [created], [expire], [serialized], [tags], [checksum] FROM {' . $this->connection->escapeTable($this->bin) . '} WHERE [cid] IN ( :cids[] ) ORDER BY [cid]', [':cids[]' => array_keys($cid_mapping)])->fetchAll();
    }
    catch (\Exception) {
      // Nothing to do.
    }
    // Before checking the validity of each item individually, register the
    // cache tags for all returned cache items for preloading, this allows the
    // cache tag service to optimize cache tag lookups.
    if ($this->checksumProvider instanceof CacheTagsChecksumPreloadInterface) {
      $tags_for_preload = [];
      foreach ($result as $item) {
        if ($item->tags) {
          $tags_for_preload[] = explode(' ', $item->tags);
        }
      }
      $this->checksumProvider->registerCacheTagsForPreload(array_merge(...$tags_for_preload));
    }
    $cache = [];
    foreach ($result as $item) {
      // Map the cache ID back to the original.
      $item->cid = $cid_mapping[$item->cid];
      $item = $this->prepareItem($item, $allow_invalid);
      if ($item) {
        $cache[$item->cid] = $item;
      }
    }
    $cids = array_diff($cids, array_keys($cache));
    return $cache;
  }

  /**
   * Prepares a cached item.
   *
   * Checks that items are either permanent or did not expire, and unserializes
   * data as appropriate.
   *
   * @param object $cache
   *   An item loaded from self::get() or self::getMultiple().
   * @param bool $allow_invalid
   *   If FALSE, the method returns FALSE if the cache item is not valid.
   *
   * @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.
   */
  protected function prepareItem($cache, $allow_invalid) {
    if (!isset($cache->data)) {
      return FALSE;
    }

    $cache->tags = $cache->tags ? explode(' ', $cache->tags) : [];

    // Check expire time.
    $cache->valid = $cache->expire == Cache::PERMANENT || $cache->expire >= $this->time->getRequestTime();

    // Check if invalidateTags() has been called with any of the item's tags.
    if (!$this->checksumProvider->isValid($cache->checksum, $cache->tags)) {
      $cache->valid = FALSE;
    }

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

    // Unserialize and return the cached data.
    if ($cache->serialized) {
      $cache->data = $this->serializer->decode($cache->data);
    }

    return $cache;
  }

  /**
   * {@inheritdoc}
   */
  public function set($cid, $data, $expire = Cache::PERMANENT, array $tags = []) {
    $this->setMultiple([
      $cid => [
        'data' => $data,
        'expire' => $expire,
        'tags' => $tags,
      ],
    ]);
  }

  /**
   * {@inheritdoc}
   */
  public function setMultiple(array $items) {
    $try_again = FALSE;
    try {
      // The bin might not yet exist.
      $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) {
      $this->doSetMultiple($items);
    }
  }

  /**
   * Stores multiple items in the persistent cache.
   *
   * @param array $items
   *   An array of cache items, keyed by cid.
   *
   * @see \Drupal\Core\Cache\CacheBackendInterface::setMultiple()
   */
  protected function doSetMultiple(array $items) {
    // Chunk the items as the database might not be able to receive thousands
    // of items in a single query.
    $chunks = array_chunk($items, self::MAX_ITEMS_PER_CACHE_SET, TRUE);

    foreach ($chunks as $chunk_items) {
      $values = [];

      foreach ($chunk_items as $cid => $item) {
        $item += [
          'expire' => CacheBackendInterface::CACHE_PERMANENT,
          'tags' => [],
        ];

        assert(Inspector::assertAllStrings($item['tags']), 'Cache Tags must be strings.');
        $item['tags'] = array_unique($item['tags']);
        // Sort the cache tags so that they are stored consistently in the DB.
        sort($item['tags']);

        $fields = [
          'cid' => $this->normalizeCid($cid),
          'expire' => $item['expire'],
          'created' => round(microtime(TRUE), 3),
          'tags' => implode(' ', $item['tags']),
          'checksum' => $this->checksumProvider->getCurrentChecksum($item['tags']),
        ];

        // Avoid useless writes.
        if ($fields['checksum'] === CacheTagsChecksumInterface::INVALID_CHECKSUM_WHILE_IN_TRANSACTION) {
          continue;
        }

        if (!is_string($item['data'])) {
          $fields['data'] = $this->serializer->encode($item['data']);
          $fields['serialized'] = 1;
        }
        else {
          $fields['data'] = $item['data'];
          $fields['serialized'] = 0;
        }
        $values[] = $fields;
      }

      // If all $items were useless writes, we may end up with zero writes.
      if (count($values) === 0) {
        return;
      }

      // Use an upsert query which is atomic and optimized for multiple-row
      // merges.
      $query = $this->connection
        ->upsert($this->bin)
        ->key('cid')
        ->fields(['cid', 'expire', 'created', 'tags', 'checksum', 'data', 'serialized']);
      foreach ($values as $fields) {
        // Only pass the values since the order of $fields matches the order of
        // the insert fields. This is a performance optimization to avoid
        // unnecessary loops within the method.
        $query->values(array_values($fields));
      }

      $query->execute();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function delete($cid) {
    $this->deleteMultiple([$cid]);
  }

  /**
   * {@inheritdoc}
   */
  public function deleteMultiple(array $cids) {
    $cids = array_values(array_map([$this, 'normalizeCid'], $cids));
    try {
      // Delete in chunks when a large array is passed.
      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}
   */
  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}.
      if (!$this->ensureBinExists()) {
        $this->catchException($e);
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function invalidate($cid) {
    $this->invalidateMultiple([$cid]);
  }

  /**
   * {@inheritdoc}
   */
  public function invalidateMultiple(array $cids) {
    $cids = array_values(array_map([$this, 'normalizeCid'], $cids));
    try {
      // Update in chunks when a large array is passed.
      $requestTime = $this->time->getRequestTime();
      foreach (array_chunk($cids, 1000) as $cids_chunk) {
        $this->connection->update($this->bin)
          ->fields(['expire' => $requestTime - 1])
          ->condition('cid', $cids_chunk, 'IN')
          ->execute();
      }
    }
    catch (\Exception $e) {
      $this->catchException($e);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function invalidateAll() {
    @trigger_error("CacheBackendInterface::invalidateAll() is deprecated in drupal:11.2.0 and is removed from drupal:12.0.0. Use CacheBackendInterface::deleteAll() or cache tag invalidation instead. See https://www.drupal.org/node/3500622", E_USER_DEPRECATED);
    try {
      $this->connection->update($this->bin)
        ->fields(['expire' => $this->time->getRequestTime() - 1])
        ->execute();
    }
    catch (\Exception $e) {
      $this->catchException($e);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function garbageCollection() {
    try {
      // Bounded size cache bin, using FIFO.
      if ($this->maxRows !== static::MAXIMUM_NONE) {
        $first_invalid_create_time = $this->connection->select($this->bin)
          ->fields($this->bin, ['created'])
          ->orderBy("{$this->bin}.created", 'DESC')
          ->range($this->maxRows, 1)
          ->execute()
          ->fetchField();

        if ($first_invalid_create_time) {
          $this->connection->delete($this->bin)
            ->condition('created', $first_invalid_create_time, '<=')
            ->execute();
        }
      }

      $this->connection->delete($this->bin)
        ->condition('expire', Cache::PERMANENT, '<>')
        ->condition('expire', $this->time->getRequestTime(), '<')
        ->execute();
    }
    catch (\Exception) {
      // 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.
    }
  }

  /**
   * {@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);
        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 (DatabaseException) {
      return TRUE;
    }
    return FALSE;
  }

  /**
   * Act on an exception when cache might be stale.
   *
   * If the table does not yet exist, that's fine, but if the table exists and
   * yet the query failed, then the cache is stale and the exception needs to
   * propagate.
   *
   * @param \Exception $e
   *   The exception.
   * @param string|null $table_name
   *   The table name. Defaults to $this->bin.
   *
   * @throws \Exception
   */
  protected function catchException(\Exception $e, $table_name = NULL) {
    if ($this->connection->schema()->tableExists($table_name ?: $this->bin)) {
      throw $e;
    }
  }

  /**
   * Normalizes a cache ID in order to comply with database limitations.
   *
   * @param string $cid
   *   The passed in cache ID.
   *
   * @return string
   *   An ASCII-encoded cache ID that is at most 255 characters long.
   */
  protected function normalizeCid($cid) {
    // Nothing to do if the ID is a US ASCII string of 255 characters or less.
    // Additionally check for trailing spaces in the cache ID because MySQL
    // may or may not take these into account when making comparisons.
    // @see https://dev.mysql.com/doc/refman/9.0/en/char.html
    $cid_is_ascii = mb_check_encoding($cid, 'ASCII');
    if (strlen($cid) <= 255 && $cid_is_ascii && !str_ends_with($cid, ' ')) {
      return $cid;
    }
    // Return a string that uses as much as possible of the original cache ID
    // with the hash appended.
    $hash = Crypt::hashBase64($cid);
    if (!$cid_is_ascii) {
      return $hash;
    }
    return substr($cid, 0, 255 - strlen($hash)) . $hash;
  }

  /**
   * Defines the schema for the {cache_*} bin tables.
   *
   * @internal
   */
  public function schemaDefinition() {
    $schema = [
      'description' => 'Storage for the cache API.',
      'fields' => [
        'cid' => [
          'description' => 'Primary Key: Unique cache ID.',
          'type' => 'varchar_ascii',
          'length' => 255,
          'not null' => TRUE,
          'default' => '',
          'binary' => TRUE,
        ],
        'data' => [
          'description' => 'A collection of data to cache.',
          'type' => 'blob',
          'not null' => FALSE,
          'size' => 'big',
        ],
        'expire' => [
          'description' => 'A Unix timestamp indicating when the cache entry should expire, or ' . Cache::PERMANENT . ' for never.',
          'type' => 'int',
          'not null' => TRUE,
          'default' => 0,
          'size' => 'big',
        ],
        'created' => [
          'description' => 'A timestamp with millisecond precision indicating when the cache entry was created.',
          'type' => 'numeric',
          'precision' => 14,
          'scale' => 3,
          'not null' => TRUE,
          'default' => 0,
        ],
        'serialized' => [
          'description' => 'A flag to indicate whether content is serialized (1) or not (0).',
          'type' => 'int',
          'size' => 'small',
          'not null' => TRUE,
          'default' => 0,
        ],
        'tags' => [
          'description' => 'Space-separated list of cache tags for this entry.',
          'type' => 'text',
          'size' => 'big',
          'not null' => FALSE,
        ],
        'checksum' => [
          'description' => 'The tag invalidation checksum when this entry was saved.',
          'type' => 'varchar_ascii',
          'length' => 255,
          'not null' => TRUE,
        ],
      ],
      'indexes' => [
        'expire' => ['expire'],
        'created' => ['created'],
      ],
      'primary key' => ['cid'],
    ];
    return $schema;
  }

  /**
   * Gets the maximum number of rows for this cache bin table.
   *
   * @return int
   *   The maximum number of rows that this cache bin table is allowed to store.
   */
  public function getMaxRows() {
    return $this->maxRows;
  }

}