ActiveQuery.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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 array $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. $models = $this->createModels($rows);
  128. if (!empty($this->with)) {
  129. $this->findWith($this->with, $models);
  130. }
  131. if (!$this->asArray) {
  132. foreach ($models as $model) {
  133. $model->afterFind();
  134. }
  135. }
  136. return $models;
  137. } else {
  138. return [];
  139. }
  140. }
  141. /**
  142. * Executes the query and returns a single row of result.
  143. * @param Connection $db the database connection used to execute the query.
  144. * If this parameter is not given, the `db` application component will be used.
  145. * @return ActiveRecord|array|null a single row of query result. Depending on the setting of [[asArray]],
  146. * the query result may be either an array or an ActiveRecord object. Null will be returned
  147. * if the query results in nothing.
  148. */
  149. public function one($db = null)
  150. {
  151. if ($this->emulateExecution) {
  152. return null;
  153. }
  154. // TODO add support for orderBy
  155. $data = $this->executeScript($db, 'One');
  156. if (empty($data)) {
  157. return null;
  158. }
  159. $row = [];
  160. $c = count($data);
  161. for ($i = 0; $i < $c;) {
  162. $row[$data[$i++]] = $data[$i++];
  163. }
  164. if ($this->asArray) {
  165. $model = $row;
  166. } else {
  167. /* @var $class ActiveRecord */
  168. $class = $this->modelClass;
  169. $model = $class::instantiate($row);
  170. $class = get_class($model);
  171. $class::populateRecord($model, $row);
  172. }
  173. if (!empty($this->with)) {
  174. $models = [$model];
  175. $this->findWith($this->with, $models);
  176. $model = $models[0];
  177. }
  178. if (!$this->asArray) {
  179. $model->afterFind();
  180. }
  181. return $model;
  182. }
  183. /**
  184. * Returns the number of records.
  185. * @param string $q the COUNT expression. This parameter is ignored by this implementation.
  186. * @param Connection $db the database connection used to execute the query.
  187. * If this parameter is not given, the `db` application component will be used.
  188. * @return int number of records
  189. */
  190. public function count($q = '*', $db = null)
  191. {
  192. if ($this->emulateExecution) {
  193. return 0;
  194. }
  195. if ($this->where === null) {
  196. /* @var $modelClass ActiveRecord */
  197. $modelClass = $this->modelClass;
  198. if ($db === null) {
  199. $db = $modelClass::getDb();
  200. }
  201. return $db->executeCommand('LLEN', [$modelClass::keyPrefix()]);
  202. } else {
  203. return $this->executeScript($db, 'Count');
  204. }
  205. }
  206. /**
  207. * Returns a value indicating whether the query result contains any row of data.
  208. * @param Connection $db the database connection used to execute the query.
  209. * If this parameter is not given, the `db` application component will be used.
  210. * @return bool whether the query result contains any row of data.
  211. */
  212. public function exists($db = null)
  213. {
  214. if ($this->emulateExecution) {
  215. return false;
  216. }
  217. return $this->one($db) !== null;
  218. }
  219. /**
  220. * Executes the query and returns the first column of the result.
  221. * @param string $column name of the column to select
  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 array the first column of the query result. An empty array is returned if the query results in nothing.
  225. */
  226. public function column($column, $db = null)
  227. {
  228. if ($this->emulateExecution) {
  229. return [];
  230. }
  231. // TODO add support for orderBy
  232. return $this->executeScript($db, 'Column', $column);
  233. }
  234. /**
  235. * Returns the number of records.
  236. * @param string $column the column to sum up
  237. * @param Connection $db the database connection used to execute the query.
  238. * If this parameter is not given, the `db` application component will be used.
  239. * @return int number of records
  240. */
  241. public function sum($column, $db = null)
  242. {
  243. if ($this->emulateExecution) {
  244. return 0;
  245. }
  246. return $this->executeScript($db, 'Sum', $column);
  247. }
  248. /**
  249. * Returns the average of the specified column values.
  250. * @param string $column the column name or expression.
  251. * Make sure you properly quote column names in the expression.
  252. * @param Connection $db the database connection used to execute the query.
  253. * If this parameter is not given, the `db` application component will be used.
  254. * @return int the average of the specified column values.
  255. */
  256. public function average($column, $db = null)
  257. {
  258. if ($this->emulateExecution) {
  259. return 0;
  260. }
  261. return $this->executeScript($db, 'Average', $column);
  262. }
  263. /**
  264. * Returns the minimum of the specified column values.
  265. * @param string $column the column name or expression.
  266. * Make sure you properly quote column names in the expression.
  267. * @param Connection $db the database connection used to execute the query.
  268. * If this parameter is not given, the `db` application component will be used.
  269. * @return int the minimum of the specified column values.
  270. */
  271. public function min($column, $db = null)
  272. {
  273. if ($this->emulateExecution) {
  274. return null;
  275. }
  276. return $this->executeScript($db, 'Min', $column);
  277. }
  278. /**
  279. * Returns the maximum of the specified column values.
  280. * @param string $column the column name or expression.
  281. * Make sure you properly quote column names in the expression.
  282. * @param Connection $db the database connection used to execute the query.
  283. * If this parameter is not given, the `db` application component will be used.
  284. * @return int the maximum of the specified column values.
  285. */
  286. public function max($column, $db = null)
  287. {
  288. if ($this->emulateExecution) {
  289. return null;
  290. }
  291. return $this->executeScript($db, 'Max', $column);
  292. }
  293. /**
  294. * Returns the query result as a scalar value.
  295. * The value returned will be the specified attribute in the first record of the query results.
  296. * @param string $attribute name of the attribute to select
  297. * @param Connection $db the database connection used to execute the query.
  298. * If this parameter is not given, the `db` application component will be used.
  299. * @return string the value of the specified attribute in the first record of the query result.
  300. * Null is returned if the query result is empty.
  301. */
  302. public function scalar($attribute, $db = null)
  303. {
  304. if ($this->emulateExecution) {
  305. return null;
  306. }
  307. $record = $this->one($db);
  308. if ($record !== null) {
  309. return $record->hasAttribute($attribute) ? $record->$attribute : null;
  310. } else {
  311. return null;
  312. }
  313. }
  314. /**
  315. * Executes a script created by [[LuaScriptBuilder]]
  316. * @param Connection|null $db the database connection used to execute the query.
  317. * If this parameter is not given, the `db` application component will be used.
  318. * @param string $type the type of the script to generate
  319. * @param string $columnName
  320. * @throws NotSupportedException
  321. * @return array|bool|null|string
  322. */
  323. protected function executeScript($db, $type, $columnName = null)
  324. {
  325. if ($this->primaryModel !== null) {
  326. // lazy loading
  327. if ($this->via instanceof self) {
  328. // via junction table
  329. $viaModels = $this->via->findJunctionRows([$this->primaryModel]);
  330. $this->filterByModels($viaModels);
  331. } elseif (is_array($this->via)) {
  332. // via relation
  333. /* @var $viaQuery ActiveQuery */
  334. list($viaName, $viaQuery) = $this->via;
  335. if ($viaQuery->multiple) {
  336. $viaModels = $viaQuery->all();
  337. $this->primaryModel->populateRelation($viaName, $viaModels);
  338. } else {
  339. $model = $viaQuery->one();
  340. $this->primaryModel->populateRelation($viaName, $model);
  341. $viaModels = $model === null ? [] : [$model];
  342. }
  343. $this->filterByModels($viaModels);
  344. } else {
  345. $this->filterByModels([$this->primaryModel]);
  346. }
  347. }
  348. if (!empty($this->orderBy)) {
  349. throw new NotSupportedException('orderBy is currently not supported by redis ActiveRecord.');
  350. }
  351. /* @var $modelClass ActiveRecord */
  352. $modelClass = $this->modelClass;
  353. if ($db === null) {
  354. $db = $modelClass::getDb();
  355. }
  356. // find by primary key if possible. This is much faster than scanning all records
  357. if (is_array($this->where) && (
  358. !isset($this->where[0]) && $modelClass::isPrimaryKey(array_keys($this->where)) ||
  359. isset($this->where[0]) && $this->where[0] === 'in' && $modelClass::isPrimaryKey((array) $this->where[1])
  360. )) {
  361. return $this->findByPk($db, $type, $columnName);
  362. }
  363. $method = 'build' . $type;
  364. $script = $db->getLuaScriptBuilder()->$method($this, $columnName);
  365. return $db->executeCommand('EVAL', [$script, 0]);
  366. }
  367. /**
  368. * Fetch by pk if possible as this is much faster
  369. * @param Connection $db the database connection used to execute the query.
  370. * If this parameter is not given, the `db` application component will be used.
  371. * @param string $type the type of the script to generate
  372. * @param string $columnName
  373. * @return array|bool|null|string
  374. * @throws \yii\base\InvalidParamException
  375. * @throws \yii\base\NotSupportedException
  376. */
  377. private function findByPk($db, $type, $columnName = null)
  378. {
  379. if (isset($this->where[0]) && $this->where[0] === 'in') {
  380. $pks = (array) $this->where[2];
  381. } elseif (count($this->where) == 1) {
  382. $pks = (array) reset($this->where);
  383. } else {
  384. foreach ($this->where as $values) {
  385. if (is_array($values)) {
  386. // TODO support composite IN for composite PK
  387. throw new NotSupportedException('Find by composite PK is not supported by redis ActiveRecord.');
  388. }
  389. }
  390. $pks = [$this->where];
  391. }
  392. /* @var $modelClass ActiveRecord */
  393. $modelClass = $this->modelClass;
  394. if ($type == 'Count') {
  395. $start = 0;
  396. $limit = null;
  397. } else {
  398. $start = $this->offset === null ? 0 : $this->offset;
  399. $limit = $this->limit;
  400. }
  401. $i = 0;
  402. $data = [];
  403. foreach ($pks as $pk) {
  404. if (++$i > $start && ($limit === null || $i <= $start + $limit)) {
  405. $key = $modelClass::keyPrefix() . ':a:' . $modelClass::buildKey($pk);
  406. $result = $db->executeCommand('HGETALL', [$key]);
  407. if (!empty($result)) {
  408. $data[] = $result;
  409. if ($type === 'One' && $this->orderBy === null) {
  410. break;
  411. }
  412. }
  413. }
  414. }
  415. // TODO support orderBy
  416. switch ($type) {
  417. case 'All':
  418. return $data;
  419. case 'One':
  420. return reset($data);
  421. case 'Count':
  422. return count($data);
  423. case 'Column':
  424. $column = [];
  425. foreach ($data as $dataRow) {
  426. $row = [];
  427. $c = count($dataRow);
  428. for ($i = 0; $i < $c;) {
  429. $row[$dataRow[$i++]] = $dataRow[$i++];
  430. }
  431. $column[] = $row[$columnName];
  432. }
  433. return $column;
  434. case 'Sum':
  435. $sum = 0;
  436. foreach ($data as $dataRow) {
  437. $c = count($dataRow);
  438. for ($i = 0; $i < $c;) {
  439. if ($dataRow[$i++] == $columnName) {
  440. $sum += $dataRow[$i];
  441. break;
  442. }
  443. }
  444. }
  445. return $sum;
  446. case 'Average':
  447. $sum = 0;
  448. $count = 0;
  449. foreach ($data as $dataRow) {
  450. $count++;
  451. $c = count($dataRow);
  452. for ($i = 0; $i < $c;) {
  453. if ($dataRow[$i++] == $columnName) {
  454. $sum += $dataRow[$i];
  455. break;
  456. }
  457. }
  458. }
  459. return $sum / $count;
  460. case 'Min':
  461. $min = null;
  462. foreach ($data as $dataRow) {
  463. $c = count($dataRow);
  464. for ($i = 0; $i < $c;) {
  465. if ($dataRow[$i++] == $columnName && ($min == null || $dataRow[$i] < $min)) {
  466. $min = $dataRow[$i];
  467. break;
  468. }
  469. }
  470. }
  471. return $min;
  472. case 'Max':
  473. $max = null;
  474. foreach ($data as $dataRow) {
  475. $c = count($dataRow);
  476. for ($i = 0; $i < $c;) {
  477. if ($dataRow[$i++] == $columnName && ($max == null || $dataRow[$i] > $max)) {
  478. $max = $dataRow[$i];
  479. break;
  480. }
  481. }
  482. }
  483. return $max;
  484. }
  485. throw new InvalidParamException('Unknown fetch type: ' . $type);
  486. }
  487. }