TableDiffFormatter: Don't repeatedly call array_shift()
[lhc/web/wiklou.git] / includes / utils / BatchRowIterator.php
1 <?php
2 /**
3 * Allows iterating a large number of rows in batches transparently.
4 * By default when iterated over returns the full query result as an
5 * array of rows. Can be wrapped in RecursiveIteratorIterator to
6 * collapse those arrays into a single stream of rows queried in batches.
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 * @ingroup Maintenance
25 */
26 class BatchRowIterator implements RecursiveIterator {
27
28 /**
29 * @var IDatabase $db The database to read from
30 */
31 protected $db;
32
33 /**
34 * @var string $table The name of the table to read from
35 */
36 protected $table;
37
38 /**
39 * @var array $primaryKey The name of the primary key(s)
40 */
41 protected $primaryKey;
42
43 /**
44 * @var integer $batchSize The number of rows to fetch per iteration
45 */
46 protected $batchSize;
47
48 /**
49 * @var array $conditions Array of strings containing SQL conditions
50 * to add to the query
51 */
52 protected $conditions = [];
53
54 /**
55 * @var array $joinConditions
56 */
57 protected $joinConditions = [];
58
59 /**
60 * @var array $fetchColumns List of column names to select from the
61 * table suitable for use with IDatabase::select()
62 */
63 protected $fetchColumns;
64
65 /**
66 * @var string $orderBy SQL Order by condition generated from $this->primaryKey
67 */
68 protected $orderBy;
69
70 /**
71 * @var array $current The current iterator value
72 */
73 private $current = [];
74
75 /**
76 * @var integer key 0-indexed number of pages fetched since self::reset()
77 */
78 private $key;
79
80 /**
81 * @param IDatabase $db The database to read from
82 * @param string $table The name of the table to read from
83 * @param string|array $primaryKey The name or names of the primary key columns
84 * @param integer $batchSize The number of rows to fetch per iteration
85 * @throws MWException
86 */
87 public function __construct( IDatabase $db, $table, $primaryKey, $batchSize ) {
88 if ( $batchSize < 1 ) {
89 throw new MWException( 'Batch size must be at least 1 row.' );
90 }
91 $this->db = $db;
92 $this->table = $table;
93 $this->primaryKey = (array)$primaryKey;
94 $this->fetchColumns = $this->primaryKey;
95 $this->orderBy = implode( ' ASC,', $this->primaryKey ) . ' ASC';
96 $this->batchSize = $batchSize;
97 }
98
99 /**
100 * @param array $condition Query conditions suitable for use with
101 * IDatabase::select
102 */
103 public function addConditions( array $conditions ) {
104 $this->conditions = array_merge( $this->conditions, $conditions );
105 }
106
107 /**
108 * @param array $condition Query join conditions suitable for use
109 * with IDatabase::select
110 */
111 public function addJoinConditions( array $conditions ) {
112 $this->joinConditions = array_merge( $this->joinConditions, $conditions );
113 }
114
115 /**
116 * @param array $columns List of column names to select from the
117 * table suitable for use with IDatabase::select()
118 */
119 public function setFetchColumns( array $columns ) {
120 // If it's not the all column selector merge in the primary keys we need
121 if ( count( $columns ) === 1 && reset( $columns ) === '*' ) {
122 $this->fetchColumns = $columns;
123 } else {
124 $this->fetchColumns = array_unique( array_merge(
125 $this->primaryKey,
126 $columns
127 ) );
128 }
129 }
130
131 /**
132 * Extracts the primary key(s) from a database row.
133 *
134 * @param stdClass $row An individual database row from this iterator
135 * @return array Map of primary key column to value within the row
136 */
137 public function extractPrimaryKeys( $row ) {
138 $pk = [];
139 foreach ( $this->primaryKey as $column ) {
140 $pk[$column] = $row->$column;
141 }
142 return $pk;
143 }
144
145 /**
146 * @return array The most recently fetched set of rows from the database
147 */
148 public function current() {
149 return $this->current;
150 }
151
152 /**
153 * @return integer 0-indexed count of the page number fetched
154 */
155 public function key() {
156 return $this->key;
157 }
158
159 /**
160 * Reset the iterator to the begining of the table.
161 */
162 public function rewind() {
163 $this->key = -1; // self::next() will turn this into 0
164 $this->current = [];
165 $this->next();
166 }
167
168 /**
169 * @return boolean True when the iterator is in a valid state
170 */
171 public function valid() {
172 return (bool)$this->current;
173 }
174
175 /**
176 * @return boolean True when this result set has rows
177 */
178 public function hasChildren() {
179 return $this->current && count( $this->current );
180 }
181
182 /**
183 * @return RecursiveIterator
184 */
185 public function getChildren() {
186 return new NotRecursiveIterator( new ArrayIterator( $this->current ) );
187 }
188
189 /**
190 * Fetch the next set of rows from the database.
191 */
192 public function next() {
193 $res = $this->db->select(
194 $this->table,
195 $this->fetchColumns,
196 $this->buildConditions(),
197 __METHOD__,
198 [
199 'LIMIT' => $this->batchSize,
200 'ORDER BY' => $this->orderBy,
201 ],
202 $this->joinConditions
203 );
204
205 // The iterator is converted to an array because in addition to
206 // returning it in self::current() we need to use the end value
207 // in self::buildConditions()
208 $this->current = iterator_to_array( $res );
209 $this->key++;
210 }
211
212 /**
213 * Uses the primary key list and the maximal result row from the
214 * previous iteration to build an SQL condition sufficient for
215 * selecting the next page of results. All except the final key use
216 * `=` conditions while the final key uses a `>` condition
217 *
218 * Example output:
219 * array( '( foo = 42 AND bar > 7 ) OR ( foo > 42 )' )
220 *
221 * @return array The SQL conditions necessary to select the next set
222 * of rows in the batched query
223 */
224 protected function buildConditions() {
225 if ( !$this->current ) {
226 return $this->conditions;
227 }
228
229 $maxRow = end( $this->current );
230 $maximumValues = [];
231 foreach ( $this->primaryKey as $column ) {
232 $maximumValues[$column] = $this->db->addQuotes( $maxRow->$column );
233 }
234
235 $pkConditions = [];
236 // For example: If we have 3 primary keys
237 // first run through will generate
238 // col1 = 4 AND col2 = 7 AND col3 > 1
239 // second run through will generate
240 // col1 = 4 AND col2 > 7
241 // and the final run through will generate
242 // col1 > 4
243 while ( $maximumValues ) {
244 $pkConditions[] = $this->buildGreaterThanCondition( $maximumValues );
245 array_pop( $maximumValues );
246 }
247
248 $conditions = $this->conditions;
249 $conditions[] = sprintf( '( %s )', implode( ' ) OR ( ', $pkConditions ) );
250
251 return $conditions;
252 }
253
254 /**
255 * Given an array of column names and their maximum value generate
256 * an SQL condition where all keys except the last match $quotedMaximumValues
257 * exactly and the last column is greater than the matching value in
258 * $quotedMaximumValues
259 *
260 * @param array $quotedMaximumValues The maximum values quoted with
261 * $this->db->addQuotes()
262 * @return string An SQL condition that will select rows where all
263 * columns match the maximum value exactly except the last column
264 * which must be greater than the provided maximum value
265 */
266 protected function buildGreaterThanCondition( array $quotedMaximumValues ) {
267 $keys = array_keys( $quotedMaximumValues );
268 $lastColumn = end( $keys );
269 $lastValue = array_pop( $quotedMaximumValues );
270 $conditions = [];
271 foreach ( $quotedMaximumValues as $column => $value ) {
272 $conditions[] = "$column = $value";
273 }
274 $conditions[] = "$lastColumn > $lastValue";
275
276 return implode( ' AND ', $conditions );
277 }
278 }