Expose $wgMaxArticleSize in siteinfo query api
[mediawiki.git] / includes / utils / BatchRowIterator.php
blob419ee4730df3b3dc731d426c253be4ac1142cf80
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.
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.
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.
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
23 * @file
24 * @ingroup Maintenance
26 class BatchRowIterator implements RecursiveIterator {
28 /**
29 * @var IDatabase $db The database to read from
31 protected $db;
33 /**
34 * @var string $table The name of the table to read from
36 protected $table;
38 /**
39 * @var array $primaryKey The name of the primary key(s)
41 protected $primaryKey;
43 /**
44 * @var integer $batchSize The number of rows to fetch per iteration
46 protected $batchSize;
48 /**
49 * @var array $conditions Array of strings containing SQL conditions
50 * to add to the query
52 protected $conditions = [];
54 /**
55 * @var array $joinConditions
57 protected $joinConditions = [];
59 /**
60 * @var array $fetchColumns List of column names to select from the
61 * table suitable for use with IDatabase::select()
63 protected $fetchColumns;
65 /**
66 * @var string $orderBy SQL Order by condition generated from $this->primaryKey
68 protected $orderBy;
70 /**
71 * @var array $current The current iterator value
73 private $current = [];
75 /**
76 * @var integer key 0-indexed number of pages fetched since self::reset()
78 private $key;
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
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.' );
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;
99 /**
100 * @param array $condition Query conditions suitable for use with
101 * IDatabase::select
103 public function addConditions( array $conditions ) {
104 $this->conditions = array_merge( $this->conditions, $conditions );
108 * @param array $condition Query join conditions suitable for use
109 * with IDatabase::select
111 public function addJoinConditions( array $conditions ) {
112 $this->joinConditions = array_merge( $this->joinConditions, $conditions );
116 * @param array $columns List of column names to select from the
117 * table suitable for use with IDatabase::select()
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 ) );
132 * Extracts the primary key(s) from a database row.
134 * @param stdClass $row An individual database row from this iterator
135 * @return array Map of primary key column to value within the row
137 public function extractPrimaryKeys( $row ) {
138 $pk = [];
139 foreach ( $this->primaryKey as $alias => $column ) {
140 $name = is_numeric( $alias ) ? $column : $alias;
141 $pk[$name] = $row->{$name};
143 return $pk;
147 * @return array The most recently fetched set of rows from the database
149 public function current() {
150 return $this->current;
154 * @return integer 0-indexed count of the page number fetched
156 public function key() {
157 return $this->key;
161 * Reset the iterator to the begining of the table.
163 public function rewind() {
164 $this->key = -1; // self::next() will turn this into 0
165 $this->current = [];
166 $this->next();
170 * @return bool True when the iterator is in a valid state
172 public function valid() {
173 return (bool)$this->current;
177 * @return bool True when this result set has rows
179 public function hasChildren() {
180 return $this->current && count( $this->current );
184 * @return RecursiveIterator
186 public function getChildren() {
187 return new NotRecursiveIterator( new ArrayIterator( $this->current ) );
191 * Fetch the next set of rows from the database.
193 public function next() {
194 $res = $this->db->select(
195 $this->table,
196 $this->fetchColumns,
197 $this->buildConditions(),
198 __METHOD__,
200 'LIMIT' => $this->batchSize,
201 'ORDER BY' => $this->orderBy,
203 $this->joinConditions
206 // The iterator is converted to an array because in addition to
207 // returning it in self::current() we need to use the end value
208 // in self::buildConditions()
209 $this->current = iterator_to_array( $res );
210 $this->key++;
214 * Uses the primary key list and the maximal result row from the
215 * previous iteration to build an SQL condition sufficient for
216 * selecting the next page of results. All except the final key use
217 * `=` conditions while the final key uses a `>` condition
219 * Example output:
220 * array( '( foo = 42 AND bar > 7 ) OR ( foo > 42 )' )
222 * @return array The SQL conditions necessary to select the next set
223 * of rows in the batched query
225 protected function buildConditions() {
226 if ( !$this->current ) {
227 return $this->conditions;
230 $maxRow = end( $this->current );
231 $maximumValues = [];
232 foreach ( $this->primaryKey as $alias => $column ) {
233 $name = is_numeric( $alias ) ? $column : $alias;
234 $maximumValues[$column] = $this->db->addQuotes( $maxRow->{$name} );
237 $pkConditions = [];
238 // For example: If we have 3 primary keys
239 // first run through will generate
240 // col1 = 4 AND col2 = 7 AND col3 > 1
241 // second run through will generate
242 // col1 = 4 AND col2 > 7
243 // and the final run through will generate
244 // col1 > 4
245 while ( $maximumValues ) {
246 $pkConditions[] = $this->buildGreaterThanCondition( $maximumValues );
247 array_pop( $maximumValues );
250 $conditions = $this->conditions;
251 $conditions[] = sprintf( '( %s )', implode( ' ) OR ( ', $pkConditions ) );
253 return $conditions;
257 * Given an array of column names and their maximum value generate
258 * an SQL condition where all keys except the last match $quotedMaximumValues
259 * exactly and the last column is greater than the matching value in
260 * $quotedMaximumValues
262 * @param array $quotedMaximumValues The maximum values quoted with
263 * $this->db->addQuotes()
264 * @return string An SQL condition that will select rows where all
265 * columns match the maximum value exactly except the last column
266 * which must be greater than the provided maximum value
268 protected function buildGreaterThanCondition( array $quotedMaximumValues ) {
269 $keys = array_keys( $quotedMaximumValues );
270 $lastColumn = end( $keys );
271 $lastValue = array_pop( $quotedMaximumValues );
272 $conditions = [];
273 foreach ( $quotedMaximumValues as $column => $value ) {
274 $conditions[] = "$column = $value";
276 $conditions[] = "$lastColumn > $lastValue";
278 return implode( ' AND ', $conditions );