DatabaseBackend.php 14.4 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
40
41
42
43
  /**
   * The cache tags checksum provider.
   *
   * @var \Drupal\Core\Cache\CacheTagsChecksumInterface
   */
  protected $checksumProvider;

44
  /**
45
46
   * Constructs a DatabaseBackend object.
   *
47
48
   * @param \Drupal\Core\Database\Connection $connection
   *   The database connection.
49
50
   * @param \Drupal\Core\Cache\CacheTagsChecksumInterface $checksum_provider
   *   The cache tags checksum provider.
51
52
   * @param string $bin
   *   The cache bin for which the object is created.
53
   */
54
  public function __construct(Connection $connection, CacheTagsChecksumInterface $checksum_provider, $bin) {
55
56
57
    // All cache tables should be prefixed with 'cache_'.
    $bin = 'cache_' . $bin;

58
    $this->bin = $bin;
59
    $this->connection = $connection;
60
    $this->checksumProvider = $checksum_provider;
61
62
63
  }

  /**
64
   * Implements Drupal\Core\Cache\CacheBackendInterface::get().
65
   */
66
  public function get($cid, $allow_invalid = FALSE) {
67
    $cids = array($cid);
68
    $cache = $this->getMultiple($cids, $allow_invalid);
69
70
71
72
    return reset($cache);
  }

  /**
73
   * Implements Drupal\Core\Cache\CacheBackendInterface::getMultiple().
74
   */
75
  public function getMultiple(&$cids, $allow_invalid = FALSE) {
76
77
78
79
    $cid_mapping = array();
    foreach ($cids as $cid) {
      $cid_mapping[$this->normalizeCid($cid)] = $cid;
    }
80
81
82
83
84
85
86
    // 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.
87
88
    $result = array();
    try {
89
      $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', array(':cids[]' => array_keys($cid_mapping)));
90
91
92
93
    }
    catch (\Exception $e) {
      // Nothing to do.
    }
94
95
    $cache = array();
    foreach ($result as $item) {
96
97
      // Map the cache ID back to the original.
      $item->cid = $cid_mapping[$item->cid];
98
99
100
      $item = $this->prepareItem($item, $allow_invalid);
      if ($item) {
        $cache[$item->cid] = $item;
101
102
      }
    }
103
104
    $cids = array_diff($cids, array_keys($cache));
    return $cache;
105
106
107
108
109
110
111
112
  }

  /**
   * Prepares a cached item.
   *
   * Checks that items are either permanent or did not expire, and unserializes
   * data as appropriate.
   *
113
   * @param object $cache
114
   *   An item loaded from cache_get() or cache_get_multiple().
115
116
   * @param bool $allow_invalid
   *   If FALSE, the method returns FALSE if the cache item is not valid.
117
   *
118
119
120
   * @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.
121
   */
122
  protected function prepareItem($cache, $allow_invalid) {
123
124
125
126
    if (!isset($cache->data)) {
      return FALSE;
    }

127
128
129
    $cache->tags = $cache->tags ? explode(' ', $cache->tags) : array();

    // Check expire time.
130
    $cache->valid = $cache->expire == Cache::PERMANENT || $cache->expire >= REQUEST_TIME;
131

132
133
    // Check if invalidateTags() has been called with any of the items's tags.
    if (!$this->checksumProvider->isValid($cache->checksum, $cache->tags)) {
134
135
136
137
138
      $cache->valid = FALSE;
    }

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

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

    return $cache;
  }

  /**
150
   * Implements Drupal\Core\Cache\CacheBackendInterface::set().
151
   */
152
  public function set($cid, $data, $expire = Cache::PERMANENT, array $tags = array()) {
153
154
155
156
    Cache::validateTags($tags);
    $tags = array_unique($tags);
    // Sort the cache tags so that they are stored consistently in the database.
    sort($tags);
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
    $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) {
180
    $fields = array(
181
      'created' => round(microtime(TRUE), 3),
182
      'expire' => $expire,
183
      'tags' => implode(' ', $tags),
184
      'checksum' => $this->checksumProvider->getCurrentChecksum($tags),
185
186
187
188
    );
    if (!is_string($data)) {
      $fields['data'] = serialize($data);
      $fields['serialized'] = 1;
189
    }
190
191
192
    else {
      $fields['data'] = $data;
      $fields['serialized'] = 0;
193
    }
194

195
    $this->connection->merge($this->bin)
196
      ->key('cid', $this->normalizeCid($cid))
197
198
      ->fields($fields)
      ->execute();
199
200
  }

201
202
203
204
205
206
207
208
209
  /**
   * {@inheritdoc}
   */
  public function setMultiple(array $items) {
    // Use a transaction so that the database can write the changes in a single
    // commit.
    $transaction = $this->connection->startTransaction();

    try {
210
      // Delete all items first so we can do one insert. Rather than multiple
211
212
213
214
215
      // merge queries.
      $this->deleteMultiple(array_keys($items));

      $query = $this->connection
        ->insert($this->bin)
216
        ->fields(array('cid', 'data', 'expire', 'created', 'serialized', 'tags', 'checksum'));
217
218
219
220
221
222
223

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

224
225
226
227
        Cache::validateTags($item['tags']);
        $item['tags'] = array_unique($item['tags']);
        // Sort the cache tags so that they are stored consistently in the DB.
        sort($item['tags']);
228
229
230
231

        $fields = array(
          'cid' => $cid,
          'expire' => $item['expire'],
232
          'created' => round(microtime(TRUE), 3),
233
          'tags' => implode(' ', $item['tags']),
234
          'checksum' => $this->checksumProvider->getCurrentChecksum($item['tags']),
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
        );

        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;
    }
  }

258
  /**
259
   * Implements Drupal\Core\Cache\CacheBackendInterface::delete().
260
   */
261
  public function delete($cid) {
262
    $this->deleteMultiple(array($cid));
263
264
265
  }

  /**
266
   * Implements Drupal\Core\Cache\CacheBackendInterface::deleteMultiple().
267
   */
268
  public function deleteMultiple(array $cids) {
269
    $cids = array_values(array_map(array($this, 'normalizeCid'), $cids));
270
271
    try {
      // Delete in chunks when a large array is passed.
272
      foreach (array_chunk($cids, 1000) as $cids_chunk) {
273
        $this->connection->delete($this->bin)
274
          ->condition('cid', $cids_chunk, 'IN')
275
276
277
278
          ->execute();
      }
    }
    catch (\Exception $e) {
279
280
      // Create the cache table, which will be empty. This fixes cases during
      // core install where a cache table is cleared before it is set
281
      // with {cache_render} and {cache_data}.
282
283
284
      if (!$this->ensureBinExists()) {
        $this->catchException($e);
      }
285
286
287
    }
  }

288
289
  /**
   * Implements Drupal\Core\Cache\CacheBackendInterface::deleteAll().
290
   */
291
  public function deleteAll() {
292
293
294
295
    try {
      $this->connection->truncate($this->bin)->execute();
    }
    catch (\Exception $e) {
296
297
      // Create the cache table, which will be empty. This fixes cases during
      // core install where a cache table is cleared before it is set
298
      // with {cache_render} and {cache_data}.
299
300
301
      if (!$this->ensureBinExists()) {
        $this->catchException($e);
      }
302
    }
303
304
305
  }

  /**
306
   * Implements Drupal\Core\Cache\CacheBackendInterface::invalidate().
307
   */
308
309
  public function invalidate($cid) {
    $this->invalidateMultiple(array($cid));
310
311
  }

312
  /**
313
   * Implements Drupal\Core\Cache\CacheBackendInterface::invalidateMultiple().
314
315
   */
  public function invalidateMultiple(array $cids) {
316
    $cids = array_values(array_map(array($this, 'normalizeCid'), $cids));
317
318
    try {
      // Update in chunks when a large array is passed.
319
      foreach (array_chunk($cids, 1000) as $cids_chunk) {
320
321
        $this->connection->update($this->bin)
          ->fields(array('expire' => REQUEST_TIME - 1))
322
          ->condition('cid', $cids_chunk, 'IN')
323
324
325
326
327
          ->execute();
      }
    }
    catch (\Exception $e) {
      $this->catchException($e);
328
329
330
331
332
    }
  }

  /**
   * Implements Drupal\Core\Cache\CacheBackendInterface::invalidateAll().
333
   */
334
  public function invalidateAll() {
335
336
337
338
339
340
341
342
    try {
      $this->connection->update($this->bin)
        ->fields(array('expire' => REQUEST_TIME - 1))
        ->execute();
    }
    catch (\Exception $e) {
      $this->catchException($e);
    }
343
344
345
  }

  /**
346
347
348
   * Implements Drupal\Core\Cache\CacheBackendInterface::garbageCollection().
   */
  public function garbageCollection() {
349
    try {
350
      $this->connection->delete($this->bin)
351
        ->condition('expire', Cache::PERMANENT, '<>')
352
353
354
355
356
357
358
359
        ->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.
    }
360
361
  }

362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
  /**
   * {@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();
382
        $database_schema->createTable($this->bin, $schema_definition);
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
        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.
   *
398
399
400
   * 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.
401
402
403
404
   *
   * @param $e
   *   The exception.
   * @param string|null $table_name
405
406
407
   *   The table name. Defaults to $this->bin.
   *
   * @throws \Exception
408
409
410
411
412
413
414
   */
  protected function catchException(\Exception $e, $table_name = NULL) {
    if ($this->connection->schema()->tableExists($table_name ?: $this->bin)) {
      throw $e;
    }
  }

415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
  /**
   * 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;
  }

435
  /**
436
   * Defines the schema for the {cache_*} bin tables.
437
438
   */
  public function schemaDefinition() {
439
    $schema = array(
440
441
442
443
444
445
446
447
      'description' => 'Storage for the cache API.',
      'fields' => array(
        'cid' => array(
          'description' => 'Primary Key: Unique cache ID.',
          'type' => 'varchar',
          'length' => 255,
          'not null' => TRUE,
          'default' => '',
448
          'binary' => TRUE,
449
450
451
452
453
454
455
456
        ),
        'data' => array(
          'description' => 'A collection of data to cache.',
          'type' => 'blob',
          'not null' => FALSE,
          'size' => 'big',
        ),
        'expire' => array(
457
          'description' => 'A Unix timestamp indicating when the cache entry should expire, or ' . Cache::PERMANENT . ' for never.',
458
459
460
461
462
          'type' => 'int',
          'not null' => TRUE,
          'default' => 0,
        ),
        'created' => array(
463
464
465
466
          'description' => 'A timestamp with millisecond precision indicating when the cache entry was created.',
          'type' => 'numeric',
          'precision' => 14,
          'scale' => 3,
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
          '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,
        ),
483
484
485
486
        'checksum' => array(
          'description' => 'The tag invalidation checksum when this entry was saved.',
          'type' => 'varchar',
          'length' => 255,
487
488
489
490
491
492
493
494
495
496
          'not null' => TRUE,
        ),
      ),
      'indexes' => array(
        'expire' => array('expire'),
      ),
      'primary key' => array('cid'),
    );
    return $schema;
  }
497
}