PageRenderTime 49ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/library/cache/drivers/sqlite.php

http://github.com/pateketrueke/tetlphp
PHP | 97 lines | 69 code | 21 blank | 7 comment | 5 complexity | 2d63fc975adab9783dda70724007af6d MD5 | raw file
  1. <?php
  2. /**
  3. * SQLite cache adapter
  4. */
  5. if ( ! class_exists('SQLite3')) {
  6. raise(ln('extension_missing', array('name' => 'SQLite3')));
  7. }
  8. /**#@+
  9. * @ignore
  10. */
  11. define('CACHE_DRIVER', 'SQLite3');
  12. /**#@-*/
  13. cache::implement('link', function () {
  14. static $object = NULL;
  15. if (is_null($object)) {
  16. if ( ! is_file($db_file = TMP.DS.'--cache-db')) {
  17. touch($db_file);
  18. $tmp = new SQLite3($db_file);
  19. $tmp->exec('CREATE TABLE "data"('
  20. . '"key" CHAR(32) PRIMARY KEY,'
  21. . '"value" TEXT,'
  22. . '"expire" INTEGER'
  23. . ')');
  24. $tmp->close();
  25. unset($tmp);
  26. }
  27. $object = new SQLite3($db_file);
  28. }
  29. $time = time();
  30. $sql = 'DELETE FROM "data"';
  31. $sql .= "\nWHERE \"expire\" < $time";
  32. $object->exec($sql);
  33. return $object;
  34. });
  35. cache::implement('free_all', function () {
  36. cache::link()->exec('DELETE FROM "data"');
  37. });
  38. cache::implement('fetch_item', function ($key) {
  39. $sql = 'SELECT value FROM "data"';
  40. $sql .= "\nWHERE \"key\" = PHP('md5', '$key')";
  41. if ($tmp = cache::link()->query($sql)) {
  42. $test = @array_shift($tmp->fetchArray(SQLITE3_NUM));
  43. if (is_serialized($test)) {
  44. return unserialize($test);
  45. }
  46. cache::delete_item($key);
  47. }
  48. });
  49. cache::implement('store_item', function ($key, $val, $max) {
  50. $time = time() + $max;
  51. $val = str_replace("'", "''", serialize($val));
  52. $sql = 'REPLACE INTO "data"';
  53. $sql .= '("key", "value", "expire")';
  54. $sql .= "\nVALUES(PHP('md5', '$key'), '$val', $time)";
  55. return cache::link()->exec($sql);
  56. });
  57. cache::implement('delete_item', function ($key) {
  58. $sql = 'DELETE FROM "data"';
  59. $sql .= "\nWHERE \"key\" = PHP('md5', '$key')";
  60. return cache::link()->exec($sql);
  61. });
  62. cache::implement('check_item', function ($key) {
  63. $sql = "SELECT COUNT(*) FROM \"data\"";
  64. $sql .= "\nWHERE \"key\" = PHP('md5', '$key')";
  65. $tmp = cache::link()->query($sql);
  66. return @array_shift($tmp->fetchArray(SQLITE3_NUM)) > 0;
  67. });
  68. /* EOF: ./library/cache/drivers/sqlite.php */