ActiveQuery.php 12.2 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
			$models = $this->createModels($rows);
Carsten Brandt committed
76
			if (!empty($this->with)) {
77
				$this->findWith($this->with, $models);
Carsten Brandt committed
78 79 80 81
			}
			if (!$this->asArray) {
				foreach($models as $model) {
					$model->afterFind();
82
				}
Carsten Brandt committed
83
			}
Carsten Brandt committed
84
			return $models;
Carsten Brandt committed
85
		} else {
86
			return [];
Carsten Brandt committed
87 88 89 90
		}
	}

	/**
91 92 93
	 * 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
94 95 96 97
	 * @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.
	 */
98
	public function one($db = null)
Carsten Brandt committed
99
	{
Carsten Brandt committed
100
		// TODO add support for orderBy
101 102
		$data = $this->executeScript($db, 'One');
		if (empty($data)) {
103 104
			return null;
		}
105
		$row = [];
106 107
		$c = count($data);
		for($i = 0; $i < $c; ) {
108 109
			$row[$data[$i++]] = $data[$i++];
		}
110 111 112
		if ($this->asArray) {
			$model = $row;
		} else {
113
			/** @var ActiveRecord $class */
Carsten Brandt committed
114
			$class = $this->modelClass;
115 116
			$model = $class::instantiate($row);
			$class::populateRecord($model, $row);
Carsten Brandt committed
117
		}
118
		if (!empty($this->with)) {
119 120
			$models = [$model];
			$this->findWith($this->with, $models);
121 122
			$model = $models[0];
		}
123 124 125
		if (!$this->asArray) {
			$model->afterFind();
		}
126
		return $model;
Carsten Brandt committed
127 128 129 130
	}

	/**
	 * Returns the number of records.
131 132 133
	 * @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
134 135
	 * @return integer number of records
	 */
136
	public function count($q = '*', $db = null)
Carsten Brandt committed
137
	{
138
		if ($this->where === null) {
Carsten Brandt committed
139
			/** @var ActiveRecord $modelClass */
Carsten Brandt committed
140
			$modelClass = $this->modelClass;
141 142 143
			if ($db === null) {
				$db = $modelClass::getDb();
			}
144
			return $db->executeCommand('LLEN', [$modelClass::keyPrefix()]);
145
		} else {
146
			return $this->executeScript($db, 'Count');
147
		}
Carsten Brandt committed
148 149
	}

150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
	/**
	 * 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
170
		// TODO add support for orderBy
171 172 173
		return $this->executeScript($db, 'Column', $column);
	}

174 175 176
	/**
	 * Returns the number of records.
	 * @param string $column the column to sum up
177 178
	 * @param Connection $db the database connection used to execute the query.
	 * If this parameter is not given, the `db` application component will be used.
179 180
	 * @return integer number of records
	 */
181
	public function sum($column, $db = null)
182
	{
183
		return $this->executeScript($db, 'Sum', $column);
184 185
	}

186 187 188 189
	/**
	 * 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.
190 191
	 * @param Connection $db the database connection used to execute the query.
	 * If this parameter is not given, the `db` application component will be used.
192 193
	 * @return integer the average of the specified column values.
	 */
194
	public function average($column, $db = null)
195
	{
196
		return $this->executeScript($db, 'Average', $column);
197 198 199 200 201 202
	}

	/**
	 * 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.
203 204
	 * @param Connection $db the database connection used to execute the query.
	 * If this parameter is not given, the `db` application component will be used.
205 206
	 * @return integer the minimum of the specified column values.
	 */
207
	public function min($column, $db = null)
208
	{
209
		return $this->executeScript($db, 'Min', $column);
210 211 212 213 214 215
	}

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

Carsten Brandt committed
225 226
	/**
	 * Returns the query result as a scalar value.
227 228
	 * 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
229 230
	 * @param Connection $db the database connection used to execute the query.
	 * If this parameter is not given, the `db` application component will be used.
231 232
	 * @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
233
	 */
234
	public function scalar($attribute, $db = null)
Carsten Brandt committed
235
	{
236
		$record = $this->one($db);
237
		if ($record !== null) {
238
			return $record->hasAttribute($attribute) ? $record->$attribute : null;
239
		} else {
240
			return null;
241
		}
Carsten Brandt committed
242 243 244
	}


245 246
	/**
	 * Executes a script created by [[LuaScriptBuilder]]
247 248 249 250
	 * @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
251 252
	 * @return array|bool|null|string
	 */
253
	protected function executeScript($db, $type, $columnName = null)
254
	{
Carsten Brandt committed
255 256 257 258
		if (!empty($this->orderBy)) {
			throw new NotSupportedException('orderBy is currently not supported by redis ActiveRecord.');
		}

259 260 261 262
		/** @var ActiveRecord $modelClass */
		$modelClass = $this->modelClass;

		if ($db === null) {
263
			$db = $modelClass::getDb();
264
		}
265

266 267 268
		// 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);
269
		}
270 271 272 273

		$method = 'build' . $type;
		$script = $db->getLuaScriptBuilder()->$method($this, $columnName);
		return $db->executeCommand('EVAL', [$script, 0]);
274 275 276 277
	}

	/**
	 * Fetch by pk if possible as this is much faster
278 279 280 281 282
	 * @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
283
	 * @throws \yii\base\InvalidParamException
284
	 * @throws \yii\base\NotSupportedException
285
	 */
286
	private function findByPk($db, $type, $columnName = null)
287
	{
288 289 290
		if (count($this->where) == 1) {
			$pks = (array) reset($this->where);
		} else {
291
			foreach($this->where as $values) {
292 293
				if (is_array($values)) {
					// TODO support composite IN for composite PK
Carsten Brandt committed
294
					throw new NotSupportedException('Find by composite PK is not supported by redis ActiveRecord.');
295
				}
296
			}
297 298
			$pks = [$this->where];
		}
299

300 301 302
		/** @var ActiveRecord $modelClass */
		$modelClass = $this->modelClass;

303 304 305 306 307 308 309
		if ($type == 'Count') {
			$start = 0;
			$limit = null;
		} else {
			$start = $this->offset === null ? 0 : $this->offset;
			$limit = $this->limit;
		}
310 311 312
		$i = 0;
		$data = [];
		foreach($pks as $pk) {
313
			if (++$i > $start && ($limit === null || $i <= $start + $limit)) {
314
				$key = $modelClass::keyPrefix() . ':a:' . $modelClass::buildKey($pk);
315 316 317 318 319
				$result = $db->executeCommand('HGETALL', [$key]);
				if (!empty($result)) {
					$data[] = $result;
					if ($type === 'One' && $this->orderBy === null) {
						break;
320 321 322
					}
				}
			}
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
		}
		// 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++];
340
					}
341 342 343 344 345 346 347 348 349 350 351
					$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;
352 353
						}
					}
354 355 356 357 358 359 360 361 362 363 364 365
				}
				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;
366 367
						}
					}
368 369 370 371 372 373 374 375 376 377
				}
				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;
378 379
						}
					}
380
				}
381 382 383 384 385 386 387 388 389 390
				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;
						}
391
					}
392
				}
393
				return $max;
394
		}
395
		throw new InvalidParamException('Unknown fetch type: ' . $type);
396
	}
Carsten Brandt committed
397
}