3 * Efficient paging for SQL queries.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * IndexPager is an efficient pager which uses a (roughly unique) index in the
26 * data set to implement paging, rather than a "LIMIT offset,limit" clause.
27 * In MySQL, such a limit/offset clause requires counting through the
28 * specified number of offset rows to find the desired data, which can be
29 * expensive for large offsets.
31 * ReverseChronologicalPager is a child class of the abstract IndexPager, and
32 * contains some formatting and display code which is specific to the use of
33 * timestamps as indexes. Here is a synopsis of its operation:
35 * * The query is specified by the offset, limit and direction (dir)
36 * parameters, in addition to any subclass-specific parameters.
37 * * The offset is the non-inclusive start of the DB query. A row with an
38 * index value equal to the offset will never be shown.
39 * * The query may either be done backwards, where the rows are returned by
40 * the database in the opposite order to which they are displayed to the
41 * user, or forwards. This is specified by the "dir" parameter, dir=prev
42 * means backwards, anything else means forwards. The offset value
43 * specifies the start of the database result set, which may be either
44 * the start or end of the displayed data set. This allows "previous"
45 * links to be implemented without knowledge of the index value at the
46 * start of the previous page.
47 * * An additional row beyond the user-specified limit is always requested.
48 * This allows us to tell whether we should display a "next" link in the
49 * case of forwards mode, or a "previous" link in the case of backwards
50 * mode. Determining whether to display the other link (the one for the
51 * page before the start of the database result set) can be done
52 * heuristically by examining the offset.
54 * * An empty offset indicates that the offset condition should be omitted
55 * from the query. This naturally produces either the first page or the
56 * last page depending on the dir parameter.
58 * Subclassing the pager to implement concrete functionality should be fairly
59 * simple, please see the examples in HistoryAction.php and
60 * SpecialBlockList.php. You just need to override formatRow(),
61 * getQueryInfo() and getIndexField(). Don't forget to call the parent
62 * constructor if you override it.
66 abstract class IndexPager
extends ContextSource
implements Pager
{
68 * Constants for the $mDefaultDirection field.
70 * These are boolean for historical reasons and should stay boolean for backwards-compatibility.
72 const DIR_ASCENDING
= false;
73 const DIR_DESCENDING
= true;
76 public $mLimitsShown = array( 20, 50, 100, 250, 500 );
77 public $mDefaultLimit = 50;
78 public $mOffset, $mLimit;
79 public $mQueryDone = false;
81 public $mPastTheEndRow;
84 * The index to actually be used for ordering. This is a single column,
85 * for one ordering, even if multiple orderings are supported.
87 protected $mIndexField;
89 * An array of secondary columns to order by. These fields are not part of the offset.
90 * This is a column list for one ordering, even if multiple orderings are supported.
92 protected $mExtraSortFields;
93 /** For pages that support multiple types of ordering, which one to use.
95 protected $mOrderType;
97 * $mDefaultDirection gives the direction to use when sorting results:
98 * DIR_ASCENDING or DIR_DESCENDING. If $mIsBackwards is set, we
99 * start from the opposite end, but we still sort the page itself according
100 * to $mDefaultDirection. E.g., if $mDefaultDirection is false but we're
101 * going backwards, we'll display the last page of results, but the last
102 * result will be at the bottom, not the top.
104 * Like $mIndexField, $mDefaultDirection will be a single value even if the
105 * class supports multiple default directions for different order types.
107 public $mDefaultDirection;
108 public $mIsBackwards;
110 /** True if the current result set is the first one */
114 protected $mLastShown, $mFirstShown, $mPastTheEndIndex, $mDefaultQuery, $mNavigationBar;
117 * Whether to include the offset in the query
119 protected $mIncludeOffset = false;
122 * Result object for the query. Warning: seek before use.
128 public function __construct( IContextSource
$context = null ) {
130 $this->setContext( $context );
133 $this->mRequest
= $this->getRequest();
135 # NB: the offset is quoted, not validated. It is treated as an
136 # arbitrary string to support the widest variety of index types. Be
137 # careful outputting it into HTML!
138 $this->mOffset
= $this->mRequest
->getText( 'offset' );
140 # Use consistent behavior for the limit options
141 $this->mDefaultLimit
= $this->getUser()->getIntOption( 'rclimit' );
142 if ( !$this->mLimit
) {
143 // Don't override if a subclass calls $this->setLimit() in its constructor.
144 list( $this->mLimit
, /* $offset */ ) = $this->mRequest
->getLimitOffset();
147 $this->mIsBackwards
= ( $this->mRequest
->getVal( 'dir' ) == 'prev' );
148 # Let the subclass set the DB here; otherwise use a slave DB for the current wiki
149 $this->mDb
= $this->mDb ?
: wfGetDB( DB_SLAVE
);
151 $index = $this->getIndexField(); // column to sort on
152 $extraSort = $this->getExtraSortFields(); // extra columns to sort on for query planning
153 $order = $this->mRequest
->getVal( 'order' );
154 if ( is_array( $index ) && isset( $index[$order] ) ) {
155 $this->mOrderType
= $order;
156 $this->mIndexField
= $index[$order];
157 $this->mExtraSortFields
= isset( $extraSort[$order] )
158 ?
(array)$extraSort[$order]
160 } elseif ( is_array( $index ) ) {
161 # First element is the default
163 list( $this->mOrderType
, $this->mIndexField
) = each( $index );
164 $this->mExtraSortFields
= isset( $extraSort[$this->mOrderType
] )
165 ?
(array)$extraSort[$this->mOrderType
]
168 # $index is not an array
169 $this->mOrderType
= null;
170 $this->mIndexField
= $index;
171 $this->mExtraSortFields
= (array)$extraSort;
174 if ( !isset( $this->mDefaultDirection
) ) {
175 $dir = $this->getDefaultDirections();
176 $this->mDefaultDirection
= is_array( $dir )
177 ?
$dir[$this->mOrderType
]
183 * Get the Database object in use
187 public function getDatabase() {
192 * Do the query, using information from the object context. This function
193 * has been kept minimal to make it overridable if necessary, to allow for
194 * result sets formed from multiple DB queries.
196 public function doQuery() {
197 # Use the child class name for profiling
198 $fname = __METHOD__
. ' (' . get_class( $this ) . ')';
199 $section = Profiler
::instance()->scopedProfileIn( $fname );
201 // @todo This should probably compare to DIR_DESCENDING and DIR_ASCENDING constants
202 $descending = ( $this->mIsBackwards
== $this->mDefaultDirection
);
203 # Plus an extra row so that we can tell the "next" link should be shown
204 $queryLimit = $this->mLimit +
1;
206 if ( $this->mOffset
== '' ) {
209 // If there's an offset, we may or may not be at the first entry.
210 // The only way to tell is to run the query in the opposite
211 // direction see if we get a row.
212 $oldIncludeOffset = $this->mIncludeOffset
;
213 $this->mIncludeOffset
= !$this->mIncludeOffset
;
214 $isFirst = !$this->reallyDoQuery( $this->mOffset
, 1, !$descending )->numRows();
215 $this->mIncludeOffset
= $oldIncludeOffset;
218 $this->mResult
= $this->reallyDoQuery(
224 $this->extractResultInfo( $isFirst, $queryLimit, $this->mResult
);
225 $this->mQueryDone
= true;
227 $this->preprocessResults( $this->mResult
);
228 $this->mResult
->rewind(); // Paranoia
232 * @return ResultWrapper The result wrapper.
234 function getResult() {
235 return $this->mResult
;
239 * Set the offset from an other source than the request
241 * @param int|string $offset
243 function setOffset( $offset ) {
244 $this->mOffset
= $offset;
248 * Set the limit from an other source than the request
250 * Verifies limit is between 1 and 5000
252 * @param int|string $limit
254 function setLimit( $limit ) {
255 $limit = (int)$limit;
256 // WebRequest::getLimitOffset() puts a cap of 5000, so do same here.
257 if ( $limit > 5000 ) {
261 $this->mLimit
= $limit;
266 * Get the current limit
270 function getLimit() {
271 return $this->mLimit
;
275 * Set whether a row matching exactly the offset should be also included
276 * in the result or not. By default this is not the case, but when the
277 * offset is user-supplied this might be wanted.
279 * @param bool $include
281 public function setIncludeOffset( $include ) {
282 $this->mIncludeOffset
= $include;
286 * Extract some useful data from the result object for use by
287 * the navigation bar, put it into $this
289 * @param bool $isFirst False if there are rows before those fetched (i.e.
290 * if a "previous" link would make sense)
291 * @param int $limit Exact query limit
292 * @param ResultWrapper $res
294 function extractResultInfo( $isFirst, $limit, ResultWrapper
$res ) {
295 $numRows = $res->numRows();
297 # Remove any table prefix from index field
298 $parts = explode( '.', $this->mIndexField
);
299 $indexColumn = end( $parts );
301 $row = $res->fetchRow();
302 $firstIndex = $row[$indexColumn];
304 # Discard the extra result row if there is one
305 if ( $numRows > $this->mLimit
&& $numRows > 1 ) {
306 $res->seek( $numRows - 1 );
307 $this->mPastTheEndRow
= $res->fetchObject();
308 $this->mPastTheEndIndex
= $this->mPastTheEndRow
->$indexColumn;
309 $res->seek( $numRows - 2 );
310 $row = $res->fetchRow();
311 $lastIndex = $row[$indexColumn];
313 $this->mPastTheEndRow
= null;
314 # Setting indexes to an empty string means that they will be
315 # omitted if they would otherwise appear in URLs. It just so
316 # happens that this is the right thing to do in the standard
317 # UI, in all the relevant cases.
318 $this->mPastTheEndIndex
= '';
319 $res->seek( $numRows - 1 );
320 $row = $res->fetchRow();
321 $lastIndex = $row[$indexColumn];
326 $this->mPastTheEndRow
= null;
327 $this->mPastTheEndIndex
= '';
330 if ( $this->mIsBackwards
) {
331 $this->mIsFirst
= ( $numRows < $limit );
332 $this->mIsLast
= $isFirst;
333 $this->mLastShown
= $firstIndex;
334 $this->mFirstShown
= $lastIndex;
336 $this->mIsFirst
= $isFirst;
337 $this->mIsLast
= ( $numRows < $limit );
338 $this->mLastShown
= $lastIndex;
339 $this->mFirstShown
= $firstIndex;
344 * Get some text to go in brackets in the "function name" part of the SQL comment
348 function getSqlComment() {
349 return get_class( $this );
353 * Do a query with specified parameters, rather than using the object
356 * @param string $offset Index offset, inclusive
357 * @param int $limit Exact query limit
358 * @param bool $descending Query direction, false for ascending, true for descending
359 * @return ResultWrapper
361 public function reallyDoQuery( $offset, $limit, $descending ) {
362 list( $tables, $fields, $conds, $fname, $options, $join_conds ) =
363 $this->buildQueryInfo( $offset, $limit, $descending );
365 return $this->mDb
->select( $tables, $fields, $conds, $fname, $options, $join_conds );
369 * Build variables to use by the database wrapper.
371 * @param string $offset Index offset, inclusive
372 * @param int $limit Exact query limit
373 * @param bool $descending Query direction, false for ascending, true for descending
376 protected function buildQueryInfo( $offset, $limit, $descending ) {
377 $fname = __METHOD__
. ' (' . $this->getSqlComment() . ')';
378 $info = $this->getQueryInfo();
379 $tables = $info['tables'];
380 $fields = $info['fields'];
381 $conds = isset( $info['conds'] ) ?
$info['conds'] : array();
382 $options = isset( $info['options'] ) ?
$info['options'] : array();
383 $join_conds = isset( $info['join_conds'] ) ?
$info['join_conds'] : array();
384 $sortColumns = array_merge( array( $this->mIndexField
), $this->mExtraSortFields
);
386 $options['ORDER BY'] = $sortColumns;
387 $operator = $this->mIncludeOffset ?
'>=' : '>';
390 foreach ( $sortColumns as $col ) {
391 $orderBy[] = $col . ' DESC';
393 $options['ORDER BY'] = $orderBy;
394 $operator = $this->mIncludeOffset ?
'<=' : '<';
396 if ( $offset != '' ) {
397 $conds[] = $this->mIndexField
. $operator . $this->mDb
->addQuotes( $offset );
399 $options['LIMIT'] = intval( $limit );
400 return array( $tables, $fields, $conds, $fname, $options, $join_conds );
404 * Pre-process results; useful for performing batch existence checks, etc.
406 * @param ResultWrapper $result
408 protected function preprocessResults( $result ) {
412 * Get the formatted result list. Calls getStartBody(), formatRow() and
413 * getEndBody(), concatenates the results and returns them.
417 public function getBody() {
418 if ( !$this->mQueryDone
) {
422 if ( $this->mResult
->numRows() ) {
423 # Do any special query batches before display
424 $this->doBatchLookups();
427 # Don't use any extra rows returned by the query
428 $numRows = min( $this->mResult
->numRows(), $this->mLimit
);
430 $s = $this->getStartBody();
432 if ( $this->mIsBackwards
) {
433 for ( $i = $numRows - 1; $i >= 0; $i-- ) {
434 $this->mResult
->seek( $i );
435 $row = $this->mResult
->fetchObject();
436 $s .= $this->formatRow( $row );
439 $this->mResult
->seek( 0 );
440 for ( $i = 0; $i < $numRows; $i++
) {
441 $row = $this->mResult
->fetchObject();
442 $s .= $this->formatRow( $row );
446 $s .= $this->getEmptyBody();
448 $s .= $this->getEndBody();
455 * @param string $text Text displayed on the link
456 * @param array $query Associative array of parameter to be in the query string
457 * @param string $type Link type used to create additional attributes, like "rel", "class" or
458 * "title". Valid values (non-exhaustive list): 'first', 'last', 'prev', 'next', 'asc', 'desc'.
459 * @return string HTML fragment
461 function makeLink( $text, array $query = null, $type = null ) {
462 if ( $query === null ) {
467 if ( in_array( $type, array( 'prev', 'next' ) ) ) {
468 $attrs['rel'] = $type;
471 if ( in_array( $type, array( 'asc', 'desc' ) ) ) {
472 $attrs['title'] = wfMessage( $type == 'asc' ?
'sort-ascending' : 'sort-descending' )->text();
476 $attrs['class'] = "mw-{$type}link";
479 return Linker
::linkKnown(
483 $query +
$this->getDefaultQuery()
488 * Called from getBody(), before getStartBody() is called and
489 * after doQuery() was called. This will be called only if there
490 * are rows in the result set.
494 protected function doBatchLookups() {
498 * Hook into getBody(), allows text to be inserted at the start. This
499 * will be called even if there are no rows in the result set.
503 protected function getStartBody() {
508 * Hook into getBody() for the end of the list
512 protected function getEndBody() {
517 * Hook into getBody(), for the bit between the start and the
518 * end when there are no rows
522 protected function getEmptyBody() {
527 * Get an array of query parameters that should be put into self-links.
528 * By default, all parameters passed in the URL are used, except for a
531 * @return array Associative array
533 function getDefaultQuery() {
534 if ( !isset( $this->mDefaultQuery
) ) {
535 $this->mDefaultQuery
= $this->getRequest()->getQueryValues();
536 unset( $this->mDefaultQuery
['title'] );
537 unset( $this->mDefaultQuery
['dir'] );
538 unset( $this->mDefaultQuery
['offset'] );
539 unset( $this->mDefaultQuery
['limit'] );
540 unset( $this->mDefaultQuery
['order'] );
541 unset( $this->mDefaultQuery
['month'] );
542 unset( $this->mDefaultQuery
['year'] );
544 return $this->mDefaultQuery
;
548 * Get the number of rows in the result set
552 function getNumRows() {
553 if ( !$this->mQueryDone
) {
556 return $this->mResult
->numRows();
560 * Get a URL query array for the prev, next, first and last links.
564 function getPagingQueries() {
565 if ( !$this->mQueryDone
) {
569 # Don't announce the limit everywhere if it's the default
570 $urlLimit = $this->mLimit
== $this->mDefaultLimit ?
null : $this->mLimit
;
572 if ( $this->mIsFirst
) {
578 'offset' => $this->mFirstShown
,
581 $first = array( 'limit' => $urlLimit );
583 if ( $this->mIsLast
) {
587 $next = array( 'offset' => $this->mLastShown
, 'limit' => $urlLimit );
588 $last = array( 'dir' => 'prev', 'limit' => $urlLimit );
599 * Returns whether to show the "navigation bar"
603 function isNavigationBarShown() {
604 if ( !$this->mQueryDone
) {
607 // Hide navigation by default if there is nothing to page
608 return !( $this->mIsFirst
&& $this->mIsLast
);
612 * Get paging links. If a link is disabled, the item from $disabledTexts
613 * will be used. If there is no such item, the unlinked text from
614 * $linkTexts will be used. Both $linkTexts and $disabledTexts are arrays
617 * @param array $linkTexts
618 * @param array $disabledTexts
621 function getPagingLinks( $linkTexts, $disabledTexts = array() ) {
622 $queries = $this->getPagingQueries();
625 foreach ( $queries as $type => $query ) {
626 if ( $query !== false ) {
627 $links[$type] = $this->makeLink(
632 } elseif ( isset( $disabledTexts[$type] ) ) {
633 $links[$type] = $disabledTexts[$type];
635 $links[$type] = $linkTexts[$type];
642 function getLimitLinks() {
644 if ( $this->mIsBackwards
) {
645 $offset = $this->mPastTheEndIndex
;
647 $offset = $this->mOffset
;
649 foreach ( $this->mLimitsShown
as $limit ) {
650 $links[] = $this->makeLink(
651 $this->getLanguage()->formatNum( $limit ),
652 array( 'offset' => $offset, 'limit' => $limit ),
660 * Abstract formatting function. This should return an HTML string
661 * representing the result row $row. Rows will be concatenated and
662 * returned by getBody()
664 * @param array|stdClass $row Database row
667 abstract function formatRow( $row );
670 * This function should be overridden to provide all parameters
671 * needed for the main paged query. It returns an associative
672 * array with the following elements:
673 * tables => Table(s) for passing to Database::select()
674 * fields => Field(s) for passing to Database::select(), may be *
675 * conds => WHERE conditions
676 * options => option array
677 * join_conds => JOIN conditions
681 abstract function getQueryInfo();
684 * This function should be overridden to return the name of the index fi-
685 * eld. If the pager supports multiple orders, it may return an array of
686 * 'querykey' => 'indexfield' pairs, so that a request with &count=querykey
687 * will use indexfield to sort. In this case, the first returned key is
690 * Needless to say, it's really not a good idea to use a non-unique index
691 * for this! That won't page right.
693 * @return string|array
695 abstract function getIndexField();
698 * This function should be overridden to return the names of secondary columns
699 * to order by in addition to the column in getIndexField(). These fields will
700 * not be used in the pager offset or in any links for users.
702 * If getIndexField() returns an array of 'querykey' => 'indexfield' pairs then
703 * this must return a corresponding array of 'querykey' => array( fields...) pairs
704 * in order for a request with &count=querykey to use array( fields...) to sort.
706 * This is useful for pagers that GROUP BY a unique column (say page_id)
707 * and ORDER BY another (say page_len). Using GROUP BY and ORDER BY both on
708 * page_len,page_id avoids temp tables (given a page_len index). This would
709 * also work if page_id was non-unique but we had a page_len,page_id index.
713 protected function getExtraSortFields() {
718 * Return the default sorting direction: DIR_ASCENDING or DIR_DESCENDING.
719 * You can also have an associative array of ordertype => dir,
720 * if multiple order types are supported. In this case getIndexField()
721 * must return an array, and the keys of that must exactly match the keys
724 * For backward compatibility, this method's return value will be ignored
725 * if $this->mDefaultDirection is already set when the constructor is
726 * called, for instance if it's statically initialized. In that case the
727 * value of that variable (which must be a boolean) will be used.
729 * Note that despite its name, this does not return the value of the
730 * $this->mDefaultDirection member variable. That's the default for this
731 * particular instantiation, which is a single value. This is the set of
732 * all defaults for the class.
736 protected function getDefaultDirections() {
737 return IndexPager
::DIR_ASCENDING
;