PageRenderTime 43ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/standard/tags/release-0.9.0/library/Zend/Cache/Backend/Sqlite.php

https://github.com/jorgenils/zend-framework
PHP | 406 lines | 219 code | 26 blank | 161 comment | 38 complexity | fda5cdddda13ece0d577023c27642c47 MD5 | raw file
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Cache
  17. * @subpackage Backend
  18. * @copyright Copyright (c) 2005-2007 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. */
  21. /**
  22. * Zend_Cache_Backend_Interface
  23. */
  24. require_once 'Zend/Cache/Backend/Interface.php';
  25. /**
  26. * Zend_Cache_Backend
  27. */
  28. require_once 'Zend/Cache/Backend.php';
  29. /**
  30. * @package Zend_Cache
  31. * @subpackage Backend
  32. * @copyright Copyright (c) 2005-2007 Zend Technologies USA Inc. (http://www.zend.com)
  33. * @license http://framework.zend.com/license/new-bsd New BSD License
  34. */
  35. class Zend_Cache_Backend_Sqlite extends Zend_Cache_Backend implements Zend_Cache_Backend_Interface
  36. {
  37. // ------------------
  38. // --- Properties ---
  39. // ------------------
  40. /**
  41. * Available options
  42. *
  43. * =====> (string) cacheDBCompletePath :
  44. * - the complete path (filename included) of the SQLITE database
  45. *
  46. * ====> (int) automaticVacuumFactor :
  47. * - Disable / Tune the automatic vacuum process
  48. * - The automatic vacuum process defragment the database file (and make it smaller)
  49. * when a clean() or delete() is called
  50. * 0 => no automatic vacuum
  51. * 1 => systematic vacuum (when delete() or clean() methods are called)
  52. * x (integer) > 1 => automatic vacuum randomly 1 times on x clean() or delete()
  53. *
  54. * @var array available options
  55. */
  56. protected $_options = array(
  57. 'cacheDBCompletePath' => null,
  58. 'automaticVacuumFactor' => 10
  59. );
  60. /**
  61. * DB ressource
  62. *
  63. * @var mixed $_db
  64. */
  65. private $_db = null;
  66. // ----------------------
  67. // --- Public methods ---
  68. // ----------------------
  69. /**
  70. * Constructor
  71. *
  72. * @param array $options associative array of options
  73. */
  74. public function __construct($options = array())
  75. {
  76. if (!isset($options['cacheDBCompletePath'])) Zend_Cache::throwException('cacheDBCompletePath option has to set');
  77. $this->_db = @sqlite_open($options['cacheDBCompletePath']);
  78. if (!($this->_db)) {
  79. Zend_Cache::throwException("Impossible to open " . $options['cacheDBCompletePath'] . " cache DB file");
  80. }
  81. parent::__construct($options);
  82. }
  83. /**
  84. * Destructor
  85. */
  86. public function __destruct()
  87. {
  88. @sqlite_close($this->_db);
  89. }
  90. /**
  91. * Test if a cache is available for the given id and (if yes) return it (false else)
  92. *
  93. * @param string $id cache id
  94. * @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
  95. * @return string cached datas (or false)
  96. */
  97. public function load($id, $doNotTestCacheValidity = false)
  98. {
  99. $sql = "SELECT content FROM cache WHERE id='$id'";
  100. if (!$doNotTestCacheValidity) {
  101. $sql = $sql . " AND (expire=0 OR expire>" . time() . ')';
  102. }
  103. $result = @sqlite_query($this->_db, $sql);
  104. $row = @sqlite_fetch_array($result);
  105. if ($row) {
  106. return $row['content'];
  107. }
  108. return false;
  109. }
  110. /**
  111. * Test if a cache is available or not (for the given id)
  112. *
  113. * @param string $id cache id
  114. * @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record
  115. */
  116. public function test($id)
  117. {
  118. $sql = "SELECT lastModified FROM cache WHERE id='$id' AND (expire=0 OR expire>" . time() . ')';
  119. $result = @sqlite_query($this->_db, $sql);
  120. $row = @sqlite_fetch_array($result);
  121. if ($row) {
  122. return ((int) $row['lastModified']);
  123. }
  124. return false;
  125. }
  126. /**
  127. * Save some string datas into a cache record
  128. *
  129. * Note : $data is always "string" (serialization is done by the
  130. * core not by the backend)
  131. *
  132. * @param string $data datas to cache
  133. * @param string $id cache id
  134. * @param array $tags array of strings, the cache record will be tagged by each string entry
  135. * @param int $specificLifetime if != false, set a specific lifetime for this cache record (null => infinite lifetime)
  136. * @return boolean true if no problem
  137. */
  138. public function save($data, $id, $tags = array(), $specificLifetime = false)
  139. {
  140. if (!$this->_checkStructureVersion()) {
  141. $this->_buildStructure();
  142. if (!$this->_checkStructureVersion()) {
  143. Zend_Cache::throwException("Impossible to build cache structure in " . $this->_options['cacheDBCompletePath']);
  144. }
  145. }
  146. $lifetime = $this->getLifetime($specificLifetime);
  147. $data = @sqlite_escape_string($data);
  148. $mktime = time();
  149. if (is_null($lifetime)) {
  150. $expire = 0;
  151. } else {
  152. $expire = $mktime + $lifetime;
  153. }
  154. @sqlite_query($this->_db, "DELETE FROM cache WHERE id='$id'");
  155. $sql = "INSERT INTO cache (id, content, lastModified, expire) VALUES ('$id', '$data', $mktime, $expire)";
  156. $res = @sqlite_query($this->_db, $sql);
  157. if (!$res) {
  158. if ($this->_directives['logging']) {
  159. Zend_Log::log("Zend_Cache_Backend_Sqlite::save() : impossible to store the cache id=$id", Zend_Log::LEVEL_WARNING);
  160. }
  161. return false;
  162. }
  163. $res = true;
  164. foreach ($tags as $tag) {
  165. $res = $res && $this->_registerTag($id, $tag);
  166. }
  167. return $res;
  168. }
  169. /**
  170. * Remove a cache record
  171. *
  172. * @param string $id cache id
  173. * @return boolean true if no problem
  174. */
  175. public function remove($id)
  176. {
  177. $res = @sqlite_query($this->_db, "SELECT COUNT(*) AS nbr FROM cache WHERE id='$id'");
  178. $result1 = @sqlite_fetch_single($res);
  179. $result2 = @sqlite_query($this->_db, "DELETE FROM cache WHERE id='$id'");
  180. $result3 = @sqlite_query($this->_db, "DELETE FROM tag WHERE id='$id'");
  181. $this->_automaticVacuum();
  182. return ($result1 && $result2 && $result3);
  183. }
  184. /**
  185. * Clean some cache records
  186. *
  187. * Available modes are :
  188. * Zend_Cache::CLEANING_MODE_ALL (default) => remove all cache entries ($tags is not used)
  189. * Zend_Cache::CLEANING_MODE_OLD => remove too old cache entries ($tags is not used)
  190. * Zend_Cache::CLEANING_MODE_MATCHING_TAG => remove cache entries matching all given tags
  191. * ($tags can be an array of strings or a single string)
  192. * Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG => remove cache entries not {matching one of the given tags}
  193. * ($tags can be an array of strings or a single string)
  194. *
  195. * @param string $mode clean mode
  196. * @param tags array $tags array of tags
  197. * @return boolean true if no problem
  198. */
  199. public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
  200. {
  201. $return = $this->_clean($mode, $tags);
  202. $this->_automaticVacuum();
  203. return $return;
  204. }
  205. /**
  206. * PUBLIC METHOD FOR UNIT TESTING ONLY !
  207. *
  208. * Force a cache record to expire
  209. *
  210. * @param string $id cache id
  211. */
  212. public function ___expire($id)
  213. {
  214. $time = time() - 1;
  215. @sqlite_query($this->_db, "UPDATE cache SET lastModified=$time, expire=$time WHERE id='$id'");
  216. }
  217. /**
  218. * PUBLIC METHOD FOR UNIT TESTING ONLY !
  219. *
  220. * Unlink the database file
  221. */
  222. public function ___dropDatabaseFile()
  223. {
  224. @sqlite_close($this->_db);
  225. @unlink($this->_options['cacheDBCompletePath']);
  226. }
  227. // -----------------------
  228. // --- Private methods ---
  229. // -----------------------
  230. /**
  231. * Deal with the automatic vacuum process
  232. */
  233. private function _automaticVacuum()
  234. {
  235. if ($this->_options['automaticVacuumFactor'] > 0) {
  236. $rand = rand(1, $this->_options['automaticVacuumFactor']);
  237. if ($rand == 1) {
  238. @sqlite_query($this->_db, 'VACUUM');
  239. }
  240. }
  241. }
  242. /**
  243. * Register a cache id with the given tag
  244. *
  245. * @param string $id cache id
  246. * @param string $tag tag
  247. * @return boolean true if no problem
  248. */
  249. private function _registerTag($id, $tag) {
  250. $res = @sqlite_query($this->_db, "DELETE FROM TAG WHERE tag='$tag' AND id='$id'");
  251. $res = @sqlite_query($this->_db, "INSERT INTO tag (name, id) VALUES ('$tag', '$id')");
  252. if (!$res) {
  253. if ($this->_directives['logging']) {
  254. Zend_Log::log("Zend_Cache_Backend_Sqlite::_registerTag() : impossible to register tag=$tag on id=$id", Zend_Log::LEVEL_WARNING);
  255. }
  256. return false;
  257. }
  258. return true;
  259. }
  260. /**
  261. * Build the database structure
  262. */
  263. private function _buildStructure()
  264. {
  265. @sqlite_query($this->_db, 'DROP INDEX tag_id_index');
  266. @sqlite_query($this->_db, 'DROP INDEX tag_name_index');
  267. @sqlite_query($this->_db, 'DROP INDEX cache_id_expire_index');
  268. @sqlite_query($this->_db, 'DROP TABLE version');
  269. @sqlite_query($this->_db, 'DROP TABLE cache');
  270. @sqlite_query($this->_db, 'DROP TABLE tag');
  271. @sqlite_query($this->_db, 'CREATE TABLE version (num INTEGER PRIMARY KEY)');
  272. @sqlite_query($this->_db, 'CREATE TABLE cache (id TEXT PRIMARY KEY, content BLOB, lastModified INTEGER, expire INTEGER)');
  273. @sqlite_query($this->_db, 'CREATE TABLE tag (name TEXT, id TEXT)');
  274. @sqlite_query($this->_db, 'CREATE INDEX tag_id_index ON tag(id)');
  275. @sqlite_query($this->_db, 'CREATE INDEX tag_name_index ON tag(name)');
  276. @sqlite_query($this->_db, 'CREATE INDEX cache_id_expire_index ON cache(id, expire)');
  277. @sqlite_query($this->_db, 'INSERT INTO version (num) VALUES (1)');
  278. }
  279. /**
  280. * Check if the database structure is ok (with the good version)
  281. *
  282. * @return boolean true if ok
  283. */
  284. private function _checkStructureVersion()
  285. {
  286. $result = @sqlite_query($this->_db, "SELECT num FROM version");
  287. if (!$result) return false;
  288. $row = @sqlite_fetch_array($result);
  289. if (!$row) {
  290. return false;
  291. }
  292. if (((int) $row['num']) != 1) {
  293. // old cache structure
  294. if ($this->_directives['logging']) {
  295. Zend_Log::log('Zend_Cache_Backend_Sqlite::_checkStructureVersion() : old cache structure version detected => the cache is going to be dropped', Zend_Log::LEVEL_WARNING);
  296. }
  297. return false;
  298. }
  299. return true;
  300. }
  301. /**
  302. * Clean some cache records
  303. *
  304. * Available modes are :
  305. * Zend_Cache::CLEANING_MODE_ALL (default) => remove all cache entries ($tags is not used)
  306. * Zend_Cache::CLEANING_MODE_OLD => remove too old cache entries ($tags is not used)
  307. * Zend_Cache::CLEANING_MODE_MATCHING_TAG => remove cache entries matching all given tags
  308. * ($tags can be an array of strings or a single string)
  309. * Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG => remove cache entries not {matching one of the given tags}
  310. * ($tags can be an array of strings or a single string)
  311. *
  312. * @param string $mode clean mode
  313. * @param tags array $tags array of tags
  314. * @return boolean true if no problem
  315. */
  316. private function _clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
  317. {
  318. if ($mode==Zend_Cache::CLEANING_MODE_ALL) {
  319. $res1 = @sqlite_query($this->_db, 'DELETE FROM cache');
  320. $res2 = @sqlite_query($this->_db, 'DELETE FROM tag');
  321. return $res1 && $res2;
  322. }
  323. if ($mode==Zend_Cache::CLEANING_MODE_OLD) {
  324. $mktime = time();
  325. $res1 = @sqlite_query($this->_db, "DELETE FROM tag WHERE id IN (SELECT id FROM cache WHERE expire>0 AND expire<=$mktime)");
  326. $res2 = @sqlite_query($this->_db, "DELETE FROM cache WHERE expire>0 AND expire<=$mktime");
  327. return $res1 && $res2;
  328. }
  329. if ($mode==Zend_Cache::CLEANING_MODE_MATCHING_TAG) {
  330. $first = true;
  331. $ids = array();
  332. foreach ($tags as $tag) {
  333. $res = @sqlite_query($this->_db, "SELECT DISTINCT(id) AS id FROM tag WHERE name='$tag'");
  334. if (!$res) {
  335. return false;
  336. }
  337. $rows = @sqlite_fetch_all($res, SQLITE_ASSOC);
  338. $ids2 = array();
  339. foreach ($rows as $row) {
  340. $ids2[] = $row['id'];
  341. }
  342. if ($first) {
  343. $ids = $ids2;
  344. $first = false;
  345. } else {
  346. $ids = array_intersect($ids, $ids2);
  347. }
  348. }
  349. $result = true;
  350. foreach ($ids as $id) {
  351. $result = $result && ($this->remove($id));
  352. }
  353. return $result;
  354. }
  355. if ($mode==Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG) {
  356. $res = @sqlite_query($this->_db, "SELECT id FROM cache");
  357. $rows = @sqlite_fetch_all($res, SQLITE_ASSOC);
  358. $result = true;
  359. foreach ($rows as $row) {
  360. $id = $row['id'];
  361. $matching = false;
  362. foreach ($tags as $tag) {
  363. $res = @sqlite_query($this->_db, "SELECT COUNT(*) AS nbr FROM tag WHERE name='$tag' AND id='$id'");
  364. if (!$res) {
  365. return false;
  366. }
  367. $nbr = (int) @sqlite_fetch_single($res);
  368. if ($nbr > 0) {
  369. $matching = true;
  370. }
  371. }
  372. if (!$matching) {
  373. $result = $result && $this->remove($id);
  374. }
  375. }
  376. return $result;
  377. }
  378. return false;
  379. }
  380. }