forked from yiisoft/yii2-redis
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ActiveRecord.php
434 lines (402 loc) · 15.1 KB
/
ActiveRecord.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\redis;
use Yii;
use yii\base\InvalidConfigException;
use yii\db\BaseActiveRecord;
use yii\helpers\Inflector;
use yii\helpers\StringHelper;
/**
* ActiveRecord is the base class for classes representing relational data in terms of objects.
*
* This class implements the ActiveRecord pattern for the [redis](http://redis.io/) key-value store.
*
* For defining a record a subclass should at least implement the [[attributes()]] method to define
* attributes. A primary key can be defined via [[primaryKey()]] which defaults to `id` if not specified.
*
* The following is an example model called `Customer`:
*
* ```php
* class Customer extends \yii\redis\ActiveRecord
* {
* public function attributes()
* {
* return ['id', 'name', 'address', 'registration_date'];
* }
* }
* ```
*
* @author Carsten Brandt <[email protected]>
* @since 2.0
*/
class ActiveRecord extends BaseActiveRecord
{
/**
* Returns the database connection used by this AR class.
* By default, the "redis" application component is used as the database connection.
* You may override this method if you want to use a different database connection.
* @return Connection the database connection used by this AR class.
*/
public static function getDb()
{
return Yii::$app->get('redis');
}
/**
* @inheritdoc
* @return ActiveQuery the newly created [[ActiveQuery]] instance.
*/
public static function find()
{
return Yii::createObject(ActiveQuery::className(), [get_called_class()]);
}
/**
* Returns the primary key name(s) for this AR class.
* This method should be overridden by child classes to define the primary key.
*
* Note that an array should be returned even when it is a single primary key.
*
* @return string[] the primary keys of this record.
*/
public static function primaryKey()
{
return ['id'];
}
/**
* Returns the list of all attribute names of the model.
* This method must be overridden by child classes to define available attributes.
* @return array list of attribute names.
*/
public function attributes()
{
throw new InvalidConfigException('The attributes() method of redis ActiveRecord has to be implemented by child classes.');
}
/**
* Declares prefix of the key that represents the keys that store this records in redis.
* By default this method returns the class name as the table name by calling [[Inflector::camel2id()]].
* For example, 'Customer' becomes 'customer', and 'OrderItem' becomes
* 'order_item'. You may override this method if you want different key naming.
* @return string the prefix to apply to all AR keys
*/
public static function keyPrefix()
{
return Inflector::camel2id(StringHelper::basename(get_called_class()), '_');
}
/**
* @inheritdoc
*/
public function insert($runValidation = true, $attributes = null)
{
if ($runValidation && !$this->validate($attributes)) {
return false;
}
if (!$this->beforeSave(true)) {
return false;
}
$db = static::getDb();
$values = $this->getDirtyAttributes($attributes);
$pk = [];
foreach ($this->primaryKey() as $key) {
$pk[$key] = $values[$key] = $this->getAttribute($key);
if ($pk[$key] === null) {
// use auto increment if pk is null
$pk[$key] = $values[$key] = $db->executeCommand('INCR', [static::keyPrefix() . ':s:' . $key]);
$this->setAttribute($key, $values[$key]);
} elseif (is_numeric($pk[$key])) {
// if pk is numeric update auto increment value
$currentPk = $db->executeCommand('GET', [static::keyPrefix() . ':s:' . $key]);
if ($pk[$key] > $currentPk) {
$db->executeCommand('SET', [static::keyPrefix() . ':s:' . $key, $pk[$key]]);
}
}
}
// save pk in a findall pool
$db->executeCommand('HSET', [static::keyPrefix(), static::buildKey($pk), 0]);
$key = static::keyPrefix() . ':a:' . static::buildKey($pk);
// save attributes
$setArgs = [];
foreach ($values as $attribute => $value) {
// only insert attributes that are not null
if ($value !== null) {
if (is_bool($value)) {
$value = (int) $value;
}
$setArgs[$attribute] = $value;
}
}
if (!empty($setArgs)) {
$db->executeCommand('HMSET', [$key, $setArgs]);
}
$changedAttributes = array_fill_keys(array_keys($values), null);
$this->setOldAttributes($values);
$this->afterSave(true, $changedAttributes);
return true;
}
/**
* Updates the whole table using the provided attribute values and conditions.
* For example, to change the status to be 1 for all customers whose status is 2:
*
* ~~~
* Customer::updateAll(['status' => 1], ['id' => 2]);
* ~~~
*
* @param array $attributes attribute values (name-value pairs) to be saved into the table
* @param array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
* Please refer to [[ActiveQuery::where()]] on how to specify this parameter.
* @return integer the number of rows updated
*/
public static function updateAll($attributes, $condition = null)
{
if (empty($attributes)) {
return 0;
}
$db = static::getDb();
$n = 0;
foreach (self::fetchPks($condition) as $pk) {
$newPk = $pk;
$pk = static::buildKey($pk);
$key = static::keyPrefix() . ':a:' . $pk;
// save attributes
$delArgs = [];
foreach ($attributes as $attribute => $value) {
if (isset($newPk[$attribute])) {
$newPk[$attribute] = $value;
}
if ($value !== null) {
if (is_bool($value)) {
$value = (int) $value;
}
$setArgs[$attribute] = $value;
} else {
$delArgs[] = $attribute;
}
}
$newPk = static::buildKey($newPk);
$newKey = static::keyPrefix() . ':a:' . $newPk;
// rename index if pk changed
if ($newPk != $pk) {
$db->executeCommand('MULTI');
if (!empty($setArgs)) {
$db->executeCommand('HMSET', [$key, $setArgs]);
}
if (!empty($delArgs)) {
foreach ($delArgs as $del) {
$db->executeCommand('HDEL', [$key, $del]);
}
}
$db->executeCommand('HSET', [static::keyPrefix(), $newPk, 0]);
$db->executeCommand('HDEL', [static::keyPrefix(), $pk]);
$db->executeCommand('RENAME', [$key, $newKey]);
$db->executeCommand('EXEC');
} else {
if (!empty($setArgs)) {
$db->executeCommand('HMSET', [$key, $setArgs]);
}
if (!empty($delArgs)) {
foreach ($delArgs as $del) {
$db->executeCommand('HDEL', [$key, $del]);
}
}
}
$n++;
}
return $n;
}
/**
* Updates the whole table using the provided counter changes and conditions.
* For example, to increment all customers' age by 1,
*
* ~~~
* Customer::updateAllCounters(['age' => 1]);
* ~~~
*
* @param array $counters the counters to be updated (attribute name => increment value).
* Use negative values if you want to decrement the counters.
* @param array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
* Please refer to [[ActiveQuery::where()]] on how to specify this parameter.
* @return integer the number of rows updated
*/
public static function updateAllCounters($counters, $condition = null)
{
if (empty($counters)) {
return 0;
}
$db = static::getDb();
$n = 0;
foreach (self::fetchPks($condition) as $pk) {
$key = static::keyPrefix() . ':a:' . static::buildKey($pk);
foreach ($counters as $attribute => $value) {
$db->executeCommand('HINCRBY', [$key, $attribute, $value]);
}
$n++;
}
return $n;
}
/**
* Deletes rows in the table using the provided conditions.
* WARNING: If you do not specify any condition, this method will delete ALL rows in the table.
*
* For example, to delete all customers whose status is 3:
*
* ~~~
* Customer::deleteAll(['status' => 3]);
* ~~~
*
* @param array $condition the conditions that will be put in the WHERE part of the DELETE SQL.
* Please refer to [[ActiveQuery::where()]] on how to specify this parameter.
* @return integer the number of rows deleted
*/
public static function deleteAll($condition = null)
{
$pks = self::fetchPks($condition);
if (empty($pks)) {
return 0;
}
$db = static::getDb();
$attributeKeys = [];
$db->executeCommand('MULTI');
foreach ($pks as $pk) {
$pk = static::buildKey($pk);
$db->executeCommand('HDEL', [static::keyPrefix(), $pk]);
$attributeKeys[] = static::keyPrefix() . ':a:' . $pk;
}
$db->executeCommand('DEL', $attributeKeys);
$result = $db->executeCommand('EXEC');
return end($result);
}
private static function fetchPks($condition)
{
$query = static::find();
$query->where($condition);
$records = $query->asArray()->all(); // TODO limit fetched columns to pk
$primaryKey = static::primaryKey();
$pks = [];
foreach ($records as $record) {
$pk = [];
foreach ($primaryKey as $key) {
$pk[$key] = $record[$key];
}
$pks[] = $pk;
}
return $pks;
}
/**
* Builds a normalized key from a given primary key value.
*
* @param mixed $key the key to be normalized
* @return string the generated key
*/
public static function buildKey($key)
{
if (is_numeric($key)) {
return $key;
} elseif (is_string($key)) {
return ctype_alnum($key) && StringHelper::byteLength($key) <= 32 ? $key : md5($key);
} elseif (is_array($key)) {
if (count($key) == 1) {
return self::buildKey(reset($key));
}
ksort($key); // ensure order is always the same
$isNumeric = true;
foreach ($key as $value) {
if (!is_numeric($value)) {
$isNumeric = false;
}
}
if ($isNumeric) {
return implode('-', $key);
}
}
return md5(json_encode($key, JSON_NUMERIC_CHECK));
}
/**
* Returns the attribute values that have been modified since they are loaded or saved most recently.
* @param string[]|null $names the names of the attributes whose values may be returned if they are
* changed recently. If null, [[attributes()]] will be used.
* @return array the changed attribute values (name-value pairs)
*/
public function getDirtyAttributes($names = null)
{
if ($names === null) {
$names = $this->attributes();
}
$names = array_flip($names);
$attributes = [];
$attributesData = $this->attributes;
foreach ($attributesData as $name => $value) {
if (isset($names[$name]) && (!array_key_exists($name, $this->oldAttributes) || static::checkAttributeChanged($attributesData, $this->oldAttributes, $name))) {
$attributes[$name] = $value;
}
}
return $attributes;
}
/**
* Returns a value indicating whether the named attribute has been changed.
* @param string $name the name of the attribute.
* @param bool $identical whether the comparison of new and old value is made for
* identical values using `===`, defaults to `true`. Otherwise `==` is used for comparison.
* This parameter is available since version 2.0.4.
* @return bool whether the attribute has been changed
*/
public function isAttributeChanged($name, $identical = true)
{
return static::checkAttributeChanged($this->attributes, $this->oldAttributes, $name, $identical);
}
/**
* @param array $attributes current values
* @param array $oldAttributes old values
* @param string $name the name of the attribute.
* @param bool $identical
* @return bool whether the attribute has been changed
*/
protected static function checkAttributeChanged($attributes, $oldAttributes, $name, $identical = true)
{
if (isset($attributes[$name], $oldAttributes[$name])) {
if ($identical) {
if (is_bool($newValue = $attributes[$name])) {
$newValue = (int)$attributes[$name];
}
if (is_bool($oldValue = $oldAttributes[$name])) {
$oldValue = (int)$oldAttributes[$name];
}
if (is_array($newValue)) {
$newValue = serialize($newValue);
}
if (is_array($oldValue)) {
$oldValue = serialize($oldValue);
}
return (string)$newValue !== (string)$oldValue;
} else {
return $attributes[$name] != $oldAttributes[$name];
}
} else {
return isset($attributes[$name]) || isset($oldAttributes[$name]);
}
}
/**
* Populates an active record object using a row of data from the database/storage.
*
* This is an internal method meant to be called to create active record objects after
* fetching data from the database. It is mainly used by [[ActiveQuery]] to populate
* the query results into active records.
*
* When calling this method manually you should call [[afterFind()]] on the created
* record to trigger the [[EVENT_AFTER_FIND|afterFind Event]].
*
* @param BaseActiveRecord $record the record to be populated. In most cases this will be an instance
* created by [[instantiate()]] beforehand.
* @param array $row attribute values (name => value)
*/
public static function populateRecord($record, $row)
{
foreach ($record->attributes() as $name) {
if (!isset($row[$name])) {
$row[$name] = null;
}
}
parent::populateRecord($record, $row);
}
}