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