|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179 |
- <?php
-
-
- namespace yii\db;
-
- use yii\base\Object;
-
-
- class BatchQueryResult extends Object implements \Iterator
- {
-
-
- public $db;
-
-
- public $query;
-
-
- public $batchSize = 100;
-
-
- public $each = false;
-
-
-
- private $_dataReader;
-
-
- private $_batch;
-
-
- private $_value;
-
-
- private $_key;
-
-
-
-
- public function __destruct()
- {
-
- $this->reset();
- }
-
-
-
- public function reset()
- {
- if ($this->_dataReader !== null) {
- $this->_dataReader->close();
- }
- $this->_dataReader = null;
- $this->_batch = null;
- $this->_value = null;
- $this->_key = null;
- }
-
-
-
- public function rewind()
- {
- $this->reset();
- $this->next();
- }
-
-
-
- public function next()
- {
- if ($this->_batch === null || !$this->each || $this->each && next($this->_batch) === false) {
- $this->_batch = $this->fetchData();
- reset($this->_batch);
- }
-
- if ($this->each) {
- $this->_value = current($this->_batch);
- if ($this->query->indexBy !== null) {
- $this->_key = key($this->_batch);
- } elseif (key($this->_batch) !== null) {
- $this->_key++;
- } else {
- $this->_key = null;
- }
- } else {
- $this->_value = $this->_batch;
- $this->_key = $this->_key === null ? 0 : $this->_key + 1;
- }
- }
-
-
-
- protected function fetchData()
- {
- if ($this->_dataReader === null) {
- $this->_dataReader = $this->query->createCommand($this->db)->query();
- }
-
- $rows = [];
- $count = 0;
- while ($count++ < $this->batchSize && ($row = $this->_dataReader->read())) {
- $rows[] = $row;
- }
-
- return $this->query->populate($rows);
- }
-
-
-
- public function key()
- {
- return $this->_key;
- }
-
-
-
- public function current()
- {
- return $this->_value;
- }
-
-
-
- public function valid()
- {
- return !empty($this->_batch);
- }
- }
|