BatchQueryResult.php 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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\db;
  8. use yii\base\BaseObject;
  9. /**
  10. * BatchQueryResult represents a batch query from which you can retrieve data in batches.
  11. *
  12. * You usually do not instantiate BatchQueryResult directly. Instead, you obtain it by
  13. * calling [[Query::batch()]] or [[Query::each()]]. Because BatchQueryResult implements the [[\Iterator]] interface,
  14. * you can iterate it to obtain a batch of data in each iteration. For example,
  15. *
  16. * ```php
  17. * $query = (new Query)->from('user');
  18. * foreach ($query->batch() as $i => $users) {
  19. * // $users represents the rows in the $i-th batch
  20. * }
  21. * foreach ($query->each() as $user) {
  22. * }
  23. * ```
  24. *
  25. * @author Qiang Xue <qiang.xue@gmail.com>
  26. * @since 2.0
  27. */
  28. class BatchQueryResult extends BaseObject implements \Iterator
  29. {
  30. /**
  31. * @var Connection the DB connection to be used when performing batch query.
  32. * If null, the "db" application component will be used.
  33. */
  34. public $db;
  35. /**
  36. * @var Query the query object associated with this batch query.
  37. * Do not modify this property directly unless after [[reset()]] is called explicitly.
  38. */
  39. public $query;
  40. /**
  41. * @var int the number of rows to be returned in each batch.
  42. */
  43. public $batchSize = 100;
  44. /**
  45. * @var bool whether to return a single row during each iteration.
  46. * If false, a whole batch of rows will be returned in each iteration.
  47. */
  48. public $each = false;
  49. /**
  50. * @var DataReader the data reader associated with this batch query.
  51. */
  52. private $_dataReader;
  53. /**
  54. * @var array the data retrieved in the current batch
  55. */
  56. private $_batch;
  57. /**
  58. * @var mixed the value for the current iteration
  59. */
  60. private $_value;
  61. /**
  62. * @var string|int the key for the current iteration
  63. */
  64. private $_key;
  65. /**
  66. * @var int MSSQL error code for exception that is thrown when last batch is size less than specified batch size
  67. * @see https://github.com/yiisoft/yii2/issues/10023
  68. */
  69. private $mssqlNoMoreRowsErrorCode = -13;
  70. /**
  71. * Destructor.
  72. */
  73. public function __destruct()
  74. {
  75. // make sure cursor is closed
  76. $this->reset();
  77. }
  78. /**
  79. * Resets the batch query.
  80. * This method will clean up the existing batch query so that a new batch query can be performed.
  81. */
  82. public function reset()
  83. {
  84. if ($this->_dataReader !== null) {
  85. $this->_dataReader->close();
  86. }
  87. $this->_dataReader = null;
  88. $this->_batch = null;
  89. $this->_value = null;
  90. $this->_key = null;
  91. }
  92. /**
  93. * Resets the iterator to the initial state.
  94. * This method is required by the interface [[\Iterator]].
  95. */
  96. public function rewind()
  97. {
  98. $this->reset();
  99. $this->next();
  100. }
  101. /**
  102. * Moves the internal pointer to the next dataset.
  103. * This method is required by the interface [[\Iterator]].
  104. */
  105. public function next()
  106. {
  107. if ($this->_batch === null || !$this->each || $this->each && next($this->_batch) === false) {
  108. $this->_batch = $this->fetchData();
  109. reset($this->_batch);
  110. }
  111. if ($this->each) {
  112. $this->_value = current($this->_batch);
  113. if ($this->query->indexBy !== null) {
  114. $this->_key = key($this->_batch);
  115. } elseif (key($this->_batch) !== null) {
  116. $this->_key = $this->_key === null ? 0 : $this->_key + 1;
  117. } else {
  118. $this->_key = null;
  119. }
  120. } else {
  121. $this->_value = $this->_batch;
  122. $this->_key = $this->_key === null ? 0 : $this->_key + 1;
  123. }
  124. }
  125. /**
  126. * Fetches the next batch of data.
  127. * @return array the data fetched
  128. * @throws Exception
  129. */
  130. protected function fetchData()
  131. {
  132. if ($this->_dataReader === null) {
  133. $this->_dataReader = $this->query->createCommand($this->db)->query();
  134. }
  135. $rows = $this->getRows();
  136. return $this->query->populate($rows);
  137. }
  138. /**
  139. * Reads and collects rows for batch
  140. * @return array
  141. * @since 2.0.23
  142. */
  143. protected function getRows()
  144. {
  145. $rows = [];
  146. $count = 0;
  147. try {
  148. while ($count++ < $this->batchSize && ($row = $this->_dataReader->read())) {
  149. $rows[] = $row;
  150. }
  151. } catch (\PDOException $e) {
  152. $errorCode = isset($e->errorInfo[1]) ? $e->errorInfo[1] : null;
  153. if ($this->getDbDriverName() !== 'sqlsrv' || $errorCode !== $this->mssqlNoMoreRowsErrorCode) {
  154. throw $e;
  155. }
  156. }
  157. return $rows;
  158. }
  159. /**
  160. * Returns the index of the current dataset.
  161. * This method is required by the interface [[\Iterator]].
  162. * @return int the index of the current row.
  163. */
  164. public function key()
  165. {
  166. return $this->_key;
  167. }
  168. /**
  169. * Returns the current dataset.
  170. * This method is required by the interface [[\Iterator]].
  171. * @return mixed the current dataset.
  172. */
  173. public function current()
  174. {
  175. return $this->_value;
  176. }
  177. /**
  178. * Returns whether there is a valid dataset at the current position.
  179. * This method is required by the interface [[\Iterator]].
  180. * @return bool whether there is a valid dataset at the current position.
  181. */
  182. public function valid()
  183. {
  184. return !empty($this->_batch);
  185. }
  186. /**
  187. * Gets db driver name from the db connection that is passed to the `batch()`, if it is not passed it uses
  188. * connection from the active record model
  189. * @return string|null
  190. */
  191. private function getDbDriverName()
  192. {
  193. if (isset($this->db->driverName)) {
  194. return $this->db->driverName;
  195. }
  196. if (isset($this->_batch[0]->db->driverName)) {
  197. return $this->_batch[0]->db->driverName;
  198. }
  199. return null;
  200. }
  201. }