22use InvalidArgumentException;
23use Psr\Log\LoggerInterface;
24use Psr\Log\NullLogger;
27use Wikimedia\Assert\Assert;
38use Wikimedia\Timestamp\ConvertibleTimestamp;
65 ?LoggerInterface
$logger =
null,
71 $this->logger =
$logger ??
new NullLogger();
73 $this->errorLogger =
$errorLogger ??
static function ( Throwable $e ) {
74 trigger_error( get_class( $e ) .
': ' . $e->getMessage(), E_USER_WARNING );
82 public function bitAnd( $fieldLeft, $fieldRight ) {
83 return "($fieldLeft & $fieldRight)";
86 public function bitOr( $fieldLeft, $fieldRight ) {
87 return "($fieldLeft | $fieldRight)";
91 if ( strcspn( $s,
"\0\"`'." ) !== strlen( $s ) ) {
93 "Identifier must not contain quote, dot or null characters: got '$s'"
97 return $quoteChar . $s . $quoteChar;
137 $fields = is_array( $fields ) ? $fields : [ $fields ];
138 $values = is_array( $values ) ? $values : [ $values ];
141 foreach ( $fields as $alias => $field ) {
142 if ( is_int( $alias ) ) {
145 $encValues[] = $field;
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 ) {
160 return $sqlfunc .
'(' . implode(
',', $encValues ) .
')';
164 if ( !in_array( $op, [
'>',
'>=',
'<',
'<=' ] ) ) {
165 throw new InvalidArgumentException(
"Comparison operator must be one of '>', '>=', '<', '<='" );
167 if ( count( $conds ) === 0 ) {
168 throw new InvalidArgumentException(
"Empty input" );
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?)'
199 $encValue = $this->quoter->addQuotes( $value );
201 $sql =
"$field $op $encValue";
203 $op = rtrim( $op,
'=' );
205 $sql =
"$field $op $encValue OR ($field = $encValue AND ($sql))";
211 public function makeList( array $a, $mode = self::LIST_COMMA ) {
216 foreach ( $a as $field => $value ) {
220 if ( $mode == self::LIST_AND ) {
222 } elseif ( $mode == self::LIST_OR ) {
229 if ( ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_numeric( $field ) ) {
231 $list .=
"(" . $value->toSql( $this->quoter ) .
")";
232 } elseif ( is_array( $value ) ) {
233 throw new InvalidArgumentException( __METHOD__ .
": unexpected array value without key" );
235 throw new InvalidArgumentException( __METHOD__ .
": unexpected raw value without key" );
240 if ( $mode == self::LIST_AND || $mode == self::LIST_OR ) {
241 throw new InvalidArgumentException( __METHOD__ .
": unexpected key $field for IExpression value" );
243 throw new InvalidArgumentException( __METHOD__ .
": unexpected IExpression outside WHERE clause" );
245 } elseif ( $mode == self::LIST_SET && is_numeric( $field ) ) {
248 ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_array( $value )
251 $includeNull =
false;
252 foreach ( array_keys( $value,
null,
true ) as $nullKey ) {
254 unset( $value[$nullKey] );
256 if ( count( $value ) == 0 && !$includeNull ) {
257 throw new InvalidArgumentException(
258 __METHOD__ .
": empty input for field $field" );
259 } elseif ( count( $value ) == 0 ) {
261 $list .=
"$field IS NULL";
264 if ( $includeNull ) {
268 if ( count( $value ) == 1 ) {
271 $list .= $field .
" = " . $this->makeList( $value );
273 $list .= $field .
" IN (" . $this->makeList( $value ) .
") ";
276 if ( $includeNull ) {
277 $list .=
" OR $field IS NULL)";
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 ) ) {
289 __METHOD__ .
": array key {key} in list of values ignored",
290 [
'key' => $field,
'exception' =>
new RuntimeException() ]
292 } elseif ( $mode === self::LIST_NAMES && !is_numeric( $field ) ) {
294 __METHOD__ .
": array key {key} in list of fields ignored",
295 [
'key' => $field,
'exception' =>
new RuntimeException() ]
301 $mode == self::LIST_AND || $mode == self::LIST_OR || $mode == self::LIST_SET
303 $list .=
"$field = ";
304 } elseif ( $mode === self::LIST_COMMA && !is_numeric( $field ) ) {
306 __METHOD__ .
": array key {key} in list of values ignored",
307 [
'key' => $field,
'exception' =>
new RuntimeException() ]
309 } elseif ( $mode === self::LIST_NAMES && !is_numeric( $field ) ) {
311 __METHOD__ .
": array key {key} in list of fields ignored",
312 [
'key' => $field,
'exception' =>
new RuntimeException() ]
315 $list .= $mode == self::LIST_NAMES ? $value : $this->quoter->addQuotes( $value );
322 $this->logger->warning( ...$keyWarning );
330 foreach ( $data as $base => $sub ) {
331 if ( count( $sub ) ) {
332 $conds[] = $this->makeList(
333 [ $baseKey => $base, $subKey => array_map(
'strval', array_keys( $sub ) ) ],
340 throw new InvalidArgumentException(
"Data for $baseKey and $subKey must be non-empty" );
343 return $this->makeList( $conds, self::LIST_OR );
347 if ( count( $condsArray ) === 0 ) {
348 throw new InvalidArgumentException(
349 __METHOD__ .
": empty condition array" );
351 $condsByFieldSet = [];
352 foreach ( $condsArray as $conds ) {
353 if ( !count( $conds ) ) {
354 throw new InvalidArgumentException(
355 __METHOD__ .
": empty condition subarray" );
357 $fieldKey = implode(
',', array_keys( $conds ) );
358 $condsByFieldSet[$fieldKey][] = $conds;
361 foreach ( $condsByFieldSet as $conds ) {
362 if ( $result !==
'' ) {
365 $result .= $this->factorCondsWithCommonFields( $conds );
377 private function factorCondsWithCommonFields( $condsArray ) {
378 $first = $condsArray[array_key_first( $condsArray )];
379 if ( count( $first ) === 1 ) {
381 $field = array_key_first( $first );
383 foreach ( $condsArray as $conds ) {
384 $values[] = $conds[$field];
386 return $this->makeList( [ $field => $values ], self::LIST_AND );
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;
398 $expressionsByField1[$value1][] = $conds;
404 foreach ( $expressionsByField1 as $value1 => $expressions ) {
405 if ( $result !==
'' ) {
409 $factored = $this->factorCondsWithCommonFields( $expressions );
410 $result .=
"($field1 = " . $this->quoter->addQuotes( $value1 ) .
413 if ( count( $nullExpressions ) ) {
414 $factored = $this->factorCondsWithCommonFields( $nullExpressions );
415 if ( $result !==
'' ) {
419 $result .=
"($field1 IS NULL AND $factored)";
433 return 'CONCAT(' . implode(
',', $stringList ) .
')';
437 if ( !is_numeric( $limit ) ) {
439 "Invalid non-numeric limit passed to " . __METHOD__
445 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," :
"" )
457 [ $escapeChar,
'%',
'_' ],
458 [
"{$escapeChar}{$escapeChar}",
"{$escapeChar}%",
"{$escapeChar}_" ],
464 if ( is_array( $param ) ) {
466 $param = array_shift(
$params );
470 return ' LIKE ' . $likeValue->toSql( $this->quoter );
490 $glue = $all ?
') UNION ALL (' :
') UNION (';
492 $sql =
'(' . implode( $glue, $sqls ) .
')';
493 if ( !$this->unionSupportsOrderAndLimit() ) {
496 $sql .= $this->makeOrderBy( $options );
497 $limit = $options[
'LIMIT'] ??
null;
498 $offset = $options[
'OFFSET'] ??
false;
499 if ( $limit !==
null ) {
500 $sql = $this->limitResult( $sql, $limit, $offset );
506 public function conditional( $cond, $caseTrueExpression, $caseFalseExpression ) {
507 if ( is_array( $cond ) ) {
508 $cond = $this->makeList( $cond, self::LIST_AND );
511 $cond = $cond->toSql( $this->quoter );
514 return "(CASE WHEN $cond THEN $caseTrueExpression ELSE $caseFalseExpression END)";
518 return "REPLACE({$orig}, {$old}, {$new})";
522 $t =
new ConvertibleTimestamp( $ts );
524 return $t->getTimestamp( TS_MW );
528 if ( $ts ===
null ) {
531 return $this->timestamp( $ts );
540 return ( $expiry ==
'' || $expiry ==
'infinity' || $expiry == $this->getInfinity() )
541 ? $this->getInfinity()
542 : $this->timestamp( $expiry );
546 if ( $expiry ==
'' || $expiry ==
'infinity' || $expiry == $this->getInfinity() ) {
550 return ConvertibleTimestamp::convert( $format, $expiry );
558 $this->assertBuildSubstringParams( $startPosition, $length );
559 $functionBody =
"$input FROM $startPosition";
560 if ( $length !==
null ) {
561 $functionBody .=
" FOR $length";
563 return 'SUBSTRING(' . $functionBody .
')';
579 if ( $startPosition === 0 ) {
581 throw new InvalidArgumentException(
'Use 1 as $startPosition for the beginning of the string' );
583 if ( !is_int( $startPosition ) || $startPosition < 0 ) {
584 throw new InvalidArgumentException(
585 '$startPosition must be a positive integer'
588 if ( !( ( is_int( $length ) && $length >= 0 ) || $length ===
null ) ) {
589 throw new InvalidArgumentException(
590 '$length must be null or an integer greater than or equal to 0'
598 return "CAST( $field AS CHARACTER )";
602 return 'CAST( ' . $field .
' AS INTEGER )';
618 return $this->indexAliases[$index] ?? $index;
622 $this->tableAliases = $aliases;
626 $this->indexAliases = $aliases;
633 return $this->tableAliases;
638 $this->currentDomain->getDatabase(),
639 $this->currentDomain->getSchema(),
645 $this->currentDomain = $currentDomain;
653 return $this->currentDomain;
657 $tables, $vars, $conds =
'', $fname = __METHOD__, $options = [], $join_conds = []
659 if ( !is_array( $tables ) ) {
660 if ( $tables ===
'' || $tables ===
null || $tables ===
false ) {
662 } elseif ( is_string( $tables ) ) {
663 $tables = [ $tables ];
665 throw new DBLanguageError( __METHOD__ .
' called with incorrect table parameter' );
669 if ( is_array( $vars ) ) {
670 $fields = implode(
',', $this->fieldNamesWithAlias( $vars ) );
675 $options = (array)$options;
677 $useIndexByTable = $options[
'USE INDEX'] ?? [];
678 if ( !is_array( $useIndexByTable ) ) {
679 if ( count( $tables ) <= 1 ) {
680 $useIndexByTable = [ reset( $tables ) => $useIndexByTable ];
682 $e =
new DBLanguageError( __METHOD__ .
" got ambiguous USE INDEX ($fname)" );
683 ( $this->errorLogger )( $e );
687 $ignoreIndexByTable = $options[
'IGNORE INDEX'] ?? [];
688 if ( !is_array( $ignoreIndexByTable ) ) {
689 if ( count( $tables ) <= 1 ) {
690 $ignoreIndexByTable = [ reset( $tables ) => $ignoreIndexByTable ];
692 $e =
new DBLanguageError( __METHOD__ .
" got ambiguous IGNORE INDEX ($fname)" );
693 ( $this->errorLogger )( $e );
698 $this->selectOptionsIncludeLocking( $options ) &&
699 $this->selectFieldsOrOptionsAggregate( $vars, $options )
703 $this->logger->warning(
704 __METHOD__ .
": aggregation used with a locking SELECT ($fname)"
708 if ( count( $tables ) ) {
709 $from =
' FROM ' . $this->tableNamesWithIndexClauseOrJOIN(
719 [ $startOpts, $preLimitTail, $postLimitTail ] = $this->makeSelectOptions( $options );
721 if ( is_array( $conds ) ) {
722 $where = $this->makeList( $conds, self::LIST_AND );
724 $where = $conds->toSql( $this->quoter );
725 } elseif ( $conds ===
null || $conds ===
false ) {
727 $this->logger->warning(
731 .
' with incorrect parameters: $conds must be a string or an array',
732 [
'db_log_category' =>
'sql' ]
734 } elseif ( is_string( $conds ) ) {
737 throw new DBLanguageError( __METHOD__ .
' called with incorrect parameters' );
741 if ( $where ===
'' || $where ===
'*' ) {
742 $sql =
"SELECT $startOpts $fields $from $preLimitTail";
744 $sql =
"SELECT $startOpts $fields $from WHERE $where $preLimitTail";
747 if ( isset( $options[
'LIMIT'] ) ) {
748 $sql = $this->limitResult( $sql, $options[
'LIMIT'], $options[
'OFFSET'] ??
false );
750 $sql =
"$sql $postLimitTail";
752 if ( isset( $options[
'EXPLAIN'] ) ) {
753 $sql =
'EXPLAIN ' . $sql;
757 $fname === static::CALLER_UNKNOWN ||
758 str_starts_with( $fname,
'Wikimedia\\Rdbms\\' ) ||
759 $fname ===
'{closure}'
761 $exception =
new RuntimeException();
765 foreach ( $exception->getTrace() as $call ) {
766 if ( str_ends_with( $call[
'file'] ??
'',
'Test.php' ) ) {
769 } elseif ( str_starts_with( $call[
'class'] ??
'',
'Wikimedia\\Rdbms\\' ) ) {
771 } elseif ( str_ends_with( $call[
'class'] ??
'',
'SelectQueryBuilder' ) ) {
775 $caller = implode(
'::', array_filter( [ $call[
'class'] ??
null, $call[
'function'] ] ) );
780 if ( $fname ===
'{closure}' ) {
786 $warning =
"SQL query with incorrect caller (__METHOD__ used inside a closure: {caller}): {sql}";
788 $warning =
"SQL query did not specify the caller (guessed caller: {caller}): {sql}";
791 $this->logger->warning(
793 [
'sql' => $sql,
'caller' => $caller,
'exception' => $exception ]
804 private function selectOptionsIncludeLocking( $options ) {
805 $options = (array)$options;
806 foreach ( [
'FOR UPDATE',
'LOCK IN SHARE MODE' ] as $lock ) {
807 if ( in_array( $lock, $options,
true ) ) {
820 private function selectFieldsOrOptionsAggregate( $fields, $options ) {
821 foreach ( (array)$options as $key => $value ) {
822 if ( is_string( $key ) ) {
823 if ( preg_match(
'/^(?:GROUP BY|HAVING)$/i', $key ) ) {
826 } elseif ( is_string( $value ) ) {
827 if ( preg_match(
'/^(?:DISTINCT|DISTINCTROW)$/i', $value ) ) {
833 $regex =
'/^(?:COUNT|MIN|MAX|SUM|GROUP_CONCAT|LISTAGG|ARRAY_AGG)\s*\\(/i';
834 foreach ( (array)$fields as $field ) {
835 if ( is_string( $field ) && preg_match( $regex, $field ) ) {
851 foreach ( $fields as $alias => $field ) {
852 if ( is_numeric( $alias ) ) {
855 $retval[] = $this->fieldNameWithAlias( $field, $alias );
871 if ( !$alias || (
string)$alias === (
string)$name ) {
874 return $name .
' AS ' . $this->addIdentifierQuotes( $alias );
896 $use_index = (array)$use_index;
897 $ignore_index = (array)$ignore_index;
898 $join_conds = (array)$join_conds;
900 foreach ( $tables as $alias => $table ) {
901 if ( !is_string( $alias ) ) {
906 if ( is_array( $table ) ) {
908 if ( count( $table ) > 1 ) {
910 $this->tableNamesWithIndexClauseOrJOIN(
911 $table, $use_index, $ignore_index, $join_conds ) .
')';
914 $innerTable = reset( $table );
915 $innerAlias = key( $table );
916 $joinedTable = $this->tableNameWithAlias(
918 is_string( $innerAlias ) ? $innerAlias : $innerTable
922 $joinedTable = $this->tableNameWithAlias( $table, $alias );
926 if ( isset( $join_conds[$alias] ) ) {
927 Assert::parameterType(
'array', $join_conds[$alias],
"join_conds[$alias]" );
928 [ $joinType, $conds ] = $join_conds[$alias];
929 $tableClause = $this->normalizeJoinType( $joinType );
930 $tableClause .=
' ' . $joinedTable;
931 if ( isset( $use_index[$alias] ) ) {
932 $use = $this->useIndexClause( implode(
',', (array)$use_index[$alias] ) );
934 $tableClause .=
' ' . $use;
937 if ( isset( $ignore_index[$alias] ) ) {
938 $ignore = $this->ignoreIndexClause(
939 implode(
',', (array)$ignore_index[$alias] ) );
940 if ( $ignore !=
'' ) {
941 $tableClause .=
' ' . $ignore;
944 $on = $this->makeList( (array)$conds, self::LIST_AND );
946 $tableClause .=
' ON (' . $on .
')';
949 $retJOIN[] = $tableClause;
950 } elseif ( isset( $use_index[$alias] ) ) {
952 $tableClause = $joinedTable;
953 $tableClause .=
' ' . $this->useIndexClause(
954 implode(
',', (array)$use_index[$alias] )
957 $ret[] = $tableClause;
958 } elseif ( isset( $ignore_index[$alias] ) ) {
960 $tableClause = $joinedTable;
961 $tableClause .=
' ' . $this->ignoreIndexClause(
962 implode(
',', (array)$ignore_index[$alias] )
965 $ret[] = $tableClause;
967 $tableClause = $joinedTable;
969 $ret[] = $tableClause;
974 $implicitJoins = implode(
',', $ret );
975 $explicitJoins = implode(
' ', $retJOIN );
978 return implode(
' ', [ $implicitJoins, $explicitJoins ] );
990 switch ( strtoupper( $joinType ) ) {
998 case 'STRAIGHT_JOIN':
999 case 'STRAIGHT JOIN':
1020 if ( is_string( $table ) ) {
1021 $quotedTable = $this->tableName( $table );
1022 } elseif ( $table instanceof
Subquery ) {
1023 $quotedTable = (string)$table;
1025 throw new InvalidArgumentException(
"Table must be a string or Subquery" );
1028 if ( $alias ===
false ) {
1029 if ( $table instanceof
Subquery ) {
1030 throw new InvalidArgumentException(
"Subquery table missing alias" );
1032 $quotedTableWithAnyAlias = $quotedTable;
1034 $alias === $table &&
1036 str_contains( $alias,
'.' ) ||
1037 $this->tableName( $alias,
'raw' ) === $table
1040 $quotedTableWithAnyAlias = $quotedTable;
1042 $quotedTableWithAnyAlias = $quotedTable .
' ' . $this->addIdentifierQuotes( $alias );
1045 return $quotedTableWithAnyAlias;
1048 public function tableName(
string $name, $format =
'quoted' ) {
1049 $prefix = $this->currentDomain->getTablePrefix();
1054 str_contains( $name,
'.' ) &&
1055 !preg_match(
'/^information_schema\.[a-z_0-9]+$/', $name )
1057 ( $prefix !==
'' && str_starts_with( $name, $prefix ) )
1059 $this->logger->warning(
1060 __METHOD__ .
' called with qualified table ' . $name,
1061 [
'db_log_category' =>
'sql' ]
1066 $formattedComponents = [];
1067 foreach ( $this->qualifiedTableComponents( $name ) as $component ) {
1068 if ( $format ===
'quoted' ) {
1069 $formattedComponents[] = $this->addIdentifierQuotes( $component );
1071 $formattedComponents[] = $component;
1075 return implode(
'.', $formattedComponents );
1101 $identifiers = $this->extractTableNameComponents( $name );
1102 if ( count( $identifiers ) > 3 ) {
1103 throw new DBLanguageError(
"Too many components in table name '$name'" );
1106 if ( count( $identifiers ) == 1 && !$this->isQuotedIdentifier( $identifiers[0] ) ) {
1107 [ $table ] = $identifiers;
1108 if ( isset( $this->tableAliases[$table] ) ) {
1110 $database = $this->tableAliases[$table][
'dbname'];
1111 $schema = is_string( $this->tableAliases[$table][
'schema'] )
1112 ? $this->tableAliases[$table][
'schema']
1113 : $this->relationSchemaQualifier();
1114 $prefix = is_string( $this->tableAliases[$table][
'prefix'] )
1115 ? $this->tableAliases[$table][
'prefix']
1116 : $this->currentDomain->getTablePrefix();
1120 $schema = $this->relationSchemaQualifier();
1121 $prefix = $this->currentDomain->getTablePrefix();
1123 $qualifierIdentifiers = [ $database, $schema ];
1124 $tableIdentifier = $prefix . $table;
1126 $qualifierIdentifiers = array_slice( $identifiers, 0, -1 );
1127 $tableIdentifier = end( $identifiers );
1131 foreach ( $qualifierIdentifiers as $identifier ) {
1132 if ( $identifier !==
null && $identifier !==
'' ) {
1133 $components[] = $this->isQuotedIdentifier( $identifier )
1134 ? substr( $identifier, 1, -1 )
1138 $components[] = $this->isQuotedIdentifier( $tableIdentifier )
1139 ? substr( $tableIdentifier, 1, -1 )
1152 $quoteChar = $this->getIdentifierQuoteChar();
1154 foreach ( explode(
'.', $name ) as $component ) {
1155 if ( $this->isQuotedIdentifier( $component ) ) {
1156 $unquotedComponent = substr( $component, 1, -1 );
1158 $unquotedComponent = $component;
1160 if ( str_contains( $unquotedComponent, $quoteChar ) ) {
1162 'Table name component contains unexpected quote or dot character' );
1164 $components[] = $component;
1195 $components = $this->qualifiedTableComponents( $table );
1196 switch ( count( $components ) ) {
1198 return [ $this->currentDomain->getDatabase(), $components[0] ];
1211 return $this->currentDomain->getSchema();
1217 foreach ( $tables as $name ) {
1218 $retVal[] = $this->tableName( $name );
1234 $quoteChar = $this->getIdentifierQuoteChar();
1235 return strlen( $name ) > 1 && $name[0] === $quoteChar && $name[-1] === $quoteChar;
1279 $preLimitTail = $postLimitTail =
'';
1284 foreach ( $options as $key => $option ) {
1285 if ( is_numeric( $key ) ) {
1286 $noKeyOptions[$option] =
true;
1290 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1292 $preLimitTail .= $this->makeOrderBy( $options );
1294 if ( isset( $noKeyOptions[
'FOR UPDATE'] ) ) {
1295 $postLimitTail .=
' FOR UPDATE';
1298 if ( isset( $noKeyOptions[
'LOCK IN SHARE MODE'] ) ) {
1299 $postLimitTail .=
' LOCK IN SHARE MODE';
1302 if ( isset( $noKeyOptions[
'DISTINCT'] ) || isset( $noKeyOptions[
'DISTINCTROW'] ) ) {
1303 $startOpts .=
'DISTINCT';
1306 # Various MySQL extensions
1307 if ( isset( $noKeyOptions[
'STRAIGHT_JOIN'] ) ) {
1308 $startOpts .=
' /*! STRAIGHT_JOIN */';
1311 if ( isset( $noKeyOptions[
'SQL_BIG_RESULT'] ) ) {
1312 $startOpts .=
' SQL_BIG_RESULT';
1315 if ( isset( $noKeyOptions[
'SQL_BUFFER_RESULT'] ) ) {
1316 $startOpts .=
' SQL_BUFFER_RESULT';
1319 if ( isset( $noKeyOptions[
'SQL_SMALL_RESULT'] ) ) {
1320 $startOpts .=
' SQL_SMALL_RESULT';
1323 if ( isset( $noKeyOptions[
'SQL_CALC_FOUND_ROWS'] ) ) {
1324 $startOpts .=
' SQL_CALC_FOUND_ROWS';
1327 return [ $startOpts, $preLimitTail, $postLimitTail ];
1340 if ( isset( $options[
'GROUP BY'] ) ) {
1341 $gb = is_array( $options[
'GROUP BY'] )
1342 ? implode(
',', $options[
'GROUP BY'] )
1343 : $options[
'GROUP BY'];
1344 $sql .=
' GROUP BY ' . $gb;
1346 if ( isset( $options[
'HAVING'] ) ) {
1347 $having = is_array( $options[
'HAVING'] )
1348 ? $this->makeList( $options[
'HAVING'], self::LIST_AND )
1349 : $options[
'HAVING'];
1350 $sql .=
' HAVING ' . $having;
1365 if ( isset( $options[
'ORDER BY'] ) ) {
1366 $ob = is_array( $options[
'ORDER BY'] )
1367 ? implode(
',', $options[
'ORDER BY'] )
1368 : $options[
'ORDER BY'];
1370 return ' ORDER BY ' . $ob;
1377 $delim, $tables, $field, $conds =
'', $join_conds = []
1379 $fld =
"GROUP_CONCAT($field SEPARATOR " . $this->quoter->addQuotes( $delim ) .
')';
1381 return '(' . $this->selectSQLText( $tables, $fld, $conds, static::CALLER_SUBQUERY, [], $join_conds ) .
')';
1385 $tables, $vars, $conds =
'', $fname = __METHOD__,
1386 $options = [], $join_conds = []
1389 $this->selectSQLText( $tables, $vars, $conds, $fname, $options, $join_conds )
1394 $encTable = $this->tableName( $table );
1395 [ $sqlColumns, $sqlTuples ] = $this->makeInsertLists( $rows );
1398 "INSERT INTO $encTable ($sqlColumns) VALUES $sqlTuples",
1399 "INSERT INTO $encTable ($sqlColumns) VALUES '?'"
1415 public function makeInsertLists( array $rows, $aliasPrefix =
'', array $typeByColumn = [] ) {
1416 $firstRow = $rows[0];
1417 if ( !is_array( $firstRow ) || !$firstRow ) {
1421 $tupleColumns = array_keys( $firstRow );
1424 foreach ( $rows as $row ) {
1425 $rowColumns = array_keys( $row );
1427 if ( $rowColumns !== $tupleColumns ) {
1429 'Got row columns (' . implode(
', ', $rowColumns ) .
') ' .
1430 'instead of expected (' . implode(
', ', $tupleColumns ) .
')'
1434 $valueTuples[] =
'(' . $this->makeList( array_values( $row ), self::LIST_COMMA ) .
')';
1437 $magicAliasFields = [];
1438 foreach ( $tupleColumns as $column ) {
1439 $magicAliasFields[] = $aliasPrefix . $column;
1443 $this->makeList( $tupleColumns, self::LIST_NAMES ),
1444 implode(
',', $valueTuples ),
1445 $this->makeList( $magicAliasFields, self::LIST_NAMES )
1450 $encTable = $this->tableName( $table );
1451 [ $sqlColumns, $sqlTuples ] = $this->makeInsertLists( $rows );
1452 [ $sqlVerb, $sqlOpts ] = $this->makeInsertNonConflictingVerbAndOptions();
1455 rtrim(
"$sqlVerb $encTable ($sqlColumns) VALUES $sqlTuples $sqlOpts" ),
1456 rtrim(
"$sqlVerb $encTable ($sqlColumns) VALUES '?' $sqlOpts" )
1466 return [
'INSERT IGNORE INTO',
'' ];
1475 array $insertOptions,
1476 array $selectOptions,
1479 [ $sqlVerb, $sqlOpts ] = $this->isFlagInOptions(
'IGNORE', $insertOptions )
1480 ? $this->makeInsertNonConflictingVerbAndOptions()
1481 : [
'INSERT INTO',
'' ];
1482 $encDstTable = $this->tableName( $destTable );
1483 $sqlDstColumns = implode(
',', array_keys( $varMap ) );
1484 $selectSql = $this->selectSQLText(
1486 array_values( $varMap ),
1493 return rtrim(
"$sqlVerb $encDstTable ($sqlDstColumns) $selectSql $sqlOpts" );
1503 foreach ( array_keys( $options, $option,
true ) as $k ) {
1504 if ( is_int( $k ) ) {
1522 } elseif ( !$uniqueKey ) {
1526 if ( count( $uniqueKey ) == 1 ) {
1528 $column = reset( $uniqueKey );
1529 $values = array_column( $rows, $column );
1530 if ( count( $values ) !== count( $rows ) ) {
1531 throw new DBLanguageError(
"Missing values for unique key ($column)" );
1534 return $this->makeList( [ $column => $values ], self::LIST_AND );
1537 $nullByUniqueKeyColumn = array_fill_keys( $uniqueKey,
null );
1540 foreach ( $rows as $row ) {
1541 $rowKeyMap = array_intersect_key( $row, $nullByUniqueKeyColumn );
1542 if ( count( $rowKeyMap ) != count( $uniqueKey ) ) {
1544 "Missing values for unique key (" . implode(
',', $uniqueKey ) .
")"
1547 $orConds[] = $this->makeList( $rowKeyMap, self::LIST_AND );
1550 return count( $orConds ) > 1
1551 ? $this->makeList( $orConds, self::LIST_OR )
1557 throw new DBLanguageError( __METHOD__ .
' called with empty $conds' );
1560 $delTable = $this->tableName( $delTable );
1561 $joinTable = $this->tableName( $joinTable );
1562 $sql =
"DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
1563 if ( $conds !=
'*' ) {
1564 $sql .=
'WHERE ' . $this->makeList( $conds, self::LIST_AND );
1577 $isCondValid = ( is_string( $conds ) || is_array( $conds ) ) && $conds;
1578 if ( !$isCondValid ) {
1579 throw new DBLanguageError( __METHOD__ .
' called with empty conditions' );
1582 $encTable = $this->tableName( $table );
1583 $sql =
"DELETE FROM $encTable";
1586 $cleanCondsSql =
'';
1587 if ( $conds !== self::ALL_ROWS && $conds !== [ self::ALL_ROWS ] ) {
1588 $cleanCondsSql =
' WHERE ' . $this->scrubArray( $conds );
1589 if ( is_array( $conds ) ) {
1590 $conds = $this->makeList( $conds, self::LIST_AND );
1592 $condsSql .=
' WHERE ' . $conds;
1596 self::QUERY_CHANGE_ROWS,
1599 $sql . $cleanCondsSql
1603 private function scrubArray( $array, $listType = self::LIST_AND ) {
1604 if ( is_array( $array ) ) {
1605 $scrubbedArray = [];
1606 foreach ( $array as $key => $value ) {
1608 $scrubbedArray[$key] = $value->toGeneralizedSql();
1610 $scrubbedArray[$key] =
'?';
1613 return $this->makeList( $scrubbedArray, $listType );
1619 $isCondValid = ( is_string( $conds ) || is_array( $conds ) ) && $conds;
1620 if ( !$isCondValid ) {
1621 throw new DBLanguageError( __METHOD__ .
' called with empty conditions' );
1623 $encTable = $this->tableName( $table );
1624 $opts = $this->makeUpdateOptions( $options );
1625 $sql =
"UPDATE $opts $encTable";
1626 $condsSql =
" SET " . $this->makeList( $set, self::LIST_SET );
1627 $cleanCondsSql =
" SET " . $this->scrubArray( $set, self::LIST_SET );
1629 if ( $conds && $conds !== self::ALL_ROWS && $conds !== [ self::ALL_ROWS ] ) {
1630 $cleanCondsSql .=
' WHERE ' . $this->scrubArray( $conds );
1631 if ( is_array( $conds ) ) {
1632 $conds = $this->makeList( $conds, self::LIST_AND );
1634 $condsSql .=
' WHERE ' . $conds;
1638 self::QUERY_CHANGE_ROWS,
1641 $sql . $cleanCondsSql
1652 $opts = $this->makeUpdateOptionsArray( $options );
1654 return implode(
' ', $opts );
1665 $options = $this->normalizeOptions( $options );
1669 if ( in_array(
'IGNORE', $options ) ) {
1682 if ( is_array( $options ) ) {
1684 } elseif ( is_string( $options ) ) {
1685 return ( $options ===
'' ) ? [] : [ $options ];
1687 throw new DBLanguageError( __METHOD__ .
': expected string or array' );
1695 return "DROP TABLE " . $this->tableName( $table ) .
" CASCADE";
1726 'ROLLBACK TO SAVEPOINT',
1742 return "(SELECT __$column FROM __VALS)";
1746 return 'SAVEPOINT ' . $this->addIdentifierQuotes( $identifier );
1750 return 'RELEASE SAVEPOINT ' . $this->addIdentifierQuotes( $identifier );
1754 return 'ROLLBACK TO SAVEPOINT ' . $this->addIdentifierQuotes( $identifier );
1762 $rows = $this->normalizeRowArray( $rows );
1767 $options = $this->normalizeOptions( $options );
1768 if ( $this->isFlagInOptions(
'IGNORE', $options ) ) {
1769 [ $sql, $cleanSql ] = $this->insertNonConflictingSqlText( $table, $rows );
1771 [ $sql, $cleanSql ] = $this->insertSqlText( $table, $rows );
1773 return new Query( $sql, self::QUERY_CHANGE_ROWS,
'INSERT', $table, $cleanSql );
1782 if ( !$rowOrRows ) {
1784 } elseif ( isset( $rowOrRows[0] ) ) {
1787 $rows = [ $rowOrRows ];
1790 foreach ( $rows as $row ) {
1791 if ( !is_array( $row ) ) {
1793 } elseif ( !$row ) {
1810 $rows = $this->normalizeRowArray( $rows );
1811 if ( !$uniqueKeys ) {
1812 throw new DBLanguageError(
'No unique key specified for upsert/replace' );
1814 $uniqueKey = $this->normalizeUpsertKeys( $uniqueKeys );
1815 $this->assertValidUpsertRowArray( $rows, $uniqueKey );
1827 if ( $conds ===
null || $conds ===
false ) {
1828 $this->logger->warning(
1832 .
' with incorrect parameters: $conds must be a string or an array',
1833 [
'db_log_category' =>
'sql' ]
1836 } elseif ( $conds ===
'' ) {
1840 return is_array( $conds ) ? $conds : [ $conds ];
1848 private function normalizeUpsertKeys( $uniqueKeys ) {
1849 if ( is_string( $uniqueKeys ) ) {
1850 return [ $uniqueKeys ];
1851 } elseif ( !is_array( $uniqueKeys ) ) {
1854 if ( count( $uniqueKeys ) !== 1 || !isset( $uniqueKeys[0] ) ) {
1855 throw new DBLanguageError(
1856 "The unique key array should contain a single unique index" );
1859 $uniqueKey = $uniqueKeys[0];
1860 if ( is_string( $uniqueKey ) ) {
1863 $this->logger->warning( __METHOD__ .
1864 " called with deprecated parameter style: " .
1865 "the unique key array should be a string or array of string arrays",
1867 'exception' =>
new RuntimeException(),
1868 'db_log_category' =>
'sql',
1871 } elseif ( is_array( $uniqueKey ) ) {
1874 throw new DBLanguageError(
'Invalid unique key array entry' );
1885 foreach ( $rows as $row ) {
1886 foreach ( $uniqueKey as $column ) {
1887 if ( !isset( $row[$column] ) ) {
1889 "NULL/absent values for unique key (" . implode(
',', $uniqueKey ) .
")"
1908 throw new DBLanguageError(
"Update assignment list can't be empty for upsert" );
1913 $soleRow = ( count( $rows ) == 1 ) ? reset( $rows ) :
null;
1917 foreach ( $set as $k => $v ) {
1918 if ( is_string( $k ) ) {
1920 if ( in_array( $k, $uniqueKey,
true ) ) {
1921 if ( $soleRow && array_key_exists( $k, $soleRow ) && $soleRow[$k] === $v ) {
1922 $this->logger->warning(
1923 __METHOD__ .
" called with redundant assignment to column '$k'",
1925 'exception' =>
new RuntimeException(),
1926 'db_log_category' =>
'sql',
1931 "Cannot reassign column '$k' since it belongs to the provided unique key"
1935 } elseif ( preg_match(
'/^([a-zA-Z0-9_]+)\s*=/', $v, $m ) ) {
1937 if ( in_array( $m[1], $uniqueKey,
true ) ) {
1939 "Cannot reassign column '{$m[1]}' since it belongs to the provided unique key"
1951 if ( is_array( $var ) ) {
1954 } elseif ( count( $var ) == 1 ) {
1955 $column = $var[0] ?? reset( $var );
1967 $this->schemaVars = is_array( $vars ) ? $vars :
null;
1977 return $this->schemaVars ?? $this->getDefaultSchemaVars();
2014 $vars = $this->getSchemaVars();
2015 return preg_replace_callback(
2017 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
2018 \'\{\$ (\w+) }\' | # 3. addQuotes
2019 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
2020 /\*\$ (\w+) \*/ # 5. leave unencoded
2022 function ( $m ) use ( $vars ) {
2025 if ( isset( $m[1] ) && $m[1] !==
'' ) {
2026 if ( $m[1] ===
'i' ) {
2027 return $this->indexName( $m[2] );
2029 return $this->tableName( $m[2] );
2031 } elseif ( isset( $m[3] ) && $m[3] !==
'' && array_key_exists( $m[3], $vars ) ) {
2032 return $this->quoter->addQuotes( $vars[$m[3]] );
2033 } elseif ( isset( $m[4] ) && $m[4] !==
'' && array_key_exists( $m[4], $vars ) ) {
2034 return $this->addIdentifierQuotes( $vars[$m[4]] );
2035 } elseif ( isset( $m[5] ) && $m[5] !==
'' && array_key_exists( $m[5], $vars ) ) {
2036 return $vars[$m[5]];
2046 throw new RuntimeException(
'locking must be implemented in subclasses' );
2050 throw new RuntimeException(
'locking must be implemented in subclasses' );
2054 throw new RuntimeException(
'locking must be implemented in subclasses' );
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
array $params
The job parameters.
if(!defined('MW_SETUP_CALLBACK'))
Class to handle database/schema/prefix specifications for IDatabase.