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"
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 ) ) {
472 return ' LIKE ' . $likeValue->toSql( $this->quoter );
492 $glue = $all ?
') UNION ALL (' :
') UNION (';
494 $sql =
'(' . implode( $glue, $sqls ) .
')';
495 if ( !$this->unionSupportsOrderAndLimit() ) {
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 );
508 public function conditional( $cond, $caseTrueExpression, $caseFalseExpression ) {
509 if ( is_array( $cond ) ) {
510 $cond = $this->makeList( $cond, self::LIST_AND );
513 $cond = $cond->toSql( $this->quoter );
516 return "(CASE WHEN $cond THEN $caseTrueExpression ELSE $caseFalseExpression END)";
520 return "REPLACE({$orig}, {$old}, {$new})";
524 $t =
new ConvertibleTimestamp( $ts );
526 return $t->getTimestamp( TS_MW );
530 if ( $ts ===
null ) {
533 return $this->timestamp( $ts );
542 return ( $expiry ==
'' || $expiry ==
'infinity' || $expiry == $this->getInfinity() )
543 ? $this->getInfinity()
544 : $this->timestamp( $expiry );
548 if ( $expiry ==
'' || $expiry ==
'infinity' || $expiry == $this->getInfinity() ) {
552 return ConvertibleTimestamp::convert( $format, $expiry );
560 $this->assertBuildSubstringParams( $startPosition, $length );
561 $functionBody =
"$input FROM $startPosition";
562 if ( $length !==
null ) {
563 $functionBody .=
" FOR $length";
565 return 'SUBSTRING(' . $functionBody .
')';
581 if ( $startPosition === 0 ) {
583 throw new InvalidArgumentException(
'Use 1 as $startPosition for the beginning of the string' );
585 if ( !is_int( $startPosition ) || $startPosition < 0 ) {
586 throw new InvalidArgumentException(
587 '$startPosition must be a positive integer'
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'
600 return "CAST( $field AS CHARACTER )";
604 return 'CAST( ' . $field .
' AS INTEGER )';
620 return $this->indexAliases[$index] ?? $index;
624 $this->tableAliases = $aliases;
628 $this->indexAliases = $aliases;
635 return $this->tableAliases;
640 $this->currentDomain->getDatabase(),
641 $this->currentDomain->getSchema(),
647 $this->currentDomain = $currentDomain;
655 return $this->currentDomain;
659 $tables, $vars, $conds =
'', $fname = __METHOD__, $options = [], $join_conds = []
661 if ( !is_array( $tables ) ) {
662 if ( $tables ===
'' || $tables ===
null || $tables ===
false ) {
664 } elseif ( is_string( $tables ) ) {
665 $tables = [ $tables ];
667 throw new DBLanguageError( __METHOD__ .
' called with incorrect table parameter' );
671 if ( is_array( $vars ) ) {
672 $fields = implode(
',', $this->fieldNamesWithAlias( $vars ) );
677 $options = (array)$options;
679 $useIndexByTable = $options[
'USE INDEX'] ?? [];
680 if ( !is_array( $useIndexByTable ) ) {
681 if ( count( $tables ) <= 1 ) {
682 $useIndexByTable = [ reset( $tables ) => $useIndexByTable ];
684 $e =
new DBLanguageError( __METHOD__ .
" got ambiguous USE INDEX ($fname)" );
685 ( $this->errorLogger )( $e );
689 $ignoreIndexByTable = $options[
'IGNORE INDEX'] ?? [];
690 if ( !is_array( $ignoreIndexByTable ) ) {
691 if ( count( $tables ) <= 1 ) {
692 $ignoreIndexByTable = [ reset( $tables ) => $ignoreIndexByTable ];
694 $e =
new DBLanguageError( __METHOD__ .
" got ambiguous IGNORE INDEX ($fname)" );
695 ( $this->errorLogger )( $e );
700 $this->selectOptionsIncludeLocking( $options ) &&
701 $this->selectFieldsOrOptionsAggregate( $vars, $options )
705 $this->logger->warning(
706 __METHOD__ .
": aggregation used with a locking SELECT ($fname)"
710 if ( count( $tables ) ) {
711 $from =
' FROM ' . $this->tableNamesWithIndexClauseOrJOIN(
721 [ $startOpts, $preLimitTail, $postLimitTail ] = $this->makeSelectOptions( $options );
723 if ( is_array( $conds ) ) {
724 $where = $this->makeList( $conds, self::LIST_AND );
726 $where = $conds->toSql( $this->quoter );
727 } elseif ( $conds ===
null || $conds ===
false ) {
729 $this->logger->warning(
733 .
' with incorrect parameters: $conds must be a string or an array',
734 [
'db_log_category' =>
'sql' ]
736 } elseif ( is_string( $conds ) ) {
739 throw new DBLanguageError( __METHOD__ .
' called with incorrect parameters' );
743 if ( $where ===
'' || $where ===
'*' ) {
744 $sql =
"SELECT $startOpts $fields $from $preLimitTail";
746 $sql =
"SELECT $startOpts $fields $from WHERE $where $preLimitTail";
749 if ( isset( $options[
'LIMIT'] ) ) {
750 $sql = $this->limitResult( $sql, $options[
'LIMIT'], $options[
'OFFSET'] ??
false );
752 $sql =
"$sql $postLimitTail";
754 if ( isset( $options[
'EXPLAIN'] ) ) {
755 $sql =
'EXPLAIN ' . $sql;
759 $fname === static::CALLER_UNKNOWN ||
760 str_starts_with( $fname,
'Wikimedia\\Rdbms\\' ) ||
761 $fname ===
'{closure}'
763 $exception =
new RuntimeException();
767 foreach ( $exception->getTrace() as $call ) {
768 if ( str_ends_with( $call[
'file'] ??
'',
'Test.php' ) ) {
771 } elseif ( str_starts_with( $call[
'class'] ??
'',
'Wikimedia\\Rdbms\\' ) ) {
773 } elseif ( str_ends_with( $call[
'class'] ??
'',
'SelectQueryBuilder' ) ) {
777 $caller = implode(
'::', array_filter( [ $call[
'class'] ??
null, $call[
'function'] ] ) );
782 if ( $fname ===
'{closure}' ) {
788 $warning =
"SQL query with incorrect caller (__METHOD__ used inside a closure: {caller}): {sql}";
790 $warning =
"SQL query did not specify the caller (guessed caller: {caller}): {sql}";
793 $this->logger->warning(
795 [
'sql' => $sql,
'caller' => $caller,
'exception' => $exception ]
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 ) ) {
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 ) ) {
828 } elseif ( is_string( $value ) ) {
829 if ( preg_match(
'/^(?:DISTINCT|DISTINCTROW)$/i', $value ) ) {
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 ) ) {
853 foreach ( $fields as $alias => $field ) {
854 if ( is_numeric( $alias ) ) {
857 $retval[] = $this->fieldNameWithAlias( $field, $alias );
873 if ( !$alias || (
string)$alias === (
string)$name ) {
876 return $name .
' AS ' . $this->addIdentifierQuotes( $alias );
898 $use_index = (array)$use_index;
899 $ignore_index = (array)$ignore_index;
900 $join_conds = (array)$join_conds;
902 foreach ( $tables as $alias => $table ) {
903 if ( !is_string( $alias ) ) {
908 if ( is_array( $table ) ) {
910 if ( count( $table ) > 1 ) {
912 $this->tableNamesWithIndexClauseOrJOIN(
913 $table, $use_index, $ignore_index, $join_conds ) .
')';
916 $innerTable = reset( $table );
917 $innerAlias = key( $table );
918 $joinedTable = $this->tableNameWithAlias(
920 is_string( $innerAlias ) ? $innerAlias : $innerTable
924 $joinedTable = $this->tableNameWithAlias( $table, $alias );
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] ) ) {
934 $use = $this->useIndexClause( implode(
',', (array)$use_index[$alias] ) );
936 $tableClause .=
' ' . $use;
939 if ( isset( $ignore_index[$alias] ) ) {
940 $ignore = $this->ignoreIndexClause(
941 implode(
',', (array)$ignore_index[$alias] ) );
942 if ( $ignore !=
'' ) {
943 $tableClause .=
' ' . $ignore;
946 $on = $this->makeList( (array)$conds, self::LIST_AND );
948 $tableClause .=
' ON (' . $on .
')';
951 $retJOIN[] = $tableClause;
952 } elseif ( isset( $use_index[$alias] ) ) {
954 $tableClause = $joinedTable;
955 $tableClause .=
' ' . $this->useIndexClause(
956 implode(
',', (array)$use_index[$alias] )
959 $ret[] = $tableClause;
960 } elseif ( isset( $ignore_index[$alias] ) ) {
962 $tableClause = $joinedTable;
963 $tableClause .=
' ' . $this->ignoreIndexClause(
964 implode(
',', (array)$ignore_index[$alias] )
967 $ret[] = $tableClause;
969 $tableClause = $joinedTable;
971 $ret[] = $tableClause;
976 $implicitJoins = implode(
',', $ret );
977 $explicitJoins = implode(
' ', $retJOIN );
980 return implode(
' ', [ $implicitJoins, $explicitJoins ] );
992 switch ( strtoupper( $joinType ) ) {
1000 case 'STRAIGHT_JOIN':
1001 case 'STRAIGHT JOIN':
1022 if ( is_string( $table ) ) {
1023 $quotedTable = $this->tableName( $table );
1024 } elseif ( $table instanceof
Subquery ) {
1025 $quotedTable = (string)$table;
1027 throw new InvalidArgumentException(
"Table must be a string or Subquery" );
1030 if ( $alias ===
false || $alias === $table ) {
1031 if ( $table instanceof
Subquery ) {
1032 throw new InvalidArgumentException(
"Subquery table missing alias" );
1035 return $quotedTable;
1037 return $quotedTable .
' ' . $this->addIdentifierQuotes( $alias );
1041 public function tableName(
string $name, $format =
'quoted' ) {
1042 $prefix = $this->currentDomain->getTablePrefix();
1047 str_contains( $name,
'.' ) &&
1048 !preg_match(
'/^information_schema\.[a-z_0-9]+$/', $name )
1050 ( $prefix !==
'' && str_starts_with( $name, $prefix ) )
1052 $this->logger->warning(
1053 __METHOD__ .
' called with qualified table ' . $name,
1054 [
'db_log_category' =>
'sql' ]
1059 $formattedComponents = [];
1060 foreach ( $this->qualifiedTableComponents( $name ) as $component ) {
1061 if ( $format ===
'quoted' ) {
1062 $formattedComponents[] = $this->addIdentifierQuotes( $component );
1064 $formattedComponents[] = $component;
1068 return implode(
'.', $formattedComponents );
1094 $identifiers = $this->extractTableNameComponents( $name );
1095 if ( count( $identifiers ) > 3 ) {
1096 throw new DBLanguageError(
"Too many components in table name '$name'" );
1099 if ( count( $identifiers ) == 1 && !$this->isQuotedIdentifier( $identifiers[0] ) ) {
1100 [ $table ] = $identifiers;
1101 if ( isset( $this->tableAliases[$table] ) ) {
1103 $database = $this->tableAliases[$table][
'dbname'];
1104 $schema = is_string( $this->tableAliases[$table][
'schema'] )
1105 ? $this->tableAliases[$table][
'schema']
1106 : $this->relationSchemaQualifier();
1107 $prefix = is_string( $this->tableAliases[$table][
'prefix'] )
1108 ? $this->tableAliases[$table][
'prefix']
1109 : $this->currentDomain->getTablePrefix();
1113 $schema = $this->relationSchemaQualifier();
1114 $prefix = $this->currentDomain->getTablePrefix();
1116 $qualifierIdentifiers = [ $database, $schema ];
1117 $tableIdentifier = $prefix . $table;
1119 $qualifierIdentifiers = array_slice( $identifiers, 0, -1 );
1120 $tableIdentifier = end( $identifiers );
1124 foreach ( $qualifierIdentifiers as $identifier ) {
1125 if ( $identifier !==
null && $identifier !==
'' ) {
1126 $components[] = $this->isQuotedIdentifier( $identifier )
1127 ? substr( $identifier, 1, -1 )
1131 $components[] = $this->isQuotedIdentifier( $tableIdentifier )
1132 ? substr( $tableIdentifier, 1, -1 )
1145 $quoteChar = $this->getIdentifierQuoteChar();
1147 foreach ( explode(
'.', $name ) as $component ) {
1148 if ( $this->isQuotedIdentifier( $component ) ) {
1149 $unquotedComponent = substr( $component, 1, -1 );
1151 $unquotedComponent = $component;
1153 if ( str_contains( $unquotedComponent, $quoteChar ) ) {
1155 'Table name component contains unexpected quote or dot character' );
1157 $components[] = $component;
1188 $components = $this->qualifiedTableComponents( $table );
1189 switch ( count( $components ) ) {
1191 return [ $this->currentDomain->getDatabase(), $components[0] ];
1204 return $this->currentDomain->getSchema();
1215 foreach ( $tables as $name ) {
1216 $retVal[$name] = $this->tableName( $name );
1225 foreach ( $tables as $name ) {
1226 $retVal[] = $this->tableName( $name );
1242 $quoteChar = $this->getIdentifierQuoteChar();
1243 return strlen( $name ) > 1 && $name[0] === $quoteChar && $name[-1] === $quoteChar;
1287 $preLimitTail = $postLimitTail =
'';
1292 foreach ( $options as $key => $option ) {
1293 if ( is_numeric( $key ) ) {
1294 $noKeyOptions[$option] =
true;
1298 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1300 $preLimitTail .= $this->makeOrderBy( $options );
1302 if ( isset( $noKeyOptions[
'FOR UPDATE'] ) ) {
1303 $postLimitTail .=
' FOR UPDATE';
1306 if ( isset( $noKeyOptions[
'LOCK IN SHARE MODE'] ) ) {
1307 $postLimitTail .=
' LOCK IN SHARE MODE';
1310 if ( isset( $noKeyOptions[
'DISTINCT'] ) || isset( $noKeyOptions[
'DISTINCTROW'] ) ) {
1311 $startOpts .=
'DISTINCT';
1314 # Various MySQL extensions
1315 if ( isset( $noKeyOptions[
'STRAIGHT_JOIN'] ) ) {
1316 $startOpts .=
' /*! STRAIGHT_JOIN */';
1319 if ( isset( $noKeyOptions[
'SQL_BIG_RESULT'] ) ) {
1320 $startOpts .=
' SQL_BIG_RESULT';
1323 if ( isset( $noKeyOptions[
'SQL_BUFFER_RESULT'] ) ) {
1324 $startOpts .=
' SQL_BUFFER_RESULT';
1327 if ( isset( $noKeyOptions[
'SQL_SMALL_RESULT'] ) ) {
1328 $startOpts .=
' SQL_SMALL_RESULT';
1331 if ( isset( $noKeyOptions[
'SQL_CALC_FOUND_ROWS'] ) ) {
1332 $startOpts .=
' SQL_CALC_FOUND_ROWS';
1335 return [ $startOpts, $preLimitTail, $postLimitTail ];
1348 if ( isset( $options[
'GROUP BY'] ) ) {
1349 $gb = is_array( $options[
'GROUP BY'] )
1350 ? implode(
',', $options[
'GROUP BY'] )
1351 : $options[
'GROUP BY'];
1352 $sql .=
' GROUP BY ' . $gb;
1354 if ( isset( $options[
'HAVING'] ) ) {
1355 $having = is_array( $options[
'HAVING'] )
1356 ? $this->makeList( $options[
'HAVING'], self::LIST_AND )
1357 : $options[
'HAVING'];
1358 $sql .=
' HAVING ' . $having;
1373 if ( isset( $options[
'ORDER BY'] ) ) {
1374 $ob = is_array( $options[
'ORDER BY'] )
1375 ? implode(
',', $options[
'ORDER BY'] )
1376 : $options[
'ORDER BY'];
1378 return ' ORDER BY ' . $ob;
1385 $delim, $tables, $field, $conds =
'', $join_conds = []
1387 $fld =
"GROUP_CONCAT($field SEPARATOR " . $this->quoter->addQuotes( $delim ) .
')';
1389 return '(' . $this->selectSQLText( $tables, $fld, $conds, static::CALLER_SUBQUERY, [], $join_conds ) .
')';
1393 $tables, $vars, $conds =
'', $fname = __METHOD__,
1394 $options = [], $join_conds = []
1397 $this->selectSQLText( $tables, $vars, $conds, $fname, $options, $join_conds )
1402 $encTable = $this->tableName( $table );
1403 [ $sqlColumns, $sqlTuples ] = $this->makeInsertLists( $rows );
1406 "INSERT INTO $encTable ($sqlColumns) VALUES $sqlTuples",
1407 "INSERT INTO $encTable ($sqlColumns) VALUES '?'"
1423 public function makeInsertLists( array $rows, $aliasPrefix =
'', array $typeByColumn = [] ) {
1424 $firstRow = $rows[0];
1425 if ( !is_array( $firstRow ) || !$firstRow ) {
1429 $tupleColumns = array_keys( $firstRow );
1432 foreach ( $rows as $row ) {
1433 $rowColumns = array_keys( $row );
1435 if ( $rowColumns !== $tupleColumns ) {
1437 'Got row columns (' . implode(
', ', $rowColumns ) .
') ' .
1438 'instead of expected (' . implode(
', ', $tupleColumns ) .
')'
1442 $valueTuples[] =
'(' . $this->makeList( array_values( $row ), self::LIST_COMMA ) .
')';
1445 $magicAliasFields = [];
1446 foreach ( $tupleColumns as $column ) {
1447 $magicAliasFields[] = $aliasPrefix . $column;
1451 $this->makeList( $tupleColumns, self::LIST_NAMES ),
1452 implode(
',', $valueTuples ),
1453 $this->makeList( $magicAliasFields, self::LIST_NAMES )
1458 $encTable = $this->tableName( $table );
1459 [ $sqlColumns, $sqlTuples ] = $this->makeInsertLists( $rows );
1460 [ $sqlVerb, $sqlOpts ] = $this->makeInsertNonConflictingVerbAndOptions();
1463 rtrim(
"$sqlVerb $encTable ($sqlColumns) VALUES $sqlTuples $sqlOpts" ),
1464 rtrim(
"$sqlVerb $encTable ($sqlColumns) VALUES '?' $sqlOpts" )
1474 return [
'INSERT IGNORE INTO',
'' ];
1483 array $insertOptions,
1484 array $selectOptions,
1487 [ $sqlVerb, $sqlOpts ] = $this->isFlagInOptions(
'IGNORE', $insertOptions )
1488 ? $this->makeInsertNonConflictingVerbAndOptions()
1489 : [
'INSERT INTO',
'' ];
1490 $encDstTable = $this->tableName( $destTable );
1491 $sqlDstColumns = implode(
',', array_keys( $varMap ) );
1492 $selectSql = $this->selectSQLText(
1494 array_values( $varMap ),
1501 return rtrim(
"$sqlVerb $encDstTable ($sqlDstColumns) $selectSql $sqlOpts" );
1511 foreach ( array_keys( $options, $option,
true ) as $k ) {
1512 if ( is_int( $k ) ) {
1530 } elseif ( !$uniqueKey ) {
1534 if ( count( $uniqueKey ) == 1 ) {
1536 $column = reset( $uniqueKey );
1537 $values = array_column( $rows, $column );
1538 if ( count( $values ) !== count( $rows ) ) {
1539 throw new DBLanguageError(
"Missing values for unique key ($column)" );
1542 return $this->makeList( [ $column => $values ], self::LIST_AND );
1545 $nullByUniqueKeyColumn = array_fill_keys( $uniqueKey,
null );
1548 foreach ( $rows as $row ) {
1549 $rowKeyMap = array_intersect_key( $row, $nullByUniqueKeyColumn );
1550 if ( count( $rowKeyMap ) != count( $uniqueKey ) ) {
1552 "Missing values for unique key (" . implode(
',', $uniqueKey ) .
")"
1555 $orConds[] = $this->makeList( $rowKeyMap, self::LIST_AND );
1558 return count( $orConds ) > 1
1559 ? $this->makeList( $orConds, self::LIST_OR )
1565 throw new DBLanguageError( __METHOD__ .
' called with empty $conds' );
1568 $delTable = $this->tableName( $delTable );
1569 $joinTable = $this->tableName( $joinTable );
1570 $sql =
"DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
1571 if ( $conds !=
'*' ) {
1572 $sql .=
'WHERE ' . $this->makeList( $conds, self::LIST_AND );
1585 $isCondValid = ( is_string( $conds ) || is_array( $conds ) ) && $conds;
1586 if ( !$isCondValid ) {
1587 throw new DBLanguageError( __METHOD__ .
' called with empty conditions' );
1590 $encTable = $this->tableName( $table );
1591 $sql =
"DELETE FROM $encTable";
1594 $cleanCondsSql =
'';
1595 if ( $conds !== self::ALL_ROWS && $conds !== [ self::ALL_ROWS ] ) {
1596 $cleanCondsSql =
' WHERE ' . $this->scrubArray( $conds );
1597 if ( is_array( $conds ) ) {
1598 $conds = $this->makeList( $conds, self::LIST_AND );
1600 $condsSql .=
' WHERE ' . $conds;
1604 self::QUERY_CHANGE_ROWS,
1607 $sql . $cleanCondsSql
1611 private function scrubArray( $array, $listType = self::LIST_AND ) {
1612 if ( is_array( $array ) ) {
1613 $scrubbedArray = [];
1614 foreach ( $array as $key => $value ) {
1616 $scrubbedArray[$key] = $value->toGeneralizedSql();
1618 $scrubbedArray[$key] =
'?';
1621 return $this->makeList( $scrubbedArray, $listType );
1627 $isCondValid = ( is_string( $conds ) || is_array( $conds ) ) && $conds;
1628 if ( !$isCondValid ) {
1629 throw new DBLanguageError( __METHOD__ .
' called with empty conditions' );
1631 $encTable = $this->tableName( $table );
1632 $opts = $this->makeUpdateOptions( $options );
1633 $sql =
"UPDATE $opts $encTable";
1634 $condsSql =
" SET " . $this->makeList( $set, self::LIST_SET );
1635 $cleanCondsSql =
" SET " . $this->scrubArray( $set, self::LIST_SET );
1637 if ( $conds && $conds !== self::ALL_ROWS && $conds !== [ self::ALL_ROWS ] ) {
1638 $cleanCondsSql .=
' WHERE ' . $this->scrubArray( $conds );
1639 if ( is_array( $conds ) ) {
1640 $conds = $this->makeList( $conds, self::LIST_AND );
1642 $condsSql .=
' WHERE ' . $conds;
1646 self::QUERY_CHANGE_ROWS,
1649 $sql . $cleanCondsSql
1660 $opts = $this->makeUpdateOptionsArray( $options );
1662 return implode(
' ', $opts );
1673 $options = $this->normalizeOptions( $options );
1677 if ( in_array(
'IGNORE', $options ) ) {
1690 if ( is_array( $options ) ) {
1692 } elseif ( is_string( $options ) ) {
1693 return ( $options ===
'' ) ? [] : [ $options ];
1695 throw new DBLanguageError( __METHOD__ .
': expected string or array' );
1703 return "DROP TABLE " . $this->tableName( $table ) .
" CASCADE";
1734 'ROLLBACK TO SAVEPOINT',
1750 return "(SELECT __$column FROM __VALS)";
1754 return 'SAVEPOINT ' . $this->addIdentifierQuotes( $identifier );
1758 return 'RELEASE SAVEPOINT ' . $this->addIdentifierQuotes( $identifier );
1762 return 'ROLLBACK TO SAVEPOINT ' . $this->addIdentifierQuotes( $identifier );
1770 $rows = $this->normalizeRowArray( $rows );
1775 $options = $this->normalizeOptions( $options );
1776 if ( $this->isFlagInOptions(
'IGNORE', $options ) ) {
1777 [ $sql, $cleanSql ] = $this->insertNonConflictingSqlText( $table, $rows );
1779 [ $sql, $cleanSql ] = $this->insertSqlText( $table, $rows );
1781 return new Query( $sql, self::QUERY_CHANGE_ROWS,
'INSERT', $table, $cleanSql );
1790 if ( !$rowOrRows ) {
1792 } elseif ( isset( $rowOrRows[0] ) ) {
1795 $rows = [ $rowOrRows ];
1798 foreach ( $rows as $row ) {
1799 if ( !is_array( $row ) ) {
1801 } elseif ( !$row ) {
1818 $rows = $this->normalizeRowArray( $rows );
1819 if ( !$uniqueKeys ) {
1820 throw new DBLanguageError(
'No unique key specified for upsert/replace' );
1822 $uniqueKey = $this->normalizeUpsertKeys( $uniqueKeys );
1823 $this->assertValidUpsertRowArray( $rows, $uniqueKey );
1835 if ( $conds ===
null || $conds ===
false ) {
1836 $this->logger->warning(
1840 .
' with incorrect parameters: $conds must be a string or an array',
1841 [
'db_log_category' =>
'sql' ]
1844 } elseif ( $conds ===
'' ) {
1848 return is_array( $conds ) ? $conds : [ $conds ];
1856 private function normalizeUpsertKeys( $uniqueKeys ) {
1857 if ( is_string( $uniqueKeys ) ) {
1858 return [ $uniqueKeys ];
1859 } elseif ( !is_array( $uniqueKeys ) ) {
1862 if ( count( $uniqueKeys ) !== 1 || !isset( $uniqueKeys[0] ) ) {
1863 throw new DBLanguageError(
1864 "The unique key array should contain a single unique index" );
1867 $uniqueKey = $uniqueKeys[0];
1868 if ( is_string( $uniqueKey ) ) {
1871 $this->logger->warning( __METHOD__ .
1872 " called with deprecated parameter style: " .
1873 "the unique key array should be a string or array of string arrays",
1875 'exception' =>
new RuntimeException(),
1876 'db_log_category' =>
'sql',
1879 } elseif ( is_array( $uniqueKey ) ) {
1882 throw new DBLanguageError(
'Invalid unique key array entry' );
1893 foreach ( $rows as $row ) {
1894 foreach ( $uniqueKey as $column ) {
1895 if ( !isset( $row[$column] ) ) {
1897 "NULL/absent values for unique key (" . implode(
',', $uniqueKey ) .
")"
1916 throw new DBLanguageError(
"Update assignment list can't be empty for upsert" );
1921 $soleRow = ( count( $rows ) == 1 ) ? reset( $rows ) :
null;
1925 foreach ( $set as $k => $v ) {
1926 if ( is_string( $k ) ) {
1928 if ( in_array( $k, $uniqueKey,
true ) ) {
1929 if ( $soleRow && array_key_exists( $k, $soleRow ) && $soleRow[$k] === $v ) {
1930 $this->logger->warning(
1931 __METHOD__ .
" called with redundant assignment to column '$k'",
1933 'exception' =>
new RuntimeException(),
1934 'db_log_category' =>
'sql',
1939 "Cannot reassign column '$k' since it belongs to the provided unique key"
1943 } elseif ( preg_match(
'/^([a-zA-Z0-9_]+)\s*=/', $v, $m ) ) {
1945 if ( in_array( $m[1], $uniqueKey,
true ) ) {
1947 "Cannot reassign column '{$m[1]}' since it belongs to the provided unique key"
1959 if ( is_array( $var ) ) {
1962 } elseif ( count( $var ) == 1 ) {
1963 $column = $var[0] ?? reset( $var );
1975 $this->schemaVars = is_array( $vars ) ? $vars :
null;
1985 return $this->schemaVars ?? $this->getDefaultSchemaVars();
2022 $vars = $this->getSchemaVars();
2023 return preg_replace_callback(
2025 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
2026 \'\{\$ (\w+) }\' | # 3. addQuotes
2027 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
2028 /\*\$ (\w+) \*/ # 5. leave unencoded
2030 function ( $m ) use ( $vars ) {
2033 if ( isset( $m[1] ) && $m[1] !==
'' ) {
2034 if ( $m[1] ===
'i' ) {
2035 return $this->indexName( $m[2] );
2037 return $this->tableName( $m[2] );
2039 } elseif ( isset( $m[3] ) && $m[3] !==
'' && array_key_exists( $m[3], $vars ) ) {
2040 return $this->quoter->addQuotes( $vars[$m[3]] );
2041 } elseif ( isset( $m[4] ) && $m[4] !==
'' && array_key_exists( $m[4], $vars ) ) {
2042 return $this->addIdentifierQuotes( $vars[$m[4]] );
2043 } elseif ( isset( $m[5] ) && $m[5] !==
'' && array_key_exists( $m[5], $vars ) ) {
2044 return $vars[$m[5]];
2054 throw new RuntimeException(
'locking must be implemented in subclasses' );
2058 throw new RuntimeException(
'locking must be implemented in subclasses' );
2062 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.