ActiveQuery.php 14 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

10
use yii\base\InvalidParamException;
Carsten Brandt committed
11
use yii\base\NotSupportedException;
12 13
use yii\db\ActiveQueryInterface;
use yii\db\ActiveQueryTrait;
14
use yii\db\ActiveRelationTrait;
15
use yii\db\QueryTrait;
Carsten Brandt committed
16 17

/**
18
 * ActiveQuery represents a query associated with an Active Record class.
Carsten Brandt committed
19
 *
20 21 22 23 24 25 26
 * An ActiveQuery can be a normal query or be used in a relational context.
 *
 * ActiveQuery instances are usually created by [[ActiveRecord::find()]].
 * Relational queries are created by [[ActiveRecord::hasOne()]] and [[ActiveRecord::hasMany()]].
 *
 * Normal Query
 * ------------
27 28 29 30 31 32 33 34 35 36 37 38 39
 *
 * 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.
 *
40
 * You can use query methods, such as [[where()]], [[limit()]] and [[orderBy()]] to customize the query options.
41 42 43 44 45 46 47 48 49
 *
 * 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:
 *
50
 * ```php
51
 * $customers = Customer::find()->with('orders')->asArray()->all();
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
 * ```
 *
 * Relational query
 * ----------------
 *
 * In relational context ActiveQuery represents a relation between two Active Record classes.
 *
 * Relational ActiveQuery instances are usually created by calling [[ActiveRecord::hasOne()]] and
 * [[ActiveRecord::hasMany()]]. An Active Record class declares a relation by defining
 * a getter method which calls one of the above methods and returns the created ActiveQuery object.
 *
 * A relation is specified by [[link]] which represents the association between columns
 * of different tables; and the multiplicity of the relation is indicated by [[multiple]].
 *
 * If a relation involves a pivot table, it may be specified by [[via()]].
 * This methods may only be called in a relational context. Same is true for [[inverseOf()]], which
 * marks a relation as inverse of another relation.
Carsten Brandt committed
69 70 71 72
 *
 * @author Carsten Brandt <mail@cebe.cc>
 * @since 2.0
 */
73
class ActiveQuery extends \yii\base\Component implements ActiveQueryInterface
Carsten Brandt committed
74
{
75 76
	use QueryTrait;
	use ActiveQueryTrait;
77
	use ActiveRelationTrait;
78

Carsten Brandt committed
79
	/**
80 81 82
	 * 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.
83
	 * @return array|ActiveRecord[] the query results. If the query results in nothing, an empty array will be returned.
Carsten Brandt committed
84
	 */
85
	public function all($db = null)
Carsten Brandt committed
86 87
	{
		// TODO add support for orderBy
88 89
		$data = $this->executeScript($db, 'All');
		$rows = [];
90
		foreach($data as $dataRow) {
91
			$row = [];
92 93 94
			$c = count($dataRow);
			for($i = 0; $i < $c; ) {
				$row[$dataRow[$i++]] = $dataRow[$i++];
95 96
			}
			$rows[] = $row;
97
		}
98
		if (!empty($rows)) {
Carsten Brandt committed
99
			$models = $this->createModels($rows);
Carsten Brandt committed
100
			if (!empty($this->with)) {
101
				$this->findWith($this->with, $models);
Carsten Brandt committed
102 103 104 105
			}
			if (!$this->asArray) {
				foreach($models as $model) {
					$model->afterFind();
106
				}
Carsten Brandt committed
107
			}
Carsten Brandt committed
108
			return $models;
Carsten Brandt committed
109
		} else {
110
			return [];
Carsten Brandt committed
111 112 113 114
		}
	}

	/**
115 116 117
	 * 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
118 119 120 121
	 * @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.
	 */
122
	public function one($db = null)
Carsten Brandt committed
123
	{
Carsten Brandt committed
124
		// TODO add support for orderBy
125 126
		$data = $this->executeScript($db, 'One');
		if (empty($data)) {
127 128
			return null;
		}
129
		$row = [];
130 131
		$c = count($data);
		for($i = 0; $i < $c; ) {
132 133
			$row[$data[$i++]] = $data[$i++];
		}
134 135 136
		if ($this->asArray) {
			$model = $row;
		} else {
137
			/** @var ActiveRecord $class */
Carsten Brandt committed
138
			$class = $this->modelClass;
139 140
			$model = $class::instantiate($row);
			$class::populateRecord($model, $row);
Carsten Brandt committed
141
		}
142
		if (!empty($this->with)) {
143 144
			$models = [$model];
			$this->findWith($this->with, $models);
145 146
			$model = $models[0];
		}
147 148 149
		if (!$this->asArray) {
			$model->afterFind();
		}
150
		return $model;
Carsten Brandt committed
151 152 153 154
	}

	/**
	 * Returns the number of records.
155 156 157
	 * @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
158 159
	 * @return integer number of records
	 */
160
	public function count($q = '*', $db = null)
Carsten Brandt committed
161
	{
162
		if ($this->where === null) {
Carsten Brandt committed
163
			/** @var ActiveRecord $modelClass */
Carsten Brandt committed
164
			$modelClass = $this->modelClass;
165 166 167
			if ($db === null) {
				$db = $modelClass::getDb();
			}
168
			return $db->executeCommand('LLEN', [$modelClass::keyPrefix()]);
169
		} else {
170
			return $this->executeScript($db, 'Count');
171
		}
Carsten Brandt committed
172 173
	}

174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
	/**
	 * 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
194
		// TODO add support for orderBy
195 196 197
		return $this->executeScript($db, 'Column', $column);
	}

198 199 200
	/**
	 * Returns the number of records.
	 * @param string $column the column to sum up
201 202
	 * @param Connection $db the database connection used to execute the query.
	 * If this parameter is not given, the `db` application component will be used.
203 204
	 * @return integer number of records
	 */
205
	public function sum($column, $db = null)
206
	{
207
		return $this->executeScript($db, 'Sum', $column);
208 209
	}

210 211 212 213
	/**
	 * 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.
214 215
	 * @param Connection $db the database connection used to execute the query.
	 * If this parameter is not given, the `db` application component will be used.
216 217
	 * @return integer the average of the specified column values.
	 */
218
	public function average($column, $db = null)
219
	{
220
		return $this->executeScript($db, 'Average', $column);
221 222 223 224 225 226
	}

	/**
	 * 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.
227 228
	 * @param Connection $db the database connection used to execute the query.
	 * If this parameter is not given, the `db` application component will be used.
229 230
	 * @return integer the minimum of the specified column values.
	 */
231
	public function min($column, $db = null)
232
	{
233
		return $this->executeScript($db, 'Min', $column);
234 235 236 237 238 239
	}

	/**
	 * 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.
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.
242 243
	 * @return integer the maximum of the specified column values.
	 */
244
	public function max($column, $db = null)
245
	{
246
		return $this->executeScript($db, 'Max', $column);
247 248
	}

Carsten Brandt committed
249 250
	/**
	 * Returns the query result as a scalar value.
251 252
	 * 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
253 254
	 * @param Connection $db the database connection used to execute the query.
	 * If this parameter is not given, the `db` application component will be used.
255 256
	 * @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
257
	 */
258
	public function scalar($attribute, $db = null)
Carsten Brandt committed
259
	{
260
		$record = $this->one($db);
261
		if ($record !== null) {
262
			return $record->hasAttribute($attribute) ? $record->$attribute : null;
263
		} else {
264
			return null;
265
		}
Carsten Brandt committed
266 267 268
	}


269 270
	/**
	 * Executes a script created by [[LuaScriptBuilder]]
271 272 273 274
	 * @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
275 276
	 * @return array|bool|null|string
	 */
277
	protected function executeScript($db, $type, $columnName = null)
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
		if ($this->primaryModel !== null) {
			// lazy loading
			if ($this->via instanceof self) {
				// via pivot table
				$viaModels = $this->via->findPivotRows([$this->primaryModel]);
				$this->filterByModels($viaModels);
			} elseif (is_array($this->via)) {
				// via relation
				/** @var ActiveQuery $viaQuery */
				list($viaName, $viaQuery) = $this->via;
				if ($viaQuery->multiple) {
					$viaModels = $viaQuery->all();
					$this->primaryModel->populateRelation($viaName, $viaModels);
				} else {
					$model = $viaQuery->one();
					$this->primaryModel->populateRelation($viaName, $model);
					$viaModels = $model === null ? [] : [$model];
				}
				$this->filterByModels($viaModels);
			} else {
				$this->filterByModels([$this->primaryModel]);
			}
		}

Carsten Brandt committed
303 304 305 306
		if (!empty($this->orderBy)) {
			throw new NotSupportedException('orderBy is currently not supported by redis ActiveRecord.');
		}

307 308 309 310
		/** @var ActiveRecord $modelClass */
		$modelClass = $this->modelClass;

		if ($db === null) {
311
			$db = $modelClass::getDb();
312
		}
313

314 315 316
		// 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);
317
		}
318 319 320 321

		$method = 'build' . $type;
		$script = $db->getLuaScriptBuilder()->$method($this, $columnName);
		return $db->executeCommand('EVAL', [$script, 0]);
322 323 324 325
	}

	/**
	 * Fetch by pk if possible as this is much faster
326 327 328 329 330
	 * @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
331
	 * @throws \yii\base\InvalidParamException
332
	 * @throws \yii\base\NotSupportedException
333
	 */
334
	private function findByPk($db, $type, $columnName = null)
335
	{
336 337 338
		if (count($this->where) == 1) {
			$pks = (array) reset($this->where);
		} else {
339
			foreach($this->where as $values) {
340 341
				if (is_array($values)) {
					// TODO support composite IN for composite PK
Carsten Brandt committed
342
					throw new NotSupportedException('Find by composite PK is not supported by redis ActiveRecord.');
343
				}
344
			}
345 346
			$pks = [$this->where];
		}
347

348 349 350
		/** @var ActiveRecord $modelClass */
		$modelClass = $this->modelClass;

351 352 353 354 355 356 357
		if ($type == 'Count') {
			$start = 0;
			$limit = null;
		} else {
			$start = $this->offset === null ? 0 : $this->offset;
			$limit = $this->limit;
		}
358 359 360
		$i = 0;
		$data = [];
		foreach($pks as $pk) {
361
			if (++$i > $start && ($limit === null || $i <= $start + $limit)) {
362
				$key = $modelClass::keyPrefix() . ':a:' . $modelClass::buildKey($pk);
363 364 365 366 367
				$result = $db->executeCommand('HGETALL', [$key]);
				if (!empty($result)) {
					$data[] = $result;
					if ($type === 'One' && $this->orderBy === null) {
						break;
368 369 370
					}
				}
			}
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
		}
		// 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++];
388
					}
389 390 391 392 393 394 395 396 397 398 399
					$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;
400 401
						}
					}
402 403 404 405 406 407 408 409 410 411 412 413
				}
				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;
414 415
						}
					}
416 417 418 419 420 421 422 423 424 425
				}
				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;
426 427
						}
					}
428
				}
429 430 431 432 433 434 435 436 437 438
				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;
						}
439
					}
440
				}
441
				return $max;
442
		}
443
		throw new InvalidParamException('Unknown fetch type: ' . $type);
444
	}
Carsten Brandt committed
445
}