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 {
26 * The database connection.
28 * @var \Drupal\Core\Database\Connection
30 protected $connection;
33 * The cache tags checksum provider.
35 * @var \Drupal\Core\Cache\CacheTagsChecksumInterface
37 protected $checksumProvider;
40 * Constructs a DatabaseBackend object.
42 * @param \Drupal\Core\Database\Connection $connection
43 * The database connection.
44 * @param \Drupal\Core\Cache\CacheTagsChecksumInterface $checksum_provider
45 * The cache tags checksum provider.
47 * The cache bin for which the object is created.
49 public function __construct(Connection $connection, CacheTagsChecksumInterface $checksum_provider, $bin) {
50 // All cache tables should be prefixed with 'cache_'.
51 $bin = 'cache_' . $bin;
54 $this->connection = $connection;
55 $this->checksumProvider = $checksum_provider;
61 public function get($cid, $allow_invalid = FALSE) {
63 $cache = $this->getMultiple($cids, $allow_invalid);
70 public function getMultiple(&$cids, $allow_invalid = FALSE) {
72 foreach ($cids as $cid) {
73 $cid_mapping[$this->normalizeCid($cid)] = $cid;
75 // When serving cached pages, the overhead of using ::select() was found
76 // to add around 30% overhead to the request. Since $this->bin is a
77 // variable, this means the call to ::query() here uses a concatenated
78 // string. This is highly discouraged under any other circumstances, and
79 // is used here only due to the performance overhead we would incur
80 // otherwise. When serving an uncached page, the overhead of using
81 // ::select() is a much smaller proportion of the request.
84 $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)]);
86 catch (\Exception $e) {
90 foreach ($result as $item) {
91 // Map the cache ID back to the original.
92 $item->cid = $cid_mapping[$item->cid];
93 $item = $this->prepareItem($item, $allow_invalid);
95 $cache[$item->cid] = $item;
98 $cids = array_diff($cids, array_keys($cache));
103 * Prepares a cached item.
105 * Checks that items are either permanent or did not expire, and unserializes
106 * data as appropriate.
108 * @param object $cache
109 * An item loaded from cache_get() or cache_get_multiple().
110 * @param bool $allow_invalid
111 * If FALSE, the method returns FALSE if the cache item is not valid.
113 * @return mixed|false
114 * The item with data unserialized as appropriate and a property indicating
115 * whether the item is valid, or FALSE if there is no valid item to load.
117 protected function prepareItem($cache, $allow_invalid) {
118 if (!isset($cache->data)) {
122 $cache->tags = $cache->tags ? explode(' ', $cache->tags) : [];
124 // Check expire time.
125 $cache->valid = $cache->expire == Cache::PERMANENT || $cache->expire >= REQUEST_TIME;
127 // Check if invalidateTags() has been called with any of the items's tags.
128 if (!$this->checksumProvider->isValid($cache->checksum, $cache->tags)) {
129 $cache->valid = FALSE;
132 if (!$allow_invalid && !$cache->valid) {
136 // Unserialize and return the cached data.
137 if ($cache->serialized) {
138 $cache->data = unserialize($cache->data);
147 public function set($cid, $data, $expire = Cache::PERMANENT, array $tags = []) {
160 public function setMultiple(array $items) {
163 // The bin might not yet exist.
164 $this->doSetMultiple($items);
166 catch (\Exception $e) {
167 // If there was an exception, try to create the bins.
168 if (!$try_again = $this->ensureBinExists()) {
169 // If the exception happened for other reason than the missing bin
170 // table, propagate the exception.
174 // Now that the bin has been created, try again if necessary.
176 $this->doSetMultiple($items);
181 * Stores multiple items in the persistent cache.
183 * @param array $items
184 * An array of cache items, keyed by cid.
186 * @see \Drupal\Core\Cache\CacheBackendInterface::setMultiple()
188 protected function doSetMultiple(array $items) {
191 foreach ($items as $cid => $item) {
193 'expire' => CacheBackendInterface::CACHE_PERMANENT,
197 assert('\Drupal\Component\Assertion\Inspector::assertAllStrings($item[\'tags\'])', 'Cache Tags must be strings.');
198 $item['tags'] = array_unique($item['tags']);
199 // Sort the cache tags so that they are stored consistently in the DB.
203 'cid' => $this->normalizeCid($cid),
204 'expire' => $item['expire'],
205 'created' => round(microtime(TRUE), 3),
206 'tags' => implode(' ', $item['tags']),
207 'checksum' => $this->checksumProvider->getCurrentChecksum($item['tags']),
210 if (!is_string($item['data'])) {
211 $fields['data'] = serialize($item['data']);
212 $fields['serialized'] = 1;
215 $fields['data'] = $item['data'];
216 $fields['serialized'] = 0;
221 // Use an upsert query which is atomic and optimized for multiple-row
223 $query = $this->connection
226 ->fields(['cid', 'expire', 'created', 'tags', 'checksum', 'data', 'serialized']);
227 foreach ($values as $fields) {
228 // Only pass the values since the order of $fields matches the order of
229 // the insert fields. This is a performance optimization to avoid
230 // unnecessary loops within the method.
231 $query->values(array_values($fields));
240 public function delete($cid) {
241 $this->deleteMultiple([$cid]);
247 public function deleteMultiple(array $cids) {
248 $cids = array_values(array_map([$this, 'normalizeCid'], $cids));
250 // Delete in chunks when a large array is passed.
251 foreach (array_chunk($cids, 1000) as $cids_chunk) {
252 $this->connection->delete($this->bin)
253 ->condition('cid', $cids_chunk, 'IN')
257 catch (\Exception $e) {
258 // Create the cache table, which will be empty. This fixes cases during
259 // core install where a cache table is cleared before it is set
260 // with {cache_render} and {cache_data}.
261 if (!$this->ensureBinExists()) {
262 $this->catchException($e);
270 public function deleteAll() {
272 $this->connection->truncate($this->bin)->execute();
274 catch (\Exception $e) {
275 // Create the cache table, which will be empty. This fixes cases during
276 // core install where a cache table is cleared before it is set
277 // with {cache_render} and {cache_data}.
278 if (!$this->ensureBinExists()) {
279 $this->catchException($e);
287 public function invalidate($cid) {
288 $this->invalidateMultiple([$cid]);
294 public function invalidateMultiple(array $cids) {
295 $cids = array_values(array_map([$this, 'normalizeCid'], $cids));
297 // Update in chunks when a large array is passed.
298 foreach (array_chunk($cids, 1000) as $cids_chunk) {
299 $this->connection->update($this->bin)
300 ->fields(['expire' => REQUEST_TIME - 1])
301 ->condition('cid', $cids_chunk, 'IN')
305 catch (\Exception $e) {
306 $this->catchException($e);
313 public function invalidateAll() {
315 $this->connection->update($this->bin)
316 ->fields(['expire' => REQUEST_TIME - 1])
319 catch (\Exception $e) {
320 $this->catchException($e);
327 public function garbageCollection() {
329 $this->connection->delete($this->bin)
330 ->condition('expire', Cache::PERMANENT, '<>')
331 ->condition('expire', REQUEST_TIME, '<')
334 catch (\Exception $e) {
335 // If the table does not exist, it surely does not have garbage in it.
336 // If the table exists, the next garbage collection will clean up.
337 // There is nothing to do.
344 public function removeBin() {
346 $this->connection->schema()->dropTable($this->bin);
348 catch (\Exception $e) {
349 $this->catchException($e);
354 * Check if the cache bin exists and create it if not.
356 protected function ensureBinExists() {
358 $database_schema = $this->connection->schema();
359 if (!$database_schema->tableExists($this->bin)) {
360 $schema_definition = $this->schemaDefinition();
361 $database_schema->createTable($this->bin, $schema_definition);
365 // If another process has already created the cache table, attempting to
366 // recreate it will throw an exception. In this case just catch the
367 // exception and do nothing.
368 catch (SchemaObjectExistsException $e) {
375 * Act on an exception when cache might be stale.
377 * If the table does not yet exist, that's fine, but if the table exists and
378 * yet the query failed, then the cache is stale and the exception needs to
383 * @param string|null $table_name
384 * The table name. Defaults to $this->bin.
388 protected function catchException(\Exception $e, $table_name = NULL) {
389 if ($this->connection->schema()->tableExists($table_name ?: $this->bin)) {
395 * Normalizes a cache ID in order to comply with database limitations.
398 * The passed in cache ID.
401 * An ASCII-encoded cache ID that is at most 255 characters long.
403 protected function normalizeCid($cid) {
404 // Nothing to do if the ID is a US ASCII string of 255 characters or less.
405 $cid_is_ascii = mb_check_encoding($cid, 'ASCII');
406 if (strlen($cid) <= 255 && $cid_is_ascii) {
409 // Return a string that uses as much as possible of the original cache ID
410 // with the hash appended.
411 $hash = Crypt::hashBase64($cid);
412 if (!$cid_is_ascii) {
415 return substr($cid, 0, 255 - strlen($hash)) . $hash;
419 * Defines the schema for the {cache_*} bin tables.
421 public function schemaDefinition() {
423 'description' => 'Storage for the cache API.',
426 'description' => 'Primary Key: Unique cache ID.',
427 'type' => 'varchar_ascii',
434 'description' => 'A collection of data to cache.',
440 'description' => 'A Unix timestamp indicating when the cache entry should expire, or ' . Cache::PERMANENT . ' for never.',
446 'description' => 'A timestamp with millisecond precision indicating when the cache entry was created.',
454 'description' => 'A flag to indicate whether content is serialized (1) or not (0).',
461 'description' => 'Space-separated list of cache tags for this entry.',
467 'description' => 'The tag invalidation checksum when this entry was saved.',
468 'type' => 'varchar_ascii',
474 'expire' => ['expire'],
476 'primary key' => ['cid'],