1: <?php
2:
3: 4: 5: 6:
7:
8: namespace Nette\Caching\Storages;
9:
10: use Nette,
11: 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, data BLOB NOT NULL
33: );
34: CREATE TABLE IF NOT EXISTS tags (
35: key BLOB NOT NULL REFERENCES cache ON DELETE CASCADE,
36: tag BLOB NOT NULL
37: );
38: CREATE INDEX IF NOT EXISTS tags_key ON tags(key);
39: CREATE INDEX IF NOT EXISTS tags_tag ON tags(tag);
40: ');
41: }
42:
43:
44: 45: 46: 47: 48:
49: public function read($key)
50: {
51: $stmt = $this->pdo->prepare('SELECT data FROM cache WHERE key=?');
52: $stmt->execute(array($key));
53: if ($res = $stmt->fetchColumn()) {
54: return unserialize($res);
55: }
56: }
57:
58:
59: 60: 61: 62: 63:
64: public function lock($key)
65: {
66: }
67:
68:
69: 70: 71: 72: 73: 74: 75:
76: public function write($key, $data, array $dependencies)
77: {
78: $this->pdo->prepare('BEGIN TRANSACTION');
79: $this->pdo->prepare('REPLACE INTO cache (key, data) VALUES (?, ?)')
80: ->execute(array($key, serialize($data)));
81:
82: if (!empty($dependencies[Cache::TAGS])) {
83: foreach ((array) $dependencies[Cache::TAGS] as $tag) {
84: $arr[] = $key;
85: $arr[] = $tag;
86: }
87: $this->pdo->prepare('INSERT INTO tags (key, tag) SELECT ?, ?' . str_repeat('UNION SELECT ?, ?', count($arr) / 2 - 1))
88: ->execute($arr);
89: }
90: $this->pdo->prepare('COMMIT');
91: }
92:
93:
94: 95: 96: 97: 98:
99: public function remove($key)
100: {
101: $this->pdo->prepare('DELETE FROM cache WHERE key=?')
102: ->execute(array($key));
103: }
104:
105:
106: 107: 108: 109: 110:
111: public function clean(array $conditions)
112: {
113: if (!empty($conditions[Cache::ALL])) {
114: $this->pdo->prepare('DELETE FROM cache')->execute();
115:
116: } elseif (!empty($conditions[Cache::TAGS])) {
117: $tags = (array) $conditions[Cache::TAGS];
118: $this->pdo->prepare('DELETE FROM cache WHERE key IN (SELECT key FROM tags WHERE tag IN (?'
119: . str_repeat(',?', count($tags) - 1) . '))')->execute($tags);
120: }
121: }
122:
123: }
124: