-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDbCache.php
224 lines (190 loc) · 5.67 KB
/
DbCache.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
<?php
namespace yii1tech\cache\tagged;
use PDO;
/**
* DbCache is tag aware version of standard {@see \CDbCache}.
*
* It saves tags in the same row with cache item into a JSON field.
* Only following drivers are supported:
*
* - 'sqlite'
* - 'mysql'
* - 'pgsql'
*
* Application configuration example:
*
* ```php
* return [
* 'components' => [
* 'db' => [
* 'class' => \CDbConnection::class,
* 'connectionString' => 'mysql:host=127.0.0.1;port=3306;dbname=yiiexample',
* 'username' => 'default',
* 'password' => 'secret',
* ],
* 'cache' => [
* 'class' => \yii1tech\cache\tagged\DbCache::class,
* 'connectionID' => 'db',
* ],
* // ...
* ],
* // ...
* ];
* ```
*
* @author Paul Klimov <klimov.paul@gmail.com>
* @since 1.0
*/
class DbCache extends \CDbCache implements TagAwareCacheContract
{
/**
* @var string[] list of tags to be applied for new item.
*/
protected $currentItemTags = [];
/**
* @var bool whether GC has been performed.
*/
private $_gced = false;
/**
* {@inheritdoc}
*/
public function set($id, $value, $expire = 0, $dependency = null, array $tags = [])
{
$this->currentItemTags = $tags;
$result = parent::set($id, $value, $expire, $dependency);
$this->currentItemTags = [];
return $result;
}
/**
* {@inheritdoc}
*/
public function add($id, $value, $expire = 0, $dependency = null, array $tags = [])
{
$this->currentItemTags = $tags;
$result = parent::add($id, $value, $expire, $dependency);
$this->currentItemTags = [];
return $result;
}
/**
* {@inheritdoc}
*/
public function invalidateTags(array $tags): bool
{
if (empty($tags)) {
return true;
}
$sql = "DELETE FROM {$this->cacheTableName} WHERE tags IS NOT NULL AND ";
$params = [];
foreach ($tags as $tag) {
$params[':tag' . count($params)] = $tag;
}
$db = $this->getDbConnection();
$driverName = $db->getDriverName();
if ($driverName === 'sqlite') {
$where = $this->createTagsConditionSqlite($params);
} elseif ($driverName === 'mysql') {
$where = $this->createTagsConditionMysql($params);
} elseif ($driverName === 'pgsql') {
$where = $this->createTagsConditionPgsql($params);
} else {
throw new \LogicException("Unsupported Database driver: {$driverName}");
}
$sql .= $where;
$db->createCommand($sql)->execute($params);
return true;
}
/**
* Creates tags search condition for 'sqlite' driver.
*
* @param array<string, string> $tagParams tag parameters to be bound with SQL query.
* @return string SQL where condition part.
*/
protected function createTagsConditionSqlite(array $tagParams): string
{
$inTagsSql = implode(',', array_keys($tagParams));
return <<<"SQL"
EXISTS (
SELECT *
FROM json_each(json_extract(tags,'$'))
WHERE json_each.value IN ($inTagsSql)
)
SQL;
}
/**
* Creates tags search condition for 'mysql' driver.
*
* @param array<string, string> $tagParams tag parameters to be bound with SQL query.
* @return string SQL where condition part.
*/
protected function createTagsConditionMysql(array $tagParams): string
{
$whereParts = [];
foreach ($tagParams as $name => $value) {
$whereParts[] = "JSON_CONTAINS(`tags`, CONCAT('\"', {$name}, '\"'), '$')";
}
return '(' . implode(' OR ', $whereParts) . ')';
}
/**
* Creates tags search condition for 'pgsql' driver.
*
* @param array<string, string> $tagParams tag parameters to be bound with SQL query.
* @return string SQL where condition part.
*/
protected function createTagsConditionPgsql(array $tagParams): string
{
$whereParts = [];
foreach ($tagParams as $name => $value) {
$whereParts[] = "tag::text = CONCAT('\"', CAST({$name} AS VARCHAR), '\"'))";
}
return 'EXISTS (SELECT 1 FROM json_array_elements(tags) AS tag WHERE (' . implode(' OR ', $whereParts) . ')';
}
/**
* {@inheritdoc}
*/
protected function createCacheTable($db,$tableName)
{
$driver = $db->getDriverName();
$blob = 'BLOB';
$json = 'JSON';
if ($driver==='mysql') {
$blob = 'LONGBLOB';
} elseif($driver==='pgsql') {
$blob = 'BYTEA';
}
$sql = <<<"SQL"
CREATE TABLE $tableName
(
id CHAR(128) PRIMARY KEY,
expire INTEGER,
value $blob,
tags $json
)
SQL;
$db->createCommand($sql)->execute();
}
/**
* {@inheritdoc}
*/
protected function addValue($key, $value, $expire)
{
if (!$this->_gced && mt_rand(0, 1000000) < $this->getGCProbability()) {
$this->gc();
$this->_gced = true;
}
if ($expire > 0) {
$expire += time();
} else {
$expire = 0;
}
$tags = empty($this->currentItemTags) ? null : json_encode($this->currentItemTags);
$sql = "INSERT INTO {$this->cacheTableName} (id,expire,value,tags) VALUES ('$key',$expire,:value,:tags)";
try {
$command = $this->getDbConnection()->createCommand($sql);
$command->bindValue(':value', $value, PDO::PARAM_LOB);
$command->bindValue(':tags', $tags);
return $command->execute() > 0;
} catch(\Exception $e) {
return false;
}
}
}