3 namespace Drupal\Core\Cache;
5 use Drupal\Component\Utility\Crypt;
6 use Drupal\Core\Database\Connection;
7 use Drupal\Core\Database\SchemaObjectExistsException;
10 * Defines a default cache implementation.
12 * This is Drupal's default cache implementation. It uses the database to store
13 * cached data. Each cache bin corresponds to a database table by the same name.
17 class DatabaseBackend implements CacheBackendInterface {
20 * The default maximum number of rows that this cache bin table can store.
22 * This maximum is introduced to ensure that the database is not filled with
23 * hundred of thousand of cache entries with gigabytes in size.
25 * Read about how to change it in the @link cache Cache API topic. @endlink
27 const DEFAULT_MAX_ROWS = 5000;
30 * -1 means infinite allows numbers of rows for the cache backend.
32 const MAXIMUM_NONE = -1;
35 * The maximum number of rows that this cache bin table is allowed to store.
50 * The database connection.
52 * @var \Drupal\Core\Database\Connection
54 protected $connection;
57 * The cache tags checksum provider.
59 * @var \Drupal\Core\Cache\CacheTagsChecksumInterface
61 protected $checksumProvider;
64 * Constructs a DatabaseBackend object.
66 * @param \Drupal\Core\Database\Connection $connection
67 * The database connection.
68 * @param \Drupal\Core\Cache\CacheTagsChecksumInterface $checksum_provider
69 * The cache tags checksum provider.
71 * The cache bin for which the object is created.
72 * @param int $max_rows
73 * (optional) The maximum number of rows that are allowed in this cache bin
76 public function __construct(Connection $connection, CacheTagsChecksumInterface $checksum_provider, $bin, $max_rows = NULL) {
77 // All cache tables should be prefixed with 'cache_'.
78 $bin = 'cache_' . $bin;
81 $this->connection = $connection;
82 $this->checksumProvider = $checksum_provider;
83 $this->maxRows = $max_rows === NULL ? static::DEFAULT_MAX_ROWS : $max_rows;
89 public function get($cid, $allow_invalid = FALSE) {
91 $cache = $this->getMultiple($cids, $allow_invalid);
98 public function getMultiple(&$cids, $allow_invalid = FALSE) {
100 foreach ($cids as $cid) {
101 $cid_mapping[$this->normalizeCid($cid)] = $cid;
103 // When serving cached pages, the overhead of using ::select() was found
104 // to add around 30% overhead to the request. Since $this->bin is a
105 // variable, this means the call to ::query() here uses a concatenated
106 // string. This is highly discouraged under any other circumstances, and
107 // is used here only due to the performance overhead we would incur
108 // otherwise. When serving an uncached page, the overhead of using
109 // ::select() is a much smaller proportion of the request.
112 $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)]);
114 catch (\Exception $e) {
118 foreach ($result as $item) {
119 // Map the cache ID back to the original.
120 $item->cid = $cid_mapping[$item->cid];
121 $item = $this->prepareItem($item, $allow_invalid);
123 $cache[$item->cid] = $item;
126 $cids = array_diff($cids, array_keys($cache));
131 * Prepares a cached item.
133 * Checks that items are either permanent or did not expire, and unserializes
134 * data as appropriate.
136 * @param object $cache
137 * An item loaded from cache_get() or cache_get_multiple().
138 * @param bool $allow_invalid
139 * If FALSE, the method returns FALSE if the cache item is not valid.
141 * @return mixed|false
142 * The item with data unserialized as appropriate and a property indicating
143 * whether the item is valid, or FALSE if there is no valid item to load.
145 protected function prepareItem($cache, $allow_invalid) {
146 if (!isset($cache->data)) {
150 $cache->tags = $cache->tags ? explode(' ', $cache->tags) : [];
152 // Check expire time.
153 $cache->valid = $cache->expire == Cache::PERMANENT || $cache->expire >= REQUEST_TIME;
155 // Check if invalidateTags() has been called with any of the items's tags.
156 if (!$this->checksumProvider->isValid($cache->checksum, $cache->tags)) {
157 $cache->valid = FALSE;
160 if (!$allow_invalid && !$cache->valid) {
164 // Unserialize and return the cached data.
165 if ($cache->serialized) {
166 $cache->data = unserialize($cache->data);
175 public function set($cid, $data, $expire = Cache::PERMANENT, array $tags = []) {
188 public function setMultiple(array $items) {
191 // The bin might not yet exist.
192 $this->doSetMultiple($items);
194 catch (\Exception $e) {
195 // If there was an exception, try to create the bins.
196 if (!$try_again = $this->ensureBinExists()) {
197 // If the exception happened for other reason than the missing bin
198 // table, propagate the exception.
202 // Now that the bin has been created, try again if necessary.
204 $this->doSetMultiple($items);
209 * Stores multiple items in the persistent cache.
211 * @param array $items
212 * An array of cache items, keyed by cid.
214 * @see \Drupal\Core\Cache\CacheBackendInterface::setMultiple()
216 protected function doSetMultiple(array $items) {
219 foreach ($items as $cid => $item) {
221 'expire' => CacheBackendInterface::CACHE_PERMANENT,
225 assert('\Drupal\Component\Assertion\Inspector::assertAllStrings($item[\'tags\'])', 'Cache Tags must be strings.');
226 $item['tags'] = array_unique($item['tags']);
227 // Sort the cache tags so that they are stored consistently in the DB.
231 'cid' => $this->normalizeCid($cid),
232 'expire' => $item['expire'],
233 'created' => round(microtime(TRUE), 3),
234 'tags' => implode(' ', $item['tags']),
235 'checksum' => $this->checksumProvider->getCurrentChecksum($item['tags']),
238 if (!is_string($item['data'])) {
239 $fields['data'] = serialize($item['data']);
240 $fields['serialized'] = 1;
243 $fields['data'] = $item['data'];
244 $fields['serialized'] = 0;
249 // Use an upsert query which is atomic and optimized for multiple-row
251 $query = $this->connection
254 ->fields(['cid', 'expire', 'created', 'tags', 'checksum', 'data', 'serialized']);
255 foreach ($values as $fields) {
256 // Only pass the values since the order of $fields matches the order of
257 // the insert fields. This is a performance optimization to avoid
258 // unnecessary loops within the method.
259 $query->values(array_values($fields));
268 public function delete($cid) {
269 $this->deleteMultiple([$cid]);
275 public function deleteMultiple(array $cids) {
276 $cids = array_values(array_map([$this, 'normalizeCid'], $cids));
278 // Delete in chunks when a large array is passed.
279 foreach (array_chunk($cids, 1000) as $cids_chunk) {
280 $this->connection->delete($this->bin)
281 ->condition('cid', $cids_chunk, 'IN')
285 catch (\Exception $e) {
286 // Create the cache table, which will be empty. This fixes cases during
287 // core install where a cache table is cleared before it is set
288 // with {cache_render} and {cache_data}.
289 if (!$this->ensureBinExists()) {
290 $this->catchException($e);
298 public function deleteAll() {
300 $this->connection->truncate($this->bin)->execute();
302 catch (\Exception $e) {
303 // Create the cache table, which will be empty. This fixes cases during
304 // core install where a cache table is cleared before it is set
305 // with {cache_render} and {cache_data}.
306 if (!$this->ensureBinExists()) {
307 $this->catchException($e);
315 public function invalidate($cid) {
316 $this->invalidateMultiple([$cid]);
322 public function invalidateMultiple(array $cids) {
323 $cids = array_values(array_map([$this, 'normalizeCid'], $cids));
325 // Update in chunks when a large array is passed.
326 foreach (array_chunk($cids, 1000) as $cids_chunk) {
327 $this->connection->update($this->bin)
328 ->fields(['expire' => REQUEST_TIME - 1])
329 ->condition('cid', $cids_chunk, 'IN')
333 catch (\Exception $e) {
334 $this->catchException($e);
341 public function invalidateAll() {
343 $this->connection->update($this->bin)
344 ->fields(['expire' => REQUEST_TIME - 1])
347 catch (\Exception $e) {
348 $this->catchException($e);
355 public function garbageCollection() {
357 // Bounded size cache bin, using FIFO.
358 if ($this->maxRows !== static::MAXIMUM_NONE) {
359 $first_invalid_create_time = $this->connection->select($this->bin)
360 ->fields($this->bin, ['created'])
361 ->orderBy("{$this->bin}.created", 'DESC')
362 ->range($this->maxRows, $this->maxRows + 1)
366 if ($first_invalid_create_time) {
367 $this->connection->delete($this->bin)
368 ->condition('created', $first_invalid_create_time, '<=')
373 $this->connection->delete($this->bin)
374 ->condition('expire', Cache::PERMANENT, '<>')
375 ->condition('expire', REQUEST_TIME, '<')
378 catch (\Exception $e) {
379 // If the table does not exist, it surely does not have garbage in it.
380 // If the table exists, the next garbage collection will clean up.
381 // There is nothing to do.
388 public function removeBin() {
390 $this->connection->schema()->dropTable($this->bin);
392 catch (\Exception $e) {
393 $this->catchException($e);
398 * Check if the cache bin exists and create it if not.
400 protected function ensureBinExists() {
402 $database_schema = $this->connection->schema();
403 if (!$database_schema->tableExists($this->bin)) {
404 $schema_definition = $this->schemaDefinition();
405 $database_schema->createTable($this->bin, $schema_definition);
409 // If another process has already created the cache table, attempting to
410 // recreate it will throw an exception. In this case just catch the
411 // exception and do nothing.
412 catch (SchemaObjectExistsException $e) {
419 * Act on an exception when cache might be stale.
421 * If the table does not yet exist, that's fine, but if the table exists and
422 * yet the query failed, then the cache is stale and the exception needs to
427 * @param string|null $table_name
428 * The table name. Defaults to $this->bin.
432 protected function catchException(\Exception $e, $table_name = NULL) {
433 if ($this->connection->schema()->tableExists($table_name ?: $this->bin)) {
439 * Normalizes a cache ID in order to comply with database limitations.
442 * The passed in cache ID.
445 * An ASCII-encoded cache ID that is at most 255 characters long.
447 protected function normalizeCid($cid) {
448 // Nothing to do if the ID is a US ASCII string of 255 characters or less.
449 $cid_is_ascii = mb_check_encoding($cid, 'ASCII');
450 if (strlen($cid) <= 255 && $cid_is_ascii) {
453 // Return a string that uses as much as possible of the original cache ID
454 // with the hash appended.
455 $hash = Crypt::hashBase64($cid);
456 if (!$cid_is_ascii) {
459 return substr($cid, 0, 255 - strlen($hash)) . $hash;
463 * Defines the schema for the {cache_*} bin tables.
467 public function schemaDefinition() {
469 'description' => 'Storage for the cache API.',
472 'description' => 'Primary Key: Unique cache ID.',
473 'type' => 'varchar_ascii',
480 'description' => 'A collection of data to cache.',
486 'description' => 'A Unix timestamp indicating when the cache entry should expire, or ' . Cache::PERMANENT . ' for never.',
492 'description' => 'A timestamp with millisecond precision indicating when the cache entry was created.',
500 'description' => 'A flag to indicate whether content is serialized (1) or not (0).',
507 'description' => 'Space-separated list of cache tags for this entry.',
513 'description' => 'The tag invalidation checksum when this entry was saved.',
514 'type' => 'varchar_ascii',
520 'expire' => ['expire'],
521 'created' => ['created'],
523 'primary key' => ['cid'],
529 * The maximum number of rows that this cache bin table is allowed to store.
533 public function getMaxRows() {
534 return $this->maxRows;