ActiveRecord.php 9.47 KB
Newer Older
Carsten Brandt committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
Carsten Brandt committed
5 6 7
 * @license http://www.yiiframework.com/license/
 */

8
namespace yii\redis;
Carsten Brandt committed
9

10
use yii\base\InvalidConfigException;
Carsten Brandt committed
11
use yii\db\BaseActiveRecord;
12
use yii\helpers\Inflector;
13
use yii\helpers\StringHelper;
14

Carsten Brandt committed
15 16 17
/**
 * ActiveRecord is the base class for classes representing relational data in terms of objects.
 *
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
 * 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'];
 *     }
 * }
 * ```
 *
Carsten Brandt committed
35 36 37
 * @author Carsten Brandt <mail@cebe.cc>
 * @since 2.0
 */
Carsten Brandt committed
38
class ActiveRecord extends BaseActiveRecord
Carsten Brandt committed
39 40 41
{
	/**
	 * Returns the database connection used by this AR class.
42
	 * By default, the "redis" application component is used as the database connection.
Carsten Brandt committed
43 44 45 46 47
	 * 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()
	{
48
		return \Yii::$app->getComponent('redis');
Carsten Brandt committed
49 50
	}

51
	/**
52 53 54 55 56 57 58 59 60 61
	 * Creates an [[ActiveQuery]] instance.
	 *
	 * This method is called by [[find()]], [[findBySql()]] to start a SELECT query but also
	 * by [[hasOne()]] and [[hasMany()]] to create a relational query.
	 * You may override this method to return a customized query (e.g. `CustomerQuery` specified
	 * written for querying `Customer` purpose.)
	 *
	 * You may also define default conditions that should apply to all queries unless overridden:
	 *
	 * ```php
62
	 * public static function createQuery($config= [])
63
	 * {
64
	 *     return parent::createQuery($config)->where(['deleted' => false]);
65 66 67 68 69 70
	 * }
	 * ```
	 *
	 * Note that all queries should use [[Query::andWhere()]] and [[Query::orWhere()]] to keep the
	 * default condition. Using [[Query::where()]] will override the default condition.
	 *
71
	 * @param array $config the configuration passed to the ActiveQuery class.
72
	 * @return ActiveQuery the newly created [[ActiveQuery]] instance.
73
	 */
74
	public static function createQuery($config = [])
75
	{
76 77
		$config['modelClass'] = get_called_class();
		return new ActiveQuery($config);
78 79 80
	}

	/**
81 82 83 84 85 86
	 * 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.
87
	 */
88
	public static function primaryKey()
89
	{
90
		return ['id'];
91 92 93
	}

	/**
94 95 96
	 * 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.
97
	 */
98
	public function attributes()
99
	{
100
		throw new InvalidConfigException('The attributes() method of redis ActiveRecord has to be implemented by child classes.');
101 102
	}

103 104 105 106 107 108 109 110 111
	/**
	 * 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()
	{
112
		return Inflector::camel2id(StringHelper::basename(get_called_class()), '_');
113 114
	}

115
	/**
Qiang Xue committed
116
	 * @inheritdoc
117 118 119 120 121 122 123 124 125 126 127 128 129 130
	 */
	public function insert($runValidation = true, $attributes = null)
	{
		if ($runValidation && !$this->validate($attributes)) {
			return false;
		}
		if ($this->beforeSave(true)) {
			$db = static::getDb();
			$values = $this->getDirtyAttributes($attributes);
			$pk = [];
//			if ($values === []) {
			foreach ($this->primaryKey() as $key) {
				$pk[$key] = $values[$key] = $this->getAttribute($key);
				if ($pk[$key] === null) {
131
					$pk[$key] = $values[$key] = $db->executeCommand('INCR', [static::keyPrefix() . ':s:' . $key]);
132 133 134 135 136
					$this->setAttribute($key, $values[$key]);
				}
			}
//			}
			// save pk in a findall pool
137
			$db->executeCommand('RPUSH', [static::keyPrefix(), static::buildKey($pk)]);
138

139
			$key = static::keyPrefix() . ':a:' . static::buildKey($pk);
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
			// save attributes
			$args = [$key];
			foreach($values as $attribute => $value) {
				$args[] = $attribute;
				$args[] = $value;
			}
			$db->executeCommand('HMSET', $args);

			$this->setOldAttributes($values);
			$this->afterSave(true);
			return true;
		}
		return false;
	}

155 156 157 158 159
	/**
	 * 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:
	 *
	 * ~~~
160
	 * Customer::updateAll(['status' => 1], ['id' => 2]);
161 162 163
	 * ~~~
	 *
	 * @param array $attributes attribute values (name-value pairs) to be saved into the table
164 165
	 * @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.
166 167
	 * @return integer the number of rows updated
	 */
168
	public static function updateAll($attributes, $condition = null)
169 170 171 172
	{
		if (empty($attributes)) {
			return 0;
		}
Carsten Brandt committed
173
		$db = static::getDb();
174
		$n=0;
175 176 177
		foreach(static::fetchPks($condition) as $pk) {
			$newPk = $pk;
			$pk = static::buildKey($pk);
178
			$key = static::keyPrefix() . ':a:' . $pk;
179
			// save attributes
180
			$args = [$key];
181
			foreach($attributes as $attribute => $value) {
182 183 184
				if (isset($newPk[$attribute])) {
					$newPk[$attribute] = $value;
				}
185 186 187
				$args[] = $attribute;
				$args[] = $value;
			}
188
			$newPk = static::buildKey($newPk);
189
			$newKey = static::keyPrefix() . ':a:' . $newPk;
190
			// rename index if pk changed
191
			if ($newPk != $pk) {
192 193
				$db->executeCommand('MULTI');
				$db->executeCommand('HMSET', $args);
194 195
				$db->executeCommand('LINSERT', [static::keyPrefix(), 'AFTER', $pk, $newPk]);
				$db->executeCommand('LREM', [static::keyPrefix(), 0, $pk]);
196
				$db->executeCommand('RENAME', [$key, $newKey]);
197 198 199
				$db->executeCommand('EXEC');
			} else {
				$db->executeCommand('HMSET', $args);
200
			}
201 202 203 204 205 206 207 208 209 210
			$n++;
		}
		return $n;
	}

	/**
	 * Updates the whole table using the provided counter changes and conditions.
	 * For example, to increment all customers' age by 1,
	 *
	 * ~~~
211
	 * Customer::updateAllCounters(['age' => 1]);
212 213 214 215
	 * ~~~
	 *
	 * @param array $counters the counters to be updated (attribute name => increment value).
	 * Use negative values if you want to decrement the counters.
216 217
	 * @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.
218 219
	 * @return integer the number of rows updated
	 */
220
	public static function updateAllCounters($counters, $condition = null)
221
	{
Carsten Brandt committed
222 223 224
		if (empty($counters)) {
			return 0;
		}
225 226
		$db = static::getDb();
		$n=0;
227
		foreach(static::fetchPks($condition) as $pk) {
228
			$key = static::keyPrefix() . ':a:' . static::buildKey($pk);
229
			foreach($counters as $attribute => $value) {
230
				$db->executeCommand('HINCRBY', [$key, $attribute, $value]);
231 232 233 234 235 236 237 238 239 240 241 242 243
			}
			$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:
	 *
	 * ~~~
244
	 * Customer::deleteAll(['status' => 3]);
245 246
	 * ~~~
	 *
247 248
	 * @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.
249 250
	 * @return integer the number of rows deleted
	 */
251
	public static function deleteAll($condition = null)
252 253
	{
		$db = static::getDb();
254
		$attributeKeys = [];
255 256 257
		$pks = static::fetchPks($condition);
		$db->executeCommand('MULTI');
		foreach($pks as $pk) {
258
			$pk = static::buildKey($pk);
259 260
			$db->executeCommand('LREM', [static::keyPrefix(), 0, $pk]);
			$attributeKeys[] = static::keyPrefix() . ':a:' . $pk;
261
		}
262
		if (empty($attributeKeys)) {
263
			$db->executeCommand('EXEC');
264 265
			return 0;
		}
266 267 268
		$db->executeCommand('DEL', $attributeKeys);
		$result = $db->executeCommand('EXEC');
		return end($result);
269 270
	}

271 272 273 274 275 276 277
	private static function fetchPks($condition)
	{
		$query = static::createQuery();
		$query->where($condition);
		$records = $query->asArray()->all(); // TODO limit fetched columns to pk
		$primaryKey = static::primaryKey();

278
		$pks = [];
279
		foreach($records as $record) {
280
			$pk = [];
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
			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)) {
300
			return ctype_alnum($key) && StringHelper::byteLength($key) <= 32 ? $key : md5($key);
301 302 303 304
		} elseif (is_array($key)) {
			if (count($key) == 1) {
				return self::buildKey(reset($key));
			}
305
			ksort($key); // ensure order is always the same
306 307 308 309 310 311 312 313 314 315 316 317
			$isNumeric = true;
			foreach($key as $value) {
				if (!is_numeric($value)) {
					$isNumeric = false;
				}
			}
			if ($isNumeric) {
				return implode('-', $key);
			}
		}
		return md5(json_encode($key));
	}
Carsten Brandt committed
318
}