Database.php 20.1 KB
Newer Older
Ketan's avatar
Ketan committed
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 592
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * Tables declaration:
 *
 * CREATE TABLE IF NOT EXISTS `cache` (
 *      `id` VARCHAR(255) NOT NULL,
 *      `data` mediumblob,
 *      `create_time` int(11),
 *      `update_time` int(11),
 *      `expire_time` int(11),
 *      PRIMARY KEY  (`id`),
 *      KEY `IDX_EXPIRE_TIME` (`expire_time`)
 * )ENGINE=InnoDB DEFAULT CHARSET=utf8;
 *
 * CREATE TABLE IF NOT EXISTS `cache_tag` (
 *      `tag` VARCHAR(255) NOT NULL,
 *      `cache_id` VARCHAR(255) NOT NULL,
 *      KEY `IDX_TAG` (`tag`),
 *      KEY `IDX_CACHE_ID` (`cache_id`),
 *      CONSTRAINT `FK_CORE_CACHE_TAG` FOREIGN KEY (`cache_id`)
 *      REFERENCES `cache` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
 * ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 */

namespace Magento\Framework\Cache\Backend;

/**
 * Database cache backend.
 */
class Database extends \Zend_Cache_Backend implements \Zend_Cache_Backend_ExtendedInterface
{
    /**
     * Available options
     *
     * @var array available options
     */
    protected $_options = [
        'adapter' => '',
        'adapter_callback' => '',
        'data_table' => '',
        'data_table_callback' => '',
        'tags_table' => '',
        'tags_table_callback' => '',
        'store_data' => true,
        'infinite_loop_flag' => false,
    ];

    /**
     * @var \Magento\Framework\DB\Adapter\AdapterInterface
     */
    protected $_connection = null;

    /**
     * Constructor
     *
     * @param array $options associative array of options
     */
    public function __construct($options = [])
    {
        parent::__construct($options);
        if (empty($this->_options['adapter_callback'])) {
            if (!$this->_options['adapter'] instanceof \Magento\Framework\DB\Adapter\AdapterInterface) {
                \Zend_Cache::throwException(
                    'Option "adapter" should be declared and extend \Magento\Framework\DB\Adapter\AdapterInterface!'
                );
            }
        }
        if (empty($this->_options['data_table']) && empty($this->_options['data_table_callback'])) {
            \Zend_Cache::throwException('Option "data_table" or "data_table_callback" should be declared!');
        }
        if (empty($this->_options['tags_table']) && empty($this->_options['tags_table_callback'])) {
            \Zend_Cache::throwException('Option "tags_table" or "tags_table_callback" should be declared!');
        }
    }

    /**
     * Get DB adapter
     *
     * @return \Magento\Framework\DB\Adapter\AdapterInterface
     */
    protected function _getConnection()
    {
        if (!$this->_connection) {
            if (!empty($this->_options['adapter_callback'])) {
                $connection = call_user_func($this->_options['adapter_callback']);
            } else {
                $connection = $this->_options['adapter'];
            }
            if (!$connection instanceof \Magento\Framework\DB\Adapter\AdapterInterface) {
                \Zend_Cache::throwException(
                    'DB Adapter should be declared and extend \Magento\Framework\DB\Adapter\AdapterInterface'
                );
            } else {
                $this->_connection = $connection;
            }
        }
        return $this->_connection;
    }

    /**
     * Get table name where data is stored
     *
     * @return string
     */
    protected function _getDataTable()
    {
        if (empty($this->_options['data_table'])) {
            $this->setOption('data_table', call_user_func($this->_options['data_table_callback']));
            if (empty($this->_options['data_table'])) {
                \Zend_Cache::throwException('Failed to detect data_table option');
            }
        }
        return $this->_options['data_table'];
    }

    /**
     * Get table name where tags are stored
     *
     * @return string
     */
    protected function _getTagsTable()
    {
        if (empty($this->_options['tags_table'])) {
            $this->setOption('tags_table', call_user_func($this->_options['tags_table_callback']));
            if (empty($this->_options['tags_table'])) {
                \Zend_Cache::throwException('Failed to detect tags_table option');
            }
        }
        return $this->_options['tags_table'];
    }

    /**
     * Test if a cache is available for the given id and (if yes) return it (false else)
     *
     * Note : return value is always "string" (unserialization is done by the core not by the backend)
     *
     * @param  string $id Cache id
     * @param  boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
     * @return string|false cached datas
     */
    public function load($id, $doNotTestCacheValidity = false)
    {
        if ($this->_options['store_data'] && !$this->_options['infinite_loop_flag']) {
            $this->_options['infinite_loop_flag'] = true;
            $select = $this->_getConnection()->select()->from(
                $this->_getDataTable(),
                'data'
            )->where('id=:cache_id');

            if (!$doNotTestCacheValidity) {
                $select->where('expire_time=0 OR expire_time>?', time());
            }
            $result = $this->_getConnection()->fetchOne($select, ['cache_id' => $id]);
            $this->_options['infinite_loop_flag'] = false;
            return $result;
        } else {
            return false;
        }
    }

    /**
     * Test if a cache is available or not (for the given id)
     *
     * @param  string $id cache id
     * @return mixed|false (a cache is not available) or "last modified" timestamp (int) of the available cache record
     */
    public function test($id)
    {
        if ($this->_options['store_data'] && !$this->_options['infinite_loop_flag']) {
            $this->_options['infinite_loop_flag'] = true;
            $select = $this->_getConnection()->select()->from(
                $this->_getDataTable(),
                'update_time'
            )->where(
                'id=:cache_id'
            )->where(
                'expire_time=0 OR expire_time>?',
                time()
            );
            $result = $this->_getConnection()->fetchOne($select, ['cache_id' => $id]);
            $this->_options['infinite_loop_flag'] = false;
            return $result;
        } else {
            return false;
        }
    }

    /**
     * Save some string datas into a cache record
     *
     * Note : $data is always "string" (serialization is done by the
     * core not by the backend)
     *
     * @param string $data            Datas to cache
     * @param string $id              Cache id
     * @param string[] $tags          Array of strings, the cache record will be tagged by each string entry
     * @param int|bool $specificLifetime  Integer to set a specific lifetime or null for infinite lifetime
     * @return bool true if no problem
     */
    public function save($data, $id, $tags = [], $specificLifetime = false)
    {
        $result = false;
        if (!$this->_options['infinite_loop_flag']) {
            $this->_options['infinite_loop_flag'] = true;
            $result = true;
            if ($this->_options['store_data']) {
                $connection = $this->_getConnection();
                $dataTable = $this->_getDataTable();

                $lifetime = $this->getLifetime($specificLifetime);
                $time = time();
                $expire = $lifetime === 0 || $lifetime === null ? 0 : $time + $lifetime;

                $idCol = $connection->quoteIdentifier('id');
                $dataCol = $connection->quoteIdentifier('data');
                $createCol = $connection->quoteIdentifier('create_time');
                $updateCol = $connection->quoteIdentifier('update_time');
                $expireCol = $connection->quoteIdentifier('expire_time');

                $query = "INSERT INTO {$dataTable} ({$idCol}, {$dataCol}, {$createCol}, {$updateCol}, {$expireCol}) " .
                    "VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE {$dataCol}=VALUES({$dataCol}), " .
                    "{$updateCol}=VALUES({$updateCol}), {$expireCol}=VALUES({$expireCol})";

                $result = $connection->query($query, [$id, $data, $time, $time, $expire])->rowCount();
            }
            if ($result) {
                $result = $this->_saveTags($id, $tags);
            }
            $this->_options['infinite_loop_flag'] = false;
        }
        return $result;
    }

    /**
     * Remove a cache record
     *
     * @param  string $id Cache id
     * @return boolean True if no problem
     */
    public function remove($id)
    {
        if ($this->_options['store_data'] && !$this->_options['infinite_loop_flag']) {
            $this->_options['infinite_loop_flag'] = true;
            $result = $this->_getConnection()->delete($this->_getDataTable(), ['id=?' => $id]);
            $this->_options['infinite_loop_flag'] = false;
            return $result;
        }
        return false;
    }

    /**
     * Clean some cache records
     *
     * Available modes are :
     * \Zend_Cache::CLEANING_MODE_ALL (default)    => remove all cache entries ($tags is not used)
     * \Zend_Cache::CLEANING_MODE_OLD              => remove too old cache entries ($tags is not used)
     * \Zend_Cache::CLEANING_MODE_MATCHING_TAG     => remove cache entries matching all given tags
     *                                               ($tags can be an array of strings or a single string)
     * \Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG => remove cache entries not {matching one of the given tags}
     *                                               ($tags can be an array of strings or a single string)
     * \Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG => remove cache entries matching any given tags
     *                                               ($tags can be an array of strings or a single string)
     *
     * @param  string $mode Clean mode
     * @param  string[] $tags Array of tags
     * @return boolean true if no problem
     */
    public function clean($mode = \Zend_Cache::CLEANING_MODE_ALL, $tags = [])
    {
        if (!$this->_options['infinite_loop_flag']) {
            $this->_options['infinite_loop_flag'] = true;
            $connection = $this->_getConnection();
            switch ($mode) {
                case \Zend_Cache::CLEANING_MODE_ALL:
                    $result = $this->cleanAll($connection);
                    break;
                case \Zend_Cache::CLEANING_MODE_OLD:
                    $result = $this->cleanOld($connection);
                    break;
                case \Zend_Cache::CLEANING_MODE_MATCHING_TAG:
                case \Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
                case \Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
                    $result = $this->_cleanByTags($mode, $tags);
                    break;
                default:
                    \Zend_Cache::throwException('Invalid mode for clean() method');
                    break;
            }
            $this->_options['infinite_loop_flag'] = false;
        }

        return $result;
    }

    /**
     * Return an array of stored cache ids
     *
     * @return string[] array of stored cache ids (string)
     */
    public function getIds()
    {
        if ($this->_options['store_data']) {
            $select = $this->_getConnection()->select()->from($this->_getDataTable(), 'id');
            return $this->_getConnection()->fetchCol($select);
        } else {
            return [];
        }
    }

    /**
     * Return an array of stored tags
     *
     * @return string[] array of stored tags (string)
     */
    public function getTags()
    {
        $select = $this->_getConnection()->select()->from($this->_getTagsTable(), 'tag')->distinct(true);
        return $this->_getConnection()->fetchCol($select);
    }

    /**
     * Return an array of stored cache ids which match given tags
     *
     * In case of multiple tags, a logical AND is made between tags
     *
     * @param string[] $tags array of tags
     * @return string[] array of matching cache ids (string)
     */
    public function getIdsMatchingTags($tags = [])
    {
        $select = $this->_getConnection()->select()->from(
            $this->_getTagsTable(),
            'cache_id'
        )->distinct(
            true
        )->where(
            'tag IN(?)',
            $tags
        )->group(
            'cache_id'
        )->having(
            'COUNT(cache_id)=' . count($tags)
        );
        return $this->_getConnection()->fetchCol($select);
    }

    /**
     * Return an array of stored cache ids which don't match given tags
     *
     * In case of multiple tags, a logical OR is made between tags
     *
     * @param string[] $tags array of tags
     * @return string[] array of not matching cache ids (string)
     */
    public function getIdsNotMatchingTags($tags = [])
    {
        return array_diff($this->getIds(), $this->getIdsMatchingAnyTags($tags));
    }

    /**
     * Return an array of stored cache ids which match any given tags
     *
     * In case of multiple tags, a logical AND is made between tags
     *
     * @param string[] $tags array of tags
     * @return string[] array of any matching cache ids (string)
     */
    public function getIdsMatchingAnyTags($tags = [])
    {
        $select = $this->_getConnection()->select()->from(
            $this->_getTagsTable(),
            'cache_id'
        )->distinct(
            true
        )->where(
            'tag IN(?)',
            $tags
        );
        return $this->_getConnection()->fetchCol($select);
    }

    /**
     * Return the filling percentage of the backend storage
     *
     * @return int integer between 0 and 100
     */
    public function getFillingPercentage()
    {
        return 1;
    }

    /**
     * Return an array of metadatas for the given cache id
     *
     * The array must include these keys :
     * - expire : the expire timestamp
     * - tags : a string array of tags
     * - mtime : timestamp of last modification time
     *
     * @param string $id cache id
     * @return array|false array of metadatas (false if the cache id is not found)
     */
    public function getMetadatas($id)
    {
        $select = $this->_getConnection()->select()->from($this->_getTagsTable(), 'tag')->where('cache_id=?', $id);
        $tags = $this->_getConnection()->fetchCol($select);

        $select = $this->_getConnection()->select()->from($this->_getDataTable())->where('id=?', $id);
        $data = $this->_getConnection()->fetchRow($select);
        $res = false;
        if ($data) {
            $res = ['expire' => $data['expire_time'], 'mtime' => $data['update_time'], 'tags' => $tags];
        }
        return $res;
    }

    /**
     * Give (if possible) an extra lifetime to the given cache id
     *
     * @param string $id cache id
     * @param int $extraLifetime
     * @return boolean true if ok
     */
    public function touch($id, $extraLifetime)
    {
        if ($this->_options['store_data']) {
            return $this->_getConnection()->update(
                $this->_getDataTable(),
                ['expire_time' => new \Zend_Db_Expr('expire_time+' . $extraLifetime)],
                ['id=?' => $id, 'expire_time = 0 OR expire_time>?' => time()]
            );
        } else {
            return true;
        }
    }

    /**
     * Return an associative array of capabilities (booleans) of the backend
     *
     * The array must include these keys :
     * - automatic_cleaning (is automating cleaning necessary)
     * - tags (are tags supported)
     * - expired_read (is it possible to read expired cache records
     *                 (for doNotTestCacheValidity option for example))
     * - priority does the backend deal with priority when saving
     * - infinite_lifetime (is infinite lifetime can work with this backend)
     * - get_list (is it possible to get the list of cache ids and the complete list of tags)
     *
     * @return array associative of with capabilities
     */
    public function getCapabilities()
    {
        return [
            'automatic_cleaning' => true,
            'tags' => true,
            'expired_read' => true,
            'priority' => false,
            'infinite_lifetime' => true,
            'get_list' => true
        ];
    }

    /**
     * Save tags related to specific id
     *
     * @param string $id
     * @param string[] $tags
     * @return bool
     */
    protected function _saveTags($id, $tags)
    {
        if (!is_array($tags)) {
            $tags = [$tags];
        }
        if (empty($tags)) {
            return true;
        }

        $connection = $this->_getConnection();
        $tagsTable = $this->_getTagsTable();
        $select = $connection->select()->from($tagsTable, 'tag')->where('cache_id=?', $id)->where('tag IN(?)', $tags);

        $existingTags = $connection->fetchCol($select);
        $insertTags = array_diff($tags, $existingTags);
        if (!empty($insertTags)) {
            $query = 'INSERT IGNORE INTO ' . $tagsTable . ' (tag, cache_id) VALUES ';
            $bind = [];
            $lines = [];
            foreach ($insertTags as $tag) {
                $lines[] = '(?, ?)';
                $bind[] = $tag;
                $bind[] = $id;
            }
            $query .= implode(',', $lines);
            $connection->query($query, $bind);
        }
        $result = true;
        return $result;
    }

    /**
     * Remove cache data by tags with specified mode
     *
     * @param string $mode
     * @param string[] $tags
     * @return bool
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     */
    protected function _cleanByTags($mode, $tags)
    {
        if ($this->_options['store_data']) {
            $connection = $this->_getConnection();
            $select = $connection->select()->from($this->_getTagsTable(), 'cache_id');
            switch ($mode) {
                case \Zend_Cache::CLEANING_MODE_MATCHING_TAG:
                    $select->where('tag IN (?)', $tags)->group('cache_id')->having('COUNT(cache_id)=' . count($tags));
                    break;
                case \Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
                    $select->where('tag NOT IN (?)', $tags);
                    break;
                case \Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
                    $select->where('tag IN (?)', $tags);
                    break;
                default:
                    \Zend_Cache::throwException('Invalid mode for _cleanByTags() method');
                    break;
            }

            $result = true;
            $ids = [];
            $counter = 0;
            $stmt = $connection->query($select);
            while ($row = $stmt->fetch()) {
                $ids[] = $row['cache_id'];
                $counter++;
                if ($counter > 100) {
                    $result = $result && $connection->delete($this->_getDataTable(), ['id IN (?)' => $ids]);
                    $ids = [];
                    $counter = 0;
                }
            }
            if (!empty($ids)) {
                $result = $result && $connection->delete($this->_getDataTable(), ['id IN (?)' => $ids]);
            }
            return $result;
        } else {
            return true;
        }
    }

    /**
     * Clean all cache entries
     *
     * @param \Magento\Framework\DB\Adapter\AdapterInterface $connection
     * @return bool
     */
    private function cleanAll(\Magento\Framework\DB\Adapter\AdapterInterface $connection)
    {
        if ($this->_options['store_data']) {
            $result = $connection->query('TRUNCATE TABLE ' . $this->_getDataTable());
        } else {
            $result = true;
        }
        $result = $result && $connection->query('TRUNCATE TABLE ' . $this->_getTagsTable());
        return $result;
    }

    /**
     * Clean old cache entries
     *
     * @param \Magento\Framework\DB\Adapter\AdapterInterface $connection
     * @return bool
     */
    private function cleanOld(\Magento\Framework\DB\Adapter\AdapterInterface $connection)
    {
        if ($this->_options['store_data']) {
            $result = $connection->delete(
                $this->_getDataTable(),
                ['expire_time> ?' => 0, 'expire_time<= ?' => time()]
            );
            return $result;
        } else {
            $result = true;
            return $result;
        }
    }
}