1: <?php
2:
3: 4: 5: 6:
7:
8: namespace Nette\Caching\Storages;
9:
10: use Nette;
11: use Nette\Caching\Cache;
12:
13:
14: 15: 16:
17: class SQLiteStorage extends Nette\Object implements Nette\Caching\IStorage
18: {
19:
20: private $pdo;
21:
22:
23: public function __construct($path = ':memory:')
24: {
25: $this->pdo = new \PDO('sqlite:' . $path, NULL, NULL, array(\PDO::ATTR_PERSISTENT => TRUE));
26: $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
27: $this->pdo->exec('
28: PRAGMA foreign_keys = ON;
29: CREATE TABLE IF NOT EXISTS cache (
30: key BLOB NOT NULL PRIMARY KEY,
31: data BLOB NOT NULL
32: );
33: CREATE TABLE IF NOT EXISTS tags (
34: key BLOB NOT NULL REFERENCES cache ON DELETE CASCADE,
35: tag BLOB NOT NULL
36: );
37: CREATE INDEX IF NOT EXISTS tags_key ON tags(key);
38: CREATE INDEX IF NOT EXISTS tags_tag ON tags(tag);
39: ');
40: }
41:
42:
43: 44: 45: 46: 47:
48: public function read($key)
49: {
50: $stmt = $this->pdo->prepare('SELECT data FROM cache WHERE key=?');
51: $stmt->execute(array($key));
52: if ($res = $stmt->fetchColumn()) {
53: return unserialize($res);
54: }
55: }
56:
57:
58: 59: 60: 61: 62:
63: public function lock($key)
64: {
65: }
66:
67:
68: 69: 70: 71: 72: 73: 74:
75: public function write($key, $data, array $dependencies)
76: {
77: $this->pdo->exec('BEGIN TRANSACTION');
78: $this->pdo->prepare('REPLACE INTO cache (key, data) VALUES (?, ?)')
79: ->execute(array($key, serialize($data)));
80:
81: if (!empty($dependencies[Cache::TAGS])) {
82: foreach ((array) $dependencies[Cache::TAGS] as $tag) {
83: $arr[] = $key;
84: $arr[] = $tag;
85: }
86: $this->pdo->prepare('INSERT INTO tags (key, tag) SELECT ?, ?' . str_repeat('UNION SELECT ?, ?', count($arr) / 2 - 1))
87: ->execute($arr);
88: }
89: $this->pdo->exec('COMMIT');
90: }
91:
92:
93: 94: 95: 96: 97:
98: public function remove($key)
99: {
100: $this->pdo->prepare('DELETE FROM cache WHERE key=?')
101: ->execute(array($key));
102: }
103:
104:
105: 106: 107: 108: 109:
110: public function clean(array $conditions)
111: {
112: if (!empty($conditions[Cache::ALL])) {
113: $this->pdo->prepare('DELETE FROM cache')->execute();
114:
115: } elseif (!empty($conditions[Cache::TAGS])) {
116: $tags = (array) $conditions[Cache::TAGS];
117: $this->pdo->prepare('DELETE FROM cache WHERE key IN (SELECT key FROM tags WHERE tag IN (?'
118: . str_repeat(',?', count($tags) - 1) . '))')->execute($tags);
119: }
120: }
121:
122: }
123: