25use Wikimedia\AtEase\AtEase;
66 private $sessionLastAutoRowId;
88 foreach ( [
'KeyPath',
'CertPath',
'CAFile',
'CAPath',
'Ciphers' ] as $name ) {
94 $this->utf8Mode = !empty(
$params[
'utf8Mode'] );
106 $params[
'lagDetectionMethod'] ??
'Seconds_Behind_Master',
107 $params[
'lagDetectionOptions'] ?? [],
119 protected function open( $server, $user, $password, $db, $schema, $tablePrefix ) {
120 $this->
close( __METHOD__ );
122 if ( $schema !==
null ) {
128 $this->conn = $this->mysqlConnect( $server, $user, $password, $db );
129 }
catch ( RuntimeException $e ) {
135 if ( !$this->conn ) {
141 $db && strlen( $db ) ? $db :
null,
145 $this->platform->setPrefix( $tablePrefix );
148 if ( !$this->flagsHolder->getFlag( self::DBO_GAUGE ) ) {
150 $set[] =
'group_concat_max_len = 262144';
153 foreach ( $this->connectionVariables as $var => $val ) {
155 if ( !is_int( $val ) && !is_float( $val ) ) {
158 $set[] = $this->platform->addIdentifierQuotes( $var ) .
' = ' . $val;
163 $sql =
'SET ' . implode(
', ', $set );
164 $flags = self::QUERY_NO_RETRY | self::QUERY_CHANGE_TRX;
165 $query =
new Query( $sql, $flags,
'SET' );
168 $qs = $this->
executeQuery( $query, __METHOD__, $flags );
169 if ( $qs->res ===
false ) {
173 }
catch ( RuntimeException $e ) {
182 __CLASS__ .
": domain '{$domain->getId()}' has a schema component"
188 if ( $database ===
null ) {
190 $this->currentDomain->getDatabase(),
199 if ( $database !== $this->
getDBname() ) {
201 $query =
new Query( $sql, self::QUERY_CHANGE_TRX,
'USE' );
202 $qs = $this->
executeQuery( $query, __METHOD__, self::QUERY_CHANGE_TRX );
203 if ( $qs->res ===
false ) {
210 $this->currentDomain = $domain;
222 $error = $this->mysqlError( $this->conn );
224 $error = $this->mysqlError();
234 $row = $this->replicationReporter->getReplicationSafetyInfo( $this );
236 if ( $row->binlog_format ===
'ROW' ) {
240 if ( isset( $selectOptions[
'LIMIT'] ) ) {
251 in_array(
'NO_AUTO_COLUMNS', $insertOptions ) ||
252 (
int)$row->innodb_autoinc_lock_mode === 0
257 if ( $this->conn && $this->conn->warning_count ) {
259 $warnings = $this->conn->get_warnings();
260 $done = $warnings ===
false;
262 if ( in_array( $warnings->errno, [
274 'Insert returned unacceptable warning: ' . $warnings->message,
280 $done = !$warnings->next();
306 $conds = $this->platform->normalizeConditions( $conds, $fname );
307 $column = $this->platform->extractSingleFieldFromList( $var );
308 if ( is_string( $column ) && !in_array( $column, [
'*',
'1' ] ) ) {
309 $conds[] =
"$column IS NOT NULL";
312 $options[
'EXPLAIN'] =
true;
313 $res = $this->
select( $tables, $var, $conds, $fname, $options, $join_conds );
314 if ( $res ===
false ) {
317 if ( !$res->numRows() ) {
322 foreach ( $res as $plan ) {
323 $rows *= $plan->rows > 0 ? $plan->rows : 1;
330 $components = $this->platform->qualifiedTableComponents( $table );
331 if ( count( $components ) === 1 ) {
332 $db = $this->currentDomain->getDatabase();
333 $tableName = $components[0];
334 } elseif ( count( $components ) === 2 ) {
335 [ $db, $tableName ] = $components;
340 if ( isset( $this->sessionTempTables[$tableName] ) ) {
345 ->from(
'information_schema.tables' )
347 'table_schema' => $db,
348 'table_name' => $tableName,
361 "SELECT * FROM " . $this->
tableName( $table ) .
" LIMIT 1",
362 self::QUERY_SILENCE_ERRORS | self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
365 $res = $this->
query( $query, __METHOD__ );
370 '@phan-var MysqliResultWrapper $res';
371 return $res->getInternalFieldInfo( $field );
383 public function indexInfo( $table, $index, $fname = __METHOD__ ) {
385 $index = $this->platform->indexName( $index );
387 'SHOW INDEX FROM ' . $this->
tableName( $table ),
388 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
391 $res = $this->
query( $query, $fname );
399 foreach ( $res as $row ) {
400 if ( $row->Key_name == $index ) {
405 return $result ?:
false;
413 return $this->mysqlRealEscapeString( $s );
418 $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
419 $query =
new Query(
"SELECT @@GLOBAL.read_only AS Value", $flags,
'SELECT' );
420 $res = $this->
query( $query, __METHOD__ );
421 $row = $res->fetchObject();
423 return $row && (bool)$row->Value;
430 [ $variant ] = $this->getMySqlServerVariant();
431 if ( $variant ===
'MariaDB' ) {
432 return '[{{int:version-db-mariadb-url}} MariaDB]';
435 return '[{{int:version-db-mysql-url}} MySQL]';
441 private function getMySqlServerVariant() {
448 $parts = explode(
'-', $version, 2 );
450 $suffix = $parts[1] ??
'';
451 if ( strpos( $suffix,
'MariaDB' ) !==
false || strpos( $suffix,
'-maria-' ) !==
false ) {
457 return [ $vendor, $number ];
466 $version = $this->conn->server_info;
468 str_starts_with( $version,
'5.5.5-' ) &&
469 ( str_contains( $version,
'MariaDB' ) || str_contains( $version,
'-maria-' ) )
471 $version = substr( $version, strlen(
'5.5.5-' ) );
480 $sqlAssignments = [];
482 if ( isset( $options[
'connTimeout'] ) ) {
483 $encTimeout = (int)$options[
'connTimeout'];
484 $sqlAssignments[] =
"net_read_timeout=$encTimeout";
485 $sqlAssignments[] =
"net_write_timeout=$encTimeout";
487 if ( isset( $options[
'groupConcatMaxLen'] ) ) {
488 $maxLength = (int)$options[
'groupConcatMaxLen'];
489 $sqlAssignments[] =
"group_concat_max_len=$maxLength";
492 if ( $sqlAssignments ) {
494 'SET ' . implode(
', ', $sqlAssignments ),
495 self::QUERY_CHANGE_TRX | self::QUERY_CHANGE_NONE,
498 $this->
query( $query, __METHOD__ );
508 if ( preg_match(
'/^DELIMITER\s+(\S+)/i', $newLine, $m ) ) {
509 $this->delimiter = $m[1];
513 return parent::streamStatementEnd( $sql, $newLine );
517 $query =
new Query( $this->platform->lockIsFreeSQLText( $lockName ), self::QUERY_CHANGE_LOCKS,
'SELECT' );
518 $res = $this->
query( $query, $method );
519 $row = $res->fetchObject();
521 return ( $row->unlocked == 1 );
524 public function doLock(
string $lockName,
string $method,
int $timeout ) {
525 $query =
new Query( $this->platform->lockSQLText( $lockName, $timeout ), self::QUERY_CHANGE_LOCKS,
'SELECT' );
526 $res = $this->
query( $query, $method );
527 $row = $res->fetchObject();
529 return ( $row->acquired !==
null ) ? (float)$row->acquired :
null;
532 public function doUnlock(
string $lockName,
string $method ) {
533 $query =
new Query( $this->platform->unlockSQLText( $lockName ), self::QUERY_CHANGE_LOCKS,
'SELECT' );
534 $res = $this->
query( $query, $method );
535 $row = $res->fetchObject();
537 return ( $row->released == 1 );
547 $releaseLockFields = [];
548 foreach ( $this->sessionNamedLocks as $name => $info ) {
549 $encName = $this->
addQuotes( $this->platform->makeLockName( $name ) );
550 $releaseLockFields[] =
"RELEASE_LOCK($encName)";
552 if ( $releaseLockFields ) {
553 $sql =
'SELECT ' . implode(
',', $releaseLockFields );
554 $flags = self::QUERY_CHANGE_LOCKS | self::QUERY_NO_RETRY;
555 $query =
new Query( $sql, $flags,
'SELECT' );
556 $qs = $this->
executeQuery( $query, __METHOD__, $flags );
557 if ( $qs->res ===
false ) {
563 public function upsert( $table, array $rows, $uniqueKeys, array $set, $fname = __METHOD__ ) {
564 $identityKey = $this->platform->normalizeUpsertParams( $uniqueKeys, $rows );
568 $this->platform->assertValidUpsertSetArray( $set, $identityKey, $rows );
571 [ $sqlColumns, $sqlTuples ] = $this->platform->makeInsertLists( $rows );
572 $sqlColumnAssignments = $this->
makeList( $set, self::LIST_SET );
578 "INSERT INTO $encTable " .
579 "($sqlColumns) VALUES $sqlTuples " .
580 "ON DUPLICATE KEY UPDATE $sqlColumnAssignments";
581 $query =
new Query( $sql, self::QUERY_CHANGE_ROWS,
'INSERT', $table );
582 $this->
query( $query, $fname );
584 $this->lastQueryAffectedRows = min( $this->lastQueryAffectedRows, count( $rows ) );
587 public function replace( $table, $uniqueKeys, $rows, $fname = __METHOD__ ) {
588 $this->platform->normalizeUpsertParams( $uniqueKeys, $rows );
593 [ $sqlColumns, $sqlTuples ] = $this->platform->makeInsertLists( $rows );
595 $sql =
"REPLACE INTO $encTable ($sqlColumns) VALUES $sqlTuples";
598 $query =
new Query( $sql, self::QUERY_CHANGE_ROWS,
'REPLACE', $table );
599 $this->
query( $query, $fname );
601 $this->lastQueryAffectedRows = min( $this->lastQueryAffectedRows, count( $rows ) );
620 ( $this->
lastErrno() == 1290 && strpos( $this->
lastError(),
'--read-only' ) !== false );
627 return in_array( $errno, [ 2013, 2006, 2003, 1927, 1053 ],
true );
634 return in_array( $errno, [ 3024, 2062, 1969, 1028 ],
true );
642 [ 3024, 1969, 1022, 1062, 1216, 1217, 1137, 1146, 1051, 1054 ],
655 $oldName, $newName, $temporary =
false, $fname = __METHOD__
657 $tmp = $temporary ?
'TEMPORARY ' :
'';
662 "CREATE $tmp TABLE $newNameQuoted (LIKE $oldNameQuoted)",
663 self::QUERY_PSEUDO_PERMANENT | self::QUERY_CHANGE_SCHEMA,
664 $temporary ?
'CREATE TEMPORARY' :
'CREATE',
668 return $this->
query( $query, $fname );
678 public function listTables( $prefix =
null, $fname = __METHOD__ ) {
680 ->select(
'table_name' )
681 ->from(
'information_schema.tables' )
683 'table_schema' => $this->currentDomain->getDatabase(),
684 'table_type' =>
'BASE TABLE'
687 if ( $prefix !==
null && $prefix !==
'' ) {
688 $qb->andWhere( $this->
expr(
692 return $qb->fetchFieldValues();
706 public function listViews( $prefix =
null, $fname = __METHOD__ ) {
709 ->select(
'table_name' )
710 ->from(
'information_schema.views' )
711 ->where( [
'table_schema' => $this->currentDomain->getDatabase() ] )
714 if ( $prefix !==
null && $prefix !==
'' ) {
715 $qb->andWhere( $this->
expr(
719 return $qb->fetchFieldValues();
730 $sql = parent::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
733 $timeoutMsec = intval( $options[
'MAX_EXECUTION_TIME'] ?? 0 );
734 if ( $timeoutMsec > 0 ) {
735 [ $vendor, $number ] = $this->getMySqlServerVariant();
736 if ( $vendor ===
'MariaDB' && version_compare( $number,
'10.1.2',
'>=' ) ) {
737 $timeoutSec = $timeoutMsec / 1000;
738 $sql =
"SET STATEMENT max_statement_time=$timeoutSec FOR $sql";
739 } elseif ( $vendor ===
'MySQL' && version_compare( $number,
'5.7.0',
'>=' ) ) {
742 "SELECT /*+ MAX_EXECUTION_TIME($timeoutMsec)*/",
755 AtEase::suppressWarnings();
756 $res =
$conn->query( $sql );
757 AtEase::restoreWarnings();
759 $insertId = (int)
$conn->insert_id;
760 $this->lastQueryInsertId = $insertId;
761 $this->sessionLastAutoRowId = $insertId ?: $this->sessionLastAutoRowId;
765 $conn->affected_rows,
779 private function mysqlConnect( $server, $user, $password, $db ) {
780 if ( !function_exists(
'mysqli_init' ) ) {
781 throw $this->newExceptionAfterConnectError(
782 "MySQLi functions missing, have you compiled PHP with the --with-mysqli option?"
787 mysqli_report( MYSQLI_REPORT_OFF );
799 $hostAndPort = IPUtils::splitHostAndPort( $server );
800 if ( $hostAndPort ) {
801 $realServer = $hostAndPort[0];
802 if ( $hostAndPort[1] ) {
803 $port = $hostAndPort[1];
805 } elseif ( substr_count( $server,
':/' ) == 1 ) {
808 [ $realServer, $socket ] = explode(
':', $server, 2 );
810 $realServer = $server;
813 $mysqli = mysqli_init();
817 $flags = MYSQLI_CLIENT_FOUND_ROWS;
819 $flags |= MYSQLI_CLIENT_SSL;
828 if ( $this->getFlag( self::DBO_COMPRESS ) ) {
829 $flags |= MYSQLI_CLIENT_COMPRESS;
831 if ( $this->getFlag( self::DBO_PERSISTENT ) ) {
832 $realServer =
'p:' . $realServer;
835 if ( $this->utf8Mode ) {
838 $mysqli->options( MYSQLI_SET_CHARSET_NAME,
'utf8' );
840 $mysqli->options( MYSQLI_SET_CHARSET_NAME,
'binary' );
843 $mysqli->options( MYSQLI_OPT_CONNECT_TIMEOUT, $this->connectTimeout ?: 3 );
844 if ( $this->receiveTimeout ) {
845 $mysqli->options( MYSQLI_OPT_READ_TIMEOUT, $this->receiveTimeout );
849 $ok = $mysqli->real_connect( $realServer, $user, $password, $db, $port, $socket, $flags );
851 return $ok ? $mysqli :
null;
855 return ( $this->conn instanceof mysqli ) ? mysqli_close( $this->conn ) :
true;
859 return $this->sessionLastAutoRowId;
864 $this->sessionLastAutoRowId = 0;
868 if ( $this->lastEmulatedInsertId ===
null ) {
869 $conn = $this->getBindingHandle();
871 $this->lastEmulatedInsertId = (int)$conn->insert_id;
874 return $this->lastEmulatedInsertId;
881 if ( $this->conn instanceof mysqli ) {
882 return $this->conn->errno;
884 return mysqli_connect_errno();
892 private function mysqlError( $conn =
null ) {
893 if ( $conn ===
null ) {
894 return (
string)mysqli_connect_error();
900 private function mysqlRealEscapeString( $s ) {
901 $conn = $this->getBindingHandle();
903 return $conn->real_escape_string( (
string)$s );
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
array $params
The job parameters.
Class to handle database/schema/prefix specifications for IDatabase.