MediaWiki  master
SelectQueryBuilder.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Wikimedia\Rdbms;
4 
12 
14  public const SORT_ASC = 'ASC';
15 
17  public const SORT_DESC = 'DESC';
18 
22  private $fields = [];
23 
27  private $conds = [];
28 
32  private $caller = __CLASS__;
33 
37  protected $options = [];
38 
42  private $nextAutoAlias = 1;
43 
45  protected $db;
46 
52  public function __construct( IDatabase $db ) {
53  $this->db = $db;
54  }
55 
63  public function connection( IDatabase $db ) {
64  if ( $this->db->getType() !== $db->getType() ) {
65  throw new \InvalidArgumentException( __METHOD__ .
66  ' cannot switch to a database of a different type.' );
67  }
68  $this->db = $db;
69  return $this;
70  }
71 
91  public function queryInfo( $info ) {
92  if ( isset( $info['tables'] ) ) {
93  $this->rawTables( $info['tables'] );
94  }
95  if ( isset( $info['fields'] ) ) {
96  $this->fields( $info['fields'] );
97  }
98  if ( isset( $info['conds'] ) ) {
99  $this->where( $info['conds'] );
100  }
101  if ( isset( $info['options'] ) ) {
102  $this->options( (array)$info['options'] );
103  }
104  if ( isset( $info['join_conds'] ) ) {
105  $this->joinConds( (array)$info['join_conds'] );
106  }
107  if ( isset( $info['joins'] ) ) {
108  $this->joinConds( (array)$info['joins'] );
109  }
110  return $this;
111  }
112 
125  public function rawTables( $tables ) {
126  if ( is_array( $tables ) ) {
127  $this->tables = array_merge( $this->tables, $tables );
128  } elseif ( is_string( $tables ) ) {
129  $this->tables[] = $tables;
130  } else {
131  throw new \InvalidArgumentException( __METHOD__ .
132  ': $tables must be a string or array' );
133  }
134  return $this;
135  }
136 
142  public function newSubquery() {
143  return new self( $this->db );
144  }
145 
153  public function from( $table, $alias = null ) {
154  return $this->table( $table, $alias );
155  }
156 
163  public function tables( $tables ) {
164  foreach ( $tables as $alias => $table ) {
165  if ( is_string( $alias ) ) {
166  $this->table( $table, $alias );
167  } else {
168  $this->table( $table );
169  }
170  }
171  return $this;
172  }
173 
184  public function fields( $fields ) {
185  if ( is_array( $fields ) ) {
186  $this->fields = array_merge( $this->fields, $fields );
187  } else {
188  $this->fields[] = $fields;
189  }
190  return $this;
191  }
192 
199  public function select( $fields ) {
200  return $this->fields( $fields );
201  }
202 
211  public function field( $field, $alias = null ) {
212  if ( $alias === null ) {
213  $this->fields[] = $field;
214  } else {
215  $this->fields[$alias] = $field;
216  }
217  return $this;
218  }
219 
256  public function where( $conds ) {
257  if ( is_array( $conds ) ) {
258  $this->conds = array_merge( $this->conds, $conds );
259  } else {
260  $this->conds[] = $conds;
261  }
262  return $this;
263  }
264 
271  public function andWhere( $conds ) {
272  return $this->where( $conds );
273  }
274 
281  public function conds( $conds ) {
282  return $this->where( $conds );
283  }
284 
293  public function joinConds( array $joinConds ) {
294  $this->joinConds = array_merge( $this->joinConds, $joinConds );
295  return $this;
296  }
297 
303  protected function getAutoAlias() {
304  return 'sqb' . ( $this->nextAutoAlias++ );
305  }
306 
313  public function newJoinGroup() {
314  return new JoinGroup( $this->getAutoAlias() );
315  }
316 
327  public function offset( $offset ) {
328  $this->options['OFFSET'] = $offset;
329  return $this;
330  }
331 
342  public function limit( $limit ) {
343  $this->options['LIMIT'] = $limit;
344  return $this;
345  }
346 
354  public function lockInShareMode() {
355  $this->options[] = 'LOCK IN SHARE MODE';
356  return $this;
357  }
358 
366  public function forUpdate() {
367  $this->options[] = 'FOR UPDATE';
368  return $this;
369  }
370 
376  public function distinct() {
377  $this->options[] = 'DISTINCT';
378  return $this;
379  }
380 
390  public function groupBy( $group ) {
391  $this->mergeOption( 'GROUP BY', $group );
392  return $this;
393  }
394 
406  public function having( $having ) {
407  $this->mergeOption( 'HAVING', $having );
408  return $this;
409  }
410 
421  public function orderBy( $fields, $direction = null ) {
422  if ( $direction === null ) {
423  $this->mergeOption( 'ORDER BY', $fields );
424  } elseif ( is_array( $fields ) ) {
425  $fieldsWithDirection = [];
426  foreach ( $fields as $field ) {
427  $fieldsWithDirection[] = "$field $direction";
428  }
429  $this->mergeOption( 'ORDER BY', $fieldsWithDirection );
430  } else {
431  $this->mergeOption( 'ORDER BY', "$fields $direction" );
432  }
433  return $this;
434  }
435 
442  private function mergeOption( $name, $newArrayOrValue ) {
443  $value = isset( $this->options[$name] )
444  ? (array)$this->options[$name] : [];
445  if ( is_array( $newArrayOrValue ) ) {
446  $value = array_merge( $value, $newArrayOrValue );
447  } else {
448  $value[] = $newArrayOrValue;
449  }
450  $this->options[$name] = $value;
451  }
452 
465  public function useIndex( $index ) {
466  $this->setIndexHint( 'USE INDEX', $index );
467  return $this;
468  }
469 
482  public function ignoreIndex( $index ) {
483  $this->setIndexHint( 'IGNORE INDEX', $index );
484  return $this;
485  }
486 
493  private function setIndexHint( $type, $value ) {
494  if ( !isset( $this->options[$type] ) ) {
495  $this->options[$type] = [];
496  } elseif ( !is_array( $this->options[$type] ) ) {
497  throw new \UnexpectedValueException(
498  __METHOD__ . ": The $type option cannot be appended to " .
499  'because it is not an array. This may have been caused by a prior ' .
500  'call to option() or options().' );
501  }
502  if ( is_array( $value ) ) {
503  $this->options[$type] = array_merge( $this->options[$type], $value );
504  } elseif ( $this->lastAlias === null ) {
505  throw new \UnexpectedValueException(
506  __METHOD__ . ': Cannot append index value since there is no' .
507  'prior table' );
508  } else {
509  $this->options[$type][$this->lastAlias] = $value;
510  }
511  }
512 
518  public function explain() {
519  $this->options['EXPLAIN'] = true;
520  return $this;
521  }
522 
528  public function straightJoin() {
529  $this->options[] = 'STRAIGHT_JOIN';
530  return $this;
531  }
532 
538  public function bigResult() {
539  $this->options[] = 'SQL_BIG_RESULT';
540  return $this;
541  }
542 
548  public function bufferResult() {
549  $this->options[] = 'SQL_BUFFER_RESULT';
550  return $this;
551  }
552 
558  public function smallResult() {
559  $this->options[] = 'SQL_SMALL_RESULT';
560  return $this;
561  }
562 
568  public function calcFoundRows() {
569  $this->options[] = 'SQL_CALC_FOUND_ROWS';
570  return $this;
571  }
572 
581  public function option( $name, $value = null ) {
582  if ( $value === null ) {
583  $this->options[] = $name;
584  } else {
585  $this->options[$name] = $value;
586  }
587  return $this;
588  }
589 
597  public function options( array $options ) {
598  $this->options = array_merge( $this->options, $options );
599  return $this;
600  }
601 
608  public function caller( $fname ) {
609  $this->caller = $fname;
610  return $this;
611  }
612 
618  public function fetchResultSet() {
619  return $this->db->select( $this->tables, $this->fields, $this->conds, $this->caller,
620  $this->options, $this->joinConds );
621  }
622 
630  public function fetchField() {
631  if ( count( $this->fields ) !== 1 ) {
632  throw new \UnexpectedValueException(
633  __METHOD__ . ' expects the query to have only one field' );
634  }
635  $field = reset( $this->fields );
636  return $this->db->selectField( $this->tables, $field, $this->conds, $this->caller,
637  $this->options, $this->joinConds );
638  }
639 
647  public function fetchFieldValues() {
648  if ( count( $this->fields ) !== 1 ) {
649  throw new \UnexpectedValueException(
650  __METHOD__ . ' expects the query to have only one field' );
651  }
652  $field = reset( $this->fields );
653  return $this->db->selectFieldValues( $this->tables, $field, $this->conds, $this->caller,
654  $this->options, $this->joinConds );
655  }
656 
663  public function fetchRow() {
664  return $this->db->selectRow( $this->tables, $this->fields, $this->conds, $this->caller,
665  $this->options, $this->joinConds );
666  }
667 
675  public function fetchRowCount() {
676  return $this->db->selectRowCount( $this->tables, $this->getRowCountVar(), $this->conds,
677  $this->caller, $this->options, $this->joinConds );
678  }
679 
690  public function estimateRowCount() {
691  return $this->db->estimateRowCount( $this->tables, $this->getRowCountVar(), $this->conds,
692  $this->caller, $this->options, $this->joinConds );
693  }
694 
701  private function getRowCountVar() {
702  if ( count( $this->fields ) === 0 ) {
703  return '*';
704  } elseif ( count( $this->fields ) === 1 ) {
705  return reset( $this->fields );
706  } else {
707  throw new \UnexpectedValueException(
708  __METHOD__ . ' expects the query to have at most one field' );
709  }
710  }
711 
717  public function lockForUpdate() {
718  return $this->db->lockForUpdate( $this->tables, $this->conds, $this->caller,
719  $this->options, $this->joinConds );
720  }
721 
733  public function buildGroupConcatField( $delim ) {
734  if ( count( $this->fields ) !== 1 ) {
735  throw new \UnexpectedValueException(
736  __METHOD__ . ' expects the query to have only one field' );
737  }
738  $field = reset( $this->fields );
739  return $this->db->buildGroupConcatField( $delim, $this->tables, $field,
740  $this->conds, $this->joinConds );
741  }
742 
748  public function getSQL() {
749  return $this->db->selectSQLText( $this->tables, $this->fields, $this->conds, $this->caller,
750  $this->options, $this->joinConds );
751  }
752 
767  public function getQueryInfo( $joinsName = 'join_conds' ) {
768  $info = [
769  'tables' => $this->tables,
770  'fields' => $this->fields,
771  'conds' => $this->conds,
772  'options' => $this->options,
773  ];
774  $info[ $joinsName ] = $this->joinConds;
775  return $info;
776  }
777 }
Wikimedia\Rdbms\JoinGroupBase\$joinConds
array $joinConds
Definition: JoinGroupBase.php:14
Wikimedia\Rdbms\SelectQueryBuilder\newSubquery
newSubquery()
Get an empty SelectQueryBuilder which can be used to build a subquery of this query.
Definition: SelectQueryBuilder.php:142
Wikimedia\Rdbms\SelectQueryBuilder\calcFoundRows
calcFoundRows()
Enable the SQL_CALC_FOUND_ROWS option.
Definition: SelectQueryBuilder.php:568
Wikimedia\Rdbms\SelectQueryBuilder\joinConds
joinConds(array $joinConds)
Manually append to the $join_conds array which will be passed to IDatabase::select().
Definition: SelectQueryBuilder.php:293
Wikimedia\Rdbms\SelectQueryBuilder\$conds
array $conds
The conditions to be passed to IDatabase::select()
Definition: SelectQueryBuilder.php:27
Wikimedia\Rdbms\SelectQueryBuilder\mergeOption
mergeOption( $name, $newArrayOrValue)
Add a value to an option which may be not set or a string or array.
Definition: SelectQueryBuilder.php:442
Wikimedia\Rdbms\SelectQueryBuilder\getRowCountVar
getRowCountVar()
Private helper which extracts a field suitable for row counting from the fields array.
Definition: SelectQueryBuilder.php:701
Wikimedia\Rdbms\SelectQueryBuilder\limit
limit( $limit)
Set the query limit.
Definition: SelectQueryBuilder.php:342
Wikimedia\Rdbms\SelectQueryBuilder\options
options(array $options)
Manually set multiple options in the $options array to be passed to IDatabase::select().
Definition: SelectQueryBuilder.php:597
Wikimedia\Rdbms\SelectQueryBuilder\rawTables
rawTables( $tables)
Given a table or table array as might be passed to Database::select(), append it to the existing tabl...
Definition: SelectQueryBuilder.php:125
Wikimedia\Rdbms\SelectQueryBuilder\useIndex
useIndex( $index)
Set a USE INDEX option.
Definition: SelectQueryBuilder.php:465
Wikimedia\Rdbms\SelectQueryBuilder\connection
connection(IDatabase $db)
Change the IDatabase object the query builder is bound to.
Definition: SelectQueryBuilder.php:63
Wikimedia\Rdbms\SelectQueryBuilder\fetchResultSet
fetchResultSet()
Run the constructed SELECT query and return all results.
Definition: SelectQueryBuilder.php:618
Wikimedia\Rdbms\SelectQueryBuilder\tables
tables( $tables)
Add multiple tables.
Definition: SelectQueryBuilder.php:163
Wikimedia\Rdbms\JoinGroup
An object representing a parenthesized group of tables and their join types and conditions.
Definition: JoinGroup.php:9
Wikimedia\Rdbms
Definition: ChronologyProtector.php:24
Wikimedia\Rdbms\SelectQueryBuilder\getAutoAlias
getAutoAlias()
Get a table alias which is unique to this SelectQueryBuilder.
Definition: SelectQueryBuilder.php:303
Wikimedia\Rdbms\SelectQueryBuilder\$caller
string $caller
The caller (function name) to be passed to IDatabase::select()
Definition: SelectQueryBuilder.php:32
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
Wikimedia\Rdbms\SelectQueryBuilder\bufferResult
bufferResult()
Enable the SQL_BUFFER_RESULT option.
Definition: SelectQueryBuilder.php:548
Wikimedia\Rdbms\SelectQueryBuilder\distinct
distinct()
Enable the DISTINCT option.
Definition: SelectQueryBuilder.php:376
Wikimedia\Rdbms\JoinGroupBase
A class for code shared between SelectQueryBuilder and JoinGroup.
Definition: JoinGroupBase.php:9
Wikimedia\Rdbms\SelectQueryBuilder\__construct
__construct(IDatabase $db)
Definition: SelectQueryBuilder.php:52
Wikimedia\Rdbms\SelectQueryBuilder\newJoinGroup
newJoinGroup()
Create a parenthesized group of joins which can be added to the object like a table.
Definition: SelectQueryBuilder.php:313
Wikimedia\Rdbms\SelectQueryBuilder\caller
caller( $fname)
Set the method name to be included in an SQL comment.
Definition: SelectQueryBuilder.php:608
Wikimedia\Rdbms\SelectQueryBuilder
Definition: SelectQueryBuilder.php:11
Wikimedia\Rdbms\SelectQueryBuilder\forUpdate
forUpdate()
Enable the FOR UPDATE option.
Definition: SelectQueryBuilder.php:366
Wikimedia\Rdbms\JoinGroupBase\$lastAlias
$lastAlias
Definition: JoinGroupBase.php:16
Wikimedia\Rdbms\SelectQueryBuilder\straightJoin
straightJoin()
Enable the STRAIGHT_JOIN option.
Definition: SelectQueryBuilder.php:528
Wikimedia\Rdbms\SelectQueryBuilder\fetchRowCount
fetchRowCount()
Run the SELECT query, and return the number of results.
Definition: SelectQueryBuilder.php:675
Wikimedia\Rdbms\SelectQueryBuilder\fields
fields( $fields)
Add a field or an array of fields to the query.
Definition: SelectQueryBuilder.php:184
Wikimedia\Rdbms\SelectQueryBuilder\lockInShareMode
lockInShareMode()
Enable the LOCK IN SHARE MODE option.
Definition: SelectQueryBuilder.php:354
Wikimedia\Rdbms\SelectQueryBuilder\option
option( $name, $value=null)
Manually set an option in the $options array to be passed to IDatabase::select()
Definition: SelectQueryBuilder.php:581
Wikimedia\Rdbms\SelectQueryBuilder\getQueryInfo
getQueryInfo( $joinsName='join_conds')
Get an associative array describing the query in terms of its raw parameters to Database::select().
Definition: SelectQueryBuilder.php:767
Wikimedia\Rdbms\SelectQueryBuilder\offset
offset( $offset)
Set the offset.
Definition: SelectQueryBuilder.php:327
Wikimedia\Rdbms\SelectQueryBuilder\$options
array $options
The options to be passed to IDatabase::select()
Definition: SelectQueryBuilder.php:37
Wikimedia\Rdbms\SelectQueryBuilder\fetchRow
fetchRow()
Run the constructed SELECT query, and return the first result row.
Definition: SelectQueryBuilder.php:663
Wikimedia\Rdbms\SelectQueryBuilder\queryInfo
queryInfo( $info)
Set the query parameters to the given values, appending to the values which were already set.
Definition: SelectQueryBuilder.php:91
Wikimedia\Rdbms\SelectQueryBuilder\fetchFieldValues
fetchFieldValues()
Run the constructed SELECT query, and extract a single field from each result row,...
Definition: SelectQueryBuilder.php:647
Wikimedia\Rdbms\JoinGroupBase\$tables
array $tables
Definition: JoinGroupBase.php:11
Wikimedia\Rdbms\SelectQueryBuilder\$nextAutoAlias
int $nextAutoAlias
An integer used to assign automatic aliases to tables and groups.
Definition: SelectQueryBuilder.php:42
Wikimedia\Rdbms\SelectQueryBuilder\lockForUpdate
lockForUpdate()
Run the SELECT query with the FOR UPDATE option.
Definition: SelectQueryBuilder.php:717
Wikimedia\Rdbms\SelectQueryBuilder\conds
conds( $conds)
Add conditions to the query.
Definition: SelectQueryBuilder.php:281
Wikimedia\Rdbms\SelectQueryBuilder\andWhere
andWhere( $conds)
Add conditions to the query.
Definition: SelectQueryBuilder.php:271
Wikimedia\Rdbms\SelectQueryBuilder\bigResult
bigResult()
Enable the SQL_BIG_RESULT option.
Definition: SelectQueryBuilder.php:538
Wikimedia\Rdbms\SelectQueryBuilder\buildGroupConcatField
buildGroupConcatField( $delim)
Build a GROUP_CONCAT or equivalent statement for a query.
Definition: SelectQueryBuilder.php:733
Wikimedia\Rdbms\SelectQueryBuilder\explain
explain()
Make the query be an EXPLAIN SELECT query instead of a SELECT query.
Definition: SelectQueryBuilder.php:518
Wikimedia\Rdbms\SelectQueryBuilder\having
having( $having)
Add a HAVING clause.
Definition: SelectQueryBuilder.php:406
Wikimedia\Rdbms\IDatabase\getType
getType()
Get the RDBMS type of the server (e.g.
Wikimedia\Rdbms\SelectQueryBuilder\ignoreIndex
ignoreIndex( $index)
Set the IGNORE INDEX option.
Definition: SelectQueryBuilder.php:482
Wikimedia\Rdbms\SelectQueryBuilder\smallResult
smallResult()
Enable the SQL_SMALL_RESULT option.
Definition: SelectQueryBuilder.php:558
Wikimedia\Rdbms\SelectQueryBuilder\setIndexHint
setIndexHint( $type, $value)
Private helper for methods that set index hints.
Definition: SelectQueryBuilder.php:493
Wikimedia\Rdbms\SelectQueryBuilder\where
where( $conds)
Add conditions to the query.
Definition: SelectQueryBuilder.php:256
Wikimedia\Rdbms\SelectQueryBuilder\field
field( $field, $alias=null)
Add a single field to the query, optionally with an alias.
Definition: SelectQueryBuilder.php:211
Wikimedia\Rdbms\SelectQueryBuilder\orderBy
orderBy( $fields, $direction=null)
Set the ORDER BY clause.
Definition: SelectQueryBuilder.php:421
Wikimedia\Rdbms\SelectQueryBuilder\select
select( $fields)
Add a field or an array of fields to the query.
Definition: SelectQueryBuilder.php:199
Wikimedia\Rdbms\SelectQueryBuilder\$db
IDatabase $db
Definition: SelectQueryBuilder.php:45
Wikimedia\Rdbms\SelectQueryBuilder\fetchField
fetchField()
Run the constructed SELECT query, and return a single field extracted from the first result row.
Definition: SelectQueryBuilder.php:630
Wikimedia\Rdbms\SelectQueryBuilder\getSQL
getSQL()
Get the SQL query string which would be used by fetchResultSet().
Definition: SelectQueryBuilder.php:748
Wikimedia\Rdbms\SelectQueryBuilder\groupBy
groupBy( $group)
Add a GROUP BY clause.
Definition: SelectQueryBuilder.php:390
Wikimedia\Rdbms\SelectQueryBuilder\$fields
array $fields
The fields to be passed to IDatabase::select()
Definition: SelectQueryBuilder.php:22
Wikimedia\Rdbms\SelectQueryBuilder\from
from( $table, $alias=null)
Add a single table to the SELECT query.
Definition: SelectQueryBuilder.php:153
Wikimedia\Rdbms\SelectQueryBuilder\estimateRowCount
estimateRowCount()
Estimate the number of rows in dataset.
Definition: SelectQueryBuilder.php:690
Wikimedia\Rdbms\JoinGroupBase\table
table( $table, $alias=null)
Add a single table or a single parenthesized group.
Definition: JoinGroupBase.php:28
$type
$type
Definition: testCompression.php:52