You can not select more than 25 topics
			Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
		
		
		
		
			
				
					306 lines
				
				8.7 KiB
			
		
		
			
		
	
	
					306 lines
				
				8.7 KiB
			| 
											13 years ago
										 | <?php
 | ||
|  | /**
 | ||
|  |  * @link http://www.yiiframework.com/
 | ||
| 
											12 years ago
										 |  * @copyright Copyright (c) 2008 Yii Software LLC
 | ||
| 
											13 years ago
										 |  * @license http://www.yiiframework.com/license/
 | ||
|  |  */
 | ||
|  | 
 | ||
| 
											12 years ago
										 | namespace yii\redis;
 | ||
| 
											13 years ago
										 | 
 | ||
| 
											13 years ago
										 | use yii\base\InvalidConfigException;
 | ||
| 
											12 years ago
										 | use yii\db\BaseActiveRecord;
 | ||
| 
											12 years ago
										 | use yii\helpers\Inflector;
 | ||
| 
											12 years ago
										 | use yii\helpers\StringHelper;
 | ||
| 
											13 years ago
										 | 
 | ||
| 
											13 years ago
										 | /**
 | ||
|  |  * ActiveRecord is the base class for classes representing relational data in terms of objects.
 | ||
|  |  *
 | ||
| 
											12 years ago
										 |  * 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'];
 | ||
|  |  *     }
 | ||
|  |  * }
 | ||
|  |  * ```
 | ||
|  |  *
 | ||
| 
											13 years ago
										 |  * @author Carsten Brandt <mail@cebe.cc>
 | ||
|  |  * @since 2.0
 | ||
|  |  */
 | ||
| 
											12 years ago
										 | class ActiveRecord extends BaseActiveRecord
 | ||
| 
											13 years ago
										 | {
 | ||
|  | 	/**
 | ||
|  | 	 * Returns the database connection used by this AR class.
 | ||
| 
											13 years ago
										 | 	 * By default, the "redis" application component is used as the database connection.
 | ||
| 
											13 years ago
										 | 	 * 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()
 | ||
|  | 	{
 | ||
| 
											12 years ago
										 | 		return \Yii::$app->getComponent('redis');
 | ||
| 
											13 years ago
										 | 	}
 | ||
|  | 
 | ||
|  | 	/**
 | ||
| 
											12 years ago
										 | 	 * @inheritdoc
 | ||
| 
											12 years ago
										 | 	 */
 | ||
|  | 	public static function createQuery()
 | ||
|  | 	{
 | ||
|  | 		return new ActiveQuery(['modelClass' => get_called_class()]);
 | ||
|  | 	}
 | ||
|  | 
 | ||
|  | 	/**
 | ||
| 
											12 years ago
										 | 	 * @inheritdoc
 | ||
| 
											12 years ago
										 | 	 */
 | ||
| 
											12 years ago
										 | 	public static function createActiveRelation($config = [])
 | ||
| 
											12 years ago
										 | 	{
 | ||
|  | 		return new ActiveRelation($config);
 | ||
|  | 	}
 | ||
|  | 
 | ||
|  | 	/**
 | ||
| 
											12 years ago
										 | 	 * 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.
 | ||
| 
											12 years ago
										 | 	 */
 | ||
| 
											12 years ago
										 | 	public static function primaryKey()
 | ||
| 
											12 years ago
										 | 	{
 | ||
| 
											12 years ago
										 | 		return ['id'];
 | ||
| 
											12 years ago
										 | 	}
 | ||
|  | 
 | ||
|  | 	/**
 | ||
| 
											12 years ago
										 | 	 * 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.
 | ||
| 
											12 years ago
										 | 	 */
 | ||
| 
											12 years ago
										 | 	public function attributes()
 | ||
| 
											12 years ago
										 | 	{
 | ||
| 
											12 years ago
										 | 		throw new InvalidConfigException('The attributes() method of redis ActiveRecord has to be implemented by child classes.');
 | ||
| 
											12 years ago
										 | 	}
 | ||
|  | 
 | ||
|  | 	/**
 | ||
| 
											12 years ago
										 | 	 * 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()
 | ||
|  | 	{
 | ||
| 
											12 years ago
										 | 		return Inflector::camel2id(StringHelper::basename(get_called_class()), '_');
 | ||
| 
											12 years ago
										 | 	}
 | ||
|  | 
 | ||
|  | 	/**
 | ||
| 
											12 years ago
										 | 	 * @inheritdoc
 | ||
| 
											12 years ago
										 | 	 */
 | ||
|  | 	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) {
 | ||
| 
											12 years ago
										 | 					$pk[$key] = $values[$key] = $db->executeCommand('INCR', [static::keyPrefix() . ':s:' . $key]);
 | ||
| 
											12 years ago
										 | 					$this->setAttribute($key, $values[$key]);
 | ||
|  | 				}
 | ||
|  | 			}
 | ||
|  | //			}
 | ||
|  | 			// save pk in a findall pool
 | ||
| 
											12 years ago
										 | 			$db->executeCommand('RPUSH', [static::keyPrefix(), static::buildKey($pk)]);
 | ||
| 
											12 years ago
										 | 
 | ||
| 
											12 years ago
										 | 			$key = static::keyPrefix() . ':a:' . static::buildKey($pk);
 | ||
| 
											12 years ago
										 | 			// 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;
 | ||
|  | 	}
 | ||
|  | 
 | ||
|  | 	/**
 | ||
| 
											13 years ago
										 | 	 * 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:
 | ||
|  | 	 *
 | ||
|  | 	 * ~~~
 | ||
| 
											12 years ago
										 | 	 * Customer::updateAll(['status' => 1], ['id' => 2]);
 | ||
| 
											13 years ago
										 | 	 * ~~~
 | ||
|  | 	 *
 | ||
|  | 	 * @param array $attributes attribute values (name-value pairs) to be saved into the table
 | ||
| 
											12 years ago
										 | 	 * @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.
 | ||
| 
											13 years ago
										 | 	 * @return integer the number of rows updated
 | ||
|  | 	 */
 | ||
| 
											12 years ago
										 | 	public static function updateAll($attributes, $condition = null)
 | ||
| 
											13 years ago
										 | 	{
 | ||
|  | 		if (empty($attributes)) {
 | ||
|  | 			return 0;
 | ||
|  | 		}
 | ||
| 
											12 years ago
										 | 		$db = static::getDb();
 | ||
| 
											13 years ago
										 | 		$n=0;
 | ||
| 
											12 years ago
										 | 		foreach(static::fetchPks($condition) as $pk) {
 | ||
|  | 			$newPk = $pk;
 | ||
|  | 			$pk = static::buildKey($pk);
 | ||
| 
											12 years ago
										 | 			$key = static::keyPrefix() . ':a:' . $pk;
 | ||
| 
											13 years ago
										 | 			// save attributes
 | ||
| 
											12 years ago
										 | 			$args = [$key];
 | ||
| 
											13 years ago
										 | 			foreach($attributes as $attribute => $value) {
 | ||
| 
											12 years ago
										 | 				if (isset($newPk[$attribute])) {
 | ||
|  | 					$newPk[$attribute] = $value;
 | ||
|  | 				}
 | ||
| 
											13 years ago
										 | 				$args[] = $attribute;
 | ||
|  | 				$args[] = $value;
 | ||
|  | 			}
 | ||
| 
											12 years ago
										 | 			$newPk = static::buildKey($newPk);
 | ||
| 
											12 years ago
										 | 			$newKey = static::keyPrefix() . ':a:' . $newPk;
 | ||
| 
											12 years ago
										 | 			// rename index if pk changed
 | ||
| 
											12 years ago
										 | 			if ($newPk != $pk) {
 | ||
| 
											12 years ago
										 | 				$db->executeCommand('MULTI');
 | ||
|  | 				$db->executeCommand('HMSET', $args);
 | ||
| 
											12 years ago
										 | 				$db->executeCommand('LINSERT', [static::keyPrefix(), 'AFTER', $pk, $newPk]);
 | ||
|  | 				$db->executeCommand('LREM', [static::keyPrefix(), 0, $pk]);
 | ||
| 
											12 years ago
										 | 				$db->executeCommand('RENAME', [$key, $newKey]);
 | ||
| 
											12 years ago
										 | 				$db->executeCommand('EXEC');
 | ||
|  | 			} else {
 | ||
|  | 				$db->executeCommand('HMSET', $args);
 | ||
| 
											12 years ago
										 | 			}
 | ||
| 
											13 years ago
										 | 			$n++;
 | ||
|  | 		}
 | ||
|  | 		return $n;
 | ||
|  | 	}
 | ||
|  | 
 | ||
|  | 	/**
 | ||
|  | 	 * Updates the whole table using the provided counter changes and conditions.
 | ||
|  | 	 * For example, to increment all customers' age by 1,
 | ||
|  | 	 *
 | ||
|  | 	 * ~~~
 | ||
| 
											12 years ago
										 | 	 * Customer::updateAllCounters(['age' => 1]);
 | ||
| 
											13 years ago
										 | 	 * ~~~
 | ||
|  | 	 *
 | ||
|  | 	 * @param array $counters the counters to be updated (attribute name => increment value).
 | ||
|  | 	 * Use negative values if you want to decrement the counters.
 | ||
| 
											12 years ago
										 | 	 * @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.
 | ||
| 
											13 years ago
										 | 	 * @return integer the number of rows updated
 | ||
|  | 	 */
 | ||
| 
											12 years ago
										 | 	public static function updateAllCounters($counters, $condition = null)
 | ||
| 
											13 years ago
										 | 	{
 | ||
| 
											12 years ago
										 | 		if (empty($counters)) {
 | ||
|  | 			return 0;
 | ||
|  | 		}
 | ||
| 
											13 years ago
										 | 		$db = static::getDb();
 | ||
|  | 		$n=0;
 | ||
| 
											12 years ago
										 | 		foreach(static::fetchPks($condition) as $pk) {
 | ||
| 
											12 years ago
										 | 			$key = static::keyPrefix() . ':a:' . static::buildKey($pk);
 | ||
| 
											13 years ago
										 | 			foreach($counters as $attribute => $value) {
 | ||
| 
											12 years ago
										 | 				$db->executeCommand('HINCRBY', [$key, $attribute, $value]);
 | ||
| 
											13 years ago
										 | 			}
 | ||
|  | 			$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:
 | ||
|  | 	 *
 | ||
|  | 	 * ~~~
 | ||
| 
											12 years ago
										 | 	 * Customer::deleteAll(['status' => 3]);
 | ||
| 
											13 years ago
										 | 	 * ~~~
 | ||
|  | 	 *
 | ||
| 
											12 years ago
										 | 	 * @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.
 | ||
| 
											13 years ago
										 | 	 * @return integer the number of rows deleted
 | ||
|  | 	 */
 | ||
| 
											12 years ago
										 | 	public static function deleteAll($condition = null)
 | ||
| 
											13 years ago
										 | 	{
 | ||
|  | 		$db = static::getDb();
 | ||
| 
											12 years ago
										 | 		$attributeKeys = [];
 | ||
| 
											12 years ago
										 | 		$pks = static::fetchPks($condition);
 | ||
|  | 		$db->executeCommand('MULTI');
 | ||
|  | 		foreach($pks as $pk) {
 | ||
| 
											12 years ago
										 | 			$pk = static::buildKey($pk);
 | ||
| 
											12 years ago
										 | 			$db->executeCommand('LREM', [static::keyPrefix(), 0, $pk]);
 | ||
|  | 			$attributeKeys[] = static::keyPrefix() . ':a:' . $pk;
 | ||
| 
											13 years ago
										 | 		}
 | ||
| 
											12 years ago
										 | 		if (empty($attributeKeys)) {
 | ||
| 
											12 years ago
										 | 			$db->executeCommand('EXEC');
 | ||
| 
											12 years ago
										 | 			return 0;
 | ||
|  | 		}
 | ||
| 
											12 years ago
										 | 		$db->executeCommand('DEL', $attributeKeys);
 | ||
|  | 		$result = $db->executeCommand('EXEC');
 | ||
|  | 		return end($result);
 | ||
| 
											13 years ago
										 | 	}
 | ||
|  | 
 | ||
| 
											12 years ago
										 | 	private static function fetchPks($condition)
 | ||
|  | 	{
 | ||
|  | 		$query = static::createQuery();
 | ||
|  | 		$query->where($condition);
 | ||
|  | 		$records = $query->asArray()->all(); // TODO limit fetched columns to pk
 | ||
|  | 		$primaryKey = static::primaryKey();
 | ||
|  | 
 | ||
| 
											12 years ago
										 | 		$pks = [];
 | ||
| 
											12 years ago
										 | 		foreach($records as $record) {
 | ||
| 
											12 years ago
										 | 			$pk = [];
 | ||
| 
											12 years ago
										 | 			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)) {
 | ||
| 
											12 years ago
										 | 			return ctype_alnum($key) && StringHelper::byteLength($key) <= 32 ? $key : md5($key);
 | ||
| 
											12 years ago
										 | 		} elseif (is_array($key)) {
 | ||
|  | 			if (count($key) == 1) {
 | ||
|  | 				return self::buildKey(reset($key));
 | ||
|  | 			}
 | ||
| 
											12 years ago
										 | 			ksort($key); // ensure order is always the same
 | ||
| 
											12 years ago
										 | 			$isNumeric = true;
 | ||
|  | 			foreach($key as $value) {
 | ||
|  | 				if (!is_numeric($value)) {
 | ||
|  | 					$isNumeric = false;
 | ||
|  | 				}
 | ||
|  | 			}
 | ||
|  | 			if ($isNumeric) {
 | ||
|  | 				return implode('-', $key);
 | ||
|  | 			}
 | ||
|  | 		}
 | ||
|  | 		return md5(json_encode($key));
 | ||
|  | 	}
 | ||
| 
											13 years ago
										 | }
 |