PageRenderTime 524ms CodeModel.GetById 142ms app.highlight 15ms RepoModel.GetById 226ms app.codeStats 1ms

/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/**
 4 * SQLite cache adapter
 5 */
 6
 7if ( ! class_exists('SQLite3')) {
 8  raise(ln('extension_missing', array('name' => 'SQLite3')));
 9}
10
11/**#@+
12 * @ignore
13 */
14define('CACHE_DRIVER', 'SQLite3');
15/**#@-*/
16
17
18cache::implement('link', function () {
19  static $object = NULL;
20
21
22  if (is_null($object)) {
23    if ( ! is_file($db_file = TMP.DS.'--cache-db')) {
24      touch($db_file);
25
26      $tmp = new SQLite3($db_file);
27
28      $tmp->exec('CREATE TABLE "data"('
29                . '"key" CHAR(32) PRIMARY KEY,'
30                . '"value" TEXT,'
31                . '"expire" INTEGER'
32                . ')');
33
34      $tmp->close();
35      unset($tmp);
36    }
37
38    $object = new SQLite3($db_file);
39  }
40
41
42  $time = time();
43
44  $sql  = 'DELETE FROM "data"';
45  $sql .= "\nWHERE \"expire\" < $time";
46
47  $object->exec($sql);
48
49  return $object;
50});
51
52cache::implement('free_all', function () {
53  cache::link()->exec('DELETE FROM "data"');
54});
55
56cache::implement('fetch_item', function ($key) {
57  $sql  = 'SELECT value FROM "data"';
58  $sql .= "\nWHERE \"key\" = PHP('md5', '$key')";
59
60  if ($tmp = cache::link()->query($sql)) {
61    $test = @array_shift($tmp->fetchArray(SQLITE3_NUM));
62
63    if (is_serialized($test)) {
64      return unserialize($test);
65    }
66    cache::delete_item($key);
67  }
68});
69
70cache::implement('store_item', function ($key, $val, $max) {
71  $time = time() + $max;
72  $val  = str_replace("'", "''", serialize($val));
73
74  $sql  = 'REPLACE INTO "data"';
75  $sql .= '("key", "value", "expire")';
76  $sql .= "\nVALUES(PHP('md5', '$key'), '$val', $time)";
77
78  return cache::link()->exec($sql);
79});
80
81cache::implement('delete_item', function ($key) {
82  $sql  = 'DELETE FROM "data"';
83  $sql .= "\nWHERE \"key\" = PHP('md5', '$key')";
84
85  return cache::link()->exec($sql);
86});
87
88cache::implement('check_item', function ($key) {
89  $sql  = "SELECT COUNT(*) FROM \"data\"";
90  $sql .= "\nWHERE \"key\" = PHP('md5', '$key')";
91
92  $tmp  = cache::link()->query($sql);
93
94  return @array_shift($tmp->fetchArray(SQLITE3_NUM)) > 0;
95});
96
97/* EOF: ./library/cache/drivers/sqlite.php */