| 1 | <?php |
| 2 | |
| 3 | namespace Wikimedia\Rdbms; |
| 4 | |
| 5 | use Wikimedia\Rdbms\Platform\ISQLPlatform; |
| 6 | |
| 7 | // Very long type annotations :( |
| 8 | // phpcs:disable Generic.Files.LineLength |
| 9 | |
| 10 | /** |
| 11 | * Build SELECT queries with a fluent interface. |
| 12 | * |
| 13 | * Each query builder object must be used for a single database query only, |
| 14 | * and not be reused afterwards. To run multiple similar queries, you can |
| 15 | * create a query builder to set up most of your query, which you can use |
| 16 | * as a "template" to clone. You can then modify the cloned object for |
| 17 | * each individual query. |
| 18 | * |
| 19 | * Note that the methods in this class are not stable to override. |
| 20 | * This class may be extended to create query builders for specific database |
| 21 | * tables, such {@link \MediaWiki\Page\PageSelectQueryBuilder}, whilst still |
| 22 | * providing the same fluent interface for adding arbitrary additional |
| 23 | * conditions and such. |
| 24 | * |
| 25 | * @since 1.35 |
| 26 | * @stable to extend |
| 27 | * @ingroup Database |
| 28 | */ |
| 29 | class SelectQueryBuilder extends JoinGroupBase { |
| 30 | |
| 31 | /** sort the results in ascending order */ |
| 32 | public const SORT_ASC = 'ASC'; |
| 33 | |
| 34 | /** sort the results in descending order */ |
| 35 | public const SORT_DESC = 'DESC'; |
| 36 | |
| 37 | /** |
| 38 | * @var array The fields to be passed to IReadableDatabase::select() |
| 39 | */ |
| 40 | private $fields = []; |
| 41 | |
| 42 | /** |
| 43 | * @var array The conditions to be passed to IReadableDatabase::select() |
| 44 | */ |
| 45 | private $conds = []; |
| 46 | |
| 47 | /** |
| 48 | * @var string The caller (function name) to be passed to IReadableDatabase::select() |
| 49 | */ |
| 50 | private $caller = __CLASS__; |
| 51 | |
| 52 | /** |
| 53 | * @var array The options to be passed to IReadableDatabase::select() |
| 54 | */ |
| 55 | protected $options = []; |
| 56 | |
| 57 | /** |
| 58 | * @var int An integer used to assign automatic aliases to tables and groups |
| 59 | */ |
| 60 | private $nextAutoAlias = 1; |
| 61 | |
| 62 | /** |
| 63 | * @var bool True if $this->caller has been set |
| 64 | */ |
| 65 | private $isCallerOverridden = false; |
| 66 | |
| 67 | /** @var IReadableDatabase */ |
| 68 | protected IReadableDatabase $db; |
| 69 | |
| 70 | /** |
| 71 | * Only for use in subclasses. To create a SelectQueryBuilder instance, |
| 72 | * use `$db->newSelectQueryBuilder()` instead. |
| 73 | * |
| 74 | * @param IReadableDatabase $db |
| 75 | */ |
| 76 | public function __construct( IReadableDatabase $db ) { |
| 77 | $this->db = $db; |
| 78 | } |
| 79 | |
| 80 | /** |
| 81 | * Change the IReadableDatabase object the query builder is bound to. The specified |
| 82 | * IReadableDatabase will subsequently be used to execute the query. |
| 83 | * |
| 84 | * @param IReadableDatabase $db |
| 85 | * @return $this |
| 86 | */ |
| 87 | public function connection( IReadableDatabase $db ) { |
| 88 | if ( $this->db->getType() !== $db->getType() ) { |
| 89 | throw new \InvalidArgumentException( __METHOD__ . |
| 90 | ' cannot switch to a database of a different type.' ); |
| 91 | } |
| 92 | $this->db = $db; |
| 93 | return $this; |
| 94 | } |
| 95 | |
| 96 | /** |
| 97 | * Set the query parameters to the given values, appending to the values |
| 98 | * which were already set. This can be used to interface with legacy code. |
| 99 | * If a key is omitted, the previous value will be retained. |
| 100 | * |
| 101 | * The parameters must be formatted as required by IReadableDatabase::select. For |
| 102 | * example, JoinGroup cannot be used. |
| 103 | * |
| 104 | * @param array $info Associative array of query info, with keys: |
| 105 | * - tables: The raw array of tables to be passed to IReadableDatabase::select() |
| 106 | * - fields: The fields |
| 107 | * - conds: The conditions |
| 108 | * - options: The query options |
| 109 | * - join_conds: The join conditions |
| 110 | * - joins: Alias for join_conds. If both joins and join_conds are |
| 111 | * specified, the values will be merged. |
| 112 | * - caller: The caller signature |
| 113 | * |
| 114 | * @return $this |
| 115 | */ |
| 116 | public function queryInfo( $info ) { |
| 117 | if ( isset( $info['tables'] ) ) { |
| 118 | $this->rawTables( $info['tables'] ); |
| 119 | } |
| 120 | if ( isset( $info['fields'] ) ) { |
| 121 | $this->fields( $info['fields'] ); |
| 122 | } |
| 123 | if ( isset( $info['conds'] ) ) { |
| 124 | $this->where( $info['conds'] ); |
| 125 | } |
| 126 | if ( isset( $info['options'] ) ) { |
| 127 | $this->options( (array)$info['options'] ); |
| 128 | } |
| 129 | if ( isset( $info['join_conds'] ) ) { |
| 130 | $this->joinConds( (array)$info['join_conds'] ); |
| 131 | } |
| 132 | if ( isset( $info['joins'] ) ) { |
| 133 | $this->joinConds( (array)$info['joins'] ); |
| 134 | } |
| 135 | if ( isset( $info['caller'] ) ) { |
| 136 | $this->caller( $info['caller'] ); |
| 137 | } |
| 138 | return $this; |
| 139 | } |
| 140 | |
| 141 | /** |
| 142 | * Given a table or table array as might be passed to IReadableDatabase::select(), |
| 143 | * append it to the existing tables, interpreting nested arrays as join |
| 144 | * groups. |
| 145 | * |
| 146 | * This can be used to interface with existing code that expresses join |
| 147 | * groups as nested arrays. In new code, join groups should generally |
| 148 | * be created with newJoinGroup(), which provides a fluent interface. |
| 149 | * |
| 150 | * @param string|array $tables Table references; see {@link IReadableDatabase::select} |
| 151 | * for details |
| 152 | * @return $this |
| 153 | */ |
| 154 | public function rawTables( $tables ) { |
| 155 | if ( is_array( $tables ) ) { |
| 156 | $this->tables = array_merge( $this->tables, $tables ); |
| 157 | } elseif ( is_string( $tables ) ) { |
| 158 | $this->tables[] = $tables; |
| 159 | } else { |
| 160 | throw new \InvalidArgumentException( __METHOD__ . |
| 161 | ': $tables must be a string or array' ); |
| 162 | } |
| 163 | return $this; |
| 164 | } |
| 165 | |
| 166 | /** |
| 167 | * Merge another query builder with this one. Append the other builder's |
| 168 | * tables, joins, fields, conditions and options to this one. |
| 169 | * |
| 170 | * @since 1.41 |
| 171 | * @param SelectQueryBuilder $builder |
| 172 | * @return $this |
| 173 | */ |
| 174 | public function merge( SelectQueryBuilder $builder ) { |
| 175 | $this->rawTables( $builder->tables ); |
| 176 | $this->fields( $builder->fields ); |
| 177 | $this->where( $builder->conds ); |
| 178 | $this->options( $builder->options ); |
| 179 | $this->joinConds( $builder->joinConds ); |
| 180 | if ( $builder->isCallerOverridden ) { |
| 181 | $this->caller( $builder->caller ); |
| 182 | } |
| 183 | return $this; |
| 184 | } |
| 185 | |
| 186 | /** |
| 187 | * Get an empty SelectQueryBuilder which can be used to build a subquery |
| 188 | * of this query. |
| 189 | * @return SelectQueryBuilder |
| 190 | */ |
| 191 | public function newSubquery() { |
| 192 | return new self( $this->db ); |
| 193 | } |
| 194 | |
| 195 | /** |
| 196 | * Add a single table to the SELECT query. Alias for table(). |
| 197 | * |
| 198 | * @param string|JoinGroup|SelectQueryBuilder $table Table reference; see {@link table} |
| 199 | * for details |
| 200 | * @param-taint $table exec_sql |
| 201 | * @param string|null $alias The table alias, or null for no alias |
| 202 | * @param-taint $alias exec_sql |
| 203 | * @return $this |
| 204 | */ |
| 205 | public function from( $table, $alias = null ) { |
| 206 | return $this->table( $table, $alias ); |
| 207 | } |
| 208 | |
| 209 | /** |
| 210 | * Add multiple tables. It's recommended to use join() and leftJoin() instead in new code. |
| 211 | * |
| 212 | * @param string[] $tables Table references (string keys are aliases). See {@link table} |
| 213 | * for details. |
| 214 | * @param-taint $tables exec_sql |
| 215 | * @return $this |
| 216 | */ |
| 217 | public function tables( $tables ) { |
| 218 | foreach ( $tables as $alias => $table ) { |
| 219 | if ( is_string( $alias ) ) { |
| 220 | $this->table( $table, $alias ); |
| 221 | } else { |
| 222 | $this->table( $table ); |
| 223 | } |
| 224 | } |
| 225 | return $this; |
| 226 | } |
| 227 | |
| 228 | /** |
| 229 | * Add a field or an array of fields to the query. Each field is an SQL |
| 230 | * fragment. If the array key is non-numeric, the key is taken to be an |
| 231 | * alias for the field. |
| 232 | * |
| 233 | * @see IReadableDatabase::select() |
| 234 | * |
| 235 | * @param string|string[] $fields |
| 236 | * @param-taint $fields exec_sql |
| 237 | * @return $this |
| 238 | */ |
| 239 | public function fields( $fields ) { |
| 240 | if ( is_array( $fields ) ) { |
| 241 | $this->fields = array_merge( $this->fields, $fields ); |
| 242 | } else { |
| 243 | $this->fields[] = $fields; |
| 244 | } |
| 245 | return $this; |
| 246 | } |
| 247 | |
| 248 | /** |
| 249 | * Add a field or an array of fields to the query. Alias for fields(). |
| 250 | * |
| 251 | * @param string|string[] $fields |
| 252 | * @param-taint $fields exec_sql |
| 253 | * @return $this |
| 254 | */ |
| 255 | public function select( $fields ) { |
| 256 | return $this->fields( $fields ); |
| 257 | } |
| 258 | |
| 259 | /** |
| 260 | * Add a single field to the query, optionally with an alias. The field is |
| 261 | * an SQL fragment. It is unsafe to pass user input to this function. |
| 262 | * |
| 263 | * @param string $field |
| 264 | * @param-taint $field exec_sql |
| 265 | * @param string|null $alias |
| 266 | * @param-taint $alias exec_sql |
| 267 | * @return $this |
| 268 | */ |
| 269 | public function field( $field, $alias = null ) { |
| 270 | if ( $alias === null ) { |
| 271 | $this->fields[] = $field; |
| 272 | } else { |
| 273 | $this->fields[$alias] = $field; |
| 274 | } |
| 275 | return $this; |
| 276 | } |
| 277 | |
| 278 | /** |
| 279 | * Remove all fields from the query. |
| 280 | * |
| 281 | * @return $this |
| 282 | */ |
| 283 | public function clearFields() { |
| 284 | $this->fields = []; |
| 285 | return $this; |
| 286 | } |
| 287 | |
| 288 | /** |
| 289 | * Add conditions to the query. The supplied conditions will be appended |
| 290 | * to the existing conditions, separated by AND. |
| 291 | * |
| 292 | * @param string|IExpression|array<string,?scalar|non-empty-array<int,?scalar>|RawSQLValue>|array<int,string|IExpression> $conds |
| 293 | * @param-taint $conds exec_sql_numkey |
| 294 | * |
| 295 | * May be either a string containing a single condition, or an array of |
| 296 | * conditions. If an array is given, the conditions constructed from each |
| 297 | * element are combined with AND. |
| 298 | * |
| 299 | * Array elements may take one of two forms: |
| 300 | * |
| 301 | * - Elements with a numeric key are interpreted as raw SQL fragments. |
| 302 | * - Elements with a string key are interpreted as equality conditions, |
| 303 | * where the key is the field name. |
| 304 | * - If the value of such an array element is a scalar (such as a |
| 305 | * string), it will be treated as data and thus quoted appropriately. |
| 306 | * If it is null, an IS NULL clause will be added. |
| 307 | * - If the value is an array, an IN (...) clause will be constructed |
| 308 | * from its non-null elements, and an IS NULL clause will be added |
| 309 | * if null is present, such that the field may match any of the |
| 310 | * elements in the array. The non-null elements will be quoted. |
| 311 | * |
| 312 | * Note that expressions are often DBMS-dependent in their syntax. |
| 313 | * DBMS-independent wrappers are provided for constructing several types of |
| 314 | * expression commonly used in condition queries. See: |
| 315 | * - IReadableDatabase::buildLike() |
| 316 | * - IReadableDatabase::conditional() |
| 317 | * |
| 318 | * Untrusted user input is safe in the values of string keys, however untrusted |
| 319 | * input must not be used in the array key names or in the values of numeric keys. |
| 320 | * Escaping of untrusted input used in values of numeric keys should be done via |
| 321 | * IReadableDatabase::addQuotes() |
| 322 | * |
| 323 | * @return $this |
| 324 | */ |
| 325 | public function where( $conds ) { |
| 326 | if ( is_array( $conds ) ) { |
| 327 | foreach ( $conds as $key => $cond ) { |
| 328 | if ( is_int( $key ) ) { |
| 329 | $this->conds[] = $cond; |
| 330 | } elseif ( isset( $this->conds[$key] ) ) { |
| 331 | // @phan-suppress-previous-line PhanTypeMismatchDimFetch |
| 332 | // T288882 |
| 333 | $this->conds[] = $this->db->makeList( |
| 334 | [ $key => $cond ], IReadableDatabase::LIST_AND ); |
| 335 | } else { |
| 336 | $this->conds[$key] = $cond; |
| 337 | } |
| 338 | } |
| 339 | } else { |
| 340 | $this->conds[] = $conds; |
| 341 | } |
| 342 | return $this; |
| 343 | } |
| 344 | |
| 345 | /** |
| 346 | * Add conditions to the query. Alias for where(). |
| 347 | * |
| 348 | * @param string|IExpression|array<string,?scalar|non-empty-array<int,?scalar>|RawSQLValue>|array<int,string|IExpression> $conds |
| 349 | * @param-taint $conds exec_sql_numkey |
| 350 | * @return $this |
| 351 | */ |
| 352 | public function andWhere( $conds ) { |
| 353 | return $this->where( $conds ); |
| 354 | } |
| 355 | |
| 356 | /** |
| 357 | * Add conditions to the query. Alias for where(). |
| 358 | * |
| 359 | * @param string|IExpression|array<string,?scalar|non-empty-array<int,?scalar>|RawSQLValue>|array<int,string|IExpression> $conds |
| 360 | * @param-taint $conds exec_sql_numkey |
| 361 | * @return $this |
| 362 | */ |
| 363 | public function conds( $conds ) { |
| 364 | return $this->where( $conds ); |
| 365 | } |
| 366 | |
| 367 | /** |
| 368 | * Manually append to the $join_conds array which will be passed to |
| 369 | * IReadableDatabase::select(). This is not recommended for new code. Instead, |
| 370 | * join() and leftJoin() should be used. |
| 371 | * |
| 372 | * @param array $joinConds |
| 373 | * @return $this |
| 374 | */ |
| 375 | public function joinConds( array $joinConds ) { |
| 376 | $this->joinConds = array_merge( $this->joinConds, $joinConds ); |
| 377 | return $this; |
| 378 | } |
| 379 | |
| 380 | /** |
| 381 | * Get a table alias which is unique to this SelectQueryBuilder |
| 382 | * |
| 383 | * @return string |
| 384 | */ |
| 385 | protected function getAutoAlias() { |
| 386 | return 'sqb' . ( $this->nextAutoAlias++ ); |
| 387 | } |
| 388 | |
| 389 | /** |
| 390 | * Create a parenthesized group of joins which can be added to the object |
| 391 | * like a table. The group is initially empty. |
| 392 | * |
| 393 | * @return JoinGroup |
| 394 | */ |
| 395 | public function newJoinGroup() { |
| 396 | return new JoinGroup( $this->getAutoAlias() ); |
| 397 | } |
| 398 | |
| 399 | /** |
| 400 | * Set the offset. Skip this many rows at the start of the result set. Offset |
| 401 | * with limit() can theoretically be used for paging through a result set, |
| 402 | * but this is discouraged for performance reasons. |
| 403 | * |
| 404 | * If the query builder already has an offset, the old offset will be discarded. |
| 405 | * |
| 406 | * @param int $offset |
| 407 | * @return $this |
| 408 | */ |
| 409 | public function offset( $offset ) { |
| 410 | $this->options['OFFSET'] = $offset; |
| 411 | return $this; |
| 412 | } |
| 413 | |
| 414 | /** |
| 415 | * Set the query limit. Return at most this many rows. The rows are sorted |
| 416 | * and then the first rows are taken until the limit is reached. Limit |
| 417 | * is applied to a result set after offset. |
| 418 | * |
| 419 | * If the query builder already has a limit, the old limit will be discarded. |
| 420 | * |
| 421 | * @param int $limit |
| 422 | * @return $this |
| 423 | */ |
| 424 | public function limit( $limit ) { |
| 425 | $this->options['LIMIT'] = $limit; |
| 426 | return $this; |
| 427 | } |
| 428 | |
| 429 | /** |
| 430 | * Enable the LOCK IN SHARE MODE option. Lock the returned rows so that |
| 431 | * they can't be changed until the next COMMIT. Cannot be used with |
| 432 | * aggregate functions (COUNT, MAX, etc., but also DISTINCT). |
| 433 | * |
| 434 | * @return $this |
| 435 | */ |
| 436 | public function lockInShareMode() { |
| 437 | $this->options[] = 'LOCK IN SHARE MODE'; |
| 438 | return $this; |
| 439 | } |
| 440 | |
| 441 | /** |
| 442 | * Enable the FOR UPDATE option. Lock the returned rows so that |
| 443 | * they can't be changed until the next COMMIT. Cannot be used with |
| 444 | * aggregate functions (COUNT, MAX, etc., but also DISTINCT). |
| 445 | * |
| 446 | * @return $this |
| 447 | */ |
| 448 | public function forUpdate() { |
| 449 | $this->options[] = 'FOR UPDATE'; |
| 450 | return $this; |
| 451 | } |
| 452 | |
| 453 | /** |
| 454 | * Enable the DISTINCT option. Return only unique result rows. |
| 455 | * |
| 456 | * @return $this |
| 457 | */ |
| 458 | public function distinct() { |
| 459 | $this->options[] = 'DISTINCT'; |
| 460 | return $this; |
| 461 | } |
| 462 | |
| 463 | /** |
| 464 | * Set MAX_EXECUTION_TIME for queries. |
| 465 | * |
| 466 | * @param int $time maximum allowed time in milliseconds |
| 467 | * @return $this |
| 468 | */ |
| 469 | public function setMaxExecutionTime( int $time ) { |
| 470 | $this->options['MAX_EXECUTION_TIME'] = $time; |
| 471 | return $this; |
| 472 | } |
| 473 | |
| 474 | /** |
| 475 | * Add a GROUP BY clause. May be either an SQL fragment string naming a |
| 476 | * field or expression to group by, or an array of such SQL fragments. |
| 477 | * |
| 478 | * If there is an existing GROUP BY clause, the new one will be appended. |
| 479 | * |
| 480 | * @param string|string[] $group |
| 481 | * @param-taint $group exec_sql |
| 482 | * @return $this |
| 483 | */ |
| 484 | public function groupBy( $group ) { |
| 485 | $this->mergeOption( 'GROUP BY', $group ); |
| 486 | return $this; |
| 487 | } |
| 488 | |
| 489 | /** |
| 490 | * Add a HAVING clause. May be either a string containing a HAVING clause |
| 491 | * or an array of conditions building the HAVING clause. If an array is |
| 492 | * given, the conditions constructed from each element are combined with |
| 493 | * AND. |
| 494 | * |
| 495 | * If there is an existing HAVING clause, the new one will be appended. |
| 496 | * |
| 497 | * @param string|string[] $having |
| 498 | * @param-taint $having exec_sql_numkey |
| 499 | * @return $this |
| 500 | */ |
| 501 | public function having( $having ) { |
| 502 | $this->mergeOption( 'HAVING', $having ); |
| 503 | return $this; |
| 504 | } |
| 505 | |
| 506 | /** |
| 507 | * Set the ORDER BY clause. If it has already been set, append the |
| 508 | * additional fields to it. |
| 509 | * |
| 510 | * @param string[]|string $fields The field or list of fields to order by. |
| 511 | * @param-taint $fields exec_sql |
| 512 | * @param string|null $direction Sorting direction applied to all fields, |
| 513 | * self::SORT_ASC or self::SORT_DESC. If different fields need to be sorted in opposite |
| 514 | * directions, then this parameter must be omitted, and $fields must contain 'ASC' or 'DESC' |
| 515 | * after each field name. |
| 516 | * @param-taint $direction exec_sql |
| 517 | * @return $this |
| 518 | */ |
| 519 | public function orderBy( $fields, $direction = null ) { |
| 520 | if ( $direction === null ) { |
| 521 | $this->mergeOption( 'ORDER BY', $fields ); |
| 522 | } elseif ( is_array( $fields ) ) { |
| 523 | $fieldsWithDirection = []; |
| 524 | foreach ( $fields as $field ) { |
| 525 | $fieldsWithDirection[] = "$field $direction"; |
| 526 | } |
| 527 | $this->mergeOption( 'ORDER BY', $fieldsWithDirection ); |
| 528 | } else { |
| 529 | $this->mergeOption( 'ORDER BY', "$fields $direction" ); |
| 530 | } |
| 531 | return $this; |
| 532 | } |
| 533 | |
| 534 | /** |
| 535 | * Add a value to an option which may be not set or a string or array. |
| 536 | * |
| 537 | * @param string $name |
| 538 | * @param string|string[] $newArrayOrValue |
| 539 | */ |
| 540 | private function mergeOption( $name, $newArrayOrValue ) { |
| 541 | $value = isset( $this->options[$name] ) |
| 542 | ? (array)$this->options[$name] : []; |
| 543 | if ( is_array( $newArrayOrValue ) ) { |
| 544 | $value = array_merge( $value, $newArrayOrValue ); |
| 545 | } else { |
| 546 | $value[] = $newArrayOrValue; |
| 547 | } |
| 548 | $this->options[$name] = $value; |
| 549 | } |
| 550 | |
| 551 | /** |
| 552 | * Set a USE INDEX option. |
| 553 | * |
| 554 | * If a string is given, the index hint is applied to the most recently |
| 555 | * appended table or alias. If an array is given, it is assumed to be an |
| 556 | * associative array with the alias names in the keys and the indexes in |
| 557 | * the values, as in the USE INDEX option to IReadableDatabase::select(). The |
| 558 | * array will be merged with the existing value. |
| 559 | * |
| 560 | * @param string|string[] $index |
| 561 | * @param-taint $index exec_sql |
| 562 | * @return $this |
| 563 | */ |
| 564 | public function useIndex( $index ) { |
| 565 | $this->setIndexHint( 'USE INDEX', $index ); |
| 566 | return $this; |
| 567 | } |
| 568 | |
| 569 | /** |
| 570 | * Set the IGNORE INDEX option. |
| 571 | * |
| 572 | * If a string is given, the index hint is applied to the most recently |
| 573 | * appended table or alias. If an array is given, it is assumed to be an |
| 574 | * associative array with the alias names in the keys and the indexes in |
| 575 | * the values, as in the IGNORE INDEX option to IReadableDatabase::select(). The |
| 576 | * array will be merged with the existing value. |
| 577 | * |
| 578 | * @param string|string[] $index |
| 579 | * @param-taint $index exec_sql |
| 580 | * @return $this |
| 581 | */ |
| 582 | public function ignoreIndex( $index ) { |
| 583 | $this->setIndexHint( 'IGNORE INDEX', $index ); |
| 584 | return $this; |
| 585 | } |
| 586 | |
| 587 | /** |
| 588 | * Private helper for methods that set index hints. |
| 589 | * |
| 590 | * @param string $type |
| 591 | * @param string|string[] $value |
| 592 | */ |
| 593 | private function setIndexHint( $type, $value ) { |
| 594 | if ( !isset( $this->options[$type] ) ) { |
| 595 | $this->options[$type] = []; |
| 596 | } elseif ( !is_array( $this->options[$type] ) ) { |
| 597 | throw new \UnexpectedValueException( |
| 598 | __METHOD__ . ": The $type option cannot be appended to " . |
| 599 | 'because it is not an array. This may have been caused by a prior ' . |
| 600 | 'call to option() or options().' ); |
| 601 | } |
| 602 | if ( is_array( $value ) ) { |
| 603 | $this->options[$type] = array_merge( $this->options[$type], $value ); |
| 604 | } elseif ( $this->lastAlias === null ) { |
| 605 | throw new \UnexpectedValueException( |
| 606 | __METHOD__ . ': Cannot append index value since there is no' . |
| 607 | 'prior table' ); |
| 608 | } else { |
| 609 | $this->options[$type][$this->lastAlias] = $value; |
| 610 | } |
| 611 | } |
| 612 | |
| 613 | /** |
| 614 | * Make the query be an EXPLAIN SELECT query instead of a SELECT query. |
| 615 | * |
| 616 | * @return $this |
| 617 | */ |
| 618 | public function explain() { |
| 619 | $this->options['EXPLAIN'] = true; |
| 620 | return $this; |
| 621 | } |
| 622 | |
| 623 | /** |
| 624 | * Enable the STRAIGHT_JOIN query option. |
| 625 | * |
| 626 | * @return $this |
| 627 | */ |
| 628 | public function straightJoinOption() { |
| 629 | $this->options[] = 'STRAIGHT_JOIN'; |
| 630 | return $this; |
| 631 | } |
| 632 | |
| 633 | /** |
| 634 | * Enable the SQL_BIG_RESULT option. |
| 635 | * |
| 636 | * @return $this |
| 637 | */ |
| 638 | public function bigResult() { |
| 639 | $this->options[] = 'SQL_BIG_RESULT'; |
| 640 | return $this; |
| 641 | } |
| 642 | |
| 643 | /** |
| 644 | * Enable the SQL_BUFFER_RESULT option. |
| 645 | * |
| 646 | * @return $this |
| 647 | */ |
| 648 | public function bufferResult() { |
| 649 | $this->options[] = 'SQL_BUFFER_RESULT'; |
| 650 | return $this; |
| 651 | } |
| 652 | |
| 653 | /** |
| 654 | * Enable the SQL_SMALL_RESULT option. |
| 655 | * |
| 656 | * @return $this |
| 657 | */ |
| 658 | public function smallResult() { |
| 659 | $this->options[] = 'SQL_SMALL_RESULT'; |
| 660 | return $this; |
| 661 | } |
| 662 | |
| 663 | /** |
| 664 | * Enable the SQL_CALC_FOUND_ROWS option. |
| 665 | * |
| 666 | * @return $this |
| 667 | */ |
| 668 | public function calcFoundRows() { |
| 669 | $this->options[] = 'SQL_CALC_FOUND_ROWS'; |
| 670 | return $this; |
| 671 | } |
| 672 | |
| 673 | /** |
| 674 | * Manually set an option in the $options array to be passed to |
| 675 | * IReadableDatabase::select() |
| 676 | * |
| 677 | * @param string $name The option name |
| 678 | * @param mixed $value The option value, or null for a boolean option |
| 679 | * @return $this |
| 680 | */ |
| 681 | public function option( $name, $value = null ) { |
| 682 | if ( $value === null ) { |
| 683 | $this->options[] = $name; |
| 684 | } else { |
| 685 | $this->options[$name] = $value; |
| 686 | } |
| 687 | return $this; |
| 688 | } |
| 689 | |
| 690 | /** |
| 691 | * Manually set multiple options in the $options array to be passed to |
| 692 | * IReadableDatabase::select(). |
| 693 | * |
| 694 | * @param array $options |
| 695 | * @return $this |
| 696 | */ |
| 697 | public function options( array $options ) { |
| 698 | $this->options = array_merge( $this->options, $options ); |
| 699 | return $this; |
| 700 | } |
| 701 | |
| 702 | /** |
| 703 | * @param int $recency Bitfield of IDBAccessObject::READ_* constants |
| 704 | * @return $this |
| 705 | */ |
| 706 | public function recency( $recency ) { |
| 707 | if ( ( $recency & IDBAccessObject::READ_EXCLUSIVE ) == IDBAccessObject::READ_EXCLUSIVE ) { |
| 708 | $this->forUpdate(); |
| 709 | } elseif ( ( $recency & IDBAccessObject::READ_LOCKING ) == IDBAccessObject::READ_LOCKING ) { |
| 710 | $this->lockInShareMode(); |
| 711 | } |
| 712 | return $this; |
| 713 | } |
| 714 | |
| 715 | /** |
| 716 | * Set the method name to be included in an SQL comment. |
| 717 | * |
| 718 | * @param string $fname |
| 719 | * @param-taint $fname exec_sql |
| 720 | * @return $this |
| 721 | */ |
| 722 | public function caller( $fname ) { |
| 723 | $this->caller = $fname; |
| 724 | $this->isCallerOverridden = true; |
| 725 | return $this; |
| 726 | } |
| 727 | |
| 728 | /** |
| 729 | * get the method name of the caller, for use in sub classes |
| 730 | * |
| 731 | * @since 1.43 |
| 732 | */ |
| 733 | final protected function getCaller(): string { |
| 734 | return $this->caller; |
| 735 | } |
| 736 | |
| 737 | /** |
| 738 | * Run the constructed SELECT query and return all results. |
| 739 | * |
| 740 | * @return IResultWrapper |
| 741 | * @return-taint tainted |
| 742 | */ |
| 743 | public function fetchResultSet(): IResultWrapper { |
| 744 | return $this->db->select( $this->tables, $this->fields, $this->conds, $this->caller, |
| 745 | $this->options, $this->joinConds ); |
| 746 | } |
| 747 | |
| 748 | /** |
| 749 | * Run the constructed SELECT query, and return a single field extracted |
| 750 | * from the first result row. This may only be called when only one field |
| 751 | * has been added to the builder. |
| 752 | * |
| 753 | * @return mixed|false The value from the field, or false if nothing was found |
| 754 | * @return-taint tainted |
| 755 | */ |
| 756 | public function fetchField() { |
| 757 | if ( count( $this->fields ) !== 1 ) { |
| 758 | throw new \UnexpectedValueException( |
| 759 | __METHOD__ . ' expects the query to have only one field' ); |
| 760 | } |
| 761 | $field = reset( $this->fields ); |
| 762 | return $this->db->selectField( $this->tables, $field, $this->conds, $this->caller, |
| 763 | $this->options, $this->joinConds ); |
| 764 | } |
| 765 | |
| 766 | /** |
| 767 | * Run the constructed SELECT query, and extract a single field from each |
| 768 | * result row, returning an array containing all the values. This may only |
| 769 | * be called when only one field has been added to the builder. |
| 770 | * |
| 771 | * @return array |
| 772 | * @return-taint tainted |
| 773 | */ |
| 774 | public function fetchFieldValues(): array { |
| 775 | if ( count( $this->fields ) !== 1 ) { |
| 776 | throw new \UnexpectedValueException( |
| 777 | __METHOD__ . ' expects the query to have only one field' ); |
| 778 | } |
| 779 | $field = reset( $this->fields ); |
| 780 | return $this->db->selectFieldValues( $this->tables, $field, $this->conds, $this->caller, |
| 781 | $this->options, $this->joinConds ); |
| 782 | } |
| 783 | |
| 784 | /** |
| 785 | * Run the constructed SELECT query, and return the first result row. If |
| 786 | * there were no results, return false. |
| 787 | * |
| 788 | * @return \stdClass|false |
| 789 | * @return-taint tainted |
| 790 | */ |
| 791 | public function fetchRow() { |
| 792 | return $this->db->selectRow( $this->tables, $this->fields, $this->conds, $this->caller, |
| 793 | $this->options, $this->joinConds ); |
| 794 | } |
| 795 | |
| 796 | /** |
| 797 | * Run the SELECT query, and return the number of results. This typically |
| 798 | * uses a subquery to discard the actual results on the server side, and |
| 799 | * is useful when counting rows with a limit. |
| 800 | * |
| 801 | * To count rows without a limit, it's more efficient to use a normal |
| 802 | * COUNT() expression, for example: |
| 803 | * |
| 804 | * $queryBuilder->select( 'COUNT(*)' )->from( 'page' )->fetchField() |
| 805 | * |
| 806 | * @return int |
| 807 | */ |
| 808 | public function fetchRowCount(): int { |
| 809 | return $this->db->selectRowCount( $this->tables, $this->getRowCountVar(), $this->conds, |
| 810 | $this->caller, $this->options, $this->joinConds ); |
| 811 | } |
| 812 | |
| 813 | /** |
| 814 | * Estimate the number of rows in dataset |
| 815 | * |
| 816 | * MySQL allows you to estimate the number of rows that would be returned |
| 817 | * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using |
| 818 | * index cardinality statistics, and is notoriously inaccurate, especially |
| 819 | * when large numbers of rows have recently been added or deleted. |
| 820 | * |
| 821 | * @return int |
| 822 | */ |
| 823 | public function estimateRowCount(): int { |
| 824 | return $this->db->estimateRowCount( $this->tables, $this->getRowCountVar(), $this->conds, |
| 825 | $this->caller, $this->options, $this->joinConds ); |
| 826 | } |
| 827 | |
| 828 | /** |
| 829 | * Private helper which extracts a field suitable for row counting from the |
| 830 | * fields array |
| 831 | * |
| 832 | * @return string |
| 833 | */ |
| 834 | private function getRowCountVar() { |
| 835 | if ( count( $this->fields ) === 0 ) { |
| 836 | return '*'; |
| 837 | } elseif ( count( $this->fields ) === 1 ) { |
| 838 | return reset( $this->fields ); |
| 839 | } else { |
| 840 | throw new \UnexpectedValueException( |
| 841 | __METHOD__ . ' expects the query to have at most one field' ); |
| 842 | } |
| 843 | } |
| 844 | |
| 845 | /** |
| 846 | * Build a GROUP_CONCAT or equivalent statement for a query. |
| 847 | * |
| 848 | * This is useful for combining a field for several rows into a single string. |
| 849 | * NULL values will not appear in the output, duplicated values will appear, |
| 850 | * and the resulting delimiter-separated values have no defined sort order. |
| 851 | * Code using the results may need to use the PHP unique() or sort() methods. |
| 852 | * |
| 853 | * @param string $delim |
| 854 | * @return string |
| 855 | */ |
| 856 | public function buildGroupConcatField( $delim ) { |
| 857 | if ( count( $this->fields ) !== 1 ) { |
| 858 | throw new \UnexpectedValueException( |
| 859 | __METHOD__ . ' expects the query to have only one field' ); |
| 860 | } |
| 861 | $field = reset( $this->fields ); |
| 862 | return $this->db->buildGroupConcatField( $delim, $this->tables, $field, |
| 863 | $this->conds, $this->joinConds ); |
| 864 | } |
| 865 | |
| 866 | /** |
| 867 | * Get the SQL query string which would be used by fetchResultSet(). |
| 868 | * |
| 869 | * @return string |
| 870 | */ |
| 871 | public function getSQL() { |
| 872 | // Assume that whoever is calling this method is doing it to build a subquery |
| 873 | $caller = $this->isCallerOverridden ? $this->caller : ISQLPlatform::CALLER_SUBQUERY; |
| 874 | return $this->db->selectSQLText( $this->tables, $this->fields, $this->conds, $caller, |
| 875 | $this->options, $this->joinConds ); |
| 876 | } |
| 877 | |
| 878 | /** |
| 879 | * Get an associative array describing the query in terms of its raw parameters to |
| 880 | * IReadableDatabase::select(). This can be used to interface with legacy code. |
| 881 | * |
| 882 | * @param string $joinsName The name of the join_conds key |
| 883 | * @return array The query info array, with keys: |
| 884 | * - tables: The table array |
| 885 | * - fields: The fields |
| 886 | * - conds: The conditions |
| 887 | * - options: The query options |
| 888 | * - join_conds: The join conditions. This can also be given a different |
| 889 | * name by passing a $joinsName parameter, since some legacy code uses |
| 890 | * the name "joins". |
| 891 | * - caller: The caller signature |
| 892 | */ |
| 893 | public function getQueryInfo( $joinsName = 'join_conds' ) { |
| 894 | $info = [ |
| 895 | 'tables' => $this->tables, |
| 896 | 'fields' => $this->fields, |
| 897 | 'conds' => $this->conds, |
| 898 | 'options' => $this->options, |
| 899 | ]; |
| 900 | if ( $this->caller !== __CLASS__ ) { |
| 901 | $info['caller'] = $this->caller; |
| 902 | } |
| 903 | $info[ $joinsName ] = $this->joinConds; |
| 904 | return $info; |
| 905 | } |
| 906 | |
| 907 | /** |
| 908 | * Execute the query, but throw away the results. This is intended for |
| 909 | * locking select queries. By calling this method, the caller is indicating |
| 910 | * that the query is only done to acquire locks on the selected rows. The |
| 911 | * field list is optional. |
| 912 | * |
| 913 | * Either forUpdate() or lockInShareMode() must be called before calling |
| 914 | * this method. |
| 915 | * |
| 916 | * @see self::forUpdate() |
| 917 | * @see self::lockInShareMode() |
| 918 | * |
| 919 | * @since 1.40 |
| 920 | */ |
| 921 | public function acquireRowLocks(): void { |
| 922 | if ( !array_intersect( $this->options, [ 'FOR UPDATE', 'LOCK IN SHARE MODE' ] ) ) { |
| 923 | throw new \UnexpectedValueException( __METHOD__ . ' can only be called ' . |
| 924 | 'after forUpdate() or lockInShareMode()' ); |
| 925 | } |
| 926 | $fields = $this->fields ?: '1'; |
| 927 | $this->db->select( $this->tables, $fields, $this->conds, $this->caller, |
| 928 | $this->options, $this->joinConds ); |
| 929 | } |
| 930 | } |