ActiveQuery.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\redis;
  8. use yii\base\Component;
  9. use yii\base\InvalidParamException;
  10. use yii\base\NotSupportedException;
  11. use yii\db\ActiveQueryInterface;
  12. use yii\db\ActiveQueryTrait;
  13. use yii\db\ActiveRelationTrait;
  14. use yii\db\QueryTrait;
  15. /**
  16. * ActiveQuery represents a query associated with an Active Record class.
  17. *
  18. * An ActiveQuery can be a normal query or be used in a relational context.
  19. *
  20. * ActiveQuery instances are usually created by [[ActiveRecord::find()]].
  21. * Relational queries are created by [[ActiveRecord::hasOne()]] and [[ActiveRecord::hasMany()]].
  22. *
  23. * Normal Query
  24. * ------------
  25. *
  26. * ActiveQuery mainly provides the following methods to retrieve the query results:
  27. *
  28. * - [[one()]]: returns a single record populated with the first row of data.
  29. * - [[all()]]: returns all records based on the query results.
  30. * - [[count()]]: returns the number of records.
  31. * - [[sum()]]: returns the sum over the specified column.
  32. * - [[average()]]: returns the average over the specified column.
  33. * - [[min()]]: returns the min over the specified column.
  34. * - [[max()]]: returns the max over the specified column.
  35. * - [[scalar()]]: returns the value of the first column in the first row of the query result.
  36. * - [[exists()]]: returns a value indicating whether the query result has data or not.
  37. *
  38. * You can use query methods, such as [[where()]], [[limit()]] and [[orderBy()]] to customize the query options.
  39. *
  40. * ActiveQuery also provides the following additional query options:
  41. *
  42. * - [[with()]]: list of relations that this query should be performed with.
  43. * - [[indexBy()]]: the name of the column by which the query result should be indexed.
  44. * - [[asArray()]]: whether to return each record as an array.
  45. *
  46. * These options can be configured using methods of the same name. For example:
  47. *
  48. * ```php
  49. * $customers = Customer::find()->with('orders')->asArray()->all();
  50. * ```
  51. *
  52. * Relational query
  53. * ----------------
  54. *
  55. * In relational context ActiveQuery represents a relation between two Active Record classes.
  56. *
  57. * Relational ActiveQuery instances are usually created by calling [[ActiveRecord::hasOne()]] and
  58. * [[ActiveRecord::hasMany()]]. An Active Record class declares a relation by defining
  59. * a getter method which calls one of the above methods and returns the created ActiveQuery object.
  60. *
  61. * A relation is specified by [[link]] which represents the association between columns
  62. * of different tables; and the multiplicity of the relation is indicated by [[multiple]].
  63. *
  64. * If a relation involves a junction table, it may be specified by [[via()]].
  65. * This methods may only be called in a relational context. Same is true for [[inverseOf()]], which
  66. * marks a relation as inverse of another relation.
  67. *
  68. * @author Carsten Brandt <mail@cebe.cc>
  69. * @since 2.0
  70. */
  71. class ActiveQuery extends Component implements ActiveQueryInterface
  72. {
  73. use QueryTrait;
  74. use ActiveQueryTrait;
  75. use ActiveRelationTrait;
  76. /**
  77. * @event Event an event that is triggered when the query is initialized via [[init()]].
  78. */
  79. const EVENT_INIT = 'init';
  80. /**
  81. * Constructor.
  82. * @param string $modelClass the model class associated with this query
  83. * @param array $config configurations to be applied to the newly created query object
  84. */
  85. public function __construct($modelClass, $config = [])
  86. {
  87. $this->modelClass = $modelClass;
  88. parent::__construct($config);
  89. }
  90. /**
  91. * Initializes the object.
  92. * This method is called at the end of the constructor. The default implementation will trigger
  93. * an [[EVENT_INIT]] event. If you override this method, make sure you call the parent implementation at the end
  94. * to ensure triggering of the event.
  95. */
  96. public function init()
  97. {
  98. parent::init();
  99. $this->trigger(self::EVENT_INIT);
  100. }
  101. /**
  102. * Executes the query and returns all results as an array.
  103. * @param Connection $db the database connection used to execute the query.
  104. * If this parameter is not given, the `db` application component will be used.
  105. * @return array|ActiveRecord[] the query results. If the query results in nothing, an empty array will be returned.
  106. */
  107. public function all($db = null)
  108. {
  109. if ($this->emulateExecution) {
  110. return [];
  111. }
  112. // TODO add support for orderBy
  113. $data = $this->executeScript($db, 'All');
  114. if (empty($data)) {
  115. return [];
  116. }
  117. $rows = [];
  118. foreach ($data as $dataRow) {
  119. $row = [];
  120. $c = count($dataRow);
  121. for ($i = 0; $i < $c;) {
  122. $row[$dataRow[$i++]] = $dataRow[$i++];
  123. }
  124. $rows[] = $row;
  125. }
  126. if (empty($rows)) {
  127. return [];
  128. }
  129. $models = $this->createModels($rows);
  130. if (!empty($this->with)) {
  131. $this->findWith($this->with, $models);
  132. }
  133. if ($this->indexBy !== null) {
  134. $indexedModels = [];
  135. if (is_string($this->indexBy)) {
  136. foreach ($models as $model) {
  137. $key = $model[$this->indexBy];
  138. $indexedModels[$key] = $model;
  139. }
  140. } else {
  141. foreach ($models as $model) {
  142. $key = call_user_func($this->indexBy, $model);
  143. $indexedModels[$key] = $model;
  144. }
  145. }
  146. $models = $indexedModels;
  147. }
  148. if (!$this->asArray) {
  149. foreach ($models as $model) {
  150. $model->afterFind();
  151. }
  152. }
  153. return $models;
  154. }
  155. /**
  156. * Executes the query and returns a single row of result.
  157. * @param Connection $db the database connection used to execute the query.
  158. * If this parameter is not given, the `db` application component will be used.
  159. * @return ActiveRecord|array|null a single row of query result. Depending on the setting of [[asArray]],
  160. * the query result may be either an array or an ActiveRecord object. Null will be returned
  161. * if the query results in nothing.
  162. */
  163. public function one($db = null)
  164. {
  165. if ($this->emulateExecution) {
  166. return null;
  167. }
  168. // TODO add support for orderBy
  169. $data = $this->executeScript($db, 'One');
  170. if (empty($data)) {
  171. return null;
  172. }
  173. $row = [];
  174. $c = count($data);
  175. for ($i = 0; $i < $c;) {
  176. $row[$data[$i++]] = $data[$i++];
  177. }
  178. if ($this->asArray) {
  179. $model = $row;
  180. } else {
  181. /* @var $class ActiveRecord */
  182. $class = $this->modelClass;
  183. $model = $class::instantiate($row);
  184. $class = get_class($model);
  185. $class::populateRecord($model, $row);
  186. }
  187. if (!empty($this->with)) {
  188. $models = [$model];
  189. $this->findWith($this->with, $models);
  190. $model = $models[0];
  191. }
  192. if (!$this->asArray) {
  193. $model->afterFind();
  194. }
  195. return $model;
  196. }
  197. /**
  198. * Returns the number of records.
  199. * @param string $q the COUNT expression. This parameter is ignored by this implementation.
  200. * @param Connection $db the database connection used to execute the query.
  201. * If this parameter is not given, the `db` application component will be used.
  202. * @return int number of records
  203. */
  204. public function count($q = '*', $db = null)
  205. {
  206. if ($this->emulateExecution) {
  207. return 0;
  208. }
  209. if ($this->where === null) {
  210. /* @var $modelClass ActiveRecord */
  211. $modelClass = $this->modelClass;
  212. if ($db === null) {
  213. $db = $modelClass::getDb();
  214. }
  215. return $db->executeCommand('LLEN', [$modelClass::keyPrefix()]);
  216. } else {
  217. return $this->executeScript($db, 'Count');
  218. }
  219. }
  220. /**
  221. * Returns a value indicating whether the query result contains any row of data.
  222. * @param Connection $db the database connection used to execute the query.
  223. * If this parameter is not given, the `db` application component will be used.
  224. * @return bool whether the query result contains any row of data.
  225. */
  226. public function exists($db = null)
  227. {
  228. if ($this->emulateExecution) {
  229. return false;
  230. }
  231. return $this->one($db) !== null;
  232. }
  233. /**
  234. * Executes the query and returns the first column of the result.
  235. * @param string $column name of the column to select
  236. * @param Connection $db the database connection used to execute the query.
  237. * If this parameter is not given, the `db` application component will be used.
  238. * @return array the first column of the query result. An empty array is returned if the query results in nothing.
  239. */
  240. public function column($column, $db = null)
  241. {
  242. if ($this->emulateExecution) {
  243. return [];
  244. }
  245. // TODO add support for orderBy
  246. return $this->executeScript($db, 'Column', $column);
  247. }
  248. /**
  249. * Returns the number of records.
  250. * @param string $column the column to sum up
  251. * @param Connection $db the database connection used to execute the query.
  252. * If this parameter is not given, the `db` application component will be used.
  253. * @return int number of records
  254. */
  255. public function sum($column, $db = null)
  256. {
  257. if ($this->emulateExecution) {
  258. return 0;
  259. }
  260. return $this->executeScript($db, 'Sum', $column);
  261. }
  262. /**
  263. * Returns the average of the specified column values.
  264. * @param string $column the column name or expression.
  265. * Make sure you properly quote column names in the expression.
  266. * @param Connection $db the database connection used to execute the query.
  267. * If this parameter is not given, the `db` application component will be used.
  268. * @return int the average of the specified column values.
  269. */
  270. public function average($column, $db = null)
  271. {
  272. if ($this->emulateExecution) {
  273. return 0;
  274. }
  275. return $this->executeScript($db, 'Average', $column);
  276. }
  277. /**
  278. * Returns the minimum of the specified column values.
  279. * @param string $column the column name or expression.
  280. * Make sure you properly quote column names in the expression.
  281. * @param Connection $db the database connection used to execute the query.
  282. * If this parameter is not given, the `db` application component will be used.
  283. * @return int the minimum of the specified column values.
  284. */
  285. public function min($column, $db = null)
  286. {
  287. if ($this->emulateExecution) {
  288. return null;
  289. }
  290. return $this->executeScript($db, 'Min', $column);
  291. }
  292. /**
  293. * Returns the maximum of the specified column values.
  294. * @param string $column the column name or expression.
  295. * Make sure you properly quote column names in the expression.
  296. * @param Connection $db the database connection used to execute the query.
  297. * If this parameter is not given, the `db` application component will be used.
  298. * @return int the maximum of the specified column values.
  299. */
  300. public function max($column, $db = null)
  301. {
  302. if ($this->emulateExecution) {
  303. return null;
  304. }
  305. return $this->executeScript($db, 'Max', $column);
  306. }
  307. /**
  308. * Returns the query result as a scalar value.
  309. * The value returned will be the specified attribute in the first record of the query results.
  310. * @param string $attribute name of the attribute to select
  311. * @param Connection $db the database connection used to execute the query.
  312. * If this parameter is not given, the `db` application component will be used.
  313. * @return string the value of the specified attribute in the first record of the query result.
  314. * Null is returned if the query result is empty.
  315. */
  316. public function scalar($attribute, $db = null)
  317. {
  318. if ($this->emulateExecution) {
  319. return null;
  320. }
  321. $record = $this->one($db);
  322. if ($record !== null) {
  323. return $record->hasAttribute($attribute) ? $record->$attribute : null;
  324. } else {
  325. return null;
  326. }
  327. }
  328. /**
  329. * Executes a script created by [[LuaScriptBuilder]]
  330. * @param Connection|null $db the database connection used to execute the query.
  331. * If this parameter is not given, the `db` application component will be used.
  332. * @param string $type the type of the script to generate
  333. * @param string $columnName
  334. * @throws NotSupportedException
  335. * @return array|bool|null|string
  336. */
  337. protected function executeScript($db, $type, $columnName = null)
  338. {
  339. if ($this->primaryModel !== null) {
  340. // lazy loading
  341. if ($this->via instanceof self) {
  342. // via junction table
  343. $viaModels = $this->via->findJunctionRows([$this->primaryModel]);
  344. $this->filterByModels($viaModels);
  345. } elseif (is_array($this->via)) {
  346. // via relation
  347. /* @var $viaQuery ActiveQuery */
  348. list($viaName, $viaQuery) = $this->via;
  349. if ($viaQuery->multiple) {
  350. $viaModels = $viaQuery->all();
  351. $this->primaryModel->populateRelation($viaName, $viaModels);
  352. } else {
  353. $model = $viaQuery->one();
  354. $this->primaryModel->populateRelation($viaName, $model);
  355. $viaModels = $model === null ? [] : [$model];
  356. }
  357. $this->filterByModels($viaModels);
  358. } else {
  359. $this->filterByModels([$this->primaryModel]);
  360. }
  361. }
  362. /* @var $modelClass ActiveRecord */
  363. $modelClass = $this->modelClass;
  364. if ($db === null) {
  365. $db = $modelClass::getDb();
  366. }
  367. // find by primary key if possible. This is much faster than scanning all records
  368. if (is_array($this->where) && (
  369. !isset($this->where[0]) && $modelClass::isPrimaryKey(array_keys($this->where)) ||
  370. isset($this->where[0]) && $this->where[0] === 'in' && $modelClass::isPrimaryKey((array) $this->where[1])
  371. )) {
  372. return $this->findByPk($db, $type, $columnName);
  373. }
  374. $method = 'build' . $type;
  375. $script = $db->getLuaScriptBuilder()->$method($this, $columnName);
  376. return $db->executeCommand('EVAL', [$script, 0]);
  377. }
  378. /**
  379. * Fetch by pk if possible as this is much faster
  380. * @param Connection $db the database connection used to execute the query.
  381. * If this parameter is not given, the `db` application component will be used.
  382. * @param string $type the type of the script to generate
  383. * @param string $columnName
  384. * @return array|bool|null|string
  385. * @throws \yii\base\InvalidParamException
  386. * @throws \yii\base\NotSupportedException
  387. */
  388. private function findByPk($db, $type, $columnName = null)
  389. {
  390. $needSort = !empty($this->orderBy) && in_array($type, ['All', 'One', 'Column']);
  391. if ($needSort) {
  392. if (!is_array($this->orderBy) || count($this->orderBy) > 1) {
  393. throw new NotSupportedException(
  394. 'orderBy by multiple columns is not currently supported by redis ActiveRecord.'
  395. );
  396. }
  397. $k = key($this->orderBy);
  398. $v = $this->orderBy[$k];
  399. if (is_numeric($k)) {
  400. $orderColumn = $v;
  401. $orderType = SORT_ASC;
  402. } else {
  403. $orderColumn = $k;
  404. $orderType = $v;
  405. }
  406. }
  407. if (isset($this->where[0]) && $this->where[0] === 'in') {
  408. $pks = (array) $this->where[2];
  409. } elseif (count($this->where) == 1) {
  410. $pks = (array) reset($this->where);
  411. } else {
  412. foreach ($this->where as $values) {
  413. if (is_array($values)) {
  414. // TODO support composite IN for composite PK
  415. throw new NotSupportedException('Find by composite PK is not supported by redis ActiveRecord.');
  416. }
  417. }
  418. $pks = [$this->where];
  419. }
  420. /* @var $modelClass ActiveRecord */
  421. $modelClass = $this->modelClass;
  422. if ($type === 'Count') {
  423. $start = 0;
  424. $limit = null;
  425. } else {
  426. $start = ($this->offset === null || $this->offset < 0) ? 0 : $this->offset;
  427. $limit = ($this->limit < 0) ? null : $this->limit;
  428. }
  429. $i = 0;
  430. $data = [];
  431. $orderArray = [];
  432. foreach ($pks as $pk) {
  433. if (++$i > $start && ($limit === null || $i <= $start + $limit)) {
  434. $key = $modelClass::keyPrefix() . ':a:' . $modelClass::buildKey($pk);
  435. $result = $db->executeCommand('HGETALL', [$key]);
  436. if (!empty($result)) {
  437. $data[] = $result;
  438. if ($needSort) {
  439. $orderArray[] = $db->executeCommand('HGET', [$key, $orderColumn]);
  440. }
  441. if ($type === 'One' && $this->orderBy === null) {
  442. break;
  443. }
  444. }
  445. }
  446. }
  447. if ($needSort) {
  448. $resultData = [];
  449. if ($orderType === SORT_ASC) {
  450. asort($orderArray, SORT_NATURAL);
  451. } else {
  452. arsort($orderArray, SORT_NATURAL);
  453. }
  454. foreach ($orderArray as $orderKey => $orderItem) {
  455. $resultData[] = $data[$orderKey];
  456. }
  457. $data = $resultData;
  458. }
  459. switch ($type) {
  460. case 'All':
  461. return $data;
  462. case 'One':
  463. return reset($data);
  464. case 'Count':
  465. return count($data);
  466. case 'Column':
  467. $column = [];
  468. foreach ($data as $dataRow) {
  469. $row = [];
  470. $c = count($dataRow);
  471. for ($i = 0; $i < $c;) {
  472. $row[$dataRow[$i++]] = $dataRow[$i++];
  473. }
  474. $column[] = $row[$columnName];
  475. }
  476. return $column;
  477. case 'Sum':
  478. $sum = 0;
  479. foreach ($data as $dataRow) {
  480. $c = count($dataRow);
  481. for ($i = 0; $i < $c;) {
  482. if ($dataRow[$i++] == $columnName) {
  483. $sum += $dataRow[$i];
  484. break;
  485. }
  486. }
  487. }
  488. return $sum;
  489. case 'Average':
  490. $sum = 0;
  491. $count = 0;
  492. foreach ($data as $dataRow) {
  493. $count++;
  494. $c = count($dataRow);
  495. for ($i = 0; $i < $c;) {
  496. if ($dataRow[$i++] == $columnName) {
  497. $sum += $dataRow[$i];
  498. break;
  499. }
  500. }
  501. }
  502. return $sum / $count;
  503. case 'Min':
  504. $min = null;
  505. foreach ($data as $dataRow) {
  506. $c = count($dataRow);
  507. for ($i = 0; $i < $c;) {
  508. if ($dataRow[$i++] == $columnName && ($min == null || $dataRow[$i] < $min)) {
  509. $min = $dataRow[$i];
  510. break;
  511. }
  512. }
  513. }
  514. return $min;
  515. case 'Max':
  516. $max = null;
  517. foreach ($data as $dataRow) {
  518. $c = count($dataRow);
  519. for ($i = 0; $i < $c;) {
  520. if ($dataRow[$i++] == $columnName && ($max == null || $dataRow[$i] > $max)) {
  521. $max = $dataRow[$i];
  522. break;
  523. }
  524. }
  525. }
  526. return $max;
  527. }
  528. throw new InvalidParamException('Unknown fetch type: ' . $type);
  529. }
  530. }