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
;
26 use MediaWiki\Linker\LinkTarget
;
27 use MediaWiki\Navigation\PrevNextNavigationRenderer
;
30 * IndexPager is an efficient pager which uses a (roughly unique) index in the
31 * data set to implement paging, rather than a "LIMIT offset,limit" clause.
32 * In MySQL, such a limit/offset clause requires counting through the
33 * specified number of offset rows to find the desired data, which can be
34 * expensive for large offsets.
36 * ReverseChronologicalPager is a child class of the abstract IndexPager, and
37 * contains some formatting and display code which is specific to the use of
38 * timestamps as indexes. Here is a synopsis of its operation:
40 * * The query is specified by the offset, limit and direction (dir)
41 * parameters, in addition to any subclass-specific parameters.
42 * * The offset is the non-inclusive start of the DB query. A row with an
43 * index value equal to the offset will never be shown.
44 * * The query may either be done backwards, where the rows are returned by
45 * the database in the opposite order to which they are displayed to the
46 * user, or forwards. This is specified by the "dir" parameter, dir=prev
47 * means backwards, anything else means forwards. The offset value
48 * specifies the start of the database result set, which may be either
49 * the start or end of the displayed data set. This allows "previous"
50 * links to be implemented without knowledge of the index value at the
51 * start of the previous page.
52 * * An additional row beyond the user-specified limit is always requested.
53 * This allows us to tell whether we should display a "next" link in the
54 * case of forwards mode, or a "previous" link in the case of backwards
55 * mode. Determining whether to display the other link (the one for the
56 * page before the start of the database result set) can be done
57 * heuristically by examining the offset.
59 * * An empty offset indicates that the offset condition should be omitted
60 * from the query. This naturally produces either the first page or the
61 * last page depending on the dir parameter.
63 * Subclassing the pager to implement concrete functionality should be fairly
64 * simple, please see the examples in HistoryAction.php and
65 * SpecialBlockList.php. You just need to override formatRow(),
66 * getQueryInfo() and getIndexField(). Don't forget to call the parent
67 * constructor if you override it.
71 abstract class IndexPager
extends ContextSource
implements Pager
{
72 /** Backwards-compatible constant for $mDefaultDirection field (do not change) */
73 const DIR_ASCENDING
= false;
74 /** Backwards-compatible constant for $mDefaultDirection field (do not change) */
75 const DIR_DESCENDING
= true;
77 /** Backwards-compatible constant for reallyDoQuery() (do not change) */
78 const QUERY_ASCENDING
= true;
79 /** Backwards-compatible constant for reallyDoQuery() (do not change) */
80 const QUERY_DESCENDING
= false;
82 /** @var WebRequest */
84 /** @var int[] List of default entry limit options to be presented to clients */
85 public $mLimitsShown = [ 20, 50, 100, 250, 500 ];
86 /** @var int The default entry limit choosen for clients */
87 public $mDefaultLimit = 50;
88 /** @var mixed The starting point to enumerate entries */
90 /** @var int The maximum number of entries to show */
92 /** @var bool Whether the listing query completed */
93 public $mQueryDone = false;
96 /** @var stdClass|bool|null Extra row fetched at the end to see if the end was reached */
97 public $mPastTheEndRow;
100 * The index to actually be used for ordering. This is a single column,
101 * for one ordering, even if multiple orderings are supported.
104 protected $mIndexField;
106 * An array of secondary columns to order by. These fields are not part of the offset.
107 * This is a column list for one ordering, even if multiple orderings are supported.
110 protected $mExtraSortFields;
111 /** For pages that support multiple types of ordering, which one to use.
114 protected $mOrderType;
116 * $mDefaultDirection gives the direction to use when sorting results:
117 * DIR_ASCENDING or DIR_DESCENDING. If $mIsBackwards is set, we start from
118 * the opposite end, but we still sort the page itself according to
119 * $mDefaultDirection. For example, if $mDefaultDirection is DIR_ASCENDING
120 * but we're going backwards, we'll display the last page of results, but
121 * the last result will be at the bottom, not the top.
123 * Like $mIndexField, $mDefaultDirection will be a single value even if the
124 * class supports multiple default directions for different order types.
127 public $mDefaultDirection;
129 public $mIsBackwards;
131 /** @var bool True if the current result set is the first one */
137 protected $mLastShown;
139 protected $mFirstShown;
141 protected $mPastTheEndIndex;
143 protected $mDefaultQuery;
145 protected $mNavigationBar;
148 * Whether to include the offset in the query
151 protected $mIncludeOffset = false;
154 * Result object for the query. Warning: seek before use.
156 * @var IResultWrapper
160 public function __construct( IContextSource
$context = null ) {
162 $this->setContext( $context );
165 $this->mRequest
= $this->getRequest();
167 # NB: the offset is quoted, not validated. It is treated as an
168 # arbitrary string to support the widest variety of index types. Be
169 # careful outputting it into HTML!
170 $this->mOffset
= $this->mRequest
->getText( 'offset' );
172 # Use consistent behavior for the limit options
173 $this->mDefaultLimit
= $this->getUser()->getIntOption( 'rclimit' );
174 if ( !$this->mLimit
) {
175 // Don't override if a subclass calls $this->setLimit() in its constructor.
176 list( $this->mLimit
, /* $offset */ ) = $this->mRequest
->getLimitOffset();
179 $this->mIsBackwards
= ( $this->mRequest
->getVal( 'dir' ) == 'prev' );
180 # Let the subclass set the DB here; otherwise use a replica DB for the current wiki
181 $this->mDb
= $this->mDb ?
: wfGetDB( DB_REPLICA
);
183 $index = $this->getIndexField(); // column to sort on
184 $extraSort = $this->getExtraSortFields(); // extra columns to sort on for query planning
185 $order = $this->mRequest
->getVal( 'order' );
186 if ( is_array( $index ) && isset( $index[$order] ) ) {
187 $this->mOrderType
= $order;
188 $this->mIndexField
= $index[$order];
189 $this->mExtraSortFields
= isset( $extraSort[$order] )
190 ?
(array)$extraSort[$order]
192 } elseif ( is_array( $index ) ) {
193 # First element is the default
194 $this->mIndexField
= reset( $index );
195 $this->mOrderType
= key( $index );
196 $this->mExtraSortFields
= isset( $extraSort[$this->mOrderType
] )
197 ?
(array)$extraSort[$this->mOrderType
]
200 # $index is not an array
201 $this->mOrderType
= null;
202 $this->mIndexField
= $index;
203 $this->mExtraSortFields
= (array)$extraSort;
206 if ( !isset( $this->mDefaultDirection
) ) {
207 $dir = $this->getDefaultDirections();
208 $this->mDefaultDirection
= is_array( $dir )
209 ?
$dir[$this->mOrderType
]
215 * Get the Database object in use
219 public function getDatabase() {
224 * Do the query, using information from the object context. This function
225 * has been kept minimal to make it overridable if necessary, to allow for
226 * result sets formed from multiple DB queries.
228 public function doQuery() {
229 # Use the child class name for profiling
230 $fname = __METHOD__
. ' (' . static::class . ')';
231 /** @noinspection PhpUnusedLocalVariableInspection */
232 $section = Profiler
::instance()->scopedProfileIn( $fname );
234 $defaultOrder = ( $this->mDefaultDirection
=== self
::DIR_ASCENDING
)
235 ? self
::QUERY_ASCENDING
236 : self
::QUERY_DESCENDING
;
237 $order = $this->mIsBackwards ? self
::oppositeOrder( $defaultOrder ) : $defaultOrder;
239 # Plus an extra row so that we can tell the "next" link should be shown
240 $queryLimit = $this->mLimit +
1;
242 if ( $this->mOffset
== '' ) {
245 // If there's an offset, we may or may not be at the first entry.
246 // The only way to tell is to run the query in the opposite
247 // direction see if we get a row.
248 $oldIncludeOffset = $this->mIncludeOffset
;
249 $this->mIncludeOffset
= !$this->mIncludeOffset
;
250 $oppositeOrder = self
::oppositeOrder( $order );
251 $isFirst = !$this->reallyDoQuery( $this->mOffset
, 1, $oppositeOrder )->numRows();
252 $this->mIncludeOffset
= $oldIncludeOffset;
255 $this->mResult
= $this->reallyDoQuery(
261 $this->extractResultInfo( $isFirst, $queryLimit, $this->mResult
);
262 $this->mQueryDone
= true;
264 $this->preprocessResults( $this->mResult
);
265 $this->mResult
->rewind(); // Paranoia
269 * @param bool $order One of the IndexPager::QUERY_* class constants
270 * @return bool The opposite query order as an IndexPager::QUERY_ constant
272 final protected static function oppositeOrder( $order ) {
273 return ( $order === self
::QUERY_ASCENDING
)
274 ? self
::QUERY_DESCENDING
275 : self
::QUERY_ASCENDING
;
279 * @return IResultWrapper The result wrapper.
281 function getResult() {
282 return $this->mResult
;
286 * Set the offset from an other source than the request
288 * @param int|string $offset
290 function setOffset( $offset ) {
291 $this->mOffset
= $offset;
295 * Set the limit from an other source than the request
297 * Verifies limit is between 1 and 5000
299 * @param int|string $limit
301 function setLimit( $limit ) {
302 $limit = (int)$limit;
303 // WebRequest::getLimitOffset() puts a cap of 5000, so do same here.
304 if ( $limit > 5000 ) {
308 $this->mLimit
= $limit;
313 * Get the current limit
317 function getLimit() {
318 return $this->mLimit
;
322 * Set whether a row matching exactly the offset should be also included
323 * in the result or not. By default this is not the case, but when the
324 * offset is user-supplied this might be wanted.
326 * @param bool $include
328 public function setIncludeOffset( $include ) {
329 $this->mIncludeOffset
= $include;
333 * Extract some useful data from the result object for use by
334 * the navigation bar, put it into $this
336 * @param bool $isFirst False if there are rows before those fetched (i.e.
337 * if a "previous" link would make sense)
338 * @param int $limit Exact query limit
339 * @param IResultWrapper $res
341 function extractResultInfo( $isFirst, $limit, IResultWrapper
$res ) {
342 $numRows = $res->numRows();
344 # Remove any table prefix from index field
345 $parts = explode( '.', $this->mIndexField
);
346 $indexColumn = end( $parts );
348 $row = $res->fetchRow();
349 $firstIndex = $row[$indexColumn];
351 # Discard the extra result row if there is one
352 if ( $numRows > $this->mLimit
&& $numRows > 1 ) {
353 $res->seek( $numRows - 1 );
354 $this->mPastTheEndRow
= $res->fetchObject();
355 $this->mPastTheEndIndex
= $this->mPastTheEndRow
->$indexColumn;
356 $res->seek( $numRows - 2 );
357 $row = $res->fetchRow();
358 $lastIndex = $row[$indexColumn];
360 $this->mPastTheEndRow
= null;
361 # Setting indexes to an empty string means that they will be
362 # omitted if they would otherwise appear in URLs. It just so
363 # happens that this is the right thing to do in the standard
364 # UI, in all the relevant cases.
365 $this->mPastTheEndIndex
= '';
366 $res->seek( $numRows - 1 );
367 $row = $res->fetchRow();
368 $lastIndex = $row[$indexColumn];
373 $this->mPastTheEndRow
= null;
374 $this->mPastTheEndIndex
= '';
377 if ( $this->mIsBackwards
) {
378 $this->mIsFirst
= ( $numRows < $limit );
379 $this->mIsLast
= $isFirst;
380 $this->mLastShown
= $firstIndex;
381 $this->mFirstShown
= $lastIndex;
383 $this->mIsFirst
= $isFirst;
384 $this->mIsLast
= ( $numRows < $limit );
385 $this->mLastShown
= $lastIndex;
386 $this->mFirstShown
= $firstIndex;
391 * Get some text to go in brackets in the "function name" part of the SQL comment
395 function getSqlComment() {
396 return static::class;
400 * Do a query with specified parameters, rather than using the object context
402 * @note For b/c, query direction is true for ascending and false for descending
404 * @param string $offset Index offset, inclusive
405 * @param int $limit Exact query limit
406 * @param bool $order IndexPager::QUERY_ASCENDING or IndexPager::QUERY_DESCENDING
407 * @return IResultWrapper
409 public function reallyDoQuery( $offset, $limit, $order ) {
410 list( $tables, $fields, $conds, $fname, $options, $join_conds ) =
411 $this->buildQueryInfo( $offset, $limit, $order );
413 return $this->mDb
->select( $tables, $fields, $conds, $fname, $options, $join_conds );
417 * Build variables to use by the database wrapper.
419 * @note For b/c, query direction is true for ascending and false for descending
421 * @param string $offset Index offset, inclusive
422 * @param int $limit Exact query limit
423 * @param bool $order IndexPager::QUERY_ASCENDING or IndexPager::QUERY_DESCENDING
426 protected function buildQueryInfo( $offset, $limit, $order ) {
427 $fname = __METHOD__
. ' (' . $this->getSqlComment() . ')';
428 $info = $this->getQueryInfo();
429 $tables = $info['tables'];
430 $fields = $info['fields'];
431 $conds = $info['conds'] ??
[];
432 $options = $info['options'] ??
[];
433 $join_conds = $info['join_conds'] ??
[];
434 $sortColumns = array_merge( [ $this->mIndexField
], $this->mExtraSortFields
);
435 if ( $order === self
::QUERY_ASCENDING
) {
436 $options['ORDER BY'] = $sortColumns;
437 $operator = $this->mIncludeOffset ?
'>=' : '>';
440 foreach ( $sortColumns as $col ) {
441 $orderBy[] = $col . ' DESC';
443 $options['ORDER BY'] = $orderBy;
444 $operator = $this->mIncludeOffset ?
'<=' : '<';
446 if ( $offset != '' ) {
447 $conds[] = $this->mIndexField
. $operator . $this->mDb
->addQuotes( $offset );
449 $options['LIMIT'] = intval( $limit );
450 return [ $tables, $fields, $conds, $fname, $options, $join_conds ];
454 * Pre-process results; useful for performing batch existence checks, etc.
456 * @param IResultWrapper $result
458 protected function preprocessResults( $result ) {
462 * Get the formatted result list. Calls getStartBody(), formatRow() and
463 * getEndBody(), concatenates the results and returns them.
467 public function getBody() {
468 if ( !$this->mQueryDone
) {
472 if ( $this->mResult
->numRows() ) {
473 # Do any special query batches before display
474 $this->doBatchLookups();
477 # Don't use any extra rows returned by the query
478 $numRows = min( $this->mResult
->numRows(), $this->mLimit
);
480 $s = $this->getStartBody();
482 if ( $this->mIsBackwards
) {
483 for ( $i = $numRows - 1; $i >= 0; $i-- ) {
484 $this->mResult
->seek( $i );
485 $row = $this->mResult
->fetchObject();
486 $s .= $this->formatRow( $row );
489 $this->mResult
->seek( 0 );
490 for ( $i = 0; $i < $numRows; $i++
) {
491 $row = $this->mResult
->fetchObject();
492 $s .= $this->formatRow( $row );
496 $s .= $this->getEmptyBody();
498 $s .= $this->getEndBody();
505 * @param string $text Text displayed on the link
506 * @param array|null $query Associative array of parameter to be in the query string
507 * @param string|null $type Link type used to create additional attributes, like "rel", "class" or
508 * "title". Valid values (non-exhaustive list): 'first', 'last', 'prev', 'next', 'asc', 'desc'.
509 * @return string HTML fragment
511 function makeLink( $text, array $query = null, $type = null ) {
512 if ( $query === null ) {
517 if ( in_array( $type, [ 'prev', 'next' ] ) ) {
518 $attrs['rel'] = $type;
521 if ( in_array( $type, [ 'asc', 'desc' ] ) ) {
522 $attrs['title'] = $this->msg( $type == 'asc' ?
'sort-ascending' : 'sort-descending' )->text();
526 $attrs['class'] = "mw-{$type}link";
529 return Linker
::linkKnown(
533 $query +
$this->getDefaultQuery()
538 * Called from getBody(), before getStartBody() is called and
539 * after doQuery() was called. This will be called only if there
540 * are rows in the result set.
544 protected function doBatchLookups() {
548 * Hook into getBody(), allows text to be inserted at the start. This
549 * will be called even if there are no rows in the result set.
553 protected function getStartBody() {
558 * Hook into getBody() for the end of the list
562 protected function getEndBody() {
567 * Hook into getBody(), for the bit between the start and the
568 * end when there are no rows
572 protected function getEmptyBody() {
577 * Get an array of query parameters that should be put into self-links.
578 * By default, all parameters passed in the URL are used, except for a
581 * @return array Associative array
583 function getDefaultQuery() {
584 if ( !isset( $this->mDefaultQuery
) ) {
585 $this->mDefaultQuery
= $this->getRequest()->getQueryValues();
586 unset( $this->mDefaultQuery
['title'] );
587 unset( $this->mDefaultQuery
['dir'] );
588 unset( $this->mDefaultQuery
['offset'] );
589 unset( $this->mDefaultQuery
['limit'] );
590 unset( $this->mDefaultQuery
['order'] );
591 unset( $this->mDefaultQuery
['month'] );
592 unset( $this->mDefaultQuery
['year'] );
594 return $this->mDefaultQuery
;
598 * Get the number of rows in the result set
602 function getNumRows() {
603 if ( !$this->mQueryDone
) {
606 return $this->mResult
->numRows();
610 * Get a URL query array for the prev, next, first and last links.
614 function getPagingQueries() {
615 if ( !$this->mQueryDone
) {
619 # Don't announce the limit everywhere if it's the default
620 $urlLimit = $this->mLimit
== $this->mDefaultLimit ?
null : $this->mLimit
;
622 if ( $this->mIsFirst
) {
628 'offset' => $this->mFirstShown
,
631 $first = [ 'limit' => $urlLimit ];
633 if ( $this->mIsLast
) {
637 $next = [ 'offset' => $this->mLastShown
, 'limit' => $urlLimit ];
638 $last = [ 'dir' => 'prev', 'limit' => $urlLimit ];
649 * Returns whether to show the "navigation bar"
653 function isNavigationBarShown() {
654 if ( !$this->mQueryDone
) {
657 // Hide navigation by default if there is nothing to page
658 return !( $this->mIsFirst
&& $this->mIsLast
);
662 * Get paging links. If a link is disabled, the item from $disabledTexts
663 * will be used. If there is no such item, the unlinked text from
664 * $linkTexts will be used. Both $linkTexts and $disabledTexts are arrays
667 * @param array $linkTexts
668 * @param array $disabledTexts
671 function getPagingLinks( $linkTexts, $disabledTexts = [] ) {
672 $queries = $this->getPagingQueries();
675 foreach ( $queries as $type => $query ) {
676 if ( $query !== false ) {
677 $links[$type] = $this->makeLink(
682 } elseif ( isset( $disabledTexts[$type] ) ) {
683 $links[$type] = $disabledTexts[$type];
685 $links[$type] = $linkTexts[$type];
692 function getLimitLinks() {
694 if ( $this->mIsBackwards
) {
695 $offset = $this->mPastTheEndIndex
;
697 $offset = $this->mOffset
;
699 foreach ( $this->mLimitsShown
as $limit ) {
700 $links[] = $this->makeLink(
701 $this->getLanguage()->formatNum( $limit ),
702 [ 'offset' => $offset, 'limit' => $limit ],
710 * Abstract formatting function. This should return an HTML string
711 * representing the result row $row. Rows will be concatenated and
712 * returned by getBody()
714 * @param array|stdClass $row Database row
717 abstract function formatRow( $row );
720 * This function should be overridden to provide all parameters
721 * needed for the main paged query. It returns an associative
722 * array with the following elements:
723 * tables => Table(s) for passing to Database::select()
724 * fields => Field(s) for passing to Database::select(), may be *
725 * conds => WHERE conditions
726 * options => option array
727 * join_conds => JOIN conditions
731 abstract function getQueryInfo();
734 * This function should be overridden to return the name of the index fi-
735 * eld. If the pager supports multiple orders, it may return an array of
736 * 'querykey' => 'indexfield' pairs, so that a request with &count=querykey
737 * will use indexfield to sort. In this case, the first returned key is
740 * Needless to say, it's really not a good idea to use a non-unique index
741 * for this! That won't page right.
743 * @return string|string[]
745 abstract function getIndexField();
748 * This function should be overridden to return the names of secondary columns
749 * to order by in addition to the column in getIndexField(). These fields will
750 * not be used in the pager offset or in any links for users.
752 * If getIndexField() returns an array of 'querykey' => 'indexfield' pairs then
753 * this must return a corresponding array of 'querykey' => [ fields... ] pairs
754 * in order for a request with &count=querykey to use [ fields... ] to sort.
756 * This is useful for pagers that GROUP BY a unique column (say page_id)
757 * and ORDER BY another (say page_len). Using GROUP BY and ORDER BY both on
758 * page_len,page_id avoids temp tables (given a page_len index). This would
759 * also work if page_id was non-unique but we had a page_len,page_id index.
761 * @return string[]|array[]
763 protected function getExtraSortFields() {
768 * Return the default sorting direction: DIR_ASCENDING or DIR_DESCENDING.
769 * You can also have an associative array of ordertype => dir,
770 * if multiple order types are supported. In this case getIndexField()
771 * must return an array, and the keys of that must exactly match the keys
774 * For backward compatibility, this method's return value will be ignored
775 * if $this->mDefaultDirection is already set when the constructor is
776 * called, for instance if it's statically initialized. In that case the
777 * value of that variable (which must be a boolean) will be used.
779 * Note that despite its name, this does not return the value of the
780 * $this->mDefaultDirection member variable. That's the default for this
781 * particular instantiation, which is a single value. This is the set of
782 * all defaults for the class.
786 protected function getDefaultDirections() {
787 return self
::DIR_ASCENDING
;
791 * Generate (prev x| next x) (20|50|100...) type links for paging
793 * @param LinkTarget $title
796 * @param array $query Optional URL query parameter string
797 * @param bool $atend Optional param for specified if this is the last page
800 protected function buildPrevNextNavigation( LinkTarget
$title, $offset, $limit,
801 array $query = [], $atend = false
803 $prevNext = new PrevNextNavigationRenderer( $this );
805 return $prevNext->buildPrevNextNavigation( $title, $offset, $limit, $query, $atend );