22use InvalidArgumentException;
23use Psr\Log\LoggerInterface;
24use Psr\Log\NullLogger;
27use Wikimedia\Assert\Assert;
38use Wikimedia\Timestamp\ConvertibleTimestamp;
62 ?LoggerInterface
$logger =
null,
67 $this->logger =
$logger ??
new NullLogger();
69 $this->errorLogger =
$errorLogger ??
static function ( Throwable $e ) {
70 trigger_error( get_class( $e ) .
': ' . $e->getMessage(), E_USER_WARNING );
78 public function bitAnd( $fieldLeft, $fieldRight ) {
79 return "($fieldLeft & $fieldRight)";
82 public function bitOr( $fieldLeft, $fieldRight ) {
83 return "($fieldLeft | $fieldRight)";
87 if ( strcspn( $s,
"\0\"`'." ) !== strlen( $s ) ) {
89 "Identifier must not contain quote, dot or null characters: got '$s'"
93 return $quoteChar . $s . $quoteChar;
133 $fields = is_array( $fields ) ? $fields : [ $fields ];
134 $values = is_array( $values ) ? $values : [ $values ];
137 foreach ( $fields as $alias => $field ) {
138 if ( is_int( $alias ) ) {
141 $encValues[] = $field;
144 foreach ( $values as $value ) {
145 if ( is_int( $value ) || is_float( $value ) ) {
146 $encValues[] = $value;
147 } elseif ( is_string( $value ) ) {
148 $encValues[] = $this->quoter->addQuotes( $value );
149 } elseif ( $value ===
null ) {
156 return $sqlfunc .
'(' . implode(
',', $encValues ) .
')';
160 if ( !in_array( $op, [
'>',
'>=',
'<',
'<=' ] ) ) {
161 throw new InvalidArgumentException(
"Comparison operator must be one of '>', '>=', '<', '<='" );
163 if ( count( $conds ) === 0 ) {
164 throw new InvalidArgumentException(
"Empty input" );
189 foreach ( array_reverse( $conds ) as $field => $value ) {
190 if ( is_int( $field ) ) {
191 throw new InvalidArgumentException(
192 'Non-associative array passed to buildComparison() (typo?)'
195 $encValue = $this->quoter->addQuotes( $value );
197 $sql =
"$field $op $encValue";
199 $op = rtrim( $op,
'=' );
201 $sql =
"$field $op $encValue OR ($field = $encValue AND ($sql))";
207 public function makeList( array $a, $mode = self::LIST_COMMA ) {
212 foreach ( $a as $field => $value ) {
216 if ( $mode == self::LIST_AND ) {
218 } elseif ( $mode == self::LIST_OR ) {
225 if ( ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_numeric( $field ) ) {
227 $list .=
"(" . $value->toSql( $this->quoter ) .
")";
228 } elseif ( is_array( $value ) ) {
229 throw new InvalidArgumentException( __METHOD__ .
": unexpected array value without key" );
231 throw new InvalidArgumentException( __METHOD__ .
": unexpected raw value without key" );
236 if ( $mode == self::LIST_AND || $mode == self::LIST_OR ) {
237 throw new InvalidArgumentException( __METHOD__ .
": unexpected key $field for IExpression value" );
239 throw new InvalidArgumentException( __METHOD__ .
": unexpected IExpression outside WHERE clause" );
241 } elseif ( $mode == self::LIST_SET && is_numeric( $field ) ) {
244 ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_array( $value )
247 $includeNull =
false;
248 foreach ( array_keys( $value,
null,
true ) as $nullKey ) {
250 unset( $value[$nullKey] );
252 if ( count( $value ) == 0 && !$includeNull ) {
253 throw new InvalidArgumentException(
254 __METHOD__ .
": empty input for field $field" );
255 } elseif ( count( $value ) == 0 ) {
257 $list .=
"$field IS NULL";
260 if ( $includeNull ) {
264 if ( count( $value ) == 1 ) {
267 $list .= $field .
" = " . $this->makeList( $value );
269 $list .= $field .
" IN (" . $this->makeList( $value ) .
") ";
272 if ( $includeNull ) {
273 $list .=
" OR $field IS NULL)";
276 } elseif ( is_array( $value ) ) {
277 throw new InvalidArgumentException( __METHOD__ .
": unexpected nested array" );
278 } elseif ( $value ===
null ) {
279 if ( $mode == self::LIST_AND || $mode == self::LIST_OR ) {
280 $list .=
"$field IS ";
281 } elseif ( $mode == self::LIST_SET ) {
282 $list .=
"$field = ";
283 } elseif ( $mode === self::LIST_COMMA && !is_numeric( $field ) ) {
285 __METHOD__ .
": array key {key} in list of values ignored",
286 [
'key' => $field,
'exception' =>
new RuntimeException() ]
288 } elseif ( $mode === self::LIST_NAMES && !is_numeric( $field ) ) {
290 __METHOD__ .
": array key {key} in list of fields ignored",
291 [
'key' => $field,
'exception' =>
new RuntimeException() ]
297 $mode == self::LIST_AND || $mode == self::LIST_OR || $mode == self::LIST_SET
299 $list .=
"$field = ";
300 } elseif ( $mode === self::LIST_COMMA && !is_numeric( $field ) ) {
302 __METHOD__ .
": array key {key} in list of values ignored",
303 [
'key' => $field,
'exception' =>
new RuntimeException() ]
305 } elseif ( $mode === self::LIST_NAMES && !is_numeric( $field ) ) {
307 __METHOD__ .
": array key {key} in list of fields ignored",
308 [
'key' => $field,
'exception' =>
new RuntimeException() ]
311 $list .= $mode == self::LIST_NAMES ? $value : $this->quoter->addQuotes( $value );
318 $this->logger->warning( ...$keyWarning );
326 foreach ( $data as $base => $sub ) {
327 if ( count( $sub ) ) {
328 $conds[] = $this->makeList(
329 [ $baseKey => $base, $subKey => array_map(
'strval', array_keys( $sub ) ) ],
336 throw new InvalidArgumentException(
"Data for $baseKey and $subKey must be non-empty" );
339 return $this->makeList( $conds, self::LIST_OR );
343 if ( count( $condsArray ) === 0 ) {
344 throw new InvalidArgumentException(
345 __METHOD__ .
": empty condition array" );
347 $condsByFieldSet = [];
348 foreach ( $condsArray as $conds ) {
349 if ( !count( $conds ) ) {
350 throw new InvalidArgumentException(
351 __METHOD__ .
": empty condition subarray" );
353 $fieldKey = implode(
',', array_keys( $conds ) );
354 $condsByFieldSet[$fieldKey][] = $conds;
357 foreach ( $condsByFieldSet as $conds ) {
358 if ( $result !==
'' ) {
361 $result .= $this->factorCondsWithCommonFields( $conds );
373 private function factorCondsWithCommonFields( $condsArray ) {
374 $first = $condsArray[array_key_first( $condsArray )];
375 if ( count( $first ) === 1 ) {
377 $field = array_key_first( $first );
379 foreach ( $condsArray as $conds ) {
380 $values[] = $conds[$field];
382 return $this->makeList( [ $field => $values ], self::LIST_AND );
385 $field1 = array_key_first( $first );
386 $nullExpressions = [];
387 $expressionsByField1 = [];
388 foreach ( $condsArray as $conds ) {
389 $value1 = $conds[$field1];
390 unset( $conds[$field1] );
391 if ( $value1 ===
null ) {
392 $nullExpressions[] = $conds;
394 $expressionsByField1[$value1][] = $conds;
400 foreach ( $expressionsByField1 as $value1 => $expressions ) {
401 if ( $result !==
'' ) {
405 $factored = $this->factorCondsWithCommonFields( $expressions );
406 $result .=
"($field1 = " . $this->quoter->addQuotes( $value1 ) .
409 if ( count( $nullExpressions ) ) {
410 $factored = $this->factorCondsWithCommonFields( $nullExpressions );
411 if ( $result !==
'' ) {
415 $result .=
"($field1 IS NULL AND $factored)";
428 return 'CONCAT(' . implode(
',', $stringList ) .
')';
432 if ( !is_numeric( $limit ) ) {
434 "Invalid non-numeric limit passed to " . __METHOD__
440 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," :
"" )
451 [ $escapeChar,
'%',
'_' ],
452 [
"{$escapeChar}{$escapeChar}",
"{$escapeChar}%",
"{$escapeChar}_" ],
458 if ( is_array( $param ) ) {
460 $param = array_shift( $params );
462 $likeValue =
new LikeValue( $param, ...$params );
464 return ' LIKE ' . $likeValue->toSql( $this->quoter );
483 $glue = $all ?
') UNION ALL (' :
') UNION (';
485 $sql =
'(' . implode( $glue, $sqls ) .
')';
486 if ( !$this->unionSupportsOrderAndLimit() ) {
489 $sql .= $this->makeOrderBy( $options );
490 $limit = $options[
'LIMIT'] ??
null;
491 $offset = $options[
'OFFSET'] ??
false;
492 if ( $limit !==
null ) {
493 $sql = $this->limitResult( $sql, $limit, $offset );
499 public function conditional( $cond, $caseTrueExpression, $caseFalseExpression ) {
500 if ( is_array( $cond ) ) {
501 $cond = $this->makeList( $cond, self::LIST_AND );
504 $cond = $cond->toSql( $this->quoter );
507 return "(CASE WHEN $cond THEN $caseTrueExpression ELSE $caseFalseExpression END)";
511 return "REPLACE({$orig}, {$old}, {$new})";
515 $t =
new ConvertibleTimestamp( $ts );
517 return $t->getTimestamp( TS_MW );
521 if ( $ts ===
null ) {
524 return $this->timestamp( $ts );
533 return ( $expiry ==
'' || $expiry ==
'infinity' || $expiry == $this->getInfinity() )
534 ? $this->getInfinity()
535 : $this->timestamp( $expiry );
539 if ( $expiry ==
'' || $expiry ==
'infinity' || $expiry == $this->getInfinity() ) {
543 return ConvertibleTimestamp::convert( $format, $expiry );
550 $this->assertBuildSubstringParams( $startPosition, $length );
551 $functionBody =
"$input FROM $startPosition";
552 if ( $length !==
null ) {
553 $functionBody .=
" FOR $length";
555 return 'SUBSTRING(' . $functionBody .
')';
571 if ( $startPosition === 0 ) {
573 throw new InvalidArgumentException(
'Use 1 as $startPosition for the beginning of the string' );
575 if ( !is_int( $startPosition ) || $startPosition < 0 ) {
576 throw new InvalidArgumentException(
577 '$startPosition must be a positive integer'
580 if ( !( ( is_int( $length ) && $length >= 0 ) || $length ===
null ) ) {
581 throw new InvalidArgumentException(
582 '$length must be null or an integer greater than or equal to 0'
590 return "CAST( $field AS CHARACTER )";
594 return 'CAST( ' . $field .
' AS INTEGER )';
610 return $this->indexAliases[$index] ?? $index;
614 $this->tableAliases = $aliases;
618 $this->indexAliases = $aliases;
625 return $this->tableAliases;
630 $this->currentDomain->getDatabase(),
631 $this->currentDomain->getSchema(),
637 $this->currentDomain = $currentDomain;
645 return $this->currentDomain;
649 $tables, $vars, $conds =
'', $fname = __METHOD__, $options = [], $join_conds = []
651 if ( !is_array( $tables ) ) {
652 if ( $tables ===
'' || $tables ===
null || $tables ===
false ) {
654 } elseif ( is_string( $tables ) ) {
655 $tables = [ $tables ];
657 throw new DBLanguageError( __METHOD__ .
' called with incorrect table parameter' );
661 if ( is_array( $vars ) ) {
662 $fields = implode(
',', $this->fieldNamesWithAlias( $vars ) );
667 $options = (array)$options;
669 $useIndexByTable = $options[
'USE INDEX'] ?? [];
670 if ( !is_array( $useIndexByTable ) ) {
671 if ( count( $tables ) <= 1 ) {
672 $useIndexByTable = [ reset( $tables ) => $useIndexByTable ];
674 $e =
new DBLanguageError( __METHOD__ .
" got ambiguous USE INDEX ($fname)" );
675 ( $this->errorLogger )( $e );
679 $ignoreIndexByTable = $options[
'IGNORE INDEX'] ?? [];
680 if ( !is_array( $ignoreIndexByTable ) ) {
681 if ( count( $tables ) <= 1 ) {
682 $ignoreIndexByTable = [ reset( $tables ) => $ignoreIndexByTable ];
684 $e =
new DBLanguageError( __METHOD__ .
" got ambiguous IGNORE INDEX ($fname)" );
685 ( $this->errorLogger )( $e );
690 $this->selectOptionsIncludeLocking( $options ) &&
691 $this->selectFieldsOrOptionsAggregate( $vars, $options )
695 $this->logger->warning(
696 __METHOD__ .
": aggregation used with a locking SELECT ($fname)"
700 if ( count( $tables ) ) {
701 $from =
' FROM ' . $this->tableNamesWithIndexClauseOrJOIN(
711 [ $startOpts, $preLimitTail, $postLimitTail ] = $this->makeSelectOptions( $options );
713 if ( is_array( $conds ) ) {
714 $where = $this->makeList( $conds, self::LIST_AND );
716 $where = $conds->toSql( $this->quoter );
717 } elseif ( $conds ===
null || $conds ===
false ) {
719 $this->logger->warning(
723 .
' with incorrect parameters: $conds must be a string or an array',
724 [
'db_log_category' =>
'sql' ]
726 } elseif ( is_string( $conds ) ) {
729 throw new DBLanguageError( __METHOD__ .
' called with incorrect parameters' );
733 if ( $where ===
'' || $where ===
'*' ) {
734 $sql =
"SELECT $startOpts $fields $from $preLimitTail";
736 $sql =
"SELECT $startOpts $fields $from WHERE $where $preLimitTail";
739 if ( isset( $options[
'LIMIT'] ) ) {
740 $sql = $this->limitResult( $sql, $options[
'LIMIT'], $options[
'OFFSET'] ??
false );
742 $sql =
"$sql $postLimitTail";
744 if ( isset( $options[
'EXPLAIN'] ) ) {
745 $sql =
'EXPLAIN ' . $sql;
749 $fname === static::CALLER_UNKNOWN ||
750 str_starts_with( $fname,
'Wikimedia\\Rdbms\\' ) ||
751 $fname ===
'{closure}'
753 $exception =
new RuntimeException();
757 foreach ( $exception->getTrace() as $call ) {
758 if ( str_ends_with( $call[
'file'] ??
'',
'Test.php' ) ) {
761 } elseif ( str_starts_with( $call[
'class'] ??
'',
'Wikimedia\\Rdbms\\' ) ) {
763 } elseif ( str_ends_with( $call[
'class'] ??
'',
'SelectQueryBuilder' ) ) {
767 $caller = implode(
'::', array_filter( [ $call[
'class'] ??
null, $call[
'function'] ] ) );
772 if ( $fname ===
'{closure}' ) {
778 $warning =
"SQL query with incorrect caller (__METHOD__ used inside a closure: {caller}): {sql}";
780 $warning =
"SQL query did not specify the caller (guessed caller: {caller}): {sql}";
783 $this->logger->warning(
785 [
'sql' => $sql,
'caller' => $caller,
'exception' => $exception ]
796 private function selectOptionsIncludeLocking( $options ) {
797 $options = (array)$options;
798 foreach ( [
'FOR UPDATE',
'LOCK IN SHARE MODE' ] as $lock ) {
799 if ( in_array( $lock, $options,
true ) ) {
812 private function selectFieldsOrOptionsAggregate( $fields, $options ) {
813 foreach ( (array)$options as $key => $value ) {
814 if ( is_string( $key ) ) {
815 if ( preg_match(
'/^(?:GROUP BY|HAVING)$/i', $key ) ) {
818 } elseif ( is_string( $value ) ) {
819 if ( preg_match(
'/^(?:DISTINCT|DISTINCTROW)$/i', $value ) ) {
825 $regex =
'/^(?:COUNT|MIN|MAX|SUM|GROUP_CONCAT|LISTAGG|ARRAY_AGG)\s*\\(/i';
826 foreach ( (array)$fields as $field ) {
827 if ( is_string( $field ) && preg_match( $regex, $field ) ) {
843 foreach ( $fields as $alias => $field ) {
844 if ( is_numeric( $alias ) ) {
847 $retval[] = $this->fieldNameWithAlias( $field, $alias );
862 if ( !$alias || (
string)$alias === (
string)$name ) {
865 return $name .
' AS ' . $this->addIdentifierQuotes( $alias );
887 $use_index = (array)$use_index;
888 $ignore_index = (array)$ignore_index;
889 $join_conds = (array)$join_conds;
891 foreach ( $tables as $alias => $table ) {
892 if ( !is_string( $alias ) ) {
897 if ( is_array( $table ) ) {
899 if ( count( $table ) > 1 ) {
901 $this->tableNamesWithIndexClauseOrJOIN(
902 $table, $use_index, $ignore_index, $join_conds ) .
')';
905 $innerTable = reset( $table );
906 $innerAlias = key( $table );
907 $joinedTable = $this->tableNameWithAlias(
909 is_string( $innerAlias ) ? $innerAlias : $innerTable
913 $joinedTable = $this->tableNameWithAlias( $table, $alias );
917 if ( isset( $join_conds[$alias] ) ) {
918 Assert::parameterType(
'array', $join_conds[$alias],
"join_conds[$alias]" );
919 [ $joinType, $conds ] = $join_conds[$alias];
920 $tableClause = $this->normalizeJoinType( $joinType );
921 $tableClause .=
' ' . $joinedTable;
922 if ( isset( $use_index[$alias] ) ) {
923 $use = $this->useIndexClause( implode(
',', (array)$use_index[$alias] ) );
925 $tableClause .=
' ' . $use;
928 if ( isset( $ignore_index[$alias] ) ) {
929 $ignore = $this->ignoreIndexClause(
930 implode(
',', (array)$ignore_index[$alias] ) );
931 if ( $ignore !=
'' ) {
932 $tableClause .=
' ' . $ignore;
935 $on = $this->makeList( (array)$conds, self::LIST_AND );
937 $tableClause .=
' ON (' . $on .
')';
940 $retJOIN[] = $tableClause;
941 } elseif ( isset( $use_index[$alias] ) ) {
943 $tableClause = $joinedTable;
944 $tableClause .=
' ' . $this->useIndexClause(
945 implode(
',', (array)$use_index[$alias] )
948 $ret[] = $tableClause;
949 } elseif ( isset( $ignore_index[$alias] ) ) {
951 $tableClause = $joinedTable;
952 $tableClause .=
' ' . $this->ignoreIndexClause(
953 implode(
',', (array)$ignore_index[$alias] )
956 $ret[] = $tableClause;
958 $tableClause = $joinedTable;
960 $ret[] = $tableClause;
965 $implicitJoins = implode(
',', $ret );
966 $explicitJoins = implode(
' ', $retJOIN );
969 return implode(
' ', [ $implicitJoins, $explicitJoins ] );
981 switch ( strtoupper( $joinType ) ) {
989 case 'STRAIGHT_JOIN':
990 case 'STRAIGHT JOIN':
1011 if ( is_string( $table ) ) {
1012 $quotedTable = $this->tableName( $table );
1013 } elseif ( $table instanceof
Subquery ) {
1014 $quotedTable = (string)$table;
1016 throw new InvalidArgumentException(
"Table must be a string or Subquery" );
1019 if ( $alias ===
false ) {
1020 if ( $table instanceof
Subquery ) {
1021 throw new InvalidArgumentException(
"Subquery table missing alias" );
1023 $quotedTableWithAnyAlias = $quotedTable;
1025 $alias === $table &&
1027 str_contains( $alias,
'.' ) ||
1028 $this->tableName( $alias,
'raw' ) === $table
1031 $quotedTableWithAnyAlias = $quotedTable;
1033 $quotedTableWithAnyAlias = $quotedTable .
' ' . $this->addIdentifierQuotes( $alias );
1036 return $quotedTableWithAnyAlias;
1039 public function tableName(
string $name, $format =
'quoted' ) {
1040 $prefix = $this->currentDomain->getTablePrefix();
1045 str_contains( $name,
'.' ) &&
1046 !preg_match(
'/^information_schema\.[a-z_0-9]+$/', $name )
1048 ( $prefix !==
'' && str_starts_with( $name, $prefix ) )
1050 $this->logger->warning(
1051 __METHOD__ .
' called with qualified table ' . $name,
1052 [
'db_log_category' =>
'sql' ]
1057 $formattedComponents = [];
1058 foreach ( $this->qualifiedTableComponents( $name ) as $component ) {
1059 if ( $format ===
'quoted' ) {
1060 $formattedComponents[] = $this->addIdentifierQuotes( $component );
1062 $formattedComponents[] = $component;
1066 return implode(
'.', $formattedComponents );
1092 $identifiers = $this->extractTableNameComponents( $name );
1093 if ( count( $identifiers ) > 3 ) {
1094 throw new DBLanguageError(
"Too many components in table name '$name'" );
1097 if ( count( $identifiers ) == 1 && !$this->isQuotedIdentifier( $identifiers[0] ) ) {
1098 [ $table ] = $identifiers;
1099 if ( isset( $this->tableAliases[$table] ) ) {
1101 $database = $this->tableAliases[$table][
'dbname'];
1102 $schema = is_string( $this->tableAliases[$table][
'schema'] )
1103 ? $this->tableAliases[$table][
'schema']
1104 : $this->relationSchemaQualifier();
1105 $prefix = is_string( $this->tableAliases[$table][
'prefix'] )
1106 ? $this->tableAliases[$table][
'prefix']
1107 : $this->currentDomain->getTablePrefix();
1111 $schema = $this->relationSchemaQualifier();
1112 $prefix = $this->currentDomain->getTablePrefix();
1114 $qualifierIdentifiers = [ $database, $schema ];
1115 $tableIdentifier = $prefix . $table;
1117 $qualifierIdentifiers = array_slice( $identifiers, 0, -1 );
1118 $tableIdentifier = end( $identifiers );
1122 foreach ( $qualifierIdentifiers as $identifier ) {
1123 if ( $identifier !==
null && $identifier !==
'' ) {
1124 $components[] = $this->isQuotedIdentifier( $identifier )
1125 ? substr( $identifier, 1, -1 )
1129 $components[] = $this->isQuotedIdentifier( $tableIdentifier )
1130 ? substr( $tableIdentifier, 1, -1 )
1143 $quoteChar = $this->getIdentifierQuoteChar();
1145 foreach ( explode(
'.', $name ) as $component ) {
1146 if ( $this->isQuotedIdentifier( $component ) ) {
1147 $unquotedComponent = substr( $component, 1, -1 );
1149 $unquotedComponent = $component;
1151 if ( str_contains( $unquotedComponent, $quoteChar ) ) {
1153 'Table name component contains unexpected quote or dot character' );
1155 $components[] = $component;
1186 $components = $this->qualifiedTableComponents( $table );
1187 switch ( count( $components ) ) {
1189 return [ $this->currentDomain->getDatabase(), $components[0] ];
1201 return $this->currentDomain->getSchema();
1207 foreach ( $tables as $name ) {
1208 $retVal[] = $this->tableName( $name );
1224 $quoteChar = $this->getIdentifierQuoteChar();
1225 return strlen( $name ) > 1 && $name[0] === $quoteChar && $name[-1] === $quoteChar;
1267 $preLimitTail = $postLimitTail =
'';
1272 foreach ( $options as $key => $option ) {
1273 if ( is_numeric( $key ) ) {
1274 $noKeyOptions[$option] =
true;
1278 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1280 $preLimitTail .= $this->makeOrderBy( $options );
1282 if ( isset( $noKeyOptions[
'FOR UPDATE'] ) ) {
1283 $postLimitTail .=
' FOR UPDATE';
1286 if ( isset( $noKeyOptions[
'LOCK IN SHARE MODE'] ) ) {
1287 $postLimitTail .=
' LOCK IN SHARE MODE';
1290 if ( isset( $noKeyOptions[
'DISTINCT'] ) || isset( $noKeyOptions[
'DISTINCTROW'] ) ) {
1291 $startOpts .=
'DISTINCT';
1294 # Various MySQL extensions
1295 if ( isset( $noKeyOptions[
'STRAIGHT_JOIN'] ) ) {
1296 $startOpts .=
' /*! STRAIGHT_JOIN */';
1299 if ( isset( $noKeyOptions[
'SQL_BIG_RESULT'] ) ) {
1300 $startOpts .=
' SQL_BIG_RESULT';
1303 if ( isset( $noKeyOptions[
'SQL_BUFFER_RESULT'] ) ) {
1304 $startOpts .=
' SQL_BUFFER_RESULT';
1307 if ( isset( $noKeyOptions[
'SQL_SMALL_RESULT'] ) ) {
1308 $startOpts .=
' SQL_SMALL_RESULT';
1311 if ( isset( $noKeyOptions[
'SQL_CALC_FOUND_ROWS'] ) ) {
1312 $startOpts .=
' SQL_CALC_FOUND_ROWS';
1315 return [ $startOpts, $preLimitTail, $postLimitTail ];
1328 if ( isset( $options[
'GROUP BY'] ) ) {
1329 $gb = is_array( $options[
'GROUP BY'] )
1330 ? implode(
',', $options[
'GROUP BY'] )
1331 : $options[
'GROUP BY'];
1332 $sql .=
' GROUP BY ' . $gb;
1334 if ( isset( $options[
'HAVING'] ) ) {
1335 $having = is_array( $options[
'HAVING'] )
1336 ? $this->makeList( $options[
'HAVING'], self::LIST_AND )
1337 : $options[
'HAVING'];
1338 $sql .=
' HAVING ' . $having;
1353 if ( isset( $options[
'ORDER BY'] ) ) {
1354 $ob = is_array( $options[
'ORDER BY'] )
1355 ? implode(
',', $options[
'ORDER BY'] )
1356 : $options[
'ORDER BY'];
1358 return ' ORDER BY ' . $ob;
1365 $delim, $tables, $field, $conds =
'', $join_conds = []
1367 $fld =
"GROUP_CONCAT($field SEPARATOR " . $this->quoter->addQuotes( $delim ) .
')';
1369 return '(' . $this->selectSQLText( $tables, $fld, $conds, static::CALLER_SUBQUERY, [], $join_conds ) .
')';
1373 $tables, $vars, $conds =
'', $fname = __METHOD__,
1374 $options = [], $join_conds = []
1377 $this->selectSQLText( $tables, $vars, $conds, $fname, $options, $join_conds )
1382 $encTable = $this->tableName( $table );
1383 [ $sqlColumns, $sqlTuples ] = $this->makeInsertLists( $rows );
1386 "INSERT INTO $encTable ($sqlColumns) VALUES $sqlTuples",
1387 "INSERT INTO $encTable ($sqlColumns) VALUES '?'"
1403 public function makeInsertLists( array $rows, $aliasPrefix =
'', array $typeByColumn = [] ) {
1404 $firstRow = $rows[0];
1405 if ( !is_array( $firstRow ) || !$firstRow ) {
1409 $tupleColumns = array_keys( $firstRow );
1412 foreach ( $rows as $row ) {
1413 $rowColumns = array_keys( $row );
1415 if ( $rowColumns !== $tupleColumns ) {
1417 'Got row columns (' . implode(
', ', $rowColumns ) .
') ' .
1418 'instead of expected (' . implode(
', ', $tupleColumns ) .
')'
1422 $valueTuples[] =
'(' . $this->makeList( array_values( $row ), self::LIST_COMMA ) .
')';
1425 $magicAliasFields = [];
1426 foreach ( $tupleColumns as $column ) {
1427 $magicAliasFields[] = $aliasPrefix . $column;
1431 $this->makeList( $tupleColumns, self::LIST_NAMES ),
1432 implode(
',', $valueTuples ),
1433 $this->makeList( $magicAliasFields, self::LIST_NAMES )
1438 $encTable = $this->tableName( $table );
1439 [ $sqlColumns, $sqlTuples ] = $this->makeInsertLists( $rows );
1440 [ $sqlVerb, $sqlOpts ] = $this->makeInsertNonConflictingVerbAndOptions();
1443 rtrim(
"$sqlVerb $encTable ($sqlColumns) VALUES $sqlTuples $sqlOpts" ),
1444 rtrim(
"$sqlVerb $encTable ($sqlColumns) VALUES '?' $sqlOpts" )
1453 return [
'INSERT IGNORE INTO',
'' ];
1462 array $insertOptions,
1463 array $selectOptions,
1466 [ $sqlVerb, $sqlOpts ] = $this->isFlagInOptions(
'IGNORE', $insertOptions )
1467 ? $this->makeInsertNonConflictingVerbAndOptions()
1468 : [
'INSERT INTO',
'' ];
1469 $encDstTable = $this->tableName( $destTable );
1470 $sqlDstColumns = implode(
',', array_keys( $varMap ) );
1471 $selectSql = $this->selectSQLText(
1473 array_values( $varMap ),
1480 return rtrim(
"$sqlVerb $encDstTable ($sqlDstColumns) $selectSql $sqlOpts" );
1490 foreach ( array_keys( $options, $option,
true ) as $k ) {
1491 if ( is_int( $k ) ) {
1509 } elseif ( !$uniqueKey ) {
1513 if ( count( $uniqueKey ) == 1 ) {
1515 $column = reset( $uniqueKey );
1516 $values = array_column( $rows, $column );
1517 if ( count( $values ) !== count( $rows ) ) {
1518 throw new DBLanguageError(
"Missing values for unique key ($column)" );
1521 return $this->makeList( [ $column => $values ], self::LIST_AND );
1524 $nullByUniqueKeyColumn = array_fill_keys( $uniqueKey,
null );
1527 foreach ( $rows as $row ) {
1528 $rowKeyMap = array_intersect_key( $row, $nullByUniqueKeyColumn );
1529 if ( count( $rowKeyMap ) != count( $uniqueKey ) ) {
1531 "Missing values for unique key (" . implode(
',', $uniqueKey ) .
")"
1534 $orConds[] = $this->makeList( $rowKeyMap, self::LIST_AND );
1537 return count( $orConds ) > 1
1538 ? $this->makeList( $orConds, self::LIST_OR )
1544 throw new DBLanguageError( __METHOD__ .
' called with empty $conds' );
1547 $delTable = $this->tableName( $delTable );
1548 $joinTable = $this->tableName( $joinTable );
1549 $sql =
"DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
1550 if ( $conds !=
'*' ) {
1551 $sql .=
'WHERE ' . $this->makeList( $conds, self::LIST_AND );
1564 $isCondValid = ( is_string( $conds ) || is_array( $conds ) ) && $conds;
1565 if ( !$isCondValid ) {
1566 throw new DBLanguageError( __METHOD__ .
' called with empty conditions' );
1569 $encTable = $this->tableName( $table );
1570 $sql =
"DELETE FROM $encTable";
1573 $cleanCondsSql =
'';
1574 if ( $conds !== self::ALL_ROWS && $conds !== [ self::ALL_ROWS ] ) {
1575 $cleanCondsSql =
' WHERE ' . $this->scrubArray( $conds );
1576 if ( is_array( $conds ) ) {
1577 $conds = $this->makeList( $conds, self::LIST_AND );
1579 $condsSql .=
' WHERE ' . $conds;
1583 self::QUERY_CHANGE_ROWS,
1586 $sql . $cleanCondsSql
1594 private function scrubArray( $array,
int $listType = self::LIST_AND ): string {
1595 if ( is_array( $array ) ) {
1596 $scrubbedArray = [];
1597 foreach ( $array as $key => $value ) {
1599 $scrubbedArray[$key] = $value->toGeneralizedSql();
1601 $scrubbedArray[$key] =
'?';
1604 return $this->makeList( $scrubbedArray, $listType );
1610 $isCondValid = ( is_string( $conds ) || is_array( $conds ) ) && $conds;
1611 if ( !$isCondValid ) {
1612 throw new DBLanguageError( __METHOD__ .
' called with empty conditions' );
1614 $encTable = $this->tableName( $table );
1615 $opts = $this->makeUpdateOptions( $options );
1616 $sql =
"UPDATE $opts $encTable";
1617 $condsSql =
" SET " . $this->makeList( $set, self::LIST_SET );
1618 $cleanCondsSql =
" SET " . $this->scrubArray( $set, self::LIST_SET );
1620 if ( $conds && $conds !== self::ALL_ROWS && $conds !== [ self::ALL_ROWS ] ) {
1621 $cleanCondsSql .=
' WHERE ' . $this->scrubArray( $conds );
1622 if ( is_array( $conds ) ) {
1623 $conds = $this->makeList( $conds, self::LIST_AND );
1625 $condsSql .=
' WHERE ' . $conds;
1629 self::QUERY_CHANGE_ROWS,
1632 $sql . $cleanCondsSql
1643 $opts = $this->makeUpdateOptionsArray( $options );
1645 return implode(
' ', $opts );
1655 $options = $this->normalizeOptions( $options );
1659 if ( in_array(
'IGNORE', $options ) ) {
1672 if ( is_array( $options ) ) {
1674 } elseif ( is_string( $options ) ) {
1675 return ( $options ===
'' ) ? [] : [ $options ];
1677 throw new DBLanguageError( __METHOD__ .
': expected string or array' );
1685 return "DROP TABLE " . $this->tableName( $table ) .
" CASCADE";
1695 return QueryBuilderFromRawSql::buildQuery( $sql, 0 )->getVerb();
1716 'ROLLBACK TO SAVEPOINT',
1732 return "(SELECT __$column FROM __VALS)";
1736 return 'SAVEPOINT ' . $this->addIdentifierQuotes( $identifier );
1740 return 'RELEASE SAVEPOINT ' . $this->addIdentifierQuotes( $identifier );
1744 return 'ROLLBACK TO SAVEPOINT ' . $this->addIdentifierQuotes( $identifier );
1752 $rows = $this->normalizeRowArray( $rows );
1757 $options = $this->normalizeOptions( $options );
1758 if ( $this->isFlagInOptions(
'IGNORE', $options ) ) {
1759 [ $sql, $cleanSql ] = $this->insertNonConflictingSqlText( $table, $rows );
1761 [ $sql, $cleanSql ] = $this->insertSqlText( $table, $rows );
1763 return new Query( $sql, self::QUERY_CHANGE_ROWS,
'INSERT', $table, $cleanSql );
1772 if ( !$rowOrRows ) {
1774 } elseif ( isset( $rowOrRows[0] ) ) {
1777 $rows = [ $rowOrRows ];
1780 foreach ( $rows as $row ) {
1781 if ( !is_array( $row ) ) {
1783 } elseif ( !$row ) {
1800 $rows = $this->normalizeRowArray( $rows );
1801 if ( !$uniqueKeys ) {
1802 throw new DBLanguageError(
'No unique key specified for upsert/replace' );
1804 $uniqueKey = $this->normalizeUpsertKeys( $uniqueKeys );
1805 $this->assertValidUpsertRowArray( $rows, $uniqueKey );
1817 if ( $conds ===
null || $conds ===
false ) {
1818 $this->logger->warning(
1822 .
' with incorrect parameters: $conds must be a string or an array',
1823 [
'db_log_category' =>
'sql' ]
1826 } elseif ( $conds ===
'' ) {
1830 return is_array( $conds ) ? $conds : [ $conds ];
1838 private function normalizeUpsertKeys( $uniqueKeys ) {
1839 if ( is_string( $uniqueKeys ) ) {
1840 return [ $uniqueKeys ];
1841 } elseif ( !is_array( $uniqueKeys ) ) {
1844 if ( count( $uniqueKeys ) !== 1 || !isset( $uniqueKeys[0] ) ) {
1845 throw new DBLanguageError(
1846 "The unique key array should contain a single unique index" );
1849 $uniqueKey = $uniqueKeys[0];
1850 if ( is_string( $uniqueKey ) ) {
1853 $this->logger->warning( __METHOD__ .
1854 " called with deprecated parameter style: " .
1855 "the unique key array should be a string or array of string arrays",
1857 'exception' =>
new RuntimeException(),
1858 'db_log_category' =>
'sql',
1861 } elseif ( is_array( $uniqueKey ) ) {
1864 throw new DBLanguageError(
'Invalid unique key array entry' );
1875 foreach ( $rows as $row ) {
1876 foreach ( $uniqueKey as $column ) {
1877 if ( !isset( $row[$column] ) ) {
1879 "NULL/absent values for unique key (" . implode(
',', $uniqueKey ) .
")"
1898 throw new DBLanguageError(
"Update assignment list can't be empty for upsert" );
1903 $soleRow = ( count( $rows ) == 1 ) ? reset( $rows ) :
null;
1907 foreach ( $set as $k => $v ) {
1908 if ( is_string( $k ) ) {
1910 if ( in_array( $k, $uniqueKey,
true ) ) {
1911 if ( $soleRow && array_key_exists( $k, $soleRow ) && $soleRow[$k] === $v ) {
1912 $this->logger->warning(
1913 __METHOD__ .
" called with redundant assignment to column '$k'",
1915 'exception' =>
new RuntimeException(),
1916 'db_log_category' =>
'sql',
1921 "Cannot reassign column '$k' since it belongs to the provided unique key"
1925 } elseif ( preg_match(
'/^([a-zA-Z0-9_]+)\s*=/', $v, $m ) ) {
1927 if ( in_array( $m[1], $uniqueKey,
true ) ) {
1929 "Cannot reassign column '{$m[1]}' since it belongs to the provided unique key"
1941 if ( is_array( $var ) ) {
1944 } elseif ( count( $var ) == 1 ) {
1945 $column = $var[0] ?? reset( $var );
1957 $this->schemaVars = is_array( $vars ) ? $vars :
null;
1967 return $this->schemaVars ?? $this->getDefaultSchemaVars();
2003 $vars = $this->getSchemaVars();
2004 return preg_replace_callback(
2006 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
2007 \'\{\$ (\w+) }\' | # 3. addQuotes
2008 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
2009 /\*\$ (\w+) \*/ # 5. leave unencoded
2011 function ( $m ) use ( $vars ) {
2014 if ( isset( $m[1] ) && $m[1] !==
'' ) {
2015 if ( $m[1] ===
'i' ) {
2016 return $this->indexName( $m[2] );
2018 return $this->tableName( $m[2] );
2020 } elseif ( isset( $m[3] ) && $m[3] !==
'' && array_key_exists( $m[3], $vars ) ) {
2021 return $this->quoter->addQuotes( $vars[$m[3]] );
2022 } elseif ( isset( $m[4] ) && $m[4] !==
'' && array_key_exists( $m[4], $vars ) ) {
2023 return $this->addIdentifierQuotes( $vars[$m[4]] );
2024 } elseif ( isset( $m[5] ) && $m[5] !==
'' && array_key_exists( $m[5], $vars ) ) {
2025 return $vars[$m[5]];
2035 throw new RuntimeException(
'locking must be implemented in subclasses' );
2039 throw new RuntimeException(
'locking must be implemented in subclasses' );
2043 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.
if(!defined('MW_SETUP_CALLBACK'))
Class to handle database/schema/prefix specifications for IDatabase.