Sqlite.php 14.5 KB
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
<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Cache
 * @subpackage Backend
 * @copyright  Copyright (c) 2005-2007 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
 
 
/**
 * Zend_Cache_Backend_Interface
 */
require_once 'Zend/Cache/Backend/Interface.php';

/**
 * Zend_Cache_Backend
 */
require_once 'Zend/Cache/Backend.php';

/**
 * @package    Zend_Cache
 * @subpackage Backend
 * @copyright  Copyright (c) 2005-2007 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Cache_Backend_Sqlite extends Zend_Cache_Backend implements Zend_Cache_Backend_Interface 
{
    
    // ------------------
    // --- Properties ---
    // ------------------
       
    /**
     * Available options
     * 
     * =====> (string) cacheDBCompletePath :
     * - the complete path (filename included) of the SQLITE database
     * 
     * ====> (int) automaticVacuumFactor :
     * - Disable / Tune the automatic vacuum process
     * - The automatic vacuum process defragment the database file (and make it smaller)
     *   when a clean() or delete() is called
     *     0               => no automatic vacuum 
     *     1               => systematic vacuum (when delete() or clean() methods are called)
     *     x (integer) > 1 => automatic vacuum randomly 1 times on x clean() or delete()
     * 
     * @var array available options
     */
    protected $_options = array(
        'cacheDBCompletePath' => null,
        'automaticVacuumFactor' => 10
    ); 
  
    /**
     * DB ressource 
     * 
     * @var mixed $_db
     */
    private $_db = null;
    
    
    // ----------------------
    // --- Public methods ---
    // ----------------------
    
    /**
     * Constructor
     * 
     * @param array $options associative array of options
     */
    public function __construct($options = array())
    {      
        if (!isset($options['cacheDBCompletePath'])) Zend_Cache::throwException('cacheDBCompletePath option has to set');
        $this->_db = @sqlite_open($options['cacheDBCompletePath']);
        if (!($this->_db)) {
            Zend_Cache::throwException("Impossible to open " . $options['cacheDBCompletePath'] . " cache DB file");
        }
        parent::__construct($options);
    }
    
    /**
     * Destructor
     */
    public function __destruct()
    {
        @sqlite_close($this->_db);
    }
            
    /**
     * Test if a cache is available for the given id and (if yes) return it (false else)
     * 
     * @param string $id cache id
     * @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
     * @return string cached datas (or false)
     */
    public function load($id, $doNotTestCacheValidity = false) 
    {
        $sql = "SELECT content FROM cache WHERE id='$id'";
        if (!$doNotTestCacheValidity) {
            $sql = $sql . " AND (expire=0 OR expire>" . time() . ')';
        }
        $result = @sqlite_query($this->_db, $sql);
        $row = @sqlite_fetch_array($result);
        if ($row) {
            return $row['content'];
        }
        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)
    {
        $sql = "SELECT lastModified FROM cache WHERE id='$id' AND (expire=0 OR expire>" . time() . ')';
        $result = @sqlite_query($this->_db, $sql);
        $row = @sqlite_fetch_array($result);
        if ($row) {
            return ((int) $row['lastModified']);
        }
        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 array $tags array of strings, the cache record will be tagged by each string entry
     * @param int $specificLifetime if != false, set a specific lifetime for this cache record (null => infinite lifetime)
     * @return boolean true if no problem
     */
    public function save($data, $id, $tags = array(), $specificLifetime = false)
    {
        if (!$this->_checkStructureVersion()) {
            $this->_buildStructure();
            if (!$this->_checkStructureVersion()) {
                Zend_Cache::throwException("Impossible to build cache structure in " . $this->_options['cacheDBCompletePath']);
            }
        }    
        $lifetime = $this->getLifetime($specificLifetime);
        $data = @sqlite_escape_string($data);
        $mktime = time();
        if (is_null($lifetime)) {
            $expire = 0;
        } else {
            $expire = $mktime + $lifetime;
        }
        @sqlite_query($this->_db, "DELETE FROM cache WHERE id='$id'");
        $sql = "INSERT INTO cache (id, content, lastModified, expire) VALUES ('$id', '$data', $mktime, $expire)";
        $res = @sqlite_query($this->_db, $sql);       
        if (!$res) {
            if ($this->_directives['logging']) {
                Zend_Log::log("Zend_Cache_Backend_Sqlite::save() : impossible to store the cache id=$id", Zend_Log::LEVEL_WARNING);
            }
            return false;
        }
        $res = true;
        foreach ($tags as $tag) {
            $res = $res && $this->_registerTag($id, $tag);
        }
        return $res;
    }
    
    /**
     * Remove a cache record
     * 
     * @param string $id cache id
     * @return boolean true if no problem
     */
    public function remove($id) 
    {
        $res = @sqlite_query($this->_db, "SELECT COUNT(*) AS nbr FROM cache WHERE id='$id'");
        $result1 = @sqlite_fetch_single($res);
        $result2 = @sqlite_query($this->_db, "DELETE FROM cache WHERE id='$id'");
        $result3 = @sqlite_query($this->_db, "DELETE FROM tag WHERE id='$id'"); 
        $this->_automaticVacuum();
        return ($result1 && $result2 && $result3);       
    }
    
    /**
     * 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)      
     * 
     * @param string $mode clean mode
     * @param tags array $tags array of tags
     * @return boolean true if no problem
     */
    public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) 
    {
        $return = $this->_clean($mode, $tags);
        $this->_automaticVacuum();
        return $return;
    }
    
    /**
     * PUBLIC METHOD FOR UNIT TESTING ONLY !
     * 
     * Force a cache record to expire
     * 
     * @param string $id cache id
     */
    public function ___expire($id)
    {
        $time = time() - 1;
        @sqlite_query($this->_db, "UPDATE cache SET lastModified=$time, expire=$time WHERE id='$id'");
    }
    
    /**
     * PUBLIC METHOD FOR UNIT TESTING ONLY !
     * 
     * Unlink the database file
     */
    public function ___dropDatabaseFile()
    {
        @sqlite_close($this->_db);
        @unlink($this->_options['cacheDBCompletePath']);
    }
    
    // -----------------------
    // --- Private methods ---
    // -----------------------
    
    /**
     * Deal with the automatic vacuum process
     */
    private function _automaticVacuum() 
    {
        if ($this->_options['automaticVacuumFactor'] > 0) {
            $rand = rand(1, $this->_options['automaticVacuumFactor']);
            if ($rand == 1) {
                @sqlite_query($this->_db, 'VACUUM');
            }
        }
    }
    
    /**
     * Register a cache id with the given tag
     * 
     * @param string $id cache id
     * @param string $tag tag
     * @return boolean true if no problem
     */
    private function _registerTag($id, $tag) {
        $res = @sqlite_query($this->_db, "DELETE FROM TAG WHERE tag='$tag' AND id='$id'");
        $res = @sqlite_query($this->_db, "INSERT INTO tag (name, id) VALUES ('$tag', '$id')");
        if (!$res) {        
            if ($this->_directives['logging']) {
                Zend_Log::log("Zend_Cache_Backend_Sqlite::_registerTag() : impossible to register tag=$tag on id=$id", Zend_Log::LEVEL_WARNING);
            }
            return false;
        }
        return true;
    }
    
    /**
     * Build the database structure
     */
    private function _buildStructure()
    {
        @sqlite_query($this->_db, 'DROP INDEX tag_id_index');
        @sqlite_query($this->_db, 'DROP INDEX tag_name_index');
        @sqlite_query($this->_db, 'DROP INDEX cache_id_expire_index');
        @sqlite_query($this->_db, 'DROP TABLE version');
        @sqlite_query($this->_db, 'DROP TABLE cache');
        @sqlite_query($this->_db, 'DROP TABLE tag');
        @sqlite_query($this->_db, 'CREATE TABLE version (num INTEGER PRIMARY KEY)');
        @sqlite_query($this->_db, 'CREATE TABLE cache (id TEXT PRIMARY KEY, content BLOB, lastModified INTEGER, expire INTEGER)');
        @sqlite_query($this->_db, 'CREATE TABLE tag (name TEXT, id TEXT)');  
        @sqlite_query($this->_db, 'CREATE INDEX tag_id_index ON tag(id)');
        @sqlite_query($this->_db, 'CREATE INDEX tag_name_index ON tag(name)');
        @sqlite_query($this->_db, 'CREATE INDEX cache_id_expire_index ON cache(id, expire)');
        @sqlite_query($this->_db, 'INSERT INTO version (num) VALUES (1)');        
    }
    
    /**
     * Check if the database structure is ok (with the good version)
     * 
     * @return boolean true if ok
     */
    private function _checkStructureVersion()
    {       
        $result = @sqlite_query($this->_db, "SELECT num FROM version");
        if (!$result) return false;
        $row = @sqlite_fetch_array($result);
        if (!$row) {
            return false;
        }
        if (((int) $row['num']) != 1) {
            // old cache structure
            if ($this->_directives['logging']) {
                Zend_Log::log('Zend_Cache_Backend_Sqlite::_checkStructureVersion() : old cache structure version detected => the cache is going to be dropped', Zend_Log::LEVEL_WARNING);
            }
            return false;
        }
        return true;
    }
    
    /**
     * 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)      
     * 
     * @param string $mode clean mode
     * @param tags array $tags array of tags
     * @return boolean true if no problem
     */
    private function _clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) 
    {
        if ($mode==Zend_Cache::CLEANING_MODE_ALL) {
            $res1 = @sqlite_query($this->_db, 'DELETE FROM cache');
            $res2 = @sqlite_query($this->_db, 'DELETE FROM tag');
            return $res1 && $res2;
        }
        if ($mode==Zend_Cache::CLEANING_MODE_OLD) {
            $mktime = time();
            $res1 = @sqlite_query($this->_db, "DELETE FROM tag WHERE id IN (SELECT id FROM cache WHERE expire>0 AND expire<=$mktime)");
            $res2 = @sqlite_query($this->_db, "DELETE FROM cache WHERE expire>0 AND expire<=$mktime");
            return $res1 && $res2;
        }
        if ($mode==Zend_Cache::CLEANING_MODE_MATCHING_TAG) {
            $first = true;
            $ids = array();
            foreach ($tags as $tag) {
                $res = @sqlite_query($this->_db, "SELECT DISTINCT(id) AS id FROM tag WHERE name='$tag'");
                if (!$res) {
                    return false;
                }
                $rows = @sqlite_fetch_all($res, SQLITE_ASSOC);  
                $ids2 = array();
                foreach ($rows as $row) {
                    $ids2[] = $row['id'];
                }
                if ($first) {
                    $ids = $ids2;
                    $first = false;
                } else {
                    $ids = array_intersect($ids, $ids2);
                }
            }
            $result = true;
            foreach ($ids as $id) {
                $result = $result && ($this->remove($id));
            }
            return $result;
        }
        if ($mode==Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG) {
            $res = @sqlite_query($this->_db, "SELECT id FROM cache");
            $rows = @sqlite_fetch_all($res, SQLITE_ASSOC);    
            $result = true;
            foreach ($rows as $row) {
                $id = $row['id'];
                $matching = false;
                foreach ($tags as $tag) {
                    $res = @sqlite_query($this->_db, "SELECT COUNT(*) AS nbr FROM tag WHERE name='$tag' AND id='$id'");
                    if (!$res) {
                        return false;
                    }
                    $nbr = (int) @sqlite_fetch_single($res);
                    if ($nbr > 0) {
                        $matching = true;
                    }
                }
                if (!$matching) {
                    $result = $result && $this->remove($id);
                }
            }     
            return $result;         
        }     
        return false;
    }
    
}