ActiveQuery.php 12 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;
9
use yii\base\InvalidParamException;
Carsten Brandt committed
10
use yii\base\NotSupportedException;
11 12 13
use yii\db\ActiveQueryInterface;
use yii\db\ActiveQueryTrait;
use yii\db\QueryTrait;
Carsten Brandt committed
14 15

/**
16
 * ActiveQuery represents a query associated with an Active Record class.
Carsten Brandt committed
17
 *
18 19
 * ActiveQuery instances are usually created by [[ActiveRecord::find()]]
 * and [[ActiveRecord::count()]].
20 21 22 23 24 25 26 27 28 29 30 31 32
 *
 * ActiveQuery mainly provides the following methods to retrieve the query results:
 *
 * - [[one()]]: returns a single record populated with the first row of data.
 * - [[all()]]: returns all records based on the query results.
 * - [[count()]]: returns the number of records.
 * - [[sum()]]: returns the sum over the specified column.
 * - [[average()]]: returns the average over the specified column.
 * - [[min()]]: returns the min over the specified column.
 * - [[max()]]: returns the max over the specified column.
 * - [[scalar()]]: returns the value of the first column in the first row of the query result.
 * - [[exists()]]: returns a value indicating whether the query result has data or not.
 *
33
 * You can use query methods, such as [[where()]], [[limit()]] and [[orderBy()]] to customize the query options.
34 35 36 37 38 39 40 41 42 43 44 45
 *
 * ActiveQuery also provides the following additional query options:
 *
 * - [[with()]]: list of relations that this query should be performed with.
 * - [[indexBy()]]: the name of the column by which the query result should be indexed.
 * - [[asArray()]]: whether to return each record as an array.
 *
 * These options can be configured using methods of the same name. For example:
 *
 * ~~~
 * $customers = Customer::find()->with('orders')->asArray()->all();
 * ~~~
Carsten Brandt committed
46 47 48 49
 *
 * @author Carsten Brandt <mail@cebe.cc>
 * @since 2.0
 */
50
class ActiveQuery extends \yii\base\Component implements ActiveQueryInterface
Carsten Brandt committed
51
{
52 53
	use QueryTrait;
	use ActiveQueryTrait;
54

Carsten Brandt committed
55
	/**
56 57 58
	 * Executes the query and returns all results as an array.
	 * @param Connection $db the database connection used to execute the query.
	 * If this parameter is not given, the `db` application component will be used.
59
	 * @return array|ActiveRecord[] the query results. If the query results in nothing, an empty array will be returned.
Carsten Brandt committed
60
	 */
61
	public function all($db = null)
Carsten Brandt committed
62 63
	{
		// TODO add support for orderBy
64 65
		$data = $this->executeScript($db, 'All');
		$rows = [];
66
		foreach($data as $dataRow) {
67
			$row = [];
68 69 70
			$c = count($dataRow);
			for($i = 0; $i < $c; ) {
				$row[$dataRow[$i++]] = $dataRow[$i++];
71 72
			}
			$rows[] = $row;
73
		}
74
		if (!empty($rows)) {
Carsten Brandt committed
75 76
			$models = $this->createModels($rows);
			if (!empty($this->with)) {
77
				$this->findWith($this->with, $models);
Carsten Brandt committed
78 79 80
			}
			return $models;
		} else {
81
			return [];
Carsten Brandt committed
82 83 84 85
		}
	}

	/**
86 87 88
	 * Executes the query and returns a single row of result.
	 * @param Connection $db the database connection used to execute the query.
	 * If this parameter is not given, the `db` application component will be used.
Carsten Brandt committed
89 90 91 92
	 * @return ActiveRecord|array|null a single row of query result. Depending on the setting of [[asArray]],
	 * the query result may be either an array or an ActiveRecord object. Null will be returned
	 * if the query results in nothing.
	 */
93
	public function one($db = null)
Carsten Brandt committed
94
	{
Carsten Brandt committed
95
		// TODO add support for orderBy
96 97
		$data = $this->executeScript($db, 'One');
		if (empty($data)) {
98 99
			return null;
		}
100
		$row = [];
101 102
		$c = count($data);
		for($i = 0; $i < $c; ) {
103 104
			$row[$data[$i++]] = $data[$i++];
		}
105 106 107
		if ($this->asArray) {
			$model = $row;
		} else {
108
			/** @var ActiveRecord $class */
Carsten Brandt committed
109 110 111
			$class = $this->modelClass;
			$model = $class::create($row);
		}
112
		if (!empty($this->with)) {
113 114
			$models = [$model];
			$this->findWith($this->with, $models);
115 116 117
			$model = $models[0];
		}
		return $model;
Carsten Brandt committed
118 119 120 121
	}

	/**
	 * Returns the number of records.
122 123 124
	 * @param string $q the COUNT expression. This parameter is ignored by this implementation.
	 * @param Connection $db the database connection used to execute the query.
	 * If this parameter is not given, the `db` application component will be used.
Carsten Brandt committed
125 126
	 * @return integer number of records
	 */
127
	public function count($q = '*', $db = null)
Carsten Brandt committed
128
	{
129
		if ($this->where === null) {
Carsten Brandt committed
130
			/** @var ActiveRecord $modelClass */
Carsten Brandt committed
131
			$modelClass = $this->modelClass;
132 133 134
			if ($db === null) {
				$db = $modelClass::getDb();
			}
135
			return $db->executeCommand('LLEN', [$modelClass::keyPrefix()]);
136
		} else {
137
			return $this->executeScript($db, 'Count');
138
		}
Carsten Brandt committed
139 140
	}

141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
	/**
	 * Returns a value indicating whether the query result contains any row of data.
	 * @param Connection $db the database connection used to execute the query.
	 * If this parameter is not given, the `db` application component will be used.
	 * @return boolean whether the query result contains any row of data.
	 */
	public function exists($db = null)
	{
		return $this->one($db) !== null;
	}

	/**
	 * Executes the query and returns the first column of the result.
	 * @param string $column name of the column to select
	 * @param Connection $db the database connection used to execute the query.
	 * If this parameter is not given, the `db` application component will be used.
	 * @return array the first column of the query result. An empty array is returned if the query results in nothing.
	 */
	public function column($column, $db = null)
	{
Carsten Brandt committed
161
		// TODO add support for orderBy
162 163 164
		return $this->executeScript($db, 'Column', $column);
	}

165 166 167
	/**
	 * Returns the number of records.
	 * @param string $column the column to sum up
168 169
	 * @param Connection $db the database connection used to execute the query.
	 * If this parameter is not given, the `db` application component will be used.
170 171
	 * @return integer number of records
	 */
172
	public function sum($column, $db = null)
173
	{
174
		return $this->executeScript($db, 'Sum', $column);
175 176
	}

177 178 179 180
	/**
	 * Returns the average of the specified column values.
	 * @param string $column the column name or expression.
	 * Make sure you properly quote column names in the expression.
181 182
	 * @param Connection $db the database connection used to execute the query.
	 * If this parameter is not given, the `db` application component will be used.
183 184
	 * @return integer the average of the specified column values.
	 */
185
	public function average($column, $db = null)
186
	{
187
		return $this->executeScript($db, 'Average', $column);
188 189 190 191 192 193
	}

	/**
	 * Returns the minimum of the specified column values.
	 * @param string $column the column name or expression.
	 * Make sure you properly quote column names in the expression.
194 195
	 * @param Connection $db the database connection used to execute the query.
	 * If this parameter is not given, the `db` application component will be used.
196 197
	 * @return integer the minimum of the specified column values.
	 */
198
	public function min($column, $db = null)
199
	{
200
		return $this->executeScript($db, 'Min', $column);
201 202 203 204 205 206
	}

	/**
	 * Returns the maximum of the specified column values.
	 * @param string $column the column name or expression.
	 * Make sure you properly quote column names in the expression.
207 208
	 * @param Connection $db the database connection used to execute the query.
	 * If this parameter is not given, the `db` application component will be used.
209 210
	 * @return integer the maximum of the specified column values.
	 */
211
	public function max($column, $db = null)
212
	{
213
		return $this->executeScript($db, 'Max', $column);
214 215
	}

Carsten Brandt committed
216 217
	/**
	 * Returns the query result as a scalar value.
218 219
	 * The value returned will be the specified attribute in the first record of the query results.
	 * @param string $attribute name of the attribute to select
220 221
	 * @param Connection $db the database connection used to execute the query.
	 * If this parameter is not given, the `db` application component will be used.
222 223
	 * @return string the value of the specified attribute in the first record of the query result.
	 * Null is returned if the query result is empty.
Carsten Brandt committed
224
	 */
225
	public function scalar($attribute, $db = null)
Carsten Brandt committed
226
	{
227
		$record = $this->one($db);
228
		if ($record !== null) {
229
			return $record->hasAttribute($attribute) ? $record->$attribute : null;
230
		} else {
231
			return null;
232
		}
Carsten Brandt committed
233 234 235
	}


236 237
	/**
	 * Executes a script created by [[LuaScriptBuilder]]
238 239 240 241
	 * @param Connection $db the database connection used to execute the query.
	 * If this parameter is not given, the `db` application component will be used.
	 * @param string $type the type of the script to generate
	 * @param string $columnName
242 243
	 * @return array|bool|null|string
	 */
244
	protected function executeScript($db, $type, $columnName = null)
245
	{
Carsten Brandt committed
246 247 248 249
		if (!empty($this->orderBy)) {
			throw new NotSupportedException('orderBy is currently not supported by redis ActiveRecord.');
		}

250 251 252 253
		/** @var ActiveRecord $modelClass */
		$modelClass = $this->modelClass;

		if ($db === null) {
254
			$db = $modelClass::getDb();
255
		}
256

257 258 259
		// find by primary key if possible. This is much faster than scanning all records
		if (is_array($this->where) && !isset($this->where[0]) && $modelClass::isPrimaryKey(array_keys($this->where))) {
			return $this->findByPk($db, $type, $columnName);
260
		}
261 262 263 264

		$method = 'build' . $type;
		$script = $db->getLuaScriptBuilder()->$method($this, $columnName);
		return $db->executeCommand('EVAL', [$script, 0]);
265 266 267 268
	}

	/**
	 * Fetch by pk if possible as this is much faster
269 270 271 272 273
	 * @param Connection $db the database connection used to execute the query.
	 * If this parameter is not given, the `db` application component will be used.
	 * @param string $type the type of the script to generate
	 * @param string $columnName
	 * @return array|bool|null|string
Carsten Brandt committed
274
	 * @throws \yii\base\InvalidParamException
275
	 * @throws \yii\base\NotSupportedException
276
	 */
277
	private function findByPk($db, $type, $columnName = null)
278
	{
279 280 281 282 283 284
		if (count($this->where) == 1) {
			$pks = (array) reset($this->where);
		} else {
			foreach($this->where as $column => $values) {
				if (is_array($values)) {
					// TODO support composite IN for composite PK
Carsten Brandt committed
285
					throw new NotSupportedException('Find by composite PK is not supported by redis ActiveRecord.');
286
				}
287
			}
288 289
			$pks = [$this->where];
		}
290

291 292 293
		/** @var ActiveRecord $modelClass */
		$modelClass = $this->modelClass;

294 295 296 297 298 299 300
		if ($type == 'Count') {
			$start = 0;
			$limit = null;
		} else {
			$start = $this->offset === null ? 0 : $this->offset;
			$limit = $this->limit;
		}
301 302 303
		$i = 0;
		$data = [];
		foreach($pks as $pk) {
304
			if (++$i > $start && ($limit === null || $i <= $start + $limit)) {
305
				$key = $modelClass::keyPrefix() . ':a:' . $modelClass::buildKey($pk);
306 307 308 309 310
				$result = $db->executeCommand('HGETALL', [$key]);
				if (!empty($result)) {
					$data[] = $result;
					if ($type === 'One' && $this->orderBy === null) {
						break;
311 312 313
					}
				}
			}
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
		}
		// TODO support orderBy

		switch($type) {
			case 'All':
				return $data;
			case 'One':
				return reset($data);
			case 'Count':
				return count($data);
			case 'Column':
				$column = [];
				foreach($data as $dataRow) {
					$row = [];
					$c = count($dataRow);
					for($i = 0; $i < $c; ) {
						$row[$dataRow[$i++]] = $dataRow[$i++];
331
					}
332 333 334 335 336 337 338 339 340 341 342
					$column[] = $row[$columnName];
				}
				return $column;
			case 'Sum':
				$sum = 0;
				foreach($data as $dataRow) {
					$c = count($dataRow);
					for($i = 0; $i < $c; ) {
						if ($dataRow[$i++] == $columnName) {
							$sum += $dataRow[$i];
							break;
343 344
						}
					}
345 346 347 348 349 350 351 352 353 354 355 356
				}
				return $sum;
			case 'Average':
				$sum = 0;
				$count = 0;
				foreach($data as $dataRow) {
					$count++;
					$c = count($dataRow);
					for($i = 0; $i < $c; ) {
						if ($dataRow[$i++] == $columnName) {
							$sum += $dataRow[$i];
							break;
357 358
						}
					}
359 360 361 362 363 364 365 366 367 368
				}
				return $sum / $count;
			case 'Min':
				$min = null;
				foreach($data as $dataRow) {
					$c = count($dataRow);
					for($i = 0; $i < $c; ) {
						if ($dataRow[$i++] == $columnName && ($min == null || $dataRow[$i] < $min)) {
							$min = $dataRow[$i];
							break;
369 370
						}
					}
371
				}
372 373 374 375 376 377 378 379 380 381
				return $min;
			case 'Max':
				$max = null;
				foreach($data as $dataRow) {
					$c = count($dataRow);
					for($i = 0; $i < $c; ) {
						if ($dataRow[$i++] == $columnName && ($max == null || $dataRow[$i] > $max)) {
							$max = $dataRow[$i];
							break;
						}
382
					}
383
				}
384
				return $max;
385
		}
386
		throw new InvalidParamException('Unknown fetch type: ' . $type);
387
	}
Carsten Brandt committed
388
}