Completed
Push — master ( a9097d...0e1f22 )
by Alexander
20:34
created

BatchQueryResult::getRows()   B

Complexity

Conditions 7
Paths 11

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 7.049

Importance

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