22use InvalidArgumentException;
23use Psr\Log\LoggerInterface;
24use Psr\Log\NullLogger;
27use Wikimedia\Assert\Assert;
33use Wikimedia\Timestamp\ConvertibleTimestamp;
66 $this->logger =
$logger ??
new NullLogger();
68 $this->errorLogger =
$errorLogger ??
static function ( Throwable $e ) {
69 trigger_error( get_class( $e ) .
': ' . $e->getMessage(), E_USER_WARNING );
85 public function bitAnd( $fieldLeft, $fieldRight ) {
86 return "($fieldLeft & $fieldRight)";
93 public function bitOr( $fieldLeft, $fieldRight ) {
94 return "($fieldLeft | $fieldRight)";
102 return '"' . str_replace(
'"',
'""',
$s ) .
'"';
134 $fields = is_array( $fields ) ? $fields : [ $fields ];
135 $values = is_array( $values ) ? $values : [ $values ];
138 foreach ( $fields as $alias => $field ) {
139 if ( is_int( $alias ) ) {
142 $encValues[] = $field;
145 foreach ( $values as $value ) {
146 if ( is_int( $value ) || is_float( $value ) ) {
147 $encValues[] = $value;
148 } elseif ( is_string( $value ) ) {
149 $encValues[] = $this->quoter->addQuotes( $value );
150 } elseif ( $value ===
null ) {
157 return $sqlfunc .
'(' . implode(
',', $encValues ) .
')';
160 public function makeList( array $a, $mode = self::LIST_COMMA ) {
164 foreach ( $a as $field => $value ) {
168 if ( $mode == self::LIST_AND ) {
170 } elseif ( $mode == self::LIST_OR ) {
177 if ( ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_numeric( $field ) ) {
179 } elseif ( $mode == self::LIST_SET && is_numeric( $field ) ) {
182 ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_array( $value )
185 $includeNull =
false;
186 foreach ( array_keys( $value,
null,
true ) as $nullKey ) {
188 unset( $value[$nullKey] );
190 if ( count( $value ) == 0 && !$includeNull ) {
191 throw new InvalidArgumentException(
192 __METHOD__ .
": empty input for field $field" );
193 } elseif ( count( $value ) == 0 ) {
195 $list .=
"$field IS NULL";
198 if ( $includeNull ) {
202 if ( count( $value ) == 1 ) {
206 $value = array_values( $value )[0];
207 $list .= $field .
" = " . $this->quoter->addQuotes( $value );
209 $list .= $field .
" IN (" . $this->
makeList( $value ) .
") ";
212 if ( $includeNull ) {
213 $list .=
" OR $field IS NULL)";
216 } elseif ( $value ===
null ) {
217 if ( $mode == self::LIST_AND || $mode == self::LIST_OR ) {
218 $list .=
"$field IS ";
219 } elseif ( $mode == self::LIST_SET ) {
220 $list .=
"$field = ";
225 $mode == self::LIST_AND || $mode == self::LIST_OR || $mode == self::LIST_SET
227 $list .=
"$field = ";
229 $list .= $mode == self::LIST_NAMES ? $value : $this->quoter->addQuotes( $value );
239 foreach ( $data as
$base => $sub ) {
240 if ( count( $sub ) ) {
242 [ $baseKey =>
$base, $subKey => array_map(
'strval', array_keys( $sub ) ) ],
249 return $this->
makeList( $conds, self::LIST_OR );
257 if ( count( $condsArray ) === 0 ) {
258 throw new InvalidArgumentException(
259 __METHOD__ .
": empty condition array" );
261 $condsByFieldSet = [];
262 foreach ( $condsArray as $conds ) {
263 if ( !count( $conds ) ) {
264 throw new InvalidArgumentException(
265 __METHOD__ .
": empty condition subarray" );
267 $fieldKey = implode(
',', array_keys( $conds ) );
268 $condsByFieldSet[$fieldKey][] = $conds;
271 foreach ( $condsByFieldSet as $conds ) {
272 if ( $result !==
'' ) {
275 $result .= $this->factorCondsWithCommonFields( $conds );
287 private function factorCondsWithCommonFields( $condsArray ) {
288 $first = $condsArray[array_key_first( $condsArray )];
289 if ( count( $first ) === 1 ) {
291 $field = array_key_first( $first );
293 foreach ( $condsArray as $conds ) {
294 $values[] = $conds[$field];
296 return $this->
makeList( [ $field => $values ], self::LIST_AND );
299 $field1 = array_key_first( $first );
300 $nullExpressions = [];
301 $expressionsByField1 = [];
302 foreach ( $condsArray as $conds ) {
303 $value1 = $conds[$field1];
304 unset( $conds[$field1] );
305 if ( $value1 ===
null ) {
306 $nullExpressions[] = $conds;
308 $expressionsByField1[$value1][] = $conds;
314 foreach ( $expressionsByField1 as $value1 => $expressions ) {
315 if ( $result !==
'' ) {
319 $factored = $this->factorCondsWithCommonFields( $expressions );
320 $result .=
"($field1 = " . $this->quoter->addQuotes( $value1 ) .
323 if ( count( $nullExpressions ) ) {
324 $factored = $this->factorCondsWithCommonFields( $nullExpressions );
325 if ( $result !==
'' ) {
329 $result .=
"($field1 IS NULL AND $factored)";
343 return 'CONCAT(' . implode(
',', $stringList ) .
')';
351 if ( !is_numeric( $limit ) ) {
353 "Invalid non-numeric limit passed to " . __METHOD__
359 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," :
"" )
371 [ $escapeChar,
'%',
'_' ],
372 [
"{$escapeChar}{$escapeChar}",
"{$escapeChar}%",
"{$escapeChar}_" ],
382 if ( is_array( $param ) ) {
385 $params = func_get_args();
396 foreach ( $params as $value ) {
398 $s .= $value->toString();
405 $this->quoter->addQuotes(
$s ) .
' ESCAPE ' . $this->quoter->addQuotes( $escapeChar ) .
' ';
429 $glue = $all ?
') UNION ALL (' :
') UNION (';
431 return '(' . implode( $glue, $sqls ) .
')';
438 public function conditional( $cond, $caseTrueExpression, $caseFalseExpression ) {
439 if ( is_array( $cond ) ) {
440 $cond = $this->
makeList( $cond, self::LIST_AND );
443 return "(CASE WHEN $cond THEN $caseTrueExpression ELSE $caseFalseExpression END)";
451 return "REPLACE({$orig}, {$old}, {$new})";
459 $t =
new ConvertibleTimestamp( $ts );
461 return $t->getTimestamp( TS_MW );
465 if ( $ts ===
null ) {
481 return ( $expiry ==
'' || $expiry ==
'infinity' || $expiry == $this->
getInfinity() )
487 if ( $expiry ==
'' || $expiry ==
'infinity' || $expiry == $this->
getInfinity() ) {
491 return ConvertibleTimestamp::convert( $format, $expiry );
500 $functionBody =
"$input FROM $startPosition";
501 if ( $length !==
null ) {
502 $functionBody .=
" FOR $length";
504 return 'SUBSTRING(' . $functionBody .
')';
520 if ( $startPosition === 0 ) {
522 throw new InvalidArgumentException(
'Use 1 as $startPosition for the beginning of the string' );
524 if ( !is_int( $startPosition ) || $startPosition < 0 ) {
525 throw new InvalidArgumentException(
526 '$startPosition must be a positive integer'
529 if ( !( is_int( $length ) && $length >= 0 || $length ===
null ) ) {
530 throw new InvalidArgumentException(
531 '$length must be null or an integer greater than or equal to 0'
543 return "CAST( $field AS CHARACTER )";
551 return 'CAST( ' . $field .
' AS INTEGER )';
571 return $this->indexAliases[$index] ?? $index;
579 $this->tableAliases = $aliases;
587 $this->indexAliases = $aliases;
599 $this->currentDomain->getDatabase(),
600 $this->currentDomain->getSchema(),
614 $table, $vars, $conds =
'', $fname = __METHOD__, $options = [], $join_conds = []
616 if ( is_array( $table ) ) {
618 } elseif ( $table ===
'' || $table ===
null || $table ===
false ) {
620 } elseif ( is_string( $table ) ) {
621 $tables = [ $table ];
623 throw new DBLanguageError( __METHOD__ .
' called with incorrect table parameter' );
626 if ( is_array( $vars ) ) {
632 $options = (array)$options;
634 $useIndexByTable = $options[
'USE INDEX'] ?? [];
635 if ( !is_array( $useIndexByTable ) ) {
636 if ( count( $tables ) <= 1 ) {
637 $useIndexByTable = [ reset( $tables ) => $useIndexByTable ];
639 $e =
new DBLanguageError( __METHOD__ .
" got ambiguous USE INDEX ($fname)" );
644 $ignoreIndexByTable = $options[
'IGNORE INDEX'] ?? [];
645 if ( !is_array( $ignoreIndexByTable ) ) {
646 if ( count( $tables ) <= 1 ) {
647 $ignoreIndexByTable = [ reset( $tables ) => $ignoreIndexByTable ];
649 $e =
new DBLanguageError( __METHOD__ .
" got ambiguous IGNORE INDEX ($fname)" );
655 $this->selectOptionsIncludeLocking( $options ) &&
656 $this->selectFieldsOrOptionsAggregate( $vars, $options )
660 $this->logger->warning(
661 __METHOD__ .
": aggregation used with a locking SELECT ($fname)"
665 if ( count( $tables ) ) {
676 list( $startOpts, $preLimitTail, $postLimitTail ) = $this->
makeSelectOptions( $options );
678 if ( is_array( $conds ) ) {
679 $where = $this->
makeList( $conds, self::LIST_AND );
680 } elseif ( $conds ===
null || $conds ===
false ) {
682 $this->logger->warning(
686 .
' with incorrect parameters: $conds must be a string or an array',
687 [
'db_log_category' =>
'sql' ]
689 } elseif ( is_string( $conds ) ) {
692 throw new DBLanguageError( __METHOD__ .
' called with incorrect parameters' );
696 if ( $where ===
'' || $where ===
'*' ) {
697 $sql =
"SELECT $startOpts $fields $from $preLimitTail";
699 $sql =
"SELECT $startOpts $fields $from WHERE $where $preLimitTail";
702 if ( isset( $options[
'LIMIT'] ) ) {
703 $sql = $this->
limitResult( $sql, $options[
'LIMIT'], $options[
'OFFSET'] ??
false );
705 $sql =
"$sql $postLimitTail";
707 if ( isset( $options[
'EXPLAIN'] ) ) {
708 $sql =
'EXPLAIN ' . $sql;
718 private function selectOptionsIncludeLocking( $options ) {
719 $options = (array)$options;
720 foreach ( [
'FOR UPDATE',
'LOCK IN SHARE MODE' ] as $lock ) {
721 if ( in_array( $lock, $options,
true ) ) {
734 private function selectFieldsOrOptionsAggregate( $fields, $options ) {
735 foreach ( (array)$options as $key => $value ) {
736 if ( is_string( $key ) ) {
737 if ( preg_match(
'/^(?:GROUP BY|HAVING)$/i', $key ) ) {
740 } elseif ( is_string( $value ) ) {
741 if ( preg_match(
'/^(?:DISTINCT|DISTINCTROW)$/i', $value ) ) {
747 $regex =
'/^(?:COUNT|MIN|MAX|SUM|GROUP_CONCAT|LISTAGG|ARRAY_AGG)\s*\\(/i';
748 foreach ( (array)$fields as $field ) {
749 if ( is_string( $field ) && preg_match( $regex, $field ) ) {
765 foreach ( $fields as $alias => $field ) {
766 if ( is_numeric( $alias ) ) {
785 if ( !$alias || (
string)$alias === (
string)$name ) {
810 $use_index = (array)$use_index;
811 $ignore_index = (array)$ignore_index;
812 $join_conds = (array)$join_conds;
814 foreach ( $tables as $alias => $table ) {
815 if ( !is_string( $alias ) ) {
820 if ( is_array( $table ) ) {
822 if ( count( $table ) > 1 ) {
825 $table, $use_index, $ignore_index, $join_conds ) .
')';
828 $innerTable = reset( $table );
829 $innerAlias = key( $table );
832 is_string( $innerAlias ) ? $innerAlias : $innerTable
840 if ( isset( $join_conds[$alias] ) ) {
841 Assert::parameterType(
'array', $join_conds[$alias],
"join_conds[$alias]" );
842 list( $joinType, $conds ) = $join_conds[$alias];
844 $tableClause .=
' ' . $joinedTable;
845 if ( isset( $use_index[$alias] ) ) {
846 $use = $this->
useIndexClause( implode(
',', (array)$use_index[$alias] ) );
848 $tableClause .=
' ' . $use;
851 if ( isset( $ignore_index[$alias] ) ) {
853 implode(
',', (array)$ignore_index[$alias] ) );
854 if ( $ignore !=
'' ) {
855 $tableClause .=
' ' . $ignore;
858 $on = $this->
makeList( (array)$conds, self::LIST_AND );
860 $tableClause .=
' ON (' . $on .
')';
863 $retJOIN[] = $tableClause;
864 } elseif ( isset( $use_index[$alias] ) ) {
866 $tableClause = $joinedTable;
868 implode(
',', (array)$use_index[$alias] )
871 $ret[] = $tableClause;
872 } elseif ( isset( $ignore_index[$alias] ) ) {
874 $tableClause = $joinedTable;
876 implode(
',', (array)$ignore_index[$alias] )
879 $ret[] = $tableClause;
881 $tableClause = $joinedTable;
883 $ret[] = $tableClause;
888 $implicitJoins = implode(
',', $ret );
889 $explicitJoins = implode(
' ', $retJOIN );
892 return implode(
' ', [ $implicitJoins, $explicitJoins ] );
904 switch ( strtoupper( $joinType ) ) {
912 case 'STRAIGHT_JOIN':
913 case 'STRAIGHT JOIN':
934 if ( is_string( $table ) ) {
935 $quotedTable = $this->
tableName( $table );
936 } elseif ( $table instanceof
Subquery ) {
937 $quotedTable = (string)$table;
939 throw new InvalidArgumentException(
"Table must be a string or Subquery" );
942 if ( $alias ===
false || $alias === $table ) {
944 throw new InvalidArgumentException(
"Subquery table missing alias" );
957 public function tableName( $name, $format =
'quoted' ) {
960 __METHOD__ .
': got Subquery instance when expecting a string'
964 # Skip the entire process when we have a string quoted on both ends.
965 # Note that we check the end so that we will still quote any use of
966 # use of `database`.table. But won't break things if someone wants
967 # to query a database table with a dot in the name.
972 # Lets test for any bits of text that should never show up in a table
973 # name. Basically anything like JOIN or ON which are actually part of
974 # SQL queries, but may end up inside of the table value to combine
975 # sql. Such as how the API is doing.
976 # Note that we use a whitespace test rather than a \b test to avoid
977 # any remote case where a word like on may be inside of a table name
978 # surrounded by symbols which may be considered word breaks.
979 if ( preg_match(
'/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
980 $this->logger->warning(
981 __METHOD__ .
": use of subqueries is not supported this way",
983 'exception' =>
new RuntimeException(),
984 'db_log_category' =>
'sql',
991 # Split database and table into proper variables.
994 # Quote $table and apply the prefix if not quoted.
995 # $tableName might be empty if this is called from Database::replaceVars()
996 $tableName =
"{$prefix}{$table}";
997 if ( $format ===
'quoted'
1004 # Quote $schema and $database and merge them with the table name if needed
1005 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
1006 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
1018 # We reverse the explode so that database.table and table both output the correct table.
1019 $dbDetails = explode(
'.', $name, 3 );
1020 if ( $this->currentDomain ) {
1021 $currentDomainPrefix = $this->currentDomain->getTablePrefix();
1023 $currentDomainPrefix =
null;
1025 if ( count( $dbDetails ) == 3 ) {
1026 list( $database, $schema, $table ) = $dbDetails;
1027 # We don't want any prefix added in this case
1029 } elseif ( count( $dbDetails ) == 2 ) {
1030 list( $database, $table ) = $dbDetails;
1031 # We don't want any prefix added in this case
1033 # In dbs that support it, $database may actually be the schema
1034 # but that doesn't affect any of the functionality here
1037 list( $table ) = $dbDetails;
1038 if ( isset( $this->tableAliases[$table] ) ) {
1039 $database = $this->tableAliases[$table][
'dbname'];
1040 $schema = is_string( $this->tableAliases[$table][
'schema'] )
1041 ? $this->tableAliases[$table][
'schema']
1043 $prefix = is_string( $this->tableAliases[$table][
'prefix'] )
1044 ? $this->tableAliases[$table][
'prefix']
1045 : $currentDomainPrefix;
1049 $prefix = $currentDomainPrefix; # Default prefix
1053 return [ $database, $schema, $prefix, $table ];
1061 if ( $this->currentDomain ) {
1062 return $this->currentDomain->getSchema();
1073 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
1074 if ( $namespace !==
null && $namespace !==
'' ) {
1078 $relation = $namespace .
'.' . $relation;
1087 foreach ( $tables as $name ) {
1088 $retVal[$name] = $this->
tableName( $name );
1097 foreach ( $tables as $name ) {
1115 return $name[0] ==
'"' && substr( $name, -1, 1 ) ==
'"';
1160 $preLimitTail = $postLimitTail =
'';
1165 foreach ( $options as $key => $option ) {
1166 if ( is_numeric( $key ) ) {
1167 $noKeyOptions[$option] =
true;
1175 if ( isset( $noKeyOptions[
'FOR UPDATE'] ) ) {
1176 $postLimitTail .=
' FOR UPDATE';
1179 if ( isset( $noKeyOptions[
'LOCK IN SHARE MODE'] ) ) {
1180 $postLimitTail .=
' LOCK IN SHARE MODE';
1183 if ( isset( $noKeyOptions[
'DISTINCT'] ) || isset( $noKeyOptions[
'DISTINCTROW'] ) ) {
1184 $startOpts .=
'DISTINCT';
1187 # Various MySQL extensions
1188 if ( isset( $noKeyOptions[
'STRAIGHT_JOIN'] ) ) {
1189 $startOpts .=
' /*! STRAIGHT_JOIN */';
1192 if ( isset( $noKeyOptions[
'SQL_BIG_RESULT'] ) ) {
1193 $startOpts .=
' SQL_BIG_RESULT';
1196 if ( isset( $noKeyOptions[
'SQL_BUFFER_RESULT'] ) ) {
1197 $startOpts .=
' SQL_BUFFER_RESULT';
1200 if ( isset( $noKeyOptions[
'SQL_SMALL_RESULT'] ) ) {
1201 $startOpts .=
' SQL_SMALL_RESULT';
1204 if ( isset( $noKeyOptions[
'SQL_CALC_FOUND_ROWS'] ) ) {
1205 $startOpts .=
' SQL_CALC_FOUND_ROWS';
1208 return [ $startOpts, $preLimitTail, $postLimitTail ];
1221 if ( isset( $options[
'GROUP BY'] ) ) {
1222 $gb = is_array( $options[
'GROUP BY'] )
1223 ? implode(
',', $options[
'GROUP BY'] )
1224 : $options[
'GROUP BY'];
1225 $sql .=
' GROUP BY ' . $gb;
1227 if ( isset( $options[
'HAVING'] ) ) {
1228 $having = is_array( $options[
'HAVING'] )
1229 ? $this->
makeList( $options[
'HAVING'], self::LIST_AND )
1230 : $options[
'HAVING'];
1231 $sql .=
' HAVING ' . $having;
1246 if ( isset( $options[
'ORDER BY'] ) ) {
1247 $ob = is_array( $options[
'ORDER BY'] )
1248 ? implode(
',', $options[
'ORDER BY'] )
1249 : $options[
'ORDER BY'];
1251 return ' ORDER BY ' . $ob;
1260 array $permute_conds,
1262 $fname = __METHOD__,
1268 foreach ( $permute_conds as $field => $values ) {
1273 $values = array_unique( $values );
1275 foreach ( $conds as $cond ) {
1276 foreach ( $values as $value ) {
1277 $cond[$field] = $value;
1278 $newConds[] = $cond;
1284 $extra_conds = $extra_conds ===
'' ? [] : (array)$extra_conds;
1288 if ( count( $conds ) === 1 &&
1292 $table, $vars, $conds[0] + $extra_conds, $fname, $options, $join_conds
1301 $limit = $options[
'LIMIT'] ??
null;
1302 $offset = $options[
'OFFSET'] ??
false;
1303 $all = empty( $options[
'NOTALL'] ) && !in_array(
'NOTALL', $options );
1305 unset( $options[
'ORDER BY'], $options[
'LIMIT'], $options[
'OFFSET'] );
1307 if ( array_key_exists(
'INNER ORDER BY', $options ) ) {
1308 $options[
'ORDER BY'] = $options[
'INNER ORDER BY'];
1310 if ( $limit !==
null && is_numeric( $offset ) && $offset != 0 ) {
1314 $options[
'LIMIT'] = $limit + $offset;
1315 unset( $options[
'OFFSET'] );
1320 foreach ( $conds as $cond ) {
1322 $table, $vars, $cond + $extra_conds, $fname, $options, $join_conds
1326 if ( $limit !==
null ) {
1327 $sql = $this->
limitResult( $sql, $limit, $offset );
1338 $delim, $table, $field, $conds =
'', $join_conds = []
1340 $fld =
"GROUP_CONCAT($field SEPARATOR " . $this->quoter->addQuotes( $delim ) .
')';
1342 return '(' . $this->
selectSQLText( $table, $fld, $conds, __METHOD__, [], $join_conds ) .
')';
1346 $table, $vars, $conds =
'', $fname = __METHOD__,
1347 $options = [], $join_conds = []
1350 $this->
selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds )
1358 return "INSERT INTO $encTable ($sqlColumns) VALUES $sqlTuples";
1373 $firstRow = $rows[0];
1374 if ( !is_array( $firstRow ) || !$firstRow ) {
1378 $tupleColumns = array_keys( $firstRow );
1381 foreach ( $rows as $row ) {
1382 $rowColumns = array_keys( $row );
1384 if ( $rowColumns !== $tupleColumns ) {
1386 'Got row columns (' . implode(
', ', $rowColumns ) .
') ' .
1387 'instead of expected (' . implode(
', ', $tupleColumns ) .
')'
1391 $valueTuples[] =
'(' . $this->
makeList( $row, self::LIST_COMMA ) .
')';
1394 $magicAliasFields = [];
1395 foreach ( $tupleColumns as $column ) {
1396 $magicAliasFields[] = $aliasPrefix . $column;
1400 $this->
makeList( $tupleColumns, self::LIST_NAMES ),
1401 implode(
',', $valueTuples ),
1402 $this->
makeList( $magicAliasFields, self::LIST_NAMES )
1411 return rtrim(
"$sqlVerb $encTable ($sqlColumns) VALUES $sqlTuples $sqlOpts" );
1420 return [
'INSERT IGNORE INTO',
'' ];
1429 array $insertOptions,
1430 array $selectOptions,
1433 list( $sqlVerb, $sqlOpts ) = $this->
isFlagInOptions(
'IGNORE', $insertOptions )
1435 : [
'INSERT INTO',
'' ];
1436 $encDstTable = $this->
tableName( $destTable );
1437 $sqlDstColumns = implode(
',', array_keys( $varMap ) );
1440 array_values( $varMap ),
1447 return rtrim(
"$sqlVerb $encDstTable ($sqlDstColumns) $selectSql $sqlOpts" );
1457 foreach ( array_keys( $options, $option,
true ) as $k ) {
1458 if ( is_int( $k ) ) {
1476 } elseif ( !$uniqueKey ) {
1480 if ( count( $uniqueKey ) == 1 ) {
1482 $column = reset( $uniqueKey );
1483 $values = array_column( $rows, $column );
1484 if ( count( $values ) !== count( $rows ) ) {
1485 throw new DBLanguageError(
"Missing values for unique key ($column)" );
1488 return $this->
makeList( [ $column => $values ], self::LIST_AND );
1491 $nullByUniqueKeyColumn = array_fill_keys( $uniqueKey,
null );
1494 foreach ( $rows as $row ) {
1495 $rowKeyMap = array_intersect_key( $row, $nullByUniqueKeyColumn );
1496 if ( count( $rowKeyMap ) != count( $uniqueKey ) ) {
1498 "Missing values for unique key (" . implode(
',', $uniqueKey ) .
")"
1501 $orConds[] = $this->
makeList( $rowKeyMap, self::LIST_AND );
1504 return count( $orConds ) > 1
1505 ? $this->
makeList( $orConds, self::LIST_OR )
1511 throw new DBLanguageError( __METHOD__ .
' called with empty $conds' );
1514 $delTable = $this->
tableName( $delTable );
1515 $joinTable = $this->
tableName( $joinTable );
1516 $sql =
"DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
1517 if ( $conds !=
'*' ) {
1518 $sql .=
'WHERE ' . $this->
makeList( $conds, self::LIST_AND );
1529 $sql =
"DELETE FROM $table";
1531 if ( $conds !== self::ALL_ROWS ) {
1532 if ( is_array( $conds ) ) {
1533 $conds = $this->
makeList( $conds, self::LIST_AND );
1535 $sql .=
' WHERE ' . $conds;
1545 $sql =
"UPDATE $opts $table SET " . $this->
makeList( $set, self::LIST_SET );
1547 if ( $conds && $conds !== self::ALL_ROWS ) {
1548 if ( is_array( $conds ) ) {
1549 $conds = $this->
makeList( $conds, self::LIST_AND );
1551 $sql .=
' WHERE ' . $conds;
1571 $isCondValid = ( is_string( $conds ) || is_array( $conds ) ) && $conds;
1572 if ( !$isCondValid ) {
1574 wfDeprecated( $fname .
' called with empty $conds',
'1.35',
false, 4 );
1576 throw new DBLanguageError( $fname .
' called with empty conditions' );
1591 return implode(
' ', $opts );
1606 if ( in_array(
'IGNORE', $options ) ) {
1619 if ( is_array( $options ) ) {
1621 } elseif ( is_string( $options ) ) {
1622 return ( $options ===
'' ) ? [] : [ $options ];
1624 throw new DBLanguageError( __METHOD__ .
': expected string or array' );
1632 return "DROP TABLE " . $this->
tableName( $table ) .
" CASCADE";
1642 '/^\s*(rollback\s+to\s+savepoint|[a-z]+)/i',
1645 ) ? strtoupper( $m[1] ) :
null;
1668 'ROLLBACK TO SAVEPOINT',
1701 $this->
fieldHasBit( $flags, self::QUERY_CHANGE_ROWS ) ||
1702 $this->
fieldHasBit( $flags, self::QUERY_CHANGE_SCHEMA )
1708 $this->
fieldHasBit( $flags, self::QUERY_CHANGE_NONE ) ||
1709 $this->
fieldHasBit( $flags, self::QUERY_CHANGE_TRX ) ||
1710 $this->
fieldHasBit( $flags, self::QUERY_CHANGE_LOCKS )
1717 if ( preg_match(
'/^\s*\(?SELECT\b/i', $sql ) ) {
1718 return (
bool)preg_match(
'/\bFOR\s+UPDATE\)?\s*$/i', $sql );
1734 '/^\s*(BEGIN|ROLLBACK|COMMIT|SAVEPOINT|RELEASE|SET|SHOW|EXPLAIN|USE)\b/i',
1745 return ( ( $flags & $bit ) === $bit );
1751 return "(SELECT __$column FROM __VALS)";
1790 if ( !$rowOrRows ) {
1792 } elseif ( isset( $rowOrRows[0] ) ) {
1795 $rows = [ $rowOrRows ];
1798 foreach ( $rows as $row ) {
1799 if ( !is_array( $row ) ) {
1801 } elseif ( !$row ) {
1823 if ( !$uniqueKeys ) {
1825 $this->logger->warning(
1826 "upsert/replace called with no unique key",
1828 'exception' =>
new RuntimeException(),
1829 'db_log_category' =>
'sql',
1834 $identityKey = $this->normalizeUpsertKeys( $uniqueKeys );
1835 if ( $identityKey ) {
1837 if ( $allDefaultKeyValues ) {
1840 $this->logger->warning(
1841 "upsert/replace called with all-null values for unique key",
1843 'exception' =>
new RuntimeException(),
1844 'db_log_category' =>
'sql',
1850 return $identityKey;
1860 if ( $conds ===
null || $conds ===
false ) {
1861 $this->logger->warning(
1865 .
' with incorrect parameters: $conds must be a string or an array',
1866 [
'db_log_category' =>
'sql' ]
1869 } elseif ( $conds ===
'' ) {
1873 return is_array( $conds ) ? $conds : [ $conds ];
1882 private function normalizeUpsertKeys( $uniqueKeys ) {
1883 if ( is_string( $uniqueKeys ) ) {
1884 return [ $uniqueKeys ];
1885 } elseif ( !is_array( $uniqueKeys ) ) {
1888 if ( count( $uniqueKeys ) !== 1 || !isset( $uniqueKeys[0] ) ) {
1889 throw new DBLanguageError(
1890 "The unique key array should contain a single unique index" );
1893 $uniqueKey = $uniqueKeys[0];
1894 if ( is_string( $uniqueKey ) ) {
1897 $this->logger->warning( __METHOD__ .
1898 " called with deprecated parameter style: " .
1899 "the unique key array should be a string or array of string arrays",
1901 'exception' =>
new RuntimeException(),
1902 'db_log_category' =>
'sql',
1905 } elseif ( is_array( $uniqueKey ) ) {
1908 throw new DBLanguageError(
'Invalid unique key array entry' );
1921 foreach ( $rows as $row ) {
1922 foreach ( $identityKey as $column ) {
1923 $numNulls += ( isset( $row[$column] ) ? 0 : 1 );
1929 $numNulls !== ( count( $rows ) * count( $identityKey ) )
1932 "NULL/absent values for unique key (" . implode(
',', $identityKey ) .
")"
1936 return (
bool)$numNulls;
1952 $soleRow = ( count( $rows ) == 1 ) ? reset( $rows ) :
null;
1956 foreach ( $set as $k => $v ) {
1957 if ( is_string( $k ) ) {
1959 if ( in_array( $k, $identityKey,
true ) ) {
1960 if ( $soleRow && array_key_exists( $k, $soleRow ) && $soleRow[$k] === $v ) {
1961 $this->logger->warning(
1962 __METHOD__ .
" called with redundant assignment to column '$k'",
1964 'exception' =>
new RuntimeException(),
1965 'db_log_category' =>
'sql',
1970 "Cannot reassign column '$k' since it belongs to identity key"
1974 } elseif ( preg_match(
'/^([a-zA-Z0-9_]+)\s*=/', $v, $m ) ) {
1976 if ( in_array( $m[1], $identityKey,
true ) ) {
1978 "Cannot reassign column '{$m[1]}' since it belongs to identity key"
1990 if ( is_array( $var ) ) {
1993 } elseif ( count( $var ) == 1 ) {
1994 $column = $var[0] ?? reset( $var );
2006 $this->schemaVars = is_array( $vars ) ? $vars :
null;
2055 return preg_replace_callback(
2057 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
2058 \'\{\$ (\w+) }\' | # 3. addQuotes
2059 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
2060 /\*\$ (\w+) \*/ # 5. leave unencoded
2062 function ( $m ) use ( $vars ) {
2065 if ( isset( $m[1] ) && $m[1] !==
'' ) {
2066 if ( $m[1] ===
'i' ) {
2071 } elseif ( isset( $m[3] ) && $m[3] !==
'' && array_key_exists( $m[3], $vars ) ) {
2072 return $this->quoter->addQuotes( $vars[$m[3]] );
2073 } elseif ( isset( $m[4] ) && $m[4] !==
'' && array_key_exists( $m[4], $vars ) ) {
2075 } elseif ( isset( $m[5] ) && $m[5] !==
'' && array_key_exists( $m[5], $vars ) ) {
2076 return $vars[$m[5]];
2086 throw new RuntimeException(
'locking must be implemented in subclasses' );
2090 throw new RuntimeException(
'locking must be implemented in subclasses' );
2094 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.
Class to handle database/schema/prefix specifications for IDatabase.
foreach( $mmfl['setupFiles'] as $fileName) if($queue) if(empty( $mmfl['quiet'])) $s