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
24 use Wikimedia\Rdbms\IResultWrapper
;
25 use Wikimedia\Rdbms\IDatabase
;
28 * IndexPager is an efficient pager which uses a (roughly unique) index in the
29 * data set to implement paging, rather than a "LIMIT offset,limit" clause.
30 * In MySQL, such a limit/offset clause requires counting through the
31 * specified number of offset rows to find the desired data, which can be
32 * expensive for large offsets.
34 * ReverseChronologicalPager is a child class of the abstract IndexPager, and
35 * contains some formatting and display code which is specific to the use of
36 * timestamps as indexes. Here is a synopsis of its operation:
38 * * The query is specified by the offset, limit and direction (dir)
39 * parameters, in addition to any subclass-specific parameters.
40 * * The offset is the non-inclusive start of the DB query. A row with an
41 * index value equal to the offset will never be shown.
42 * * The query may either be done backwards, where the rows are returned by
43 * the database in the opposite order to which they are displayed to the
44 * user, or forwards. This is specified by the "dir" parameter, dir=prev
45 * means backwards, anything else means forwards. The offset value
46 * specifies the start of the database result set, which may be either
47 * the start or end of the displayed data set. This allows "previous"
48 * links to be implemented without knowledge of the index value at the
49 * start of the previous page.
50 * * An additional row beyond the user-specified limit is always requested.
51 * This allows us to tell whether we should display a "next" link in the
52 * case of forwards mode, or a "previous" link in the case of backwards
53 * mode. Determining whether to display the other link (the one for the
54 * page before the start of the database result set) can be done
55 * heuristically by examining the offset.
57 * * An empty offset indicates that the offset condition should be omitted
58 * from the query. This naturally produces either the first page or the
59 * last page depending on the dir parameter.
61 * Subclassing the pager to implement concrete functionality should be fairly
62 * simple, please see the examples in HistoryAction.php and
63 * SpecialBlockList.php. You just need to override formatRow(),
64 * getQueryInfo() and getIndexField(). Don't forget to call the parent
65 * constructor if you override it.
69 abstract class IndexPager
extends ContextSource
implements Pager
{
70 /** Backwards-compatible constant for $mDefaultDirection field (do not change) */
71 const DIR_ASCENDING
= false;
72 /** Backwards-compatible constant for $mDefaultDirection field (do not change) */
73 const DIR_DESCENDING
= true;
75 /** Backwards-compatible constant for reallyDoQuery() (do not change) */
76 const QUERY_ASCENDING
= true;
77 /** Backwards-compatible constant for reallyDoQuery() (do not change) */
78 const QUERY_DESCENDING
= false;
80 /** @var WebRequest */
82 /** @var int[] List of default entry limit options to be presented to clients */
83 public $mLimitsShown = [ 20, 50, 100, 250, 500 ];
84 /** @var int The default entry limit choosen for clients */
85 public $mDefaultLimit = 50;
86 /** @var mixed The starting point to enumerate entries */
88 /** @var int The maximum number of entries to show */
90 /** @var bool Whether the listing query completed */
91 public $mQueryDone = false;
94 /** @var stdClass|bool|null Extra row fetched at the end to see if the end was reached */
95 public $mPastTheEndRow;
98 * The index to actually be used for ordering. This is a single column,
99 * for one ordering, even if multiple orderings are supported.
102 protected $mIndexField;
104 * An array of secondary columns to order by. These fields are not part of the offset.
105 * This is a column list for one ordering, even if multiple orderings are supported.
108 protected $mExtraSortFields;
109 /** For pages that support multiple types of ordering, which one to use.
112 protected $mOrderType;
114 * $mDefaultDirection gives the direction to use when sorting results:
115 * DIR_ASCENDING or DIR_DESCENDING. If $mIsBackwards is set, we start from
116 * the opposite end, but we still sort the page itself according to
117 * $mDefaultDirection. For example, if $mDefaultDirection is DIR_ASCENDING
118 * but we're going backwards, we'll display the last page of results, but
119 * the last result will be at the bottom, not the top.
121 * Like $mIndexField, $mDefaultDirection will be a single value even if the
122 * class supports multiple default directions for different order types.
125 public $mDefaultDirection;
127 public $mIsBackwards;
129 /** @var bool True if the current result set is the first one */
135 protected $mLastShown;
137 protected $mFirstShown;
139 protected $mPastTheEndIndex;
141 protected $mDefaultQuery;
143 protected $mNavigationBar;
146 * Whether to include the offset in the query
149 protected $mIncludeOffset = false;
152 * Result object for the query. Warning: seek before use.
154 * @var IResultWrapper
158 public function __construct( IContextSource
$context = null ) {
160 $this->setContext( $context );
163 $this->mRequest
= $this->getRequest();
165 # NB: the offset is quoted, not validated. It is treated as an
166 # arbitrary string to support the widest variety of index types. Be
167 # careful outputting it into HTML!
168 $this->mOffset
= $this->mRequest
->getText( 'offset' );
170 # Use consistent behavior for the limit options
171 $this->mDefaultLimit
= $this->getUser()->getIntOption( 'rclimit' );
172 if ( !$this->mLimit
) {
173 // Don't override if a subclass calls $this->setLimit() in its constructor.
174 list( $this->mLimit
, /* $offset */ ) = $this->mRequest
->getLimitOffset();
177 $this->mIsBackwards
= ( $this->mRequest
->getVal( 'dir' ) == 'prev' );
178 # Let the subclass set the DB here; otherwise use a replica DB for the current wiki
179 $this->mDb
= $this->mDb ?
: wfGetDB( DB_REPLICA
);
181 $index = $this->getIndexField(); // column to sort on
182 $extraSort = $this->getExtraSortFields(); // extra columns to sort on for query planning
183 $order = $this->mRequest
->getVal( 'order' );
184 if ( is_array( $index ) && isset( $index[$order] ) ) {
185 $this->mOrderType
= $order;
186 $this->mIndexField
= $index[$order];
187 $this->mExtraSortFields
= isset( $extraSort[$order] )
188 ?
(array)$extraSort[$order]
190 } elseif ( is_array( $index ) ) {
191 # First element is the default
192 $this->mIndexField
= reset( $index );
193 $this->mOrderType
= key( $index );
194 $this->mExtraSortFields
= isset( $extraSort[$this->mOrderType
] )
195 ?
(array)$extraSort[$this->mOrderType
]
198 # $index is not an array
199 $this->mOrderType
= null;
200 $this->mIndexField
= $index;
201 $this->mExtraSortFields
= (array)$extraSort;
204 if ( !isset( $this->mDefaultDirection
) ) {
205 $dir = $this->getDefaultDirections();
206 $this->mDefaultDirection
= is_array( $dir )
207 ?
$dir[$this->mOrderType
]
213 * Get the Database object in use
217 public function getDatabase() {
222 * Do the query, using information from the object context. This function
223 * has been kept minimal to make it overridable if necessary, to allow for
224 * result sets formed from multiple DB queries.
226 public function doQuery() {
227 # Use the child class name for profiling
228 $fname = __METHOD__
. ' (' . static::class . ')';
229 /** @noinspection PhpUnusedLocalVariableInspection */
230 $section = Profiler
::instance()->scopedProfileIn( $fname );
232 $defaultOrder = ( $this->mDefaultDirection
=== self
::DIR_ASCENDING
)
233 ? self
::QUERY_ASCENDING
234 : self
::QUERY_DESCENDING
;
235 $order = $this->mIsBackwards ? self
::oppositeOrder( $defaultOrder ) : $defaultOrder;
237 # Plus an extra row so that we can tell the "next" link should be shown
238 $queryLimit = $this->mLimit +
1;
240 if ( $this->mOffset
== '' ) {
243 // If there's an offset, we may or may not be at the first entry.
244 // The only way to tell is to run the query in the opposite
245 // direction see if we get a row.
246 $oldIncludeOffset = $this->mIncludeOffset
;
247 $this->mIncludeOffset
= !$this->mIncludeOffset
;
248 $oppositeOrder = self
::oppositeOrder( $order );
249 $isFirst = !$this->reallyDoQuery( $this->mOffset
, 1, $oppositeOrder )->numRows();
250 $this->mIncludeOffset
= $oldIncludeOffset;
253 $this->mResult
= $this->reallyDoQuery(
259 $this->extractResultInfo( $isFirst, $queryLimit, $this->mResult
);
260 $this->mQueryDone
= true;
262 $this->preprocessResults( $this->mResult
);
263 $this->mResult
->rewind(); // Paranoia
267 * @param bool $order One of the IndexPager::QUERY_* class constants
268 * @return bool The opposite query order as an IndexPager::QUERY_ constant
270 final protected static function oppositeOrder( $order ) {
271 return ( $order === self
::QUERY_ASCENDING
)
272 ? self
::QUERY_DESCENDING
273 : self
::QUERY_ASCENDING
;
277 * @return IResultWrapper The result wrapper.
279 function getResult() {
280 return $this->mResult
;
284 * Set the offset from an other source than the request
286 * @param int|string $offset
288 function setOffset( $offset ) {
289 $this->mOffset
= $offset;
293 * Set the limit from an other source than the request
295 * Verifies limit is between 1 and 5000
297 * @param int|string $limit
299 function setLimit( $limit ) {
300 $limit = (int)$limit;
301 // WebRequest::getLimitOffset() puts a cap of 5000, so do same here.
302 if ( $limit > 5000 ) {
306 $this->mLimit
= $limit;
311 * Get the current limit
315 function getLimit() {
316 return $this->mLimit
;
320 * Set whether a row matching exactly the offset should be also included
321 * in the result or not. By default this is not the case, but when the
322 * offset is user-supplied this might be wanted.
324 * @param bool $include
326 public function setIncludeOffset( $include ) {
327 $this->mIncludeOffset
= $include;
331 * Extract some useful data from the result object for use by
332 * the navigation bar, put it into $this
334 * @param bool $isFirst False if there are rows before those fetched (i.e.
335 * if a "previous" link would make sense)
336 * @param int $limit Exact query limit
337 * @param IResultWrapper $res
339 function extractResultInfo( $isFirst, $limit, IResultWrapper
$res ) {
340 $numRows = $res->numRows();
342 # Remove any table prefix from index field
343 $parts = explode( '.', $this->mIndexField
);
344 $indexColumn = end( $parts );
346 $row = $res->fetchRow();
347 $firstIndex = $row[$indexColumn];
349 # Discard the extra result row if there is one
350 if ( $numRows > $this->mLimit
&& $numRows > 1 ) {
351 $res->seek( $numRows - 1 );
352 $this->mPastTheEndRow
= $res->fetchObject();
353 $this->mPastTheEndIndex
= $this->mPastTheEndRow
->$indexColumn;
354 $res->seek( $numRows - 2 );
355 $row = $res->fetchRow();
356 $lastIndex = $row[$indexColumn];
358 $this->mPastTheEndRow
= null;
359 # Setting indexes to an empty string means that they will be
360 # omitted if they would otherwise appear in URLs. It just so
361 # happens that this is the right thing to do in the standard
362 # UI, in all the relevant cases.
363 $this->mPastTheEndIndex
= '';
364 $res->seek( $numRows - 1 );
365 $row = $res->fetchRow();
366 $lastIndex = $row[$indexColumn];
371 $this->mPastTheEndRow
= null;
372 $this->mPastTheEndIndex
= '';
375 if ( $this->mIsBackwards
) {
376 $this->mIsFirst
= ( $numRows < $limit );
377 $this->mIsLast
= $isFirst;
378 $this->mLastShown
= $firstIndex;
379 $this->mFirstShown
= $lastIndex;
381 $this->mIsFirst
= $isFirst;
382 $this->mIsLast
= ( $numRows < $limit );
383 $this->mLastShown
= $lastIndex;
384 $this->mFirstShown
= $firstIndex;
389 * Get some text to go in brackets in the "function name" part of the SQL comment
393 function getSqlComment() {
394 return static::class;
398 * Do a query with specified parameters, rather than using the object context
400 * @note For b/c, query direction is true for ascending and false for descending
402 * @param string $offset Index offset, inclusive
403 * @param int $limit Exact query limit
404 * @param bool $order IndexPager::QUERY_ASCENDING or IndexPager::QUERY_DESCENDING
405 * @return IResultWrapper
407 public function reallyDoQuery( $offset, $limit, $order ) {
408 list( $tables, $fields, $conds, $fname, $options, $join_conds ) =
409 $this->buildQueryInfo( $offset, $limit, $order );
411 return $this->mDb
->select( $tables, $fields, $conds, $fname, $options, $join_conds );
415 * Build variables to use by the database wrapper.
417 * @note For b/c, query direction is true for ascending and false for descending
419 * @param string $offset Index offset, inclusive
420 * @param int $limit Exact query limit
421 * @param bool $order IndexPager::QUERY_ASCENDING or IndexPager::QUERY_DESCENDING
424 protected function buildQueryInfo( $offset, $limit, $order ) {
425 $fname = __METHOD__
. ' (' . $this->getSqlComment() . ')';
426 $info = $this->getQueryInfo();
427 $tables = $info['tables'];
428 $fields = $info['fields'];
429 $conds = $info['conds'] ??
[];
430 $options = $info['options'] ??
[];
431 $join_conds = $info['join_conds'] ??
[];
432 $sortColumns = array_merge( [ $this->mIndexField
], $this->mExtraSortFields
);
433 if ( $order === self
::QUERY_ASCENDING
) {
434 $options['ORDER BY'] = $sortColumns;
435 $operator = $this->mIncludeOffset ?
'>=' : '>';
438 foreach ( $sortColumns as $col ) {
439 $orderBy[] = $col . ' DESC';
441 $options['ORDER BY'] = $orderBy;
442 $operator = $this->mIncludeOffset ?
'<=' : '<';
444 if ( $offset != '' ) {
445 $conds[] = $this->mIndexField
. $operator . $this->mDb
->addQuotes( $offset );
447 $options['LIMIT'] = intval( $limit );
448 return [ $tables, $fields, $conds, $fname, $options, $join_conds ];
452 * Pre-process results; useful for performing batch existence checks, etc.
454 * @param IResultWrapper $result
456 protected function preprocessResults( $result ) {
460 * Get the formatted result list. Calls getStartBody(), formatRow() and
461 * getEndBody(), concatenates the results and returns them.
465 public function getBody() {
466 if ( !$this->mQueryDone
) {
470 if ( $this->mResult
->numRows() ) {
471 # Do any special query batches before display
472 $this->doBatchLookups();
475 # Don't use any extra rows returned by the query
476 $numRows = min( $this->mResult
->numRows(), $this->mLimit
);
478 $s = $this->getStartBody();
480 if ( $this->mIsBackwards
) {
481 for ( $i = $numRows - 1; $i >= 0; $i-- ) {
482 $this->mResult
->seek( $i );
483 $row = $this->mResult
->fetchObject();
484 $s .= $this->formatRow( $row );
487 $this->mResult
->seek( 0 );
488 for ( $i = 0; $i < $numRows; $i++
) {
489 $row = $this->mResult
->fetchObject();
490 $s .= $this->formatRow( $row );
494 $s .= $this->getEmptyBody();
496 $s .= $this->getEndBody();
503 * @param string $text Text displayed on the link
504 * @param array|null $query Associative array of parameter to be in the query string
505 * @param string|null $type Link type used to create additional attributes, like "rel", "class" or
506 * "title". Valid values (non-exhaustive list): 'first', 'last', 'prev', 'next', 'asc', 'desc'.
507 * @return string HTML fragment
509 function makeLink( $text, array $query = null, $type = null ) {
510 if ( $query === null ) {
515 if ( in_array( $type, [ 'prev', 'next' ] ) ) {
516 $attrs['rel'] = $type;
519 if ( in_array( $type, [ 'asc', 'desc' ] ) ) {
520 $attrs['title'] = $this->msg( $type == 'asc' ?
'sort-ascending' : 'sort-descending' )->text();
524 $attrs['class'] = "mw-{$type}link";
527 return Linker
::linkKnown(
531 $query +
$this->getDefaultQuery()
536 * Called from getBody(), before getStartBody() is called and
537 * after doQuery() was called. This will be called only if there
538 * are rows in the result set.
542 protected function doBatchLookups() {
546 * Hook into getBody(), allows text to be inserted at the start. This
547 * will be called even if there are no rows in the result set.
551 protected function getStartBody() {
556 * Hook into getBody() for the end of the list
560 protected function getEndBody() {
565 * Hook into getBody(), for the bit between the start and the
566 * end when there are no rows
570 protected function getEmptyBody() {
575 * Get an array of query parameters that should be put into self-links.
576 * By default, all parameters passed in the URL are used, except for a
579 * @return array Associative array
581 function getDefaultQuery() {
582 if ( !isset( $this->mDefaultQuery
) ) {
583 $this->mDefaultQuery
= $this->getRequest()->getQueryValues();
584 unset( $this->mDefaultQuery
['title'] );
585 unset( $this->mDefaultQuery
['dir'] );
586 unset( $this->mDefaultQuery
['offset'] );
587 unset( $this->mDefaultQuery
['limit'] );
588 unset( $this->mDefaultQuery
['order'] );
589 unset( $this->mDefaultQuery
['month'] );
590 unset( $this->mDefaultQuery
['year'] );
592 return $this->mDefaultQuery
;
596 * Get the number of rows in the result set
600 function getNumRows() {
601 if ( !$this->mQueryDone
) {
604 return $this->mResult
->numRows();
608 * Get a URL query array for the prev, next, first and last links.
612 function getPagingQueries() {
613 if ( !$this->mQueryDone
) {
617 # Don't announce the limit everywhere if it's the default
618 $urlLimit = $this->mLimit
== $this->mDefaultLimit ?
null : $this->mLimit
;
620 if ( $this->mIsFirst
) {
626 'offset' => $this->mFirstShown
,
629 $first = [ 'limit' => $urlLimit ];
631 if ( $this->mIsLast
) {
635 $next = [ 'offset' => $this->mLastShown
, 'limit' => $urlLimit ];
636 $last = [ 'dir' => 'prev', 'limit' => $urlLimit ];
647 * Returns whether to show the "navigation bar"
651 function isNavigationBarShown() {
652 if ( !$this->mQueryDone
) {
655 // Hide navigation by default if there is nothing to page
656 return !( $this->mIsFirst
&& $this->mIsLast
);
660 * Get paging links. If a link is disabled, the item from $disabledTexts
661 * will be used. If there is no such item, the unlinked text from
662 * $linkTexts will be used. Both $linkTexts and $disabledTexts are arrays
665 * @param array $linkTexts
666 * @param array $disabledTexts
669 function getPagingLinks( $linkTexts, $disabledTexts = [] ) {
670 $queries = $this->getPagingQueries();
673 foreach ( $queries as $type => $query ) {
674 if ( $query !== false ) {
675 $links[$type] = $this->makeLink(
680 } elseif ( isset( $disabledTexts[$type] ) ) {
681 $links[$type] = $disabledTexts[$type];
683 $links[$type] = $linkTexts[$type];
690 function getLimitLinks() {
692 if ( $this->mIsBackwards
) {
693 $offset = $this->mPastTheEndIndex
;
695 $offset = $this->mOffset
;
697 foreach ( $this->mLimitsShown
as $limit ) {
698 $links[] = $this->makeLink(
699 $this->getLanguage()->formatNum( $limit ),
700 [ 'offset' => $offset, 'limit' => $limit ],
708 * Abstract formatting function. This should return an HTML string
709 * representing the result row $row. Rows will be concatenated and
710 * returned by getBody()
712 * @param array|stdClass $row Database row
715 abstract function formatRow( $row );
718 * This function should be overridden to provide all parameters
719 * needed for the main paged query. It returns an associative
720 * array with the following elements:
721 * tables => Table(s) for passing to Database::select()
722 * fields => Field(s) for passing to Database::select(), may be *
723 * conds => WHERE conditions
724 * options => option array
725 * join_conds => JOIN conditions
729 abstract function getQueryInfo();
732 * This function should be overridden to return the name of the index fi-
733 * eld. If the pager supports multiple orders, it may return an array of
734 * 'querykey' => 'indexfield' pairs, so that a request with &count=querykey
735 * will use indexfield to sort. In this case, the first returned key is
738 * Needless to say, it's really not a good idea to use a non-unique index
739 * for this! That won't page right.
741 * @return string|string[]
743 abstract function getIndexField();
746 * This function should be overridden to return the names of secondary columns
747 * to order by in addition to the column in getIndexField(). These fields will
748 * not be used in the pager offset or in any links for users.
750 * If getIndexField() returns an array of 'querykey' => 'indexfield' pairs then
751 * this must return a corresponding array of 'querykey' => [ fields... ] pairs
752 * in order for a request with &count=querykey to use [ fields... ] to sort.
754 * This is useful for pagers that GROUP BY a unique column (say page_id)
755 * and ORDER BY another (say page_len). Using GROUP BY and ORDER BY both on
756 * page_len,page_id avoids temp tables (given a page_len index). This would
757 * also work if page_id was non-unique but we had a page_len,page_id index.
759 * @return string[]|array[]
761 protected function getExtraSortFields() {
766 * Return the default sorting direction: DIR_ASCENDING or DIR_DESCENDING.
767 * You can also have an associative array of ordertype => dir,
768 * if multiple order types are supported. In this case getIndexField()
769 * must return an array, and the keys of that must exactly match the keys
772 * For backward compatibility, this method's return value will be ignored
773 * if $this->mDefaultDirection is already set when the constructor is
774 * called, for instance if it's statically initialized. In that case the
775 * value of that variable (which must be a boolean) will be used.
777 * Note that despite its name, this does not return the value of the
778 * $this->mDefaultDirection member variable. That's the default for this
779 * particular instantiation, which is a single value. This is the set of
780 * all defaults for the class.
784 protected function getDefaultDirections() {
785 return self
::DIR_ASCENDING
;