Removed dep on API
[ninja.git] / system / libraries / drivers / Cache / Sqlite.php
blobdb00a6d23dc8096853addd359ed8d30725728fe1
1 <?php defined('SYSPATH') OR die('No direct access allowed.');
2 /**
3 * SQLite-based Cache driver.
5 * $Id: Sqlite.php 3917 2009-01-21 03:06:22Z zombor $
7 * @package Cache
8 * @author Kohana Team
9 * @copyright (c) 2007-2008 Kohana Team
10 * @license http://kohanaphp.com/license.html
12 class Cache_Sqlite_Driver implements Cache_Driver {
14 // SQLite database instance
15 protected $db;
17 // Database error messages
18 protected $error;
20 /**
21 * Logs an SQLite error.
23 protected static function log_error($code)
25 // Log an error
26 Kohana::log('error', 'Cache: SQLite error: '.sqlite_error_string($error));
29 /**
30 * Tests that the storage location is a directory and is writable.
32 public function __construct($filename)
34 // Get the directory name
35 $directory = str_replace('\\', '/', realpath(pathinfo($filename, PATHINFO_DIRNAME))).'/';
37 // Set the filename from the real directory path
38 $filename = $directory.basename($filename);
40 // Make sure the cache directory is writable
41 if ( ! is_dir($directory) OR ! is_writable($directory))
42 throw new Kohana_Exception('cache.unwritable', $directory);
44 // Make sure the cache database is writable
45 if (is_file($filename) AND ! is_writable($filename))
46 throw new Kohana_Exception('cache.unwritable', $filename);
48 // Open up an instance of the database
49 $this->db = new SQLiteDatabase($filename, '0666', $error);
51 // Throw an exception if there's an error
52 if ( ! empty($error))
53 throw new Kohana_Exception('cache.driver_error', sqlite_error_string($error));
55 $query = "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'caches'";
56 $tables = $this->db->query($query, SQLITE_BOTH, $error);
58 // Throw an exception if there's an error
59 if ( ! empty($error))
60 throw new Kohana_Exception('cache.driver_error', sqlite_error_string($error));
62 if ($tables->numRows() == 0)
64 Kohana::log('error', 'Cache: Initializing new SQLite cache database');
66 // Issue a CREATE TABLE command
67 $this->db->unbufferedQuery(Kohana::config('cache_sqlite.schema'));
71 /**
72 * Checks if a cache id is already set.
74 * @param string cache id
75 * @return boolean
77 public function exists($id)
79 // Find the id that matches
80 $query = "SELECT id FROM caches WHERE id = '$id'";
82 return ($this->db->query($query)->numRows() > 0);
85 /**
86 * Sets a cache item to the given data, tags, and lifetime.
88 * @param string cache id to set
89 * @param string data in the cache
90 * @param array cache tags
91 * @param integer lifetime
92 * @return bool
94 public function set($id, $data, $tags, $lifetime)
96 // Find the data hash
97 $hash = sha1($data);
99 // Escape the data
100 $data = sqlite_escape_string($data);
102 // Escape the tags
103 $tags = sqlite_escape_string(implode(',', $tags));
105 // Cache Sqlite driver expects unix timestamp
106 if ($lifetime !== 0)
108 $lifetime += time();
111 $query = $this->exists($id)
112 ? "UPDATE caches SET hash = '$hash', tags = '$tags', expiration = '$lifetime', cache = '$data' WHERE id = '$id'"
113 : "INSERT INTO caches VALUES('$id', '$hash', '$tags', '$lifetime', '$data')";
115 // Run the query
116 $this->db->unbufferedQuery($query, SQLITE_BOTH, $error);
118 empty($error) or self::log_error($error);
120 return empty($error);
124 * Finds an array of ids for a given tag.
126 * @param string tag name
127 * @return array of ids that match the tag
129 public function find($tag)
131 $query = "SELECT id FROM caches WHERE tags LIKE '%{$tag}%'";
132 $query = $this->db->query($query, SQLITE_BOTH, $error);
134 empty($error) or self::log_error($error);
136 if (empty($error) AND $query->numRows() > 0)
138 $array = array();
139 while ($row = $query->fetchObject())
141 // Add each id to the array
142 $array[] = $row->id;
144 return $array;
147 return FALSE;
151 * Fetches a cache item. This will delete the item if it is expired or if
152 * the hash does not match the stored hash.
154 * @param string cache id
155 * @return mixed|NULL
157 public function get($id)
159 $query = "SELECT id, hash, expiration, cache FROM caches WHERE id = '{$id}' LIMIT 0, 1";
160 $query = $this->db->query($query, SQLITE_BOTH, $error);
162 empty($error) or self::log_error($error);
164 if (empty($error) AND $cache = $query->fetchObject())
166 // Make sure the expiration is valid and that the hash matches
167 if (($cache->expiration != 0 AND $cache->expiration <= time()) OR $cache->hash !== sha1($cache->cache))
169 // Cache is not valid, delete it now
170 $this->delete($cache->id);
172 else
174 // Return the valid cache data
175 return $cache->cache;
179 // No valid cache found
180 return NULL;
184 * Deletes a cache item by id or tag
186 * @param string cache id or tag, or TRUE for "all items"
187 * @param bool use tags
188 * @return bool
190 public function delete($id, $tag = FALSE)
192 if ($id === TRUE)
194 // Delete all caches
195 $where = '1';
197 elseif ($tag == FALSE)
199 // Delete by id
200 $where = "id = '{$id}'";
202 else
204 // Delete by tag
205 $where = "tags LIKE '%{$tag}%'";
208 $this->db->unbufferedQuery('DELETE FROM caches WHERE '.$where, SQLITE_BOTH, $error);
210 empty($error) or self::log_error($error);
212 return empty($error);
216 * Deletes all cache files that are older than the current time.
218 public function delete_expired()
220 // Delete all expired caches
221 $query = 'DELETE FROM caches WHERE expiration != 0 AND expiration <= '.time();
223 $this->db->unbufferedQuery($query);
225 return TRUE;
228 } // End Cache SQLite Driver