Debian Codegraph @

includes/libs/rdbms/platform/SQLPlatform.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20 namespace Wikimedia\Rdbms\Platform;
21
22 use InvalidArgumentException;
23 use Psr\Log\LoggerInterface;
24 use Psr\Log\NullLogger;
25 use RuntimeException;
26 use Throwable;
27 use Wikimedia\Assert\Assert;
28 use Wikimedia\Rdbms\Database\DbQuoter;
29 use Wikimedia\Rdbms\DatabaseDomain;
30 use Wikimedia\Rdbms\DBLanguageError;
31 use Wikimedia\Rdbms\IExpression;
32 use Wikimedia\Rdbms\LikeMatch;
33 use Wikimedia\Rdbms\LikeValue;
34 use Wikimedia\Rdbms\Query;
35 use Wikimedia\Rdbms\QueryBuilderFromRawSql;
36 use Wikimedia\Rdbms\RawSQLValue;
37 use Wikimedia\Rdbms\Subquery;
38 use Wikimedia\Timestamp\ConvertibleTimestamp;
39
40 /**
41 * Sql abstraction object.
42 * This class nor any of its subclasses shouldn't create a db connection.
43 * It also should not become stateful. The constructor should only rely on addQuotes() method in Database.
44 * Later that should be replaced with an implementation that doesn't use db connections.
45 * @since 1.39
46 */
47 class SQLPlatform implements ISQLPlatform {
48 /** @var array[] Current map of (table => (dbname, schema, prefix) map) */
49 protected $tableAliases = [];
50 /** @var string[] Current map of (index alias => index) */
51 protected $indexAliases = [];
52 /** @var DatabaseDomain|null */
53 protected $currentDomain;
54 /** @var array|null Current variables use for schema element placeholders */
55 protected $schemaVars;
56 /** @var DbQuoter */
57 protected $quoter;
58 /** @var LoggerInterface */
59 protected $logger;
60 /** @var callable Error logging callback */
61 protected $errorLogger;
62
63 public function __construct(
64 DbQuoter $quoter,
65 ?LoggerInterface $logger = null,
66 ?DatabaseDomain $currentDomain = null,
67 $errorLogger = null
68
69 ) {
70 $this->quoter = $quoter;
71 $this->logger = $logger ?? new NullLogger();
72 $this->currentDomain = $currentDomain ?: DatabaseDomain::newUnspecified();
73 $this->errorLogger = $errorLogger ?? static function ( Throwable $e ) {
74 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING );
75 };
76 }
77
78 public function bitNot( $field ) {
79 return "(~$field)";
80 }
81
82 public function bitAnd( $fieldLeft, $fieldRight ) {
83 return "($fieldLeft & $fieldRight)";
84 }
85
86 public function bitOr( $fieldLeft, $fieldRight ) {
87 return "($fieldLeft | $fieldRight)";
88 }
89
90 public function addIdentifierQuotes( $s ) {
91 if ( strcspn( $s, "\0\"`'." ) !== strlen( $s ) ) {
92 throw new DBLanguageError(
93 "Identifier must not contain quote, dot or null characters: got '$s'"
94 );
95 }
96 $quoteChar = $this->getIdentifierQuoteChar();
97 return $quoteChar . $s . $quoteChar;
98 }
99
100 /**
101 * Get the character used for identifier quoting
102 * @return string
103 */
104 protected function getIdentifierQuoteChar() {
105 return '"';
106 }
107
108 /**
109 * @inheritDoc
110 */
111 public function buildGreatest( $fields, $values ) {
112 return $this->buildSuperlative( 'GREATEST', $fields, $values );
113 }
114
115 /**
116 * @inheritDoc
117 */
118 public function buildLeast( $fields, $values ) {
119 return $this->buildSuperlative( 'LEAST', $fields, $values );
120 }
121
122 /**
123 * Build a superlative function statement comparing columns/values
124 *
125 * Integer and float values in $values will not be quoted
126 *
127 * If $fields is an array, then each value with a string key is treated as an expression
128 * (which must be manually quoted); such string keys do not appear in the SQL and are only
129 * descriptive aliases.
130 *
131 * @param string $sqlfunc Name of a SQL function
132 * @param string|string[] $fields Name(s) of column(s) with values to compare
133 * @param string|int|float|string[]|int[]|float[] $values Values to compare
134 * @return string
135 */
136 protected function buildSuperlative( $sqlfunc, $fields, $values ) {
137 $fields = is_array( $fields ) ? $fields : [ $fields ];
138 $values = is_array( $values ) ? $values : [ $values ];
139
140 $encValues = [];
141 foreach ( $fields as $alias => $field ) {
142 if ( is_int( $alias ) ) {
143 $encValues[] = $this->addIdentifierQuotes( $field );
144 } else {
145 $encValues[] = $field; // expression
146 }
147 }
148 foreach ( $values as $value ) {
149 if ( is_int( $value ) || is_float( $value ) ) {
150 $encValues[] = $value;
151 } elseif ( is_string( $value ) ) {
152 $encValues[] = $this->quoter->addQuotes( $value );
153 } elseif ( $value === null ) {
154 throw new DBLanguageError( 'Null value in superlative' );
155 } else {
156 throw new DBLanguageError( 'Unexpected value type in superlative' );
157 }
158 }
159
160 return $sqlfunc . '(' . implode( ',', $encValues ) . ')';
161 }
162
163 public function buildComparison( string $op, array $conds ): string {
164 if ( !in_array( $op, [ '>', '>=', '<', '<=' ] ) ) {
165 throw new InvalidArgumentException( "Comparison operator must be one of '>', '>=', '<', '<='" );
166 }
167 if ( count( $conds ) === 0 ) {
168 throw new InvalidArgumentException( "Empty input" );
169 }
170
171 // Construct a condition string by starting with the least significant part of the index, and
172 // adding more significant parts progressively to the left of the string.
173 //
174 // For example, given $conds = [ 'a' => 4, 'b' => 7, 'c' => 1 ], this will generate a condition
175 // like this:
176 //
177 // WHERE a > 4
178 // OR (a = 4 AND (b > 7
179 // OR (b = 7 AND (c > 1))))
180 //
181 // …which is equivalent to the following, which might be easier to understand:
182 //
183 // WHERE a > 4
184 // OR a = 4 AND b > 7
185 // OR a = 4 AND b = 7 AND c > 1
186 //
187 // …and also equivalent to the following, using tuple comparison syntax, which is most intuitive
188 // but apparently performs worse:
189 //
190 // WHERE (a, b, c) > (4, 7, 1)
191
192 $sql = '';
193 foreach ( array_reverse( $conds ) as $field => $value ) {
194 if ( is_int( $field ) ) {
195 throw new InvalidArgumentException(
196 'Non-associative array passed to buildComparison() (typo?)'
197 );
198 }
199 $encValue = $this->quoter->addQuotes( $value );
200 if ( $sql === '' ) {
201 $sql = "$field $op $encValue";
202 // Change '>=' to '>' etc. for remaining fields, as the equality is handled separately
203 $op = rtrim( $op, '=' );
204 } else {
205 $sql = "$field $op $encValue OR ($field = $encValue AND ($sql))";
206 }
207 }
208 return $sql;
209 }
210
211 public function makeList( array $a, $mode = self::LIST_COMMA ) {
212 $first = true;
213 $list = '';
214 $keyWarning = null;
215
216 foreach ( $a as $field => $value ) {
217 if ( $first ) {
218 $first = false;
219 } else {
220 if ( $mode == self::LIST_AND ) {
221 $list .= ' AND ';
222 } elseif ( $mode == self::LIST_OR ) {
223 $list .= ' OR ';
224 } else {
225 $list .= ',';
226 }
227 }
228
229 if ( ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_numeric( $field ) ) {
230 if ( $value instanceof IExpression ) {
231 $list .= "(" . $value->toSql( $this->quoter ) . ")";
232 } elseif ( is_array( $value ) ) {
233 throw new InvalidArgumentException( __METHOD__ . ": unexpected array value without key" );
234 } elseif ( $value instanceof RawSQLValue ) {
235 throw new InvalidArgumentException( __METHOD__ . ": unexpected raw value without key" );
236 } else {
237 $list .= "($value)";
238 }
239 } elseif ( $value instanceof IExpression ) {
240 if ( $mode == self::LIST_AND || $mode == self::LIST_OR ) {
241 throw new InvalidArgumentException( __METHOD__ . ": unexpected key $field for IExpression value" );
242 } else {
243 throw new InvalidArgumentException( __METHOD__ . ": unexpected IExpression outside WHERE clause" );
244 }
245 } elseif ( $mode == self::LIST_SET && is_numeric( $field ) ) {
246 $list .= "$value";
247 } elseif (
248 ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_array( $value )
249 ) {
250 // Remove null from array to be handled separately if found
251 $includeNull = false;
252 foreach ( array_keys( $value, null, true ) as $nullKey ) {
253 $includeNull = true;
254 unset( $value[$nullKey] );
255 }
256 if ( count( $value ) == 0 && !$includeNull ) {
257 throw new InvalidArgumentException(
258 __METHOD__ . ": empty input for field $field" );
259 } elseif ( count( $value ) == 0 ) {
260 // only check if $field is null
261 $list .= "$field IS NULL";
262 } else {
263 // IN clause contains at least one valid element
264 if ( $includeNull ) {
265 // Group subconditions to ensure correct precedence
266 $list .= '(';
267 }
268 if ( count( $value ) == 1 ) {
269 // Special-case single values, as IN isn't terribly efficient
270 // (but call makeList() so that warnings are emitted if needed)
271 $list .= $field . " = " . $this->makeList( $value );
272 } else {
273 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
274 }
275 // if null present in array, append IS NULL
276 if ( $includeNull ) {
277 $list .= " OR $field IS NULL)";
278 }
279 }
280 } elseif ( is_array( $value ) ) {
281 throw new InvalidArgumentException( __METHOD__ . ": unexpected nested array" );
282 } elseif ( $value === null ) {
283 if ( $mode == self::LIST_AND || $mode == self::LIST_OR ) {
284 $list .= "$field IS ";
285 } elseif ( $mode == self::LIST_SET ) {
286 $list .= "$field = ";
287 } elseif ( $mode === self::LIST_COMMA && !is_numeric( $field ) ) {
288 $keyWarning ??= [
289 __METHOD__ . ": array key {key} in list of values ignored",
290 [ 'key' => $field, 'exception' => new RuntimeException() ]
291 ];
292 } elseif ( $mode === self::LIST_NAMES && !is_numeric( $field ) ) {
293 $keyWarning ??= [
294 __METHOD__ . ": array key {key} in list of fields ignored",
295 [ 'key' => $field, 'exception' => new RuntimeException() ]
296 ];
297 }
298 $list .= 'NULL';
299 } else {
300 if (
301 $mode == self::LIST_AND || $mode == self::LIST_OR || $mode == self::LIST_SET
302 ) {
303 $list .= "$field = ";
304 } elseif ( $mode === self::LIST_COMMA && !is_numeric( $field ) ) {
305 $keyWarning ??= [
306 __METHOD__ . ": array key {key} in list of values ignored",
307 [ 'key' => $field, 'exception' => new RuntimeException() ]
308 ];
309 } elseif ( $mode === self::LIST_NAMES && !is_numeric( $field ) ) {
310 $keyWarning ??= [
311 __METHOD__ . ": array key {key} in list of fields ignored",
312 [ 'key' => $field, 'exception' => new RuntimeException() ]
313 ];
314 }
315 $list .= $mode == self::LIST_NAMES ? $value : $this->quoter->addQuotes( $value );
316 }
317 }
318
319 if ( $keyWarning ) {
320 // Only log one warning about this per function call, to reduce log spam when a dynamically
321 // generated associative array is passed
322 $this->logger->warning( ...$keyWarning );
323 }
324
325 return $list;
326 }
327
328 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
329 $conds = [];
330 foreach ( $data as $base => $sub ) {
331 if ( count( $sub ) ) {
332 $conds[] = $this->makeList(
333 [ $baseKey => $base, $subKey => array_map( 'strval', array_keys( $sub ) ) ],
334 self::LIST_AND
335 );
336 }
337 }
338
339 if ( !$conds ) {
340 throw new InvalidArgumentException( "Data for $baseKey and $subKey must be non-empty" );
341 }
342
343 return $this->makeList( $conds, self::LIST_OR );
344 }
345
346 public function factorConds( $condsArray ) {
347 if ( count( $condsArray ) === 0 ) {
348 throw new InvalidArgumentException(
349 __METHOD__ . ": empty condition array" );
350 }
351 $condsByFieldSet = [];
352 foreach ( $condsArray as $conds ) {
353 if ( !count( $conds ) ) {
354 throw new InvalidArgumentException(
355 __METHOD__ . ": empty condition subarray" );
356 }
357 $fieldKey = implode( ',', array_keys( $conds ) );
358 $condsByFieldSet[$fieldKey][] = $conds;
359 }
360 $result = '';
361 foreach ( $condsByFieldSet as $conds ) {
362 if ( $result !== '' ) {
363 $result .= ' OR ';
364 }
365 $result .= $this->factorCondsWithCommonFields( $conds );
366 }
367 return $result;
368 }
369
370 /**
371 * Same as factorConds() but with each element in the array having the same
372 * set of array keys. Validation is done by the caller.
373 *
374 * @param array $condsArray
375 * @return string
376 */
377 private function factorCondsWithCommonFields( $condsArray ) {
378 $first = $condsArray[array_key_first( $condsArray )];
379 if ( count( $first ) === 1 ) {
380 // IN clause
381 $field = array_key_first( $first );
382 $values = [];
383 foreach ( $condsArray as $conds ) {
384 $values[] = $conds[$field];
385 }
386 return $this->makeList( [ $field => $values ], self::LIST_AND );
387 }
388
389 $field1 = array_key_first( $first );
390 $nullExpressions = [];
391 $expressionsByField1 = [];
392 foreach ( $condsArray as $conds ) {
393 $value1 = $conds[$field1];
394 unset( $conds[$field1] );
395 if ( $value1 === null ) {
396 $nullExpressions[] = $conds;
397 } else {
398 $expressionsByField1[$value1][] = $conds;
399 }
400
401 }
402 $wrap = false;
403 $result = '';
404 foreach ( $expressionsByField1 as $value1 => $expressions ) {
405 if ( $result !== '' ) {
406 $result .= ' OR ';
407 $wrap = true;
408 }
409 $factored = $this->factorCondsWithCommonFields( $expressions );
410 $result .= "($field1 = " . $this->quoter->addQuotes( $value1 ) .
411 " AND $factored)";
412 }
413 if ( count( $nullExpressions ) ) {
414 $factored = $this->factorCondsWithCommonFields( $nullExpressions );
415 if ( $result !== '' ) {
416 $result .= ' OR ';
417 $wrap = true;
418 }
419 $result .= "($field1 IS NULL AND $factored)";
420 }
421 if ( $wrap ) {
422 return "($result)";
423 } else {
424 return $result;
425 }
426 }
427
428 /**
429 * @inheritDoc
430 * @stable to override
431 */
432 public function buildConcat( $stringList ) {
433 return 'CONCAT(' . implode( ',', $stringList ) . ')';
434 }
435
436 public function limitResult( $sql, $limit, $offset = false ) {
437 if ( !is_numeric( $limit ) ) {
438 throw new DBLanguageError(
439 "Invalid non-numeric limit passed to " . __METHOD__
440 );
441 }
442 // This version works in MySQL and SQLite. It will very likely need to be
443 // overridden for most other RDBMS subclasses.
444 return "$sql LIMIT "
445 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
446 . "{$limit} ";
447 }
448
449 /**
450 * @stable to override
451 * @param string $s
452 * @param string $escapeChar
453 * @return string
454 */
455 public function escapeLikeInternal( $s, $escapeChar = '`' ) {
456 return str_replace(
457 [ $escapeChar, '%', '_' ],
458 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
459 $s
460 );
461 }
462
463 public function buildLike( $param, ...$params ) {
464 if ( is_array( $param ) ) {
465 $params = $param;
466 } else {
467 $params = func_get_args();
468 }
469 // @phan-suppress-next-line PhanParamTooFewUnpack
470 $likeValue = new LikeValue( ...$params );
471
472 return ' LIKE ' . $likeValue->toSql( $this->quoter );
473 }
474
475 public function anyChar() {
476 return new LikeMatch( '_' );
477 }
478
479 public function anyString() {
480 return new LikeMatch( '%' );
481 }
482
483 /**
484 * @inheritDoc
485 * @stable to override
486 */
487 public function unionSupportsOrderAndLimit() {
488 return true; // True for almost every DB supported
489 }
490
491 public function unionQueries( $sqls, $all, $options = [] ) {
492 $glue = $all ? ') UNION ALL (' : ') UNION (';
493
494 $sql = '(' . implode( $glue, $sqls ) . ')';
495 if ( !$this->unionSupportsOrderAndLimit() ) {
496 return $sql;
497 }
498 $sql .= $this->makeOrderBy( $options );
499 $limit = $options['LIMIT'] ?? null;
500 $offset = $options['OFFSET'] ?? false;
501 if ( $limit !== null ) {
502 $sql = $this->limitResult( $sql, $limit, $offset );
503 }
504
505 return $sql;
506 }
507
508 public function conditional( $cond, $caseTrueExpression, $caseFalseExpression ) {
509 if ( is_array( $cond ) ) {
510 $cond = $this->makeList( $cond, self::LIST_AND );
511 }
512 if ( $cond instanceof IExpression ) {
513 $cond = $cond->toSql( $this->quoter );
514 }
515
516 return "(CASE WHEN $cond THEN $caseTrueExpression ELSE $caseFalseExpression END)";
517 }
518
519 public function strreplace( $orig, $old, $new ) {
520 return "REPLACE({$orig}, {$old}, {$new})";
521 }
522
523 public function timestamp( $ts = 0 ) {
524 $t = new ConvertibleTimestamp( $ts );
525 // Let errors bubble up to avoid putting garbage in the DB
526 return $t->getTimestamp( TS_MW );
527 }
528
529 public function timestampOrNull( $ts = null ) {
530 if ( $ts === null ) {
531 return null;
532 } else {
533 return $this->timestamp( $ts );
534 }
535 }
536
537 public function getInfinity() {
538 return 'infinity';
539 }
540
541 public function encodeExpiry( $expiry ) {
542 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
543 ? $this->getInfinity()
544 : $this->timestamp( $expiry );
545 }
546
547 public function decodeExpiry( $expiry, $format = TS_MW ) {
548 if ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() ) {
549 return 'infinity';
550 }
551
552 return ConvertibleTimestamp::convert( $format, $expiry );
553 }
554
555 /**
556 * @inheritDoc
557 * @stable to override
558 */
559 public function buildSubstring( $input, $startPosition, $length = null ) {
560 $this->assertBuildSubstringParams( $startPosition, $length );
561 $functionBody = "$input FROM $startPosition";
562 if ( $length !== null ) {
563 $functionBody .= " FOR $length";
564 }
565 return 'SUBSTRING(' . $functionBody . ')';
566 }
567
568 /**
569 * Check type and bounds for parameters to self::buildSubstring()
570 *
571 * All supported databases have substring functions that behave the same for
572 * positive $startPosition and non-negative $length, but behaviors differ when
573 * given negative $startPosition or negative $length. The simplest
574 * solution to that is to just forbid those values.
575 *
576 * @param int $startPosition
577 * @param int|null $length
578 * @since 1.31 in Database, moved to SQLPlatform in 1.39
579 */
580 protected function assertBuildSubstringParams( $startPosition, $length ) {
581 if ( $startPosition === 0 ) {
582 // The DBMSs we support use 1-based indexing here.
583 throw new InvalidArgumentException( 'Use 1 as $startPosition for the beginning of the string' );
584 }
585 if ( !is_int( $startPosition ) || $startPosition < 0 ) {
586 throw new InvalidArgumentException(
587 '$startPosition must be a positive integer'
588 );
589 }
590 if ( !( ( is_int( $length ) && $length >= 0 ) || $length === null ) ) {
591 throw new InvalidArgumentException(
592 '$length must be null or an integer greater than or equal to 0'
593 );
594 }
595 }
596
597 public function buildStringCast( $field ) {
598 // In theory this should work for any standards-compliant
599 // SQL implementation, although it may not be the best way to do it.
600 return "CAST( $field AS CHARACTER )";
601 }
602
603 public function buildIntegerCast( $field ) {
604 return 'CAST( ' . $field . ' AS INTEGER )';
605 }
606
607 public function implicitOrderby() {
608 return true;
609 }
610
611 /**
612 * Allows for index remapping in queries where this is not consistent across DBMS
613 *
614 * TODO: Make it protected once all the code is moved over.
615 *
616 * @param string $index
617 * @return string
618 */
619 public function indexName( $index ) {
620 return $this->indexAliases[$index] ?? $index;
621 }
622
623 public function setTableAliases( array $aliases ) {
624 $this->tableAliases = $aliases;
625 }
626
627 public function setIndexAliases( array $aliases ) {
628 $this->indexAliases = $aliases;
629 }
630
631 /**
632 * @return array[]
633 */
634 public function getTableAliases() {
635 return $this->tableAliases;
636 }
637
638 public function setPrefix( $prefix ) {
639 $this->currentDomain = new DatabaseDomain(
640 $this->currentDomain->getDatabase(),
641 $this->currentDomain->getSchema(),
642 $prefix
643 );
644 }
645
646 public function setCurrentDomain( DatabaseDomain $currentDomain ) {
647 $this->currentDomain = $currentDomain;
648 }
649
650 /**
651 * @internal For use by tests
652 * @return DatabaseDomain
653 */
654 public function getCurrentDomain() {
655 return $this->currentDomain;
656 }
657
658 public function selectSQLText(
659 $tables, $vars, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
660 ) {
661 if ( !is_array( $tables ) ) {
662 if ( $tables === '' || $tables === null || $tables === false ) {
663 $tables = [];
664 } elseif ( is_string( $tables ) ) {
665 $tables = [ $tables ];
666 } else {
667 throw new DBLanguageError( __METHOD__ . ' called with incorrect table parameter' );
668 }
669 }
670
671 if ( is_array( $vars ) ) {
672 $fields = implode( ',', $this->fieldNamesWithAlias( $vars ) );
673 } else {
674 $fields = $vars;
675 }
676
677 $options = (array)$options;
678
679 $useIndexByTable = $options['USE INDEX'] ?? [];
680 if ( !is_array( $useIndexByTable ) ) {
681 if ( count( $tables ) <= 1 ) {
682 $useIndexByTable = [ reset( $tables ) => $useIndexByTable ];
683 } else {
684 $e = new DBLanguageError( __METHOD__ . " got ambiguous USE INDEX ($fname)" );
685 ( $this->errorLogger )( $e );
686 }
687 }
688
689 $ignoreIndexByTable = $options['IGNORE INDEX'] ?? [];
690 if ( !is_array( $ignoreIndexByTable ) ) {
691 if ( count( $tables ) <= 1 ) {
692 $ignoreIndexByTable = [ reset( $tables ) => $ignoreIndexByTable ];
693 } else {
694 $e = new DBLanguageError( __METHOD__ . " got ambiguous IGNORE INDEX ($fname)" );
695 ( $this->errorLogger )( $e );
696 }
697 }
698
699 if (
700 $this->selectOptionsIncludeLocking( $options ) &&
701 $this->selectFieldsOrOptionsAggregate( $vars, $options )
702 ) {
703 // Some DB types (e.g. postgres) disallow FOR UPDATE with aggregate
704 // functions. Discourage use of such queries to encourage compatibility.
705 $this->logger->warning(
706 __METHOD__ . ": aggregation used with a locking SELECT ($fname)"
707 );
708 }
709
710 if ( count( $tables ) ) {
711 $from = ' FROM ' . $this->tableNamesWithIndexClauseOrJOIN(
712 $tables,
713 $useIndexByTable,
714 $ignoreIndexByTable,
715 $join_conds
716 );
717 } else {
718 $from = '';
719 }
720
721 [ $startOpts, $preLimitTail, $postLimitTail ] = $this->makeSelectOptions( $options );
722
723 if ( is_array( $conds ) ) {
724 $where = $this->makeList( $conds, self::LIST_AND );
725 } elseif ( $conds instanceof IExpression ) {
726 $where = $conds->toSql( $this->quoter );
727 } elseif ( $conds === null || $conds === false ) {
728 $where = '';
729 $this->logger->warning(
730 __METHOD__
731 . ' called from '
732 . $fname
733 . ' with incorrect parameters: $conds must be a string or an array',
734 [ 'db_log_category' => 'sql' ]
735 );
736 } elseif ( is_string( $conds ) ) {
737 $where = $conds;
738 } else {
739 throw new DBLanguageError( __METHOD__ . ' called with incorrect parameters' );
740 }
741
742 // Keep historical extra spaces after FROM to avoid testing failures
743 if ( $where === '' || $where === '*' ) {
744 $sql = "SELECT $startOpts $fields $from $preLimitTail";
745 } else {
746 $sql = "SELECT $startOpts $fields $from WHERE $where $preLimitTail";
747 }
748
749 if ( isset( $options['LIMIT'] ) ) {
750 $sql = $this->limitResult( $sql, $options['LIMIT'], $options['OFFSET'] ?? false );
751 }
752 $sql = "$sql $postLimitTail";
753
754 if ( isset( $options['EXPLAIN'] ) ) {
755 $sql = 'EXPLAIN ' . $sql;
756 }
757
758 if (
759 $fname === static::CALLER_UNKNOWN ||
760 str_starts_with( $fname, 'Wikimedia\\Rdbms\\' ) ||
761 $fname === '{closure}'
762 ) {
763 $exception = new RuntimeException();
764
765 // Try to figure out and report the real caller
766 $caller = '';
767 foreach ( $exception->getTrace() as $call ) {
768 if ( str_ends_with( $call['file'] ?? '', 'Test.php' ) ) {
769 // Don't warn when called directly by test code, adding callers there is pointless
770 break;
771 } elseif ( str_starts_with( $call['class'] ?? '', 'Wikimedia\\Rdbms\\' ) ) {
772 // Keep looking for the caller of a rdbms method
773 } elseif ( str_ends_with( $call['class'] ?? '', 'SelectQueryBuilder' ) ) {
774 // Keep looking for the caller of any custom SelectQueryBuilder
775 } else {
776 // Warn about the external caller we found
777 $caller = implode( '::', array_filter( [ $call['class'] ?? null, $call['function'] ] ) );
778 break;
779 }
780 }
781
782 if ( $fname === '{closure}' ) {
783 // Someone did ->caller( __METHOD__ ) in a local function, e.g. in a callback to
784 // getWithSetCallback(), MWCallableUpdate or doAtomicSection(). That's not very helpful.
785 // Provide a more specific message. The caller has to be provided like this:
786 // $method = __METHOD__;
787 // function ( ... ) use ( $method ) { ... }
788 $warning = "SQL query with incorrect caller (__METHOD__ used inside a closure: {caller}): {sql}";
789 } else {
790 $warning = "SQL query did not specify the caller (guessed caller: {caller}): {sql}";
791 }
792
793 $this->logger->warning(
794 $warning,
795 [ 'sql' => $sql, 'caller' => $caller, 'exception' => $exception ]
796 );
797 }
798
799 return $sql;
800 }
801
802 /**
803 * @param string|array $options
804 * @return bool
805 */
806 private function selectOptionsIncludeLocking( $options ) {
807 $options = (array)$options;
808 foreach ( [ 'FOR UPDATE', 'LOCK IN SHARE MODE' ] as $lock ) {
809 if ( in_array( $lock, $options, true ) ) {
810 return true;
811 }
812 }
813
814 return false;
815 }
816
817 /**
818 * @param array|string $fields
819 * @param array|string $options
820 * @return bool
821 */
822 private function selectFieldsOrOptionsAggregate( $fields, $options ) {
823 foreach ( (array)$options as $key => $value ) {
824 if ( is_string( $key ) ) {
825 if ( preg_match( '/^(?:GROUP BY|HAVING)$/i', $key ) ) {
826 return true;
827 }
828 } elseif ( is_string( $value ) ) {
829 if ( preg_match( '/^(?:DISTINCT|DISTINCTROW)$/i', $value ) ) {
830 return true;
831 }
832 }
833 }
834
835 $regex = '/^(?:COUNT|MIN|MAX|SUM|GROUP_CONCAT|LISTAGG|ARRAY_AGG)\s*\\(/i';
836 foreach ( (array)$fields as $field ) {
837 if ( is_string( $field ) && preg_match( $regex, $field ) ) {
838 return true;
839 }
840 }
841
842 return false;
843 }
844
845 /**
846 * Gets an array of aliased field names
847 *
848 * @param array $fields [ [alias] => field ]
849 * @return string[] See fieldNameWithAlias()
850 */
851 protected function fieldNamesWithAlias( $fields ) {
852 $retval = [];
853 foreach ( $fields as $alias => $field ) {
854 if ( is_numeric( $alias ) ) {
855 $alias = $field;
856 }
857 $retval[] = $this->fieldNameWithAlias( $field, $alias );
858 }
859
860 return $retval;
861 }
862
863 /**
864 * Get an aliased field name
865 * e.g. fieldName AS newFieldName
866 *
867 * @stable to override
868 * @param string $name Field name
869 * @param string|false $alias Alias (optional)
870 * @return string SQL name for aliased field. Will not alias a field to its own name
871 */
872 public function fieldNameWithAlias( $name, $alias = false ) {
873 if ( !$alias || (string)$alias === (string)$name ) {
874 return $name;
875 } else {
876 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
877 }
878 }
879
880 /**
881 * Get the aliased table name clause for a FROM clause
882 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
883 *
884 * @param array $tables Array of ([alias] => table reference)
885 * @param array $use_index Same as for select()
886 * @param array $ignore_index Same as for select()
887 * @param array $join_conds Same as for select()
888 * @return string
889 */
890 protected function tableNamesWithIndexClauseOrJOIN(
891 $tables,
892 $use_index = [],
893 $ignore_index = [],
894 $join_conds = []
895 ) {
896 $ret = [];
897 $retJOIN = [];
898 $use_index = (array)$use_index;
899 $ignore_index = (array)$ignore_index;
900 $join_conds = (array)$join_conds;
901
902 foreach ( $tables as $alias => $table ) {
903 if ( !is_string( $alias ) ) {
904 // No alias? Set it equal to the table name
905 $alias = $table;
906 }
907
908 if ( is_array( $table ) ) {
909 // A parenthesized group
910 if ( count( $table ) > 1 ) {
911 $joinedTable = '(' .
912 $this->tableNamesWithIndexClauseOrJOIN(
913 $table, $use_index, $ignore_index, $join_conds ) . ')';
914 } else {
915 // Degenerate case
916 $innerTable = reset( $table );
917 $innerAlias = key( $table );
918 $joinedTable = $this->tableNameWithAlias(
919 $innerTable,
920 is_string( $innerAlias ) ? $innerAlias : $innerTable
921 );
922 }
923 } else {
924 $joinedTable = $this->tableNameWithAlias( $table, $alias );
925 }
926
927 // Is there a JOIN clause for this table?
928 if ( isset( $join_conds[$alias] ) ) {
929 Assert::parameterType( 'array', $join_conds[$alias], "join_conds[$alias]" );
930 [ $joinType, $conds ] = $join_conds[$alias];
931 $tableClause = $this->normalizeJoinType( $joinType );
932 $tableClause .= ' ' . $joinedTable;
933 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
934 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
935 if ( $use != '' ) {
936 $tableClause .= ' ' . $use;
937 }
938 }
939 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
940 $ignore = $this->ignoreIndexClause(
941 implode( ',', (array)$ignore_index[$alias] ) );
942 if ( $ignore != '' ) {
943 $tableClause .= ' ' . $ignore;
944 }
945 }
946 $on = $this->makeList( (array)$conds, self::LIST_AND );
947 if ( $on != '' ) {
948 $tableClause .= ' ON (' . $on . ')';
949 }
950
951 $retJOIN[] = $tableClause;
952 } elseif ( isset( $use_index[$alias] ) ) {
953 // Is there an INDEX clause for this table?
954 $tableClause = $joinedTable;
955 $tableClause .= ' ' . $this->useIndexClause(
956 implode( ',', (array)$use_index[$alias] )
957 );
958
959 $ret[] = $tableClause;
960 } elseif ( isset( $ignore_index[$alias] ) ) {
961 // Is there an INDEX clause for this table?
962 $tableClause = $joinedTable;
963 $tableClause .= ' ' . $this->ignoreIndexClause(
964 implode( ',', (array)$ignore_index[$alias] )
965 );
966
967 $ret[] = $tableClause;
968 } else {
969 $tableClause = $joinedTable;
970
971 $ret[] = $tableClause;
972 }
973 }
974
975 // We can't separate explicit JOIN clauses with ',', use ' ' for those
976 $implicitJoins = implode( ',', $ret );
977 $explicitJoins = implode( ' ', $retJOIN );
978
979 // Compile our final table clause
980 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
981 }
982
983 /**
984 * Validate and normalize a join type
985 *
986 * Subclasses may override this to add supported join types.
987 *
988 * @param string $joinType
989 * @return string
990 */
991 protected function normalizeJoinType( string $joinType ) {
992 switch ( strtoupper( $joinType ) ) {
993 case 'JOIN':
994 case 'INNER JOIN':
995 return 'JOIN';
996
997 case 'LEFT JOIN':
998 return 'LEFT JOIN';
999
1000 case 'STRAIGHT_JOIN':
1001 case 'STRAIGHT JOIN':
1002 // MySQL only
1003 return 'JOIN';
1004
1005 default:
1006 return $joinType;
1007 }
1008 }
1009
1010 /**
1011 * Get an aliased table name
1012 *
1013 * This returns strings like "tableName AS newTableName" for aliased tables
1014 * and "(SELECT * from tableA) newTablename" for subqueries (e.g. derived tables)
1015 *
1016 * @see Database::tableName()
1017 * @param string|Subquery $table The unqualified name of a table, or Subquery
1018 * @param string|false $alias Table alias (optional)
1019 * @return string SQL name for aliased table. Will not alias a table to its own name
1020 */
1021 protected function tableNameWithAlias( $table, $alias = false ) {
1022 if ( is_string( $table ) ) {
1023 $quotedTable = $this->tableName( $table );
1024 } elseif ( $table instanceof Subquery ) {
1025 $quotedTable = (string)$table;
1026 } else {
1027 throw new InvalidArgumentException( "Table must be a string or Subquery" );
1028 }
1029
1030 if ( $alias === false ) {
1031 if ( $table instanceof Subquery ) {
1032 throw new InvalidArgumentException( "Subquery table missing alias" );
1033 }
1034 $quotedTableWithAnyAlias = $quotedTable;
1035 } elseif (
1036 $alias === $table &&
1037 (
1038 str_contains( $alias, '.' ) ||
1039 $this->tableName( $alias, 'raw' ) === $table
1040 )
1041 ) {
1042 $quotedTableWithAnyAlias = $quotedTable;
1043 } else {
1044 $quotedTableWithAnyAlias = $quotedTable . ' ' . $this->addIdentifierQuotes( $alias );
1045 }
1046
1047 return $quotedTableWithAnyAlias;
1048 }
1049
1050 public function tableName( string $name, $format = 'quoted' ) {
1051 $prefix = $this->currentDomain->getTablePrefix();
1052
1053 // Warn about table names that look qualified
1054 if (
1055 (
1056 str_contains( $name, '.' ) &&
1057 !preg_match( '/^information_schema\.[a-z_0-9]+$/', $name )
1058 ) ||
1059 ( $prefix !== '' && str_starts_with( $name, $prefix ) )
1060 ) {
1061 $this->logger->warning(
1062 __METHOD__ . ' called with qualified table ' . $name,
1063 [ 'db_log_category' => 'sql' ]
1064 );
1065 }
1066
1067 // Extract necessary database, schema, table identifiers and quote them as needed
1068 $formattedComponents = [];
1069 foreach ( $this->qualifiedTableComponents( $name ) as $component ) {
1070 if ( $format === 'quoted' ) {
1071 $formattedComponents[] = $this->addIdentifierQuotes( $component );
1072 } else {
1073 $formattedComponents[] = $component;
1074 }
1075 }
1076
1077 return implode( '.', $formattedComponents );
1078 }
1079
1080 /**
1081 * Get the table components needed for a query given the currently selected database/schema
1082 *
1083 * The resulting array will take one of the follow forms:
1084 * - <table identifier>
1085 * - <database identifier>.<table identifier> (e.g. non-Postgres)
1086 * - <schema identifier>.<table identifier> (e.g. Postgres-only)
1087 * - <database identifier>.<schema identifier>.<table identifier> (e.g. Postgres-only)
1088 *
1089 * If the provided table name only consists of an unquoted table identifier that has an
1090 * entry in ({@link getTableAliases()}), then, the resulting components will be determined
1091 * from the alias configuration. If such alias configuration does not specify the table
1092 * prefix, then the current DB domain prefix will be prepended to the table identifier.
1093 *
1094 * In all other cases where the provided table name only consists of an unquoted table
1095 * identifier, the current DB domain prefix will be prepended to the table identifier.
1096 *
1097 * Empty database/schema identifiers are omitted from the resulting array.
1098 *
1099 * @param string $name Table name as database.schema.table, database.table, or table
1100 * @return string[] Non-empty list of unquoted identifiers that form the qualified table name
1101 */
1102 public function qualifiedTableComponents( $name ) {
1103 $identifiers = $this->extractTableNameComponents( $name );
1104 if ( count( $identifiers ) > 3 ) {
1105 throw new DBLanguageError( "Too many components in table name '$name'" );
1106 }
1107 // Table alias config and prefixes only apply to unquoted single-identifier names
1108 if ( count( $identifiers ) == 1 && !$this->isQuotedIdentifier( $identifiers[0] ) ) {
1109 [ $table ] = $identifiers;
1110 if ( isset( $this->tableAliases[$table] ) ) {
1111 // This is an "alias" table that uses a different db/schema/prefix scheme
1112 $database = $this->tableAliases[$table]['dbname'];
1113 $schema = is_string( $this->tableAliases[$table]['schema'] )
1114 ? $this->tableAliases[$table]['schema']
1115 : $this->relationSchemaQualifier();
1116 $prefix = is_string( $this->tableAliases[$table]['prefix'] )
1117 ? $this->tableAliases[$table]['prefix']
1118 : $this->currentDomain->getTablePrefix();
1119 } else {
1120 // Use the current database domain to resolve the schema and prefix
1121 $database = '';
1122 $schema = $this->relationSchemaQualifier();
1123 $prefix = $this->currentDomain->getTablePrefix();
1124 }
1125 $qualifierIdentifiers = [ $database, $schema ];
1126 $tableIdentifier = $prefix . $table;
1127 } else {
1128 $qualifierIdentifiers = array_slice( $identifiers, 0, -1 );
1129 $tableIdentifier = end( $identifiers );
1130 }
1131
1132 $components = [];
1133 foreach ( $qualifierIdentifiers as $identifier ) {
1134 if ( $identifier !== null && $identifier !== '' ) {
1135 $components[] = $this->isQuotedIdentifier( $identifier )
1136 ? substr( $identifier, 1, -1 )
1137 : $identifier;
1138 }
1139 }
1140 $components[] = $this->isQuotedIdentifier( $tableIdentifier )
1141 ? substr( $tableIdentifier, 1, -1 )
1142 : $tableIdentifier;
1143
1144 return $components;
1145 }
1146
1147 /**
1148 * Extract the dot-separated components of a table name, preserving identifier quotation
1149 *
1150 * @param string $name Table name, possible qualified with db or db+schema
1151 * @return string[] Non-empty list of the identifiers included in the provided table name
1152 */
1153 public function extractTableNameComponents( string $name ) {
1154 $quoteChar = $this->getIdentifierQuoteChar();
1155 $components = [];
1156 foreach ( explode( '.', $name ) as $component ) {
1157 if ( $this->isQuotedIdentifier( $component ) ) {
1158 $unquotedComponent = substr( $component, 1, -1 );
1159 } else {
1160 $unquotedComponent = $component;
1161 }
1162 if ( str_contains( $unquotedComponent, $quoteChar ) ) {
1163 throw new DBLanguageError(
1164 'Table name component contains unexpected quote or dot character' );
1165 }
1166 $components[] = $component;
1167 }
1168 return $components;
1169 }
1170
1171 /**
1172 * Get the database identifer and prefixed table name identifier for a table
1173 *
1174 * The table name is assumed to be relative to the current DB domain
1175 *
1176 * This method is useful for TEMPORARY table tracking. In MySQL, temp tables with identical
1177 * names can co-exist on different databases, which can be done via CREATE and USE. Note
1178 * that SQLite/PostgreSQL do not allow changing the database within a session. This method
1179 * omits the schema identifier and set it to empty string for several reasons:
1180 * - MySQL/MariaDB do not support schemas at all.
1181 * - SQLite/PostgreSQL put all TEMPORARY tables in the same schema (TEMP and pgtemp,
1182 * respectively). When these engines resolve a table reference, they first check for
1183 * a matching table in the temp schema, before checking the current DB domain schema.
1184 * Note that this breaks table segregation based on the schema component of the DB
1185 * domain, e.g. a temp table with unqualified name "x" resolves to the same underlying
1186 * table whether the current DB domain is "my_db-schema1-mw_" or "my_db-schema2-mw_".
1187 * By ignoring the schema, we can at least account for this.
1188 * - Exposing the the TEMP/pg_temp schema here would be too leaky of an abstraction,
1189 * running the risk of unexpected results, such as identifiers that don't match. It is
1190 * easier to just avoid creating identically-named TEMPORARY tables on different schemas.
1191 *
1192 * @internal only to be used inside rdbms library
1193 * @param string $table Table name
1194 * @return array{0:string,1:string} (unquoted database name, unquoted prefixed table name)
1195 */
1196 public function getDatabaseAndTableIdentifier( string $table ) {
1197 $components = $this->qualifiedTableComponents( $table );
1198 switch ( count( $components ) ) {
1199 case 1:
1200 return [ $this->currentDomain->getDatabase() ?? '', $components[0] ];
1201 case 2:
1202 return $components;
1203 default:
1204 throw new DBLanguageError( 'Too many table components' );
1205 }
1206 }
1207
1208 /**
1209 * @stable to override
1210 * @return string|null Schema to use to qualify relations in queries
1211 */
1212 protected function relationSchemaQualifier() {
1213 return $this->currentDomain->getSchema();
1214 }
1215
1216 /**
1217 * @deprecated since 1.39.
1218 */
1219 public function tableNames( ...$tables ) {
1220 wfDeprecated( __METHOD__, '1.39' );
1221
1222 $retVal = [];
1223
1224 foreach ( $tables as $name ) {
1225 $retVal[$name] = $this->tableName( $name );
1226 }
1227
1228 return $retVal;
1229 }
1230
1231 public function tableNamesN( ...$tables ) {
1232 $retVal = [];
1233
1234 foreach ( $tables as $name ) {
1235 $retVal[] = $this->tableName( $name );
1236 }
1237
1238 return $retVal;
1239 }
1240
1241 /**
1242 * Returns if the given identifier looks quoted or not according to
1243 * the database convention for quoting identifiers
1244 *
1245 * @note Do not use this to determine if untrusted input is safe.
1246 * A malicious user can trick this function.
1247 * @param string $name
1248 * @return bool
1249 */
1250 public function isQuotedIdentifier( $name ) {
1251 $quoteChar = $this->getIdentifierQuoteChar();
1252 return strlen( $name ) > 1 && $name[0] === $quoteChar && $name[-1] === $quoteChar;
1253 }
1254
1255 /**
1256 * USE INDEX clause.
1257 *
1258 * This can be used as optimisation in queries that affect tables with multiple
1259 * indexes if the database does not pick the most optimal one by default.
1260 * The "right" index might vary between database backends and versions thereof,
1261 * as such in practice this is biased toward specifically improving performance
1262 * of large wiki farms that use MySQL or MariaDB (like Wikipedia).
1263 *
1264 * @stable to override
1265 * @param string $index
1266 * @return string
1267 */
1268 public function useIndexClause( $index ) {
1269 return '';
1270 }
1271
1272 /**
1273 * IGNORE INDEX clause.
1274 *
1275 * The inverse of Database::useIndexClause.
1276 *
1277 * @param string $index
1278 * @return string
1279 */
1280 public function ignoreIndexClause( $index ) {
1281 return '';
1282 }
1283
1284 /**
1285 * Returns an optional USE INDEX clause to go after the table, and a
1286 * string to go at the end of the query.
1287 *
1288 * @see Database::select()
1289 *
1290 * @stable to override
1291 * @param array $options Associative array of options to be turned into
1292 * an SQL query, valid keys are listed in the function.
1293 * @return string[] (START OPTIONS, PRE-LIMIT TAIL, POST-LIMIT TAIL)
1294 */
1295 protected function makeSelectOptions( array $options ) {
1296 $preLimitTail = $postLimitTail = '';
1297 $startOpts = '';
1298
1299 $noKeyOptions = [];
1300
1301 foreach ( $options as $key => $option ) {
1302 if ( is_numeric( $key ) ) {
1303 $noKeyOptions[$option] = true;
1304 }
1305 }
1306
1307 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1308
1309 $preLimitTail .= $this->makeOrderBy( $options );
1310
1311 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1312 $postLimitTail .= ' FOR UPDATE';
1313 }
1314
1315 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1316 $postLimitTail .= ' LOCK IN SHARE MODE';
1317 }
1318
1319 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1320 $startOpts .= 'DISTINCT';
1321 }
1322
1323 # Various MySQL extensions
1324 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1325 $startOpts .= ' /*! STRAIGHT_JOIN */';
1326 }
1327
1328 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1329 $startOpts .= ' SQL_BIG_RESULT';
1330 }
1331
1332 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1333 $startOpts .= ' SQL_BUFFER_RESULT';
1334 }
1335
1336 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1337 $startOpts .= ' SQL_SMALL_RESULT';
1338 }
1339
1340 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1341 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1342 }
1343
1344 return [ $startOpts, $preLimitTail, $postLimitTail ];
1345 }
1346
1347 /**
1348 * Returns an optional GROUP BY with an optional HAVING
1349 *
1350 * @param array $options Associative array of options
1351 * @return string
1352 * @see Database::select()
1353 * @since 1.21
1354 */
1355 protected function makeGroupByWithHaving( $options ) {
1356 $sql = '';
1357 if ( isset( $options['GROUP BY'] ) ) {
1358 $gb = is_array( $options['GROUP BY'] )
1359 ? implode( ',', $options['GROUP BY'] )
1360 : $options['GROUP BY'];
1361 $sql .= ' GROUP BY ' . $gb;
1362 }
1363 if ( isset( $options['HAVING'] ) ) {
1364 $having = is_array( $options['HAVING'] )
1365 ? $this->makeList( $options['HAVING'], self::LIST_AND )
1366 : $options['HAVING'];
1367 $sql .= ' HAVING ' . $having;
1368 }
1369
1370 return $sql;
1371 }
1372
1373 /**
1374 * Returns an optional ORDER BY
1375 *
1376 * @param array $options Associative array of options
1377 * @return string
1378 * @see Database::select()
1379 * @since 1.21
1380 */
1381 protected function makeOrderBy( $options ) {
1382 if ( isset( $options['ORDER BY'] ) ) {
1383 $ob = is_array( $options['ORDER BY'] )
1384 ? implode( ',', $options['ORDER BY'] )
1385 : $options['ORDER BY'];
1386
1387 return ' ORDER BY ' . $ob;
1388 }
1389
1390 return '';
1391 }
1392
1393 public function buildGroupConcatField(
1394 $delim, $tables, $field, $conds = '', $join_conds = []
1395 ) {
1396 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->quoter->addQuotes( $delim ) . ')';
1397
1398 return '(' . $this->selectSQLText( $tables, $fld, $conds, static::CALLER_SUBQUERY, [], $join_conds ) . ')';
1399 }
1400
1401 public function buildSelectSubquery(
1402 $tables, $vars, $conds = '', $fname = __METHOD__,
1403 $options = [], $join_conds = []
1404 ) {
1405 return new Subquery(
1406 $this->selectSQLText( $tables, $vars, $conds, $fname, $options, $join_conds )
1407 );
1408 }
1409
1410 public function insertSqlText( $table, array $rows ) {
1411 $encTable = $this->tableName( $table );
1412 [ $sqlColumns, $sqlTuples ] = $this->makeInsertLists( $rows );
1413
1414 return [
1415 "INSERT INTO $encTable ($sqlColumns) VALUES $sqlTuples",
1416 "INSERT INTO $encTable ($sqlColumns) VALUES '?'"
1417 ];
1418 }
1419
1420 /**
1421 * Make SQL lists of columns, row tuples, and column aliases for INSERT/VALUES expressions
1422 *
1423 * The tuple column order is that of the columns of the first provided row.
1424 * The provided rows must have exactly the same keys and ordering thereof.
1425 *
1426 * @param array[] $rows Non-empty list of (column => value) maps
1427 * @param string $aliasPrefix Optional prefix to prepend to the magic alias names
1428 * @param string[] $typeByColumn Optional map of (column => data type)
1429 * @return array (comma-separated columns, comma-separated tuples, comma-separated aliases)
1430 * @since 1.35
1431 */
1432 public function makeInsertLists( array $rows, $aliasPrefix = '', array $typeByColumn = [] ) {
1433 $firstRow = $rows[0];
1434 if ( !is_array( $firstRow ) || !$firstRow ) {
1435 throw new DBLanguageError( 'Got an empty row list or empty row' );
1436 }
1437 // List of columns that define the value tuple ordering
1438 $tupleColumns = array_keys( $firstRow );
1439
1440 $valueTuples = [];
1441 foreach ( $rows as $row ) {
1442 $rowColumns = array_keys( $row );
1443 // VALUES(...) requires a uniform correspondence of (column => value)
1444 if ( $rowColumns !== $tupleColumns ) {
1445 throw new DBLanguageError(
1446 'Got row columns (' . implode( ', ', $rowColumns ) . ') ' .
1447 'instead of expected (' . implode( ', ', $tupleColumns ) . ')'
1448 );
1449 }
1450 // Make the value tuple that defines this row
1451 $valueTuples[] = '(' . $this->makeList( array_values( $row ), self::LIST_COMMA ) . ')';
1452 }
1453
1454 $magicAliasFields = [];
1455 foreach ( $tupleColumns as $column ) {
1456 $magicAliasFields[] = $aliasPrefix . $column;
1457 }
1458
1459 return [
1460 $this->makeList( $tupleColumns, self::LIST_NAMES ),
1461 implode( ',', $valueTuples ),
1462 $this->makeList( $magicAliasFields, self::LIST_NAMES )
1463 ];
1464 }
1465
1466 public function insertNonConflictingSqlText( $table, array $rows ) {
1467 $encTable = $this->tableName( $table );
1468 [ $sqlColumns, $sqlTuples ] = $this->makeInsertLists( $rows );
1469 [ $sqlVerb, $sqlOpts ] = $this->makeInsertNonConflictingVerbAndOptions();
1470
1471 return [
1472 rtrim( "$sqlVerb $encTable ($sqlColumns) VALUES $sqlTuples $sqlOpts" ),
1473 rtrim( "$sqlVerb $encTable ($sqlColumns) VALUES '?' $sqlOpts" )
1474 ];
1475 }
1476
1477 /**
1478 * @stable to override
1479 * @return string[] ("INSERT"-style SQL verb, "ON CONFLICT"-style clause or "")
1480 * @since 1.35
1481 */
1482 protected function makeInsertNonConflictingVerbAndOptions() {
1483 return [ 'INSERT IGNORE INTO', '' ];
1484 }
1485
1486 public function insertSelectNativeSqlText(
1487 $destTable,
1488 $srcTable,
1489 array $varMap,
1490 $conds,
1491 $fname,
1492 array $insertOptions,
1493 array $selectOptions,
1494 $selectJoinConds
1495 ) {
1496 [ $sqlVerb, $sqlOpts ] = $this->isFlagInOptions( 'IGNORE', $insertOptions )
1497 ? $this->makeInsertNonConflictingVerbAndOptions()
1498 : [ 'INSERT INTO', '' ];
1499 $encDstTable = $this->tableName( $destTable );
1500 $sqlDstColumns = implode( ',', array_keys( $varMap ) );
1501 $selectSql = $this->selectSQLText(
1502 $srcTable,
1503 array_values( $varMap ),
1504 $conds,
1505 $fname,
1506 $selectOptions,
1507 $selectJoinConds
1508 );
1509
1510 return rtrim( "$sqlVerb $encDstTable ($sqlDstColumns) $selectSql $sqlOpts" );
1511 }
1512
1513 /**
1514 * @param string $option Query option flag (e.g. "IGNORE" or "FOR UPDATE")
1515 * @param array $options Combination option/value map and boolean option list
1516 * @return bool Whether the option appears as an integer-keyed value in the options
1517 * @since 1.35
1518 */
1519 public function isFlagInOptions( $option, array $options ) {
1520 foreach ( array_keys( $options, $option, true ) as $k ) {
1521 if ( is_int( $k ) ) {
1522 return true;
1523 }
1524 }
1525
1526 return false;
1527 }
1528
1529 /**
1530 * Build an SQL condition to find rows with matching key values to those in $rows.
1531 *
1532 * @param array[] $rows Non-empty list of rows
1533 * @param string[] $uniqueKey List of columns that define a single unique index
1534 * @return string
1535 */
1536 public function makeKeyCollisionCondition( array $rows, array $uniqueKey ) {
1537 if ( !$rows ) {
1538 throw new DBLanguageError( "Empty row array" );
1539 } elseif ( !$uniqueKey ) {
1540 throw new DBLanguageError( "Empty unique key array" );
1541 }
1542
1543 if ( count( $uniqueKey ) == 1 ) {
1544 // Use a simple IN(...) clause
1545 $column = reset( $uniqueKey );
1546 $values = array_column( $rows, $column );
1547 if ( count( $values ) !== count( $rows ) ) {
1548 throw new DBLanguageError( "Missing values for unique key ($column)" );
1549 }
1550
1551 return $this->makeList( [ $column => $values ], self::LIST_AND );
1552 }
1553
1554 $nullByUniqueKeyColumn = array_fill_keys( $uniqueKey, null );
1555
1556 $orConds = [];
1557 foreach ( $rows as $row ) {
1558 $rowKeyMap = array_intersect_key( $row, $nullByUniqueKeyColumn );
1559 if ( count( $rowKeyMap ) != count( $uniqueKey ) ) {
1560 throw new DBLanguageError(
1561 "Missing values for unique key (" . implode( ',', $uniqueKey ) . ")"
1562 );
1563 }
1564 $orConds[] = $this->makeList( $rowKeyMap, self::LIST_AND );
1565 }
1566
1567 return count( $orConds ) > 1
1568 ? $this->makeList( $orConds, self::LIST_OR )
1569 : $orConds[0];
1570 }
1571
1572 public function deleteJoinSqlText( $delTable, $joinTable, $delVar, $joinVar, $conds ) {
1573 if ( !$conds ) {
1574 throw new DBLanguageError( __METHOD__ . ' called with empty $conds' );
1575 }
1576
1577 $delTable = $this->tableName( $delTable );
1578 $joinTable = $this->tableName( $joinTable );
1579 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
1580 if ( $conds != '*' ) {
1581 $sql .= 'WHERE ' . $this->makeList( $conds, self::LIST_AND );
1582 }
1583 $sql .= ')';
1584
1585 return $sql;
1586 }
1587
1588 /**
1589 * @param string $table The unqualified name of a table
1590 * @param string|array $conds
1591 * @return Query
1592 */
1593 public function deleteSqlText( $table, $conds ) {
1594 $isCondValid = ( is_string( $conds ) || is_array( $conds ) ) && $conds;
1595 if ( !$isCondValid ) {
1596 throw new DBLanguageError( __METHOD__ . ' called with empty conditions' );
1597 }
1598
1599 $encTable = $this->tableName( $table );
1600 $sql = "DELETE FROM $encTable";
1601
1602 $condsSql = '';
1603 $cleanCondsSql = '';
1604 if ( $conds !== self::ALL_ROWS && $conds !== [ self::ALL_ROWS ] ) {
1605 $cleanCondsSql = ' WHERE ' . $this->scrubArray( $conds );
1606 if ( is_array( $conds ) ) {
1607 $conds = $this->makeList( $conds, self::LIST_AND );
1608 }
1609 $condsSql .= ' WHERE ' . $conds;
1610 }
1611 return new Query(
1612 $sql . $condsSql,
1613 self::QUERY_CHANGE_ROWS,
1614 'DELETE',
1615 $table,
1616 $sql . $cleanCondsSql
1617 );
1618 }
1619
1620 private function scrubArray( $array, $listType = self::LIST_AND ) {
1621 if ( is_array( $array ) ) {
1622 $scrubbedArray = [];
1623 foreach ( $array as $key => $value ) {
1624 if ( $value instanceof IExpression ) {
1625 $scrubbedArray[$key] = $value->toGeneralizedSql();
1626 } else {
1627 $scrubbedArray[$key] = '?';
1628 }
1629 }
1630 return $this->makeList( $scrubbedArray, $listType );
1631 }
1632 return '?';
1633 }
1634
1635 public function updateSqlText( $table, $set, $conds, $options ) {
1636 $isCondValid = ( is_string( $conds ) || is_array( $conds ) ) && $conds;
1637 if ( !$isCondValid ) {
1638 throw new DBLanguageError( __METHOD__ . ' called with empty conditions' );
1639 }
1640 $encTable = $this->tableName( $table );
1641 $opts = $this->makeUpdateOptions( $options );
1642 $sql = "UPDATE $opts $encTable";
1643 $condsSql = " SET " . $this->makeList( $set, self::LIST_SET );
1644 $cleanCondsSql = " SET " . $this->scrubArray( $set, self::LIST_SET );
1645
1646 if ( $conds && $conds !== self::ALL_ROWS && $conds !== [ self::ALL_ROWS ] ) {
1647 $cleanCondsSql .= ' WHERE ' . $this->scrubArray( $conds );
1648 if ( is_array( $conds ) ) {
1649 $conds = $this->makeList( $conds, self::LIST_AND );
1650 }
1651 $condsSql .= ' WHERE ' . $conds;
1652 }
1653 return new Query(
1654 $sql . $condsSql,
1655 self::QUERY_CHANGE_ROWS,
1656 'UPDATE',
1657 $table,
1658 $sql . $cleanCondsSql
1659 );
1660 }
1661
1662 /**
1663 * Make UPDATE options for the Database::update function
1664 *
1665 * @param array $options The options passed to Database::update
1666 * @return string
1667 */
1668 protected function makeUpdateOptions( $options ) {
1669 $opts = $this->makeUpdateOptionsArray( $options );
1670
1671 return implode( ' ', $opts );
1672 }
1673
1674 /**
1675 * Make UPDATE options array for Database::makeUpdateOptions
1676 *
1677 * @stable to override
1678 * @param array $options
1679 * @return array
1680 */
1681 protected function makeUpdateOptionsArray( $options ) {
1682 $options = $this->normalizeOptions( $options );
1683
1684 $opts = [];
1685
1686 if ( in_array( 'IGNORE', $options ) ) {
1687 $opts[] = 'IGNORE';
1688 }
1689
1690 return $opts;
1691 }
1692
1693 /**
1694 * @param string|array $options
1695 * @return array Combination option/value map and boolean option list
1696 * @since 1.35, moved to SQLPlatform in 1.39
1697 */
1698 final public function normalizeOptions( $options ) {
1699 if ( is_array( $options ) ) {
1700 return $options;
1701 } elseif ( is_string( $options ) ) {
1702 return ( $options === '' ) ? [] : [ $options ];
1703 } else {
1704 throw new DBLanguageError( __METHOD__ . ': expected string or array' );
1705 }
1706 }
1707
1708 public function dropTableSqlText( $table ) {
1709 // https://mariadb.com/kb/en/drop-table/
1710 // https://dev.mysql.com/doc/refman/8.0/en/drop-table.html
1711 // https://www.postgresql.org/docs/9.2/sql-truncate.html
1712 return "DROP TABLE " . $this->tableName( $table ) . " CASCADE";
1713 }
1714
1715 /**
1716 * @param string $sql SQL query
1717 * @return string|null
1718 * @deprecated Since 1.42
1719 */
1720 public function getQueryVerb( $sql ) {
1721 wfDeprecated( __METHOD__, '1.42' );
1722 return QueryBuilderFromRawSql::buildQuery( $sql, 0 )->getVerb();
1723 }
1724
1725 /**
1726 * Determine whether a SQL statement is sensitive to isolation level.
1727 *
1728 * A SQL statement is considered transactable if its result could vary
1729 * depending on the transaction isolation level. Operational commands
1730 * such as 'SET' and 'SHOW' are not considered to be transactable.
1731 *
1732 * Main purpose: Used by query() to decide whether to begin a transaction
1733 * before the current query (in DBO_TRX mode, on by default).
1734 *
1735 * @return bool
1736 */
1737 public function isTransactableQuery( Query $sql ) {
1738 return !in_array(
1739 $sql->getVerb(),
1740 [
1741 'BEGIN',
1742 'ROLLBACK',
1743 'ROLLBACK TO SAVEPOINT',
1744 'COMMIT',
1745 'SET',
1746 'SHOW',
1747 'CREATE',
1748 'ALTER',
1749 'USE',
1750 'SHOW'
1751 ],
1752 true
1753 );
1754 }
1755
1756 public function buildExcludedValue( $column ) {
1757 /* @see Database::upsert() */
1758 // This can be treated like a single value since __VALS is a single row table
1759 return "(SELECT __$column FROM __VALS)";
1760 }
1761
1762 public function savepointSqlText( $identifier ) {
1763 return 'SAVEPOINT ' . $this->addIdentifierQuotes( $identifier );
1764 }
1765
1766 public function releaseSavepointSqlText( $identifier ) {
1767 return 'RELEASE SAVEPOINT ' . $this->addIdentifierQuotes( $identifier );
1768 }
1769
1770 public function rollbackToSavepointSqlText( $identifier ) {
1771 return 'ROLLBACK TO SAVEPOINT ' . $this->addIdentifierQuotes( $identifier );
1772 }
1773
1774 public function rollbackSqlText() {
1775 return 'ROLLBACK';
1776 }
1777
1778 public function dispatchingInsertSqlText( $table, $rows, $options ) {
1779 $rows = $this->normalizeRowArray( $rows );
1780 if ( !$rows ) {
1781 return false;
1782 }
1783
1784 $options = $this->normalizeOptions( $options );
1785 if ( $this->isFlagInOptions( 'IGNORE', $options ) ) {
1786 [ $sql, $cleanSql ] = $this->insertNonConflictingSqlText( $table, $rows );
1787 } else {
1788 [ $sql, $cleanSql ] = $this->insertSqlText( $table, $rows );
1789 }
1790 return new Query( $sql, self::QUERY_CHANGE_ROWS, 'INSERT', $table, $cleanSql );
1791 }
1792
1793 /**
1794 * @param array $rowOrRows A single (field => value) map or a list of such maps
1795 * @return array[] List of (field => value) maps
1796 * @since 1.35
1797 */
1798 final protected function normalizeRowArray( array $rowOrRows ) {
1799 if ( !$rowOrRows ) {
1800 $rows = [];
1801 } elseif ( isset( $rowOrRows[0] ) ) {
1802 $rows = $rowOrRows;
1803 } else {
1804 $rows = [ $rowOrRows ];
1805 }
1806
1807 foreach ( $rows as $row ) {
1808 if ( !is_array( $row ) ) {
1809 throw new DBLanguageError( "Got non-array in row array" );
1810 } elseif ( !$row ) {
1811 throw new DBLanguageError( "Got empty array in row array" );
1812 }
1813 }
1814
1815 return $rows;
1816 }
1817
1818 /**
1819 * Validate and normalize parameters to upsert() or replace()
1820 *
1821 * @param string|string[]|string[][] $uniqueKeys Unique indexes (only one is allowed)
1822 * @param array[] &$rows The row array, which will be replaced with a normalized version.
1823 * @return string[] List of columns that defines a single unique index
1824 * @since 1.35
1825 */
1826 final public function normalizeUpsertParams( $uniqueKeys, &$rows ) {
1827 $rows = $this->normalizeRowArray( $rows );
1828 if ( !$uniqueKeys ) {
1829 throw new DBLanguageError( 'No unique key specified for upsert/replace' );
1830 }
1831 $uniqueKey = $this->normalizeUpsertKeys( $uniqueKeys );
1832 $this->assertValidUpsertRowArray( $rows, $uniqueKey );
1833
1834 return $uniqueKey;
1835 }
1836
1837 /**
1838 * @param array|string $conds
1839 * @param string $fname
1840 * @return array
1841 * @since 1.31
1842 */
1843 final public function normalizeConditions( $conds, $fname ) {
1844 if ( $conds === null || $conds === false ) {
1845 $this->logger->warning(
1846 __METHOD__
1847 . ' called from '
1848 . $fname
1849 . ' with incorrect parameters: $conds must be a string or an array',
1850 [ 'db_log_category' => 'sql' ]
1851 );
1852 return [];
1853 } elseif ( $conds === '' ) {
1854 return [];
1855 }
1856
1857 return is_array( $conds ) ? $conds : [ $conds ];
1858 }
1859
1860 /**
1861 * @param string|string[]|string[][] $uniqueKeys Unique indexes (only one is allowed)
1862 * @return string[] List of columns that defines a single unique index
1863 * @since 1.35
1864 */
1865 private function normalizeUpsertKeys( $uniqueKeys ) {
1866 if ( is_string( $uniqueKeys ) ) {
1867 return [ $uniqueKeys ];
1868 } elseif ( !is_array( $uniqueKeys ) ) {
1869 throw new DBLanguageError( 'Invalid unique key array' );
1870 } else {
1871 if ( count( $uniqueKeys ) !== 1 || !isset( $uniqueKeys[0] ) ) {
1872 throw new DBLanguageError(
1873 "The unique key array should contain a single unique index" );
1874 }
1875
1876 $uniqueKey = $uniqueKeys[0];
1877 if ( is_string( $uniqueKey ) ) {
1878 // Passing a list of strings for single-column unique keys is too
1879 // easily confused with passing the columns of composite unique key
1880 $this->logger->warning( __METHOD__ .
1881 " called with deprecated parameter style: " .
1882 "the unique key array should be a string or array of string arrays",
1883 [
1884 'exception' => new RuntimeException(),
1885 'db_log_category' => 'sql',
1886 ] );
1887 return $uniqueKeys;
1888 } elseif ( is_array( $uniqueKey ) ) {
1889 return $uniqueKey;
1890 } else {
1891 throw new DBLanguageError( 'Invalid unique key array entry' );
1892 }
1893 }
1894 }
1895
1896 /**
1897 * @param array<int,array> $rows Normalized list of rows to insert
1898 * @param string[] $uniqueKey Columns of the unique key to UPSERT upon
1899 * @since 1.37
1900 */
1901 final protected function assertValidUpsertRowArray( array $rows, array $uniqueKey ) {
1902 foreach ( $rows as $row ) {
1903 foreach ( $uniqueKey as $column ) {
1904 if ( !isset( $row[$column] ) ) {
1905 throw new DBLanguageError(
1906 "NULL/absent values for unique key (" . implode( ',', $uniqueKey ) . ")"
1907 );
1908 }
1909 }
1910 }
1911 }
1912
1913 /**
1914 * @param array $set Combined column/literal assignment map and SQL assignment list
1915 * @param string[] $uniqueKey Columns of the unique key to UPSERT upon
1916 * @param array<int,array> $rows List of rows to upsert
1917 * @since 1.37
1918 */
1919 final public function assertValidUpsertSetArray(
1920 array $set,
1921 array $uniqueKey,
1922 array $rows
1923 ) {
1924 if ( !$set ) {
1925 throw new DBLanguageError( "Update assignment list can't be empty for upsert" );
1926 }
1927
1928 // Sloppy callers might construct the SET array using the ROW array, leaving redundant
1929 // column definitions for unique key columns. Detect this for backwards compatibility.
1930 $soleRow = ( count( $rows ) == 1 ) ? reset( $rows ) : null;
1931 // Disallow value changes for any columns in the unique key. This avoids additional
1932 // insertion order dependencies that are unwieldy and difficult to implement efficiently
1933 // in PostgreSQL.
1934 foreach ( $set as $k => $v ) {
1935 if ( is_string( $k ) ) {
1936 // Key is a column name and value is a literal (e.g. string, int, null, ...)
1937 if ( in_array( $k, $uniqueKey, true ) ) {
1938 if ( $soleRow && array_key_exists( $k, $soleRow ) && $soleRow[$k] === $v ) {
1939 $this->logger->warning(
1940 __METHOD__ . " called with redundant assignment to column '$k'",
1941 [
1942 'exception' => new RuntimeException(),
1943 'db_log_category' => 'sql',
1944 ]
1945 );
1946 } else {
1947 throw new DBLanguageError(
1948 "Cannot reassign column '$k' since it belongs to the provided unique key"
1949 );
1950 }
1951 }
1952 } elseif ( preg_match( '/^([a-zA-Z0-9_]+)\s*=/', $v, $m ) ) {
1953 // Value is of the form "<unquoted alphanumeric column> = <SQL expression>"
1954 if ( in_array( $m[1], $uniqueKey, true ) ) {
1955 throw new DBLanguageError(
1956 "Cannot reassign column '{$m[1]}' since it belongs to the provided unique key"
1957 );
1958 }
1959 }
1960 }
1961 }
1962
1963 /**
1964 * @param array|string $var Field parameter in the style of select()
1965 * @return string|null Column name or null; ignores aliases
1966 */
1967 final public function extractSingleFieldFromList( $var ) {
1968 if ( is_array( $var ) ) {
1969 if ( !$var ) {
1970 $column = null;
1971 } elseif ( count( $var ) == 1 ) {
1972 $column = $var[0] ?? reset( $var );
1973 } else {
1974 throw new DBLanguageError( __METHOD__ . ': got multiple columns' );
1975 }
1976 } else {
1977 $column = $var;
1978 }
1979
1980 return $column;
1981 }
1982
1983 public function setSchemaVars( $vars ) {
1984 $this->schemaVars = is_array( $vars ) ? $vars : null;
1985 }
1986
1987 /**
1988 * Get schema variables. If none have been set via setSchemaVars(), then
1989 * use some defaults from the current object.
1990 *
1991 * @return array
1992 */
1993 protected function getSchemaVars() {
1994 return $this->schemaVars ?? $this->getDefaultSchemaVars();
1995 }
1996
1997 /**
1998 * Get schema variables to use if none have been set via setSchemaVars().
1999 *
2000 * Override this in derived classes to provide variables for tables.sql
2001 * and SQL patch files.
2002 *
2003 * @stable to override
2004 * @return array
2005 */
2006 protected function getDefaultSchemaVars() {
2007 return [];
2008 }
2009
2010 /**
2011 * Database-independent variable replacement. Replaces a set of variables
2012 * in an SQL statement with their contents as given by $this->getSchemaVars().
2013 *
2014 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
2015 *
2016 * - '{$var}' should be used for text and is passed through the database's
2017 * addQuotes method.
2018 * - `{$var}` should be used for identifiers (e.g. table and database names).
2019 * It is passed through the database's addIdentifierQuotes method which
2020 * can be overridden if the database uses something other than backticks.
2021 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
2022 * database's tableName method.
2023 * - / *i* / passes the name that follows through the database's indexName method.
2024 * - In all other cases, / *$var* / is left unencoded. Except for table options,
2025 * its use should be avoided. In 1.24 and older, string encoding was applied.
2026 *
2027 * @param string $ins SQL statement to replace variables in
2028 * @return string The new SQL statement with variables replaced
2029 */
2030 public function replaceVars( $ins ) {
2031 $vars = $this->getSchemaVars();
2032 return preg_replace_callback(
2033 '!
2034 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
2035 \'\{\$ (\w+) }\' | # 3. addQuotes
2036 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
2037 /\*\$ (\w+) \*/ # 5. leave unencoded
2038 !x',
2039 function ( $m ) use ( $vars ) {
2040 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
2041 // check for both nonexistent keys *and* the empty string.
2042 if ( isset( $m[1] ) && $m[1] !== '' ) {
2043 if ( $m[1] === 'i' ) {
2044 return $this->indexName( $m[2] );
2045 } else {
2046 return $this->tableName( $m[2] );
2047 }
2048 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
2049 return $this->quoter->addQuotes( $vars[$m[3]] );
2050 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
2051 return $this->addIdentifierQuotes( $vars[$m[4]] );
2052 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
2053 return $vars[$m[5]];
2054 } else {
2055 return $m[0];
2056 }
2057 },
2058 $ins
2059 );
2060 }
2061
2062 public function lockSQLText( $lockName, $timeout ) {
2063 throw new RuntimeException( 'locking must be implemented in subclasses' );
2064 }
2065
2066 public function lockIsFreeSQLText( $lockName ) {
2067 throw new RuntimeException( 'locking must be implemented in subclasses' );
2068 }
2069
2070 public function unlockSQLText( $lockName ) {
2071 throw new RuntimeException( 'locking must be implemented in subclasses' );
2072 }
2073 }