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 MediaWiki\Linker\LinkRenderer
;
25 use MediaWiki\MediaWikiServices
;
26 use MediaWiki\Navigation\PrevNextNavigationRenderer
;
27 use Wikimedia\Rdbms\IDatabase
;
28 use Wikimedia\Rdbms\IResultWrapper
;
31 * IndexPager is an efficient pager which uses a (roughly unique) index in the
32 * data set to implement paging, rather than a "LIMIT offset,limit" clause.
33 * In MySQL, such a limit/offset clause requires counting through the
34 * specified number of offset rows to find the desired data, which can be
35 * expensive for large offsets.
37 * ReverseChronologicalPager is a child class of the abstract IndexPager, and
38 * contains some formatting and display code which is specific to the use of
39 * timestamps as indexes. Here is a synopsis of its operation:
41 * * The query is specified by the offset, limit and direction (dir)
42 * parameters, in addition to any subclass-specific parameters.
43 * * The offset is the non-inclusive start of the DB query. A row with an
44 * index value equal to the offset will never be shown.
45 * * The query may either be done backwards, where the rows are returned by
46 * the database in the opposite order to which they are displayed to the
47 * user, or forwards. This is specified by the "dir" parameter, dir=prev
48 * means backwards, anything else means forwards. The offset value
49 * specifies the start of the database result set, which may be either
50 * the start or end of the displayed data set. This allows "previous"
51 * links to be implemented without knowledge of the index value at the
52 * start of the previous page.
53 * * An additional row beyond the user-specified limit is always requested.
54 * This allows us to tell whether we should display a "next" link in the
55 * case of forwards mode, or a "previous" link in the case of backwards
56 * mode. Determining whether to display the other link (the one for the
57 * page before the start of the database result set) can be done
58 * heuristically by examining the offset.
60 * * An empty offset indicates that the offset condition should be omitted
61 * from the query. This naturally produces either the first page or the
62 * last page depending on the dir parameter.
64 * Subclassing the pager to implement concrete functionality should be fairly
65 * simple, please see the examples in HistoryAction.php and
66 * SpecialBlockList.php. You just need to override formatRow(),
67 * getQueryInfo() and getIndexField(). Don't forget to call the parent
68 * constructor if you override it.
72 abstract class IndexPager
extends ContextSource
implements Pager
{
73 /** Backwards-compatible constant for $mDefaultDirection field (do not change) */
74 const DIR_ASCENDING
= false;
75 /** Backwards-compatible constant for $mDefaultDirection field (do not change) */
76 const DIR_DESCENDING
= true;
78 /** Backwards-compatible constant for reallyDoQuery() (do not change) */
79 const QUERY_ASCENDING
= true;
80 /** Backwards-compatible constant for reallyDoQuery() (do not change) */
81 const QUERY_DESCENDING
= false;
83 /** @var WebRequest */
85 /** @var int[] List of default entry limit options to be presented to clients */
86 public $mLimitsShown = [ 20, 50, 100, 250, 500 ];
87 /** @var int The default entry limit choosen for clients */
88 public $mDefaultLimit = 50;
89 /** @var mixed The starting point to enumerate entries */
91 /** @var int The maximum number of entries to show */
93 /** @var bool Whether the listing query completed */
94 public $mQueryDone = false;
97 /** @var stdClass|bool|null Extra row fetched at the end to see if the end was reached */
98 public $mPastTheEndRow;
101 * The index to actually be used for ordering. This is a single column,
102 * for one ordering, even if multiple orderings are supported.
105 protected $mIndexField;
107 * An array of secondary columns to order by. These fields are not part of the offset.
108 * This is a column list for one ordering, even if multiple orderings are supported.
111 protected $mExtraSortFields;
112 /** For pages that support multiple types of ordering, which one to use.
115 protected $mOrderType;
117 * $mDefaultDirection gives the direction to use when sorting results:
118 * DIR_ASCENDING or DIR_DESCENDING. If $mIsBackwards is set, we start from
119 * the opposite end, but we still sort the page itself according to
120 * $mDefaultDirection. For example, if $mDefaultDirection is DIR_ASCENDING
121 * but we're going backwards, we'll display the last page of results, but
122 * the last result will be at the bottom, not the top.
124 * Like $mIndexField, $mDefaultDirection will be a single value even if the
125 * class supports multiple default directions for different order types.
128 public $mDefaultDirection;
130 public $mIsBackwards;
132 /** @var bool True if the current result set is the first one */
138 protected $mLastShown;
140 protected $mFirstShown;
142 protected $mPastTheEndIndex;
144 protected $mDefaultQuery;
146 protected $mNavigationBar;
149 * Whether to include the offset in the query
152 protected $mIncludeOffset = false;
155 * Result object for the query. Warning: seek before use.
157 * @var IResultWrapper
161 /** @var LinkRenderer */
162 private $linkRenderer;
164 public function __construct( IContextSource
$context = null, LinkRenderer
$linkRenderer = null ) {
166 $this->setContext( $context );
169 $this->mRequest
= $this->getRequest();
171 # NB: the offset is quoted, not validated. It is treated as an
172 # arbitrary string to support the widest variety of index types. Be
173 # careful outputting it into HTML!
174 $this->mOffset
= $this->mRequest
->getText( 'offset' );
176 # Use consistent behavior for the limit options
177 $this->mDefaultLimit
= $this->getUser()->getIntOption( 'rclimit' );
178 if ( !$this->mLimit
) {
179 // Don't override if a subclass calls $this->setLimit() in its constructor.
180 list( $this->mLimit
, /* $offset */ ) = $this->mRequest
->getLimitOffset();
183 $this->mIsBackwards
= ( $this->mRequest
->getVal( 'dir' ) == 'prev' );
184 # Let the subclass set the DB here; otherwise use a replica DB for the current wiki
185 $this->mDb
= $this->mDb ?
: wfGetDB( DB_REPLICA
);
187 $index = $this->getIndexField(); // column to sort on
188 $extraSort = $this->getExtraSortFields(); // extra columns to sort on for query planning
189 $order = $this->mRequest
->getVal( 'order' );
190 if ( is_array( $index ) && isset( $index[$order] ) ) {
191 $this->mOrderType
= $order;
192 $this->mIndexField
= $index[$order];
193 $this->mExtraSortFields
= isset( $extraSort[$order] )
194 ?
(array)$extraSort[$order]
196 } elseif ( is_array( $index ) ) {
197 # First element is the default
198 $this->mIndexField
= reset( $index );
199 $this->mOrderType
= key( $index );
200 $this->mExtraSortFields
= isset( $extraSort[$this->mOrderType
] )
201 ?
(array)$extraSort[$this->mOrderType
]
204 # $index is not an array
205 $this->mOrderType
= null;
206 $this->mIndexField
= $index;
207 $this->mExtraSortFields
= (array)$extraSort;
210 if ( !isset( $this->mDefaultDirection
) ) {
211 $dir = $this->getDefaultDirections();
212 $this->mDefaultDirection
= is_array( $dir )
213 ?
$dir[$this->mOrderType
]
216 $this->linkRenderer
= $linkRenderer;
220 * Get the Database object in use
224 public function getDatabase() {
229 * Do the query, using information from the object context. This function
230 * has been kept minimal to make it overridable if necessary, to allow for
231 * result sets formed from multiple DB queries.
233 public function doQuery() {
234 # Use the child class name for profiling
235 $fname = __METHOD__
. ' (' . static::class . ')';
236 /** @noinspection PhpUnusedLocalVariableInspection */
237 $section = Profiler
::instance()->scopedProfileIn( $fname );
239 $defaultOrder = ( $this->mDefaultDirection
=== self
::DIR_ASCENDING
)
240 ? self
::QUERY_ASCENDING
241 : self
::QUERY_DESCENDING
;
242 $order = $this->mIsBackwards ? self
::oppositeOrder( $defaultOrder ) : $defaultOrder;
244 # Plus an extra row so that we can tell the "next" link should be shown
245 $queryLimit = $this->mLimit +
1;
247 if ( $this->mOffset
== '' ) {
250 // If there's an offset, we may or may not be at the first entry.
251 // The only way to tell is to run the query in the opposite
252 // direction see if we get a row.
253 $oldIncludeOffset = $this->mIncludeOffset
;
254 $this->mIncludeOffset
= !$this->mIncludeOffset
;
255 $oppositeOrder = self
::oppositeOrder( $order );
256 $isFirst = !$this->reallyDoQuery( $this->mOffset
, 1, $oppositeOrder )->numRows();
257 $this->mIncludeOffset
= $oldIncludeOffset;
260 $this->mResult
= $this->reallyDoQuery(
266 $this->extractResultInfo( $isFirst, $queryLimit, $this->mResult
);
267 $this->mQueryDone
= true;
269 $this->preprocessResults( $this->mResult
);
270 $this->mResult
->rewind(); // Paranoia
274 * @param bool $order One of the IndexPager::QUERY_* class constants
275 * @return bool The opposite query order as an IndexPager::QUERY_ constant
277 final protected static function oppositeOrder( $order ) {
278 return ( $order === self
::QUERY_ASCENDING
)
279 ? self
::QUERY_DESCENDING
280 : self
::QUERY_ASCENDING
;
284 * @return IResultWrapper The result wrapper.
286 function getResult() {
287 return $this->mResult
;
291 * Set the offset from an other source than the request
293 * @param int|string $offset
295 function setOffset( $offset ) {
296 $this->mOffset
= $offset;
300 * Set the limit from an other source than the request
302 * Verifies limit is between 1 and 5000
304 * @param int|string $limit
306 function setLimit( $limit ) {
307 $limit = (int)$limit;
308 // WebRequest::getLimitOffset() puts a cap of 5000, so do same here.
309 if ( $limit > 5000 ) {
313 $this->mLimit
= $limit;
318 * Get the current limit
322 function getLimit() {
323 return $this->mLimit
;
327 * Set whether a row matching exactly the offset should be also included
328 * in the result or not. By default this is not the case, but when the
329 * offset is user-supplied this might be wanted.
331 * @param bool $include
333 public function setIncludeOffset( $include ) {
334 $this->mIncludeOffset
= $include;
338 * Extract some useful data from the result object for use by
339 * the navigation bar, put it into $this
341 * @param bool $isFirst False if there are rows before those fetched (i.e.
342 * if a "previous" link would make sense)
343 * @param int $limit Exact query limit
344 * @param IResultWrapper $res
346 function extractResultInfo( $isFirst, $limit, IResultWrapper
$res ) {
347 $numRows = $res->numRows();
349 # Remove any table prefix from index field
350 $parts = explode( '.', $this->mIndexField
);
351 $indexColumn = end( $parts );
353 $row = $res->fetchRow();
354 $firstIndex = $row[$indexColumn];
356 # Discard the extra result row if there is one
357 if ( $numRows > $this->mLimit
&& $numRows > 1 ) {
358 $res->seek( $numRows - 1 );
359 $this->mPastTheEndRow
= $res->fetchObject();
360 $this->mPastTheEndIndex
= $this->mPastTheEndRow
->$indexColumn;
361 $res->seek( $numRows - 2 );
362 $row = $res->fetchRow();
363 $lastIndex = $row[$indexColumn];
365 $this->mPastTheEndRow
= null;
366 # Setting indexes to an empty string means that they will be
367 # omitted if they would otherwise appear in URLs. It just so
368 # happens that this is the right thing to do in the standard
369 # UI, in all the relevant cases.
370 $this->mPastTheEndIndex
= '';
371 $res->seek( $numRows - 1 );
372 $row = $res->fetchRow();
373 $lastIndex = $row[$indexColumn];
378 $this->mPastTheEndRow
= null;
379 $this->mPastTheEndIndex
= '';
382 if ( $this->mIsBackwards
) {
383 $this->mIsFirst
= ( $numRows < $limit );
384 $this->mIsLast
= $isFirst;
385 $this->mLastShown
= $firstIndex;
386 $this->mFirstShown
= $lastIndex;
388 $this->mIsFirst
= $isFirst;
389 $this->mIsLast
= ( $numRows < $limit );
390 $this->mLastShown
= $lastIndex;
391 $this->mFirstShown
= $firstIndex;
396 * Get some text to go in brackets in the "function name" part of the SQL comment
400 function getSqlComment() {
401 return static::class;
405 * Do a query with specified parameters, rather than using the object context
407 * @note For b/c, query direction is true for ascending and false for descending
409 * @param string $offset Index offset, inclusive
410 * @param int $limit Exact query limit
411 * @param bool $order IndexPager::QUERY_ASCENDING or IndexPager::QUERY_DESCENDING
412 * @return IResultWrapper
414 public function reallyDoQuery( $offset, $limit, $order ) {
415 list( $tables, $fields, $conds, $fname, $options, $join_conds ) =
416 $this->buildQueryInfo( $offset, $limit, $order );
418 return $this->mDb
->select( $tables, $fields, $conds, $fname, $options, $join_conds );
422 * Build variables to use by the database wrapper.
424 * @note For b/c, query direction is true for ascending and false for descending
426 * @param string $offset Index offset, inclusive
427 * @param int $limit Exact query limit
428 * @param bool $order IndexPager::QUERY_ASCENDING or IndexPager::QUERY_DESCENDING
431 protected function buildQueryInfo( $offset, $limit, $order ) {
432 $fname = __METHOD__
. ' (' . $this->getSqlComment() . ')';
433 $info = $this->getQueryInfo();
434 $tables = $info['tables'];
435 $fields = $info['fields'];
436 $conds = $info['conds'] ??
[];
437 $options = $info['options'] ??
[];
438 $join_conds = $info['join_conds'] ??
[];
439 $sortColumns = array_merge( [ $this->mIndexField
], $this->mExtraSortFields
);
440 if ( $order === self
::QUERY_ASCENDING
) {
441 $options['ORDER BY'] = $sortColumns;
442 $operator = $this->mIncludeOffset ?
'>=' : '>';
445 foreach ( $sortColumns as $col ) {
446 $orderBy[] = $col . ' DESC';
448 $options['ORDER BY'] = $orderBy;
449 $operator = $this->mIncludeOffset ?
'<=' : '<';
451 if ( $offset != '' ) {
452 $conds[] = $this->mIndexField
. $operator . $this->mDb
->addQuotes( $offset );
454 $options['LIMIT'] = intval( $limit );
455 return [ $tables, $fields, $conds, $fname, $options, $join_conds ];
459 * Pre-process results; useful for performing batch existence checks, etc.
461 * @param IResultWrapper $result
463 protected function preprocessResults( $result ) {
467 * Get the formatted result list. Calls getStartBody(), formatRow() and
468 * getEndBody(), concatenates the results and returns them.
472 public function getBody() {
473 if ( !$this->mQueryDone
) {
477 if ( $this->mResult
->numRows() ) {
478 # Do any special query batches before display
479 $this->doBatchLookups();
482 # Don't use any extra rows returned by the query
483 $numRows = min( $this->mResult
->numRows(), $this->mLimit
);
485 $s = $this->getStartBody();
487 if ( $this->mIsBackwards
) {
488 for ( $i = $numRows - 1; $i >= 0; $i-- ) {
489 $this->mResult
->seek( $i );
490 $row = $this->mResult
->fetchObject();
491 $s .= $this->formatRow( $row );
494 $this->mResult
->seek( 0 );
495 for ( $i = 0; $i < $numRows; $i++
) {
496 $row = $this->mResult
->fetchObject();
497 $s .= $this->formatRow( $row );
501 $s .= $this->getEmptyBody();
503 $s .= $this->getEndBody();
510 * @param string $text Text displayed on the link
511 * @param array|null $query Associative array of parameter to be in the query string
512 * @param string|null $type Link type used to create additional attributes, like "rel", "class" or
513 * "title". Valid values (non-exhaustive list): 'first', 'last', 'prev', 'next', 'asc', 'desc'.
514 * @return string HTML fragment
516 function makeLink( $text, array $query = null, $type = null ) {
517 if ( $query === null ) {
522 if ( in_array( $type, [ 'prev', 'next' ] ) ) {
523 $attrs['rel'] = $type;
526 if ( in_array( $type, [ 'asc', 'desc' ] ) ) {
527 $attrs['title'] = $this->msg( $type == 'asc' ?
'sort-ascending' : 'sort-descending' )->text();
531 $attrs['class'] = "mw-{$type}link";
534 return $this->getLinkRenderer()->makeKnownLink(
536 new HtmlArmor( $text ),
538 $query +
$this->getDefaultQuery()
543 * Called from getBody(), before getStartBody() is called and
544 * after doQuery() was called. This will be called only if there
545 * are rows in the result set.
549 protected function doBatchLookups() {
553 * Hook into getBody(), allows text to be inserted at the start. This
554 * will be called even if there are no rows in the result set.
558 protected function getStartBody() {
563 * Hook into getBody() for the end of the list
567 protected function getEndBody() {
572 * Hook into getBody(), for the bit between the start and the
573 * end when there are no rows
577 protected function getEmptyBody() {
582 * Get an array of query parameters that should be put into self-links.
583 * By default, all parameters passed in the URL are used, except for a
586 * @return array Associative array
588 function getDefaultQuery() {
589 if ( !isset( $this->mDefaultQuery
) ) {
590 $this->mDefaultQuery
= $this->getRequest()->getQueryValues();
591 unset( $this->mDefaultQuery
['title'] );
592 unset( $this->mDefaultQuery
['dir'] );
593 unset( $this->mDefaultQuery
['offset'] );
594 unset( $this->mDefaultQuery
['limit'] );
595 unset( $this->mDefaultQuery
['order'] );
596 unset( $this->mDefaultQuery
['month'] );
597 unset( $this->mDefaultQuery
['year'] );
599 return $this->mDefaultQuery
;
603 * Get the number of rows in the result set
607 function getNumRows() {
608 if ( !$this->mQueryDone
) {
611 return $this->mResult
->numRows();
615 * Get a URL query array for the prev, next, first and last links.
619 function getPagingQueries() {
620 if ( !$this->mQueryDone
) {
624 # Don't announce the limit everywhere if it's the default
625 $urlLimit = $this->mLimit
== $this->mDefaultLimit ?
null : $this->mLimit
;
627 if ( $this->mIsFirst
) {
633 'offset' => $this->mFirstShown
,
636 $first = [ 'limit' => $urlLimit ];
638 if ( $this->mIsLast
) {
642 $next = [ 'offset' => $this->mLastShown
, 'limit' => $urlLimit ];
643 $last = [ 'dir' => 'prev', 'limit' => $urlLimit ];
654 * Returns whether to show the "navigation bar"
658 function isNavigationBarShown() {
659 if ( !$this->mQueryDone
) {
662 // Hide navigation by default if there is nothing to page
663 return !( $this->mIsFirst
&& $this->mIsLast
);
667 * Get paging links. If a link is disabled, the item from $disabledTexts
668 * will be used. If there is no such item, the unlinked text from
669 * $linkTexts will be used. Both $linkTexts and $disabledTexts are arrays
672 * @param array $linkTexts
673 * @param array $disabledTexts
676 function getPagingLinks( $linkTexts, $disabledTexts = [] ) {
677 $queries = $this->getPagingQueries();
680 foreach ( $queries as $type => $query ) {
681 if ( $query !== false ) {
682 $links[$type] = $this->makeLink(
687 } elseif ( isset( $disabledTexts[$type] ) ) {
688 $links[$type] = $disabledTexts[$type];
690 $links[$type] = $linkTexts[$type];
697 function getLimitLinks() {
699 if ( $this->mIsBackwards
) {
700 $offset = $this->mPastTheEndIndex
;
702 $offset = $this->mOffset
;
704 foreach ( $this->mLimitsShown
as $limit ) {
705 $links[] = $this->makeLink(
706 $this->getLanguage()->formatNum( $limit ),
707 [ 'offset' => $offset, 'limit' => $limit ],
715 * Abstract formatting function. This should return an HTML string
716 * representing the result row $row. Rows will be concatenated and
717 * returned by getBody()
719 * @param array|stdClass $row Database row
722 abstract function formatRow( $row );
725 * This function should be overridden to provide all parameters
726 * needed for the main paged query. It returns an associative
727 * array with the following elements:
728 * tables => Table(s) for passing to Database::select()
729 * fields => Field(s) for passing to Database::select(), may be *
730 * conds => WHERE conditions
731 * options => option array
732 * join_conds => JOIN conditions
736 abstract function getQueryInfo();
739 * This function should be overridden to return the name of the index fi-
740 * eld. If the pager supports multiple orders, it may return an array of
741 * 'querykey' => 'indexfield' pairs, so that a request with &count=querykey
742 * will use indexfield to sort. In this case, the first returned key is
745 * Needless to say, it's really not a good idea to use a non-unique index
746 * for this! That won't page right.
748 * @return string|string[]
750 abstract function getIndexField();
753 * This function should be overridden to return the names of secondary columns
754 * to order by in addition to the column in getIndexField(). These fields will
755 * not be used in the pager offset or in any links for users.
757 * If getIndexField() returns an array of 'querykey' => 'indexfield' pairs then
758 * this must return a corresponding array of 'querykey' => [ fields... ] pairs
759 * in order for a request with &count=querykey to use [ fields... ] to sort.
761 * This is useful for pagers that GROUP BY a unique column (say page_id)
762 * and ORDER BY another (say page_len). Using GROUP BY and ORDER BY both on
763 * page_len,page_id avoids temp tables (given a page_len index). This would
764 * also work if page_id was non-unique but we had a page_len,page_id index.
766 * @return string[]|array[]
768 protected function getExtraSortFields() {
773 * Return the default sorting direction: DIR_ASCENDING or DIR_DESCENDING.
774 * You can also have an associative array of ordertype => dir,
775 * if multiple order types are supported. In this case getIndexField()
776 * must return an array, and the keys of that must exactly match the keys
779 * For backward compatibility, this method's return value will be ignored
780 * if $this->mDefaultDirection is already set when the constructor is
781 * called, for instance if it's statically initialized. In that case the
782 * value of that variable (which must be a boolean) will be used.
784 * Note that despite its name, this does not return the value of the
785 * $this->mDefaultDirection member variable. That's the default for this
786 * particular instantiation, which is a single value. This is the set of
787 * all defaults for the class.
791 protected function getDefaultDirections() {
792 return self
::DIR_ASCENDING
;
796 * Generate (prev x| next x) (20|50|100...) type links for paging
798 * @param Title $title
801 * @param array $query Optional URL query parameter string
802 * @param bool $atend Optional param for specified if this is the last page
805 protected function buildPrevNextNavigation( Title
$title, $offset, $limit,
806 array $query = [], $atend = false
808 $prevNext = new PrevNextNavigationRenderer( $this );
810 return $prevNext->buildPrevNextNavigation( $title, $offset, $limit, $query, $atend );
813 protected function getLinkRenderer() {
814 if ( $this->linkRenderer
=== null ) {
815 $this->linkRenderer
= MediaWikiServices
::getInstance()->getLinkRenderer();
817 return $this->linkRenderer
;