ActiveQuery.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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. }
  217. return $this->executeScript($db, 'Count');
  218. }
  219. /**
  220. * Returns a value indicating whether the query result contains any row of data.
  221. * @param Connection $db the database connection used to execute the query.
  222. * If this parameter is not given, the `db` application component will be used.
  223. * @return bool whether the query result contains any row of data.
  224. */
  225. public function exists($db = null)
  226. {
  227. if ($this->emulateExecution) {
  228. return false;
  229. }
  230. return $this->one($db) !== null;
  231. }
  232. /**
  233. * Executes the query and returns the first column of the result.
  234. * @param string $column name of the column to select
  235. * @param Connection $db the database connection used to execute the query.
  236. * If this parameter is not given, the `db` application component will be used.
  237. * @return array the first column of the query result. An empty array is returned if the query results in nothing.
  238. */
  239. public function column($column, $db = null)
  240. {
  241. if ($this->emulateExecution) {
  242. return [];
  243. }
  244. // TODO add support for orderBy
  245. return $this->executeScript($db, 'Column', $column);
  246. }
  247. /**
  248. * Returns the number of records.
  249. * @param string $column the column to sum up
  250. * @param Connection $db the database connection used to execute the query.
  251. * If this parameter is not given, the `db` application component will be used.
  252. * @return int number of records
  253. */
  254. public function sum($column, $db = null)
  255. {
  256. if ($this->emulateExecution) {
  257. return 0;
  258. }
  259. return $this->executeScript($db, 'Sum', $column);
  260. }
  261. /**
  262. * Returns the average of the specified column values.
  263. * @param string $column the column name or expression.
  264. * Make sure you properly quote column names in the expression.
  265. * @param Connection $db the database connection used to execute the query.
  266. * If this parameter is not given, the `db` application component will be used.
  267. * @return int the average of the specified column values.
  268. */
  269. public function average($column, $db = null)
  270. {
  271. if ($this->emulateExecution) {
  272. return 0;
  273. }
  274. return $this->executeScript($db, 'Average', $column);
  275. }
  276. /**
  277. * Returns the minimum of the specified column values.
  278. * @param string $column the column name or expression.
  279. * Make sure you properly quote column names in the expression.
  280. * @param Connection $db the database connection used to execute the query.
  281. * If this parameter is not given, the `db` application component will be used.
  282. * @return int the minimum of the specified column values.
  283. */
  284. public function min($column, $db = null)
  285. {
  286. if ($this->emulateExecution) {
  287. return null;
  288. }
  289. return $this->executeScript($db, 'Min', $column);
  290. }
  291. /**
  292. * Returns the maximum of the specified column values.
  293. * @param string $column the column name or expression.
  294. * Make sure you properly quote column names in the expression.
  295. * @param Connection $db the database connection used to execute the query.
  296. * If this parameter is not given, the `db` application component will be used.
  297. * @return int the maximum of the specified column values.
  298. */
  299. public function max($column, $db = null)
  300. {
  301. if ($this->emulateExecution) {
  302. return null;
  303. }
  304. return $this->executeScript($db, 'Max', $column);
  305. }
  306. /**
  307. * Returns the query result as a scalar value.
  308. * The value returned will be the specified attribute in the first record of the query results.
  309. * @param string $attribute name of the attribute to select
  310. * @param Connection $db the database connection used to execute the query.
  311. * If this parameter is not given, the `db` application component will be used.
  312. * @return string the value of the specified attribute in the first record of the query result.
  313. * Null is returned if the query result is empty.
  314. */
  315. public function scalar($attribute, $db = null)
  316. {
  317. if ($this->emulateExecution) {
  318. return null;
  319. }
  320. $record = $this->one($db);
  321. if ($record !== null) {
  322. return $record->hasAttribute($attribute) ? $record->$attribute : null;
  323. }
  324. return null;
  325. }
  326. /**
  327. * Executes a script created by [[LuaScriptBuilder]]
  328. * @param Connection|null $db the database connection used to execute the query.
  329. * If this parameter is not given, the `db` application component will be used.
  330. * @param string $type the type of the script to generate
  331. * @param string $columnName
  332. * @throws NotSupportedException
  333. * @return array|bool|null|string
  334. */
  335. protected function executeScript($db, $type, $columnName = null)
  336. {
  337. if ($this->primaryModel !== null) {
  338. // lazy loading
  339. if ($this->via instanceof self) {
  340. // via junction table
  341. $viaModels = $this->via->findJunctionRows([$this->primaryModel]);
  342. $this->filterByModels($viaModels);
  343. } elseif (is_array($this->via)) {
  344. // via relation
  345. /* @var $viaQuery ActiveQuery */
  346. list($viaName, $viaQuery) = $this->via;
  347. if ($viaQuery->multiple) {
  348. $viaModels = $viaQuery->all();
  349. $this->primaryModel->populateRelation($viaName, $viaModels);
  350. } else {
  351. $model = $viaQuery->one();
  352. $this->primaryModel->populateRelation($viaName, $model);
  353. $viaModels = $model === null ? [] : [$model];
  354. }
  355. $this->filterByModels($viaModels);
  356. } else {
  357. $this->filterByModels([$this->primaryModel]);
  358. }
  359. }
  360. /* @var $modelClass ActiveRecord */
  361. $modelClass = $this->modelClass;
  362. if ($db === null) {
  363. $db = $modelClass::getDb();
  364. }
  365. // find by primary key if possible. This is much faster than scanning all records
  366. if (
  367. is_array($this->where)
  368. && (
  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. ) {
  373. return $this->findByPk($db, $type, $columnName);
  374. }
  375. $method = 'build' . $type;
  376. $script = $db->getLuaScriptBuilder()->$method($this, $columnName);
  377. return $db->executeCommand('EVAL', [$script, 0]);
  378. }
  379. /**
  380. * Fetch by pk if possible as this is much faster
  381. * @param Connection $db the database connection used to execute the query.
  382. * If this parameter is not given, the `db` application component will be used.
  383. * @param string $type the type of the script to generate
  384. * @param string $columnName
  385. * @return array|bool|null|string
  386. * @throws \yii\base\InvalidParamException
  387. * @throws \yii\base\NotSupportedException
  388. */
  389. private function findByPk($db, $type, $columnName = null)
  390. {
  391. $needSort = !empty($this->orderBy) && in_array($type, ['All', 'One', 'Column']);
  392. if ($needSort) {
  393. if (!is_array($this->orderBy) || count($this->orderBy) > 1) {
  394. throw new NotSupportedException(
  395. 'orderBy by multiple columns is not currently supported by redis ActiveRecord.'
  396. );
  397. }
  398. $k = key($this->orderBy);
  399. $v = $this->orderBy[$k];
  400. if (is_numeric($k)) {
  401. $orderColumn = $v;
  402. $orderType = SORT_ASC;
  403. } else {
  404. $orderColumn = $k;
  405. $orderType = $v;
  406. }
  407. }
  408. if (isset($this->where[0]) && $this->where[0] === 'in') {
  409. $pks = (array) $this->where[2];
  410. } elseif (count($this->where) == 1) {
  411. $pks = (array) reset($this->where);
  412. } else {
  413. foreach ($this->where as $values) {
  414. if (is_array($values)) {
  415. // TODO support composite IN for composite PK
  416. throw new NotSupportedException('Find by composite PK is not supported by redis ActiveRecord.');
  417. }
  418. }
  419. $pks = [$this->where];
  420. }
  421. /* @var $modelClass ActiveRecord */
  422. $modelClass = $this->modelClass;
  423. if ($type === 'Count') {
  424. $start = 0;
  425. $limit = null;
  426. } else {
  427. $start = ($this->offset === null || $this->offset < 0) ? 0 : $this->offset;
  428. $limit = ($this->limit < 0) ? null : $this->limit;
  429. }
  430. $i = 0;
  431. $data = [];
  432. $orderArray = [];
  433. foreach ($pks as $pk) {
  434. if (++$i > $start && ($limit === null || $i <= $start + $limit)) {
  435. $key = $modelClass::keyPrefix() . ':a:' . $modelClass::buildKey($pk);
  436. $result = $db->executeCommand('HGETALL', [$key]);
  437. if (!empty($result)) {
  438. $data[] = $result;
  439. if ($needSort) {
  440. $orderArray[] = $db->executeCommand('HGET', [$key, $orderColumn]);
  441. }
  442. if ($type === 'One' && $this->orderBy === null) {
  443. break;
  444. }
  445. }
  446. }
  447. }
  448. if ($needSort) {
  449. $resultData = [];
  450. if ($orderType === SORT_ASC) {
  451. asort($orderArray, SORT_NATURAL);
  452. } else {
  453. arsort($orderArray, SORT_NATURAL);
  454. }
  455. foreach ($orderArray as $orderKey => $orderItem) {
  456. $resultData[] = $data[$orderKey];
  457. }
  458. $data = $resultData;
  459. }
  460. switch ($type) {
  461. case 'All':
  462. return $data;
  463. case 'One':
  464. return reset($data);
  465. case 'Count':
  466. return count($data);
  467. case 'Column':
  468. $column = [];
  469. foreach ($data as $dataRow) {
  470. $row = [];
  471. $c = count($dataRow);
  472. for ($i = 0; $i < $c;) {
  473. $row[$dataRow[$i++]] = $dataRow[$i++];
  474. }
  475. $column[] = $row[$columnName];
  476. }
  477. return $column;
  478. case 'Sum':
  479. $sum = 0;
  480. foreach ($data as $dataRow) {
  481. $c = count($dataRow);
  482. for ($i = 0; $i < $c;) {
  483. if ($dataRow[$i++] == $columnName) {
  484. $sum += $dataRow[$i];
  485. break;
  486. }
  487. }
  488. }
  489. return $sum;
  490. case 'Average':
  491. $sum = 0;
  492. $count = 0;
  493. foreach ($data as $dataRow) {
  494. $count++;
  495. $c = count($dataRow);
  496. for ($i = 0; $i < $c;) {
  497. if ($dataRow[$i++] == $columnName) {
  498. $sum += $dataRow[$i];
  499. break;
  500. }
  501. }
  502. }
  503. return $sum / $count;
  504. case 'Min':
  505. $min = null;
  506. foreach ($data as $dataRow) {
  507. $c = count($dataRow);
  508. for ($i = 0; $i < $c;) {
  509. if ($dataRow[$i++] == $columnName && ($min == null || $dataRow[$i] < $min)) {
  510. $min = $dataRow[$i];
  511. break;
  512. }
  513. }
  514. }
  515. return $min;
  516. case 'Max':
  517. $max = null;
  518. foreach ($data as $dataRow) {
  519. $c = count($dataRow);
  520. for ($i = 0; $i < $c;) {
  521. if ($dataRow[$i++] == $columnName && ($max == null || $dataRow[$i] > $max)) {
  522. $max = $dataRow[$i];
  523. break;
  524. }
  525. }
  526. }
  527. return $max;
  528. }
  529. throw new InvalidParamException('Unknown fetch type: ' . $type);
  530. }
  531. }