wfMsgForContentNoTrans() was removed
[mediawiki.git] / includes / utils / BatchRowIterator.php
blob07cb2bcd0eb786e646a16d474814e243f9f35725
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 = array();
54 /**
55 * @var array $joinConditions
57 protected $joinConditions = array();
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 = array();
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 = array();
139 foreach ( $this->primaryKey as $column ) {
140 $pk[$column] = $row->$column;
142 return $pk;
146 * @return array The most recently fetched set of rows from the database
148 public function current() {
149 return $this->current;
153 * @return integer 0-indexed count of the page number fetched
155 public function key() {
156 return $this->key;
160 * Reset the iterator to the begining of the table.
162 public function rewind() {
163 $this->key = -1; // self::next() will turn this into 0
164 $this->current = array();
165 $this->next();
169 * @return boolean True when the iterator is in a valid state
171 public function valid() {
172 return (bool)$this->current;
176 * @return boolean True when this result set has rows
178 public function hasChildren() {
179 return $this->current && count( $this->current );
183 * @return RecursiveIterator
185 public function getChildren() {
186 return new NotRecursiveIterator( new ArrayIterator( $this->current ) );
190 * Fetch the next set of rows from the database.
192 public function next() {
193 $res = $this->db->select(
194 $this->table,
195 $this->fetchColumns,
196 $this->buildConditions(),
197 __METHOD__,
198 array(
199 'LIMIT' => $this->batchSize,
200 'ORDER BY' => $this->orderBy,
202 $this->joinConditions
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++;
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
218 * Example output:
219 * array( '( foo = 42 AND bar > 7 ) OR ( foo > 42 )' )
221 * @return array The SQL conditions necessary to select the next set
222 * of rows in the batched query
224 protected function buildConditions() {
225 if ( !$this->current ) {
226 return $this->conditions;
229 $maxRow = end( $this->current );
230 $maximumValues = array();
231 foreach ( $this->primaryKey as $column ) {
232 $maximumValues[$column] = $this->db->addQuotes( $maxRow->$column );
235 $pkConditions = array();
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 );
248 $conditions = $this->conditions;
249 $conditions[] = sprintf( '( %s )', implode( ' ) OR ( ', $pkConditions ) );
251 return $conditions;
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
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
266 protected function buildGreaterThanCondition( array $quotedMaximumValues ) {
267 $keys = array_keys( $quotedMaximumValues );
268 $lastColumn = end( $keys );
269 $lastValue = array_pop( $quotedMaximumValues );
270 $conditions = array();
271 foreach ( $quotedMaximumValues as $column => $value ) {
272 $conditions[] = "$column = $value";
274 $conditions[] = "$lastColumn > $lastValue";
276 return implode( ' AND ', $conditions );