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.
323 lines
9.2 KiB
323 lines
9.2 KiB
12 years ago
|
<?php
|
||
|
/**
|
||
|
* @link http://www.yiiframework.com/
|
||
11 years ago
|
* @copyright Copyright (c) 2008 Yii Software LLC
|
||
12 years ago
|
* @license http://www.yiiframework.com/license/
|
||
|
*/
|
||
|
|
||
11 years ago
|
namespace yii\redis;
|
||
12 years ago
|
|
||
12 years ago
|
use yii\base\InvalidConfigException;
|
||
12 years ago
|
use yii\base\NotSupportedException;
|
||
11 years ago
|
use yii\helpers\StringHelper;
|
||
12 years ago
|
|
||
12 years ago
|
/**
|
||
|
* ActiveRecord is the base class for classes representing relational data in terms of objects.
|
||
|
*
|
||
11 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'];
|
||
|
* }
|
||
|
* }
|
||
|
* ```
|
||
|
*
|
||
12 years ago
|
* @author Carsten Brandt <mail@cebe.cc>
|
||
|
* @since 2.0
|
||
|
*/
|
||
11 years ago
|
class ActiveRecord extends \yii\db\ActiveRecord
|
||
12 years ago
|
{
|
||
|
/**
|
||
|
* Returns the database connection used by this AR class.
|
||
12 years ago
|
* By default, the "redis" application component is used as the database connection.
|
||
12 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()
|
||
|
{
|
||
11 years ago
|
return \Yii::$app->getComponent('redis');
|
||
12 years ago
|
}
|
||
|
|
||
|
/**
|
||
11 years ago
|
* @inheritDoc
|
||
|
*/
|
||
|
public static function createQuery()
|
||
|
{
|
||
|
return new ActiveQuery(['modelClass' => get_called_class()]);
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* @inheritDoc
|
||
|
*/
|
||
11 years ago
|
public static function createActiveRelation($config = [])
|
||
11 years ago
|
{
|
||
|
return new ActiveRelation($config);
|
||
|
}
|
||
|
|
||
|
/**
|
||
11 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.
|
||
11 years ago
|
*/
|
||
11 years ago
|
public static function primaryKey()
|
||
11 years ago
|
{
|
||
11 years ago
|
return ['id'];
|
||
11 years ago
|
}
|
||
|
|
||
|
/**
|
||
11 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.
|
||
11 years ago
|
*/
|
||
11 years ago
|
public static function attributes()
|
||
11 years ago
|
{
|
||
11 years ago
|
throw new InvalidConfigException('The attributes() method of redis ActiveRecord has to be implemented by child classes.');
|
||
11 years ago
|
}
|
||
|
|
||
|
/**
|
||
|
* @inheritDocs
|
||
|
*/
|
||
|
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) {
|
||
|
$pk[$key] = $values[$key] = $db->executeCommand('INCR', [static::tableName() . ':s:' . $key]);
|
||
|
$this->setAttribute($key, $values[$key]);
|
||
|
}
|
||
|
}
|
||
|
// }
|
||
|
// save pk in a findall pool
|
||
|
$db->executeCommand('RPUSH', [static::tableName(), static::buildKey($pk)]);
|
||
|
|
||
|
$key = static::tableName() . ':a:' . static::buildKey($pk);
|
||
|
// 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;
|
||
|
}
|
||
|
|
||
|
/**
|
||
12 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:
|
||
|
*
|
||
|
* ~~~
|
||
11 years ago
|
* Customer::updateAll(['status' => 1], ['id' => 2]);
|
||
12 years ago
|
* ~~~
|
||
|
*
|
||
|
* @param array $attributes attribute values (name-value pairs) to be saved into the table
|
||
11 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.
|
||
|
* @param array $params this parameter is ignored in redis implementation.
|
||
12 years ago
|
* @return integer the number of rows updated
|
||
|
*/
|
||
11 years ago
|
public static function updateAll($attributes, $condition = null, $params = [])
|
||
12 years ago
|
{
|
||
|
if (empty($attributes)) {
|
||
|
return 0;
|
||
|
}
|
||
11 years ago
|
$db = static::getDb();
|
||
12 years ago
|
$n=0;
|
||
11 years ago
|
foreach(static::fetchPks($condition) as $pk) {
|
||
|
$newPk = $pk;
|
||
|
$pk = static::buildKey($pk);
|
||
|
$key = static::tableName() . ':a:' . $pk;
|
||
12 years ago
|
// save attributes
|
||
11 years ago
|
$args = [$key];
|
||
12 years ago
|
foreach($attributes as $attribute => $value) {
|
||
11 years ago
|
if (isset($newPk[$attribute])) {
|
||
|
$newPk[$attribute] = $value;
|
||
|
}
|
||
12 years ago
|
$args[] = $attribute;
|
||
|
$args[] = $value;
|
||
|
}
|
||
11 years ago
|
$newPk = static::buildKey($newPk);
|
||
|
$newKey = static::tableName() . ':a:' . $newPk;
|
||
11 years ago
|
// rename index if pk changed
|
||
11 years ago
|
if ($newPk != $pk) {
|
||
11 years ago
|
$db->executeCommand('MULTI');
|
||
|
$db->executeCommand('HMSET', $args);
|
||
11 years ago
|
$db->executeCommand('LINSERT', [static::tableName(), 'AFTER', $pk, $newPk]);
|
||
|
$db->executeCommand('LREM', [static::tableName(), 0, $pk]);
|
||
|
$db->executeCommand('RENAME', [$key, $newKey]);
|
||
11 years ago
|
$db->executeCommand('EXEC');
|
||
|
} else {
|
||
|
$db->executeCommand('HMSET', $args);
|
||
11 years ago
|
}
|
||
12 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,
|
||
|
*
|
||
|
* ~~~
|
||
11 years ago
|
* Customer::updateAllCounters(['age' => 1]);
|
||
12 years ago
|
* ~~~
|
||
|
*
|
||
|
* @param array $counters the counters to be updated (attribute name => increment value).
|
||
|
* Use negative values if you want to decrement the counters.
|
||
11 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.
|
||
|
* @param array $params this parameter is ignored in redis implementation.
|
||
12 years ago
|
* @return integer the number of rows updated
|
||
|
*/
|
||
11 years ago
|
public static function updateAllCounters($counters, $condition = null, $params = [])
|
||
12 years ago
|
{
|
||
11 years ago
|
if (empty($counters)) {
|
||
|
return 0;
|
||
|
}
|
||
12 years ago
|
$db = static::getDb();
|
||
|
$n=0;
|
||
11 years ago
|
foreach(static::fetchPks($condition) as $pk) {
|
||
|
$key = static::tableName() . ':a:' . static::buildKey($pk);
|
||
12 years ago
|
foreach($counters as $attribute => $value) {
|
||
11 years ago
|
$db->executeCommand('HINCRBY', [$key, $attribute, $value]);
|
||
12 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:
|
||
|
*
|
||
|
* ~~~
|
||
11 years ago
|
* Customer::deleteAll(['status' => 3]);
|
||
12 years ago
|
* ~~~
|
||
|
*
|
||
11 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.
|
||
|
* @param array $params this parameter is ignored in redis implementation.
|
||
12 years ago
|
* @return integer the number of rows deleted
|
||
|
*/
|
||
11 years ago
|
public static function deleteAll($condition = null, $params = [])
|
||
12 years ago
|
{
|
||
|
$db = static::getDb();
|
||
11 years ago
|
$attributeKeys = [];
|
||
11 years ago
|
$pks = static::fetchPks($condition);
|
||
|
$db->executeCommand('MULTI');
|
||
|
foreach($pks as $pk) {
|
||
11 years ago
|
$pk = static::buildKey($pk);
|
||
11 years ago
|
$db->executeCommand('LREM', [static::tableName(), 0, $pk]);
|
||
12 years ago
|
$attributeKeys[] = static::tableName() . ':a:' . $pk;
|
||
12 years ago
|
}
|
||
11 years ago
|
if (empty($attributeKeys)) {
|
||
11 years ago
|
$db->executeCommand('EXEC');
|
||
11 years ago
|
return 0;
|
||
|
}
|
||
11 years ago
|
$db->executeCommand('DEL', $attributeKeys);
|
||
|
$result = $db->executeCommand('EXEC');
|
||
|
return end($result);
|
||
12 years ago
|
}
|
||
|
|
||
11 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();
|
||
|
|
||
11 years ago
|
$pks = [];
|
||
11 years ago
|
foreach($records as $record) {
|
||
11 years ago
|
$pk = [];
|
||
11 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)) {
|
||
|
return ctype_alnum($key) && StringHelper::strlen($key) <= 32 ? $key : md5($key);
|
||
|
} elseif (is_array($key)) {
|
||
|
if (count($key) == 1) {
|
||
|
return self::buildKey(reset($key));
|
||
|
}
|
||
11 years ago
|
ksort($key); // ensure order is always the same
|
||
11 years ago
|
$isNumeric = true;
|
||
|
foreach($key as $value) {
|
||
|
if (!is_numeric($value)) {
|
||
|
$isNumeric = false;
|
||
|
}
|
||
|
}
|
||
|
if ($isNumeric) {
|
||
|
return implode('-', $key);
|
||
|
}
|
||
|
}
|
||
|
return md5(json_encode($key));
|
||
|
}
|
||
|
|
||
12 years ago
|
/**
|
||
11 years ago
|
* @inheritdoc
|
||
|
*/
|
||
|
public static function getTableSchema()
|
||
|
{
|
||
11 years ago
|
throw new NotSupportedException('getTableSchema() is not supported by redis ActiveRecord.');
|
||
11 years ago
|
}
|
||
|
|
||
|
/**
|
||
|
* @inheritdoc
|
||
|
*/
|
||
|
public static function findBySql($sql, $params = [])
|
||
|
{
|
||
11 years ago
|
throw new NotSupportedException('findBySql() is not supported by redis ActiveRecord.');
|
||
11 years ago
|
}
|
||
|
|
||
|
/**
|
||
11 years ago
|
* Returns a value indicating whether the specified operation is transactional in the current [[scenario]].
|
||
|
* This method will always return false as transactional operations are not supported by redis.
|
||
|
* @param integer $operation the operation to check. Possible values are [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]].
|
||
|
* @return boolean whether the specified operation is transactional in the current [[scenario]].
|
||
11 years ago
|
*/
|
||
11 years ago
|
public function isTransactional($operation)
|
||
11 years ago
|
{
|
||
11 years ago
|
return false;
|
||
11 years ago
|
}
|
||
12 years ago
|
}
|