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 !==
'' ) ? $db :
null,
148 if ( !$this->
flagsHolder->getFlag( self::DBO_GAUGE ) ) {
150 $set[] =
'group_concat_max_len = 262144';
155 if ( !is_int( $val ) && !is_float( $val ) ) {
158 $set[] = $this->
platform->addIdentifierQuotes( $var ) .
' = ' . $val;
163 $sql =
'SET ' . implode(
', ', $set );
169 if ( $qs->res ===
false ) {
173 }
catch ( RuntimeException $e ) {
182 __CLASS__ .
": domain '{$domain->getId()}' has a schema component"
188 if ( $database ===
null ) {
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 ) {
211 $this->
platform->setCurrentDomain( $domain );
222 $error = $this->mysqlError( $this->conn );
224 $error = $this->mysqlError();
227 $error = $this->mysqlError() ?: $this->lastConnectError;
233 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions, $fname = __METHOD__ ) {
234 $row = $this->replicationReporter->getReplicationSafetyInfo( $this, $fname );
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();
293 $conds = $this->
platform->normalizeConditions( $conds, $fname );
294 $column = $this->
platform->extractSingleFieldFromList( $var );
295 if ( is_string( $column ) && !in_array( $column, [
'*',
'1' ] ) ) {
296 $conds[] =
"$column IS NOT NULL";
299 $options[
'EXPLAIN'] =
true;
300 $res = $this->
select( $tables, $var, $conds, $fname, $options, $join_conds );
301 if ( $res ===
false ) {
304 if ( !$res->numRows() ) {
309 foreach ( $res as $plan ) {
310 $rows *= $plan->rows > 0 ? $plan->rows : 1;
317 [ $db, $pt ] = $this->platform->getDatabaseAndTableIdentifier( $table );
318 if ( isset( $this->sessionTempTables[$db][$pt] ) ) {
322 return (
bool)$this->newSelectQueryBuilder()
324 ->from(
'information_schema.tables' )
326 'table_schema' => $db,
340 "SELECT * FROM " . $this->tableName( $table ) .
" LIMIT 1",
341 self::QUERY_SILENCE_ERRORS | self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
344 $res = $this->query( $query, __METHOD__ );
349 '@phan-var MysqliResultWrapper $res';
350 return $res->getInternalFieldInfo( $field );
353 public function indexInfo( $table, $index, $fname = __METHOD__ ) {
355 $index = $this->platform->indexName( $index );
357 'SHOW INDEX FROM ' . $this->tableName( $table ),
358 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
361 $res = $this->query( $query, $fname );
363 foreach ( $res as $row ) {
364 if ( $row->Key_name === $index ) {
365 return [
'unique' => !$row->Non_unique ];
377 return $this->mysqlRealEscapeString( $s );
382 $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
383 $query =
new Query(
"SELECT @@GLOBAL.read_only AS Value", $flags,
'SELECT' );
384 $res = $this->query( $query, __METHOD__ );
385 $row = $res->fetchObject();
387 return $row && (bool)$row->Value;
394 [ $variant ] = $this->getMySqlServerVariant();
395 if ( $variant ===
'MariaDB' ) {
396 return '[{{int:version-db-mariadb-url}} MariaDB]';
399 return '[{{int:version-db-mysql-url}} MySQL]';
405 private function getMySqlServerVariant() {
406 $version = $this->getServerVersion();
412 $parts = explode(
'-', $version, 2 );
414 $suffix = $parts[1] ??
'';
415 if ( strpos( $suffix,
'MariaDB' ) !==
false || strpos( $suffix,
'-maria-' ) !==
false ) {
421 return [ $vendor, $number ];
430 $version = $this->conn->server_info;
432 str_starts_with( $version,
'5.5.5-' ) &&
433 ( str_contains( $version,
'MariaDB' ) || str_contains( $version,
'-maria-' ) )
435 $version = substr( $version, strlen(
'5.5.5-' ) );
444 $sqlAssignments = [];
446 if ( isset( $options[
'connTimeout'] ) ) {
447 $encTimeout = (int)$options[
'connTimeout'];
448 $sqlAssignments[] =
"net_read_timeout=$encTimeout";
449 $sqlAssignments[] =
"net_write_timeout=$encTimeout";
451 if ( isset( $options[
'groupConcatMaxLen'] ) ) {
452 $maxLength = (int)$options[
'groupConcatMaxLen'];
453 $sqlAssignments[] =
"group_concat_max_len=$maxLength";
456 if ( $sqlAssignments ) {
458 'SET ' . implode(
', ', $sqlAssignments ),
459 self::QUERY_CHANGE_TRX | self::QUERY_CHANGE_NONE,
462 $this->query( $query, __METHOD__ );
472 if ( preg_match(
'/^DELIMITER\s+(\S+)/i', $newLine, $m ) ) {
473 $this->delimiter = $m[1];
477 return parent::streamStatementEnd( $sql, $newLine );
481 $query =
new Query( $this->platform->lockIsFreeSQLText( $lockName ), self::QUERY_CHANGE_LOCKS,
'SELECT' );
482 $res = $this->query( $query, $method );
483 $row = $res->fetchObject();
485 return ( $row->unlocked == 1 );
488 public function doLock(
string $lockName,
string $method,
int $timeout ) {
489 $query =
new Query( $this->platform->lockSQLText( $lockName, $timeout ), self::QUERY_CHANGE_LOCKS,
'SELECT' );
490 $res = $this->query( $query, $method );
491 $row = $res->fetchObject();
493 return ( $row->acquired !==
null ) ? (float)$row->acquired :
null;
496 public function doUnlock(
string $lockName,
string $method ) {
497 $query =
new Query( $this->platform->unlockSQLText( $lockName ), self::QUERY_CHANGE_LOCKS,
'SELECT' );
498 $res = $this->query( $query, $method );
499 $row = $res->fetchObject();
501 return ( $row->released == 1 );
507 $releaseLockFields = [];
508 foreach ( $this->sessionNamedLocks as $name => $info ) {
509 $encName = $this->addQuotes( $this->platform->makeLockName( $name ) );
510 $releaseLockFields[] =
"RELEASE_LOCK($encName)";
512 if ( $releaseLockFields ) {
513 $sql =
'SELECT ' . implode(
',', $releaseLockFields );
514 $flags = self::QUERY_CHANGE_LOCKS | self::QUERY_NO_RETRY;
515 $query =
new Query( $sql, $flags,
'SELECT' );
516 $qs = $this->executeQuery( $query, __METHOD__, $flags );
517 if ( $qs->res ===
false ) {
518 $this->reportQueryError( $qs->message, $qs->code, $sql, $fname,
true );
523 public function upsert( $table, array $rows, $uniqueKeys, array $set, $fname = __METHOD__ ) {
524 $identityKey = $this->platform->normalizeUpsertParams( $uniqueKeys, $rows );
528 $this->platform->assertValidUpsertSetArray( $set, $identityKey, $rows );
530 $encTable = $this->tableName( $table );
531 [ $sqlColumns, $sqlTuples ] = $this->platform->makeInsertLists( $rows );
532 $sqlColumnAssignments = $this->makeList( $set, self::LIST_SET );
538 "INSERT INTO $encTable " .
539 "($sqlColumns) VALUES $sqlTuples " .
540 "ON DUPLICATE KEY UPDATE $sqlColumnAssignments";
541 $query =
new Query( $sql, self::QUERY_CHANGE_ROWS,
'INSERT', $table );
542 $this->query( $query, $fname );
544 $this->lastQueryAffectedRows = min( $this->lastQueryAffectedRows, count( $rows ) );
547 public function replace( $table, $uniqueKeys, $rows, $fname = __METHOD__ ) {
548 $this->platform->normalizeUpsertParams( $uniqueKeys, $rows );
552 $encTable = $this->tableName( $table );
553 [ $sqlColumns, $sqlTuples ] = $this->platform->makeInsertLists( $rows );
555 $sql =
"REPLACE INTO $encTable ($sqlColumns) VALUES $sqlTuples";
558 $query =
new Query( $sql, self::QUERY_CHANGE_ROWS,
'REPLACE', $table );
559 $this->query( $query, $fname );
561 $this->lastQueryAffectedRows = min( $this->lastQueryAffectedRows, count( $rows ) );
568 return in_array( $errno, [ 2013, 2006, 2003, 1927, 1053 ],
true );
575 return in_array( $errno, [ 3024, 2062, 1969, 1028 ],
true );
583 [ 3024, 1969, 1022, 1062, 1216, 1217, 1137, 1146, 1051, 1054 ],
596 $oldName, $newName, $temporary =
false, $fname = __METHOD__
598 $tmp = $temporary ?
'TEMPORARY ' :
'';
599 $newNameQuoted = $this->addIdentifierQuotes( $newName );
600 $oldNameQuoted = $this->addIdentifierQuotes( $oldName );
603 "CREATE $tmp TABLE $newNameQuoted (LIKE $oldNameQuoted)",
604 self::QUERY_PSEUDO_PERMANENT | self::QUERY_CHANGE_SCHEMA,
605 $temporary ?
'CREATE TEMPORARY' :
'CREATE',
609 return $this->query( $query, $fname );
619 public function listTables( $prefix =
null, $fname = __METHOD__ ) {
620 $qb = $this->newSelectQueryBuilder()
621 ->select(
'table_name' )
622 ->from(
'information_schema.tables' )
624 'table_schema' => $this->currentDomain->getDatabase(),
625 'table_type' =>
'BASE TABLE'
628 if ( $prefix !==
null && $prefix !==
'' ) {
629 $qb->andWhere( $this->expr(
633 return $qb->fetchFieldValues();
644 $sql = parent::selectSQLText( $tables, $vars, $conds, $fname, $options, $join_conds );
647 $timeoutMsec = intval( $options[
'MAX_EXECUTION_TIME'] ?? 0 );
648 if ( $timeoutMsec > 0 ) {
649 [ $vendor, $number ] = $this->getMySqlServerVariant();
650 if ( $vendor ===
'MariaDB' && version_compare( $number,
'10.1.2',
'>=' ) ) {
651 $timeoutSec = $timeoutMsec / 1000;
652 $sql =
"SET STATEMENT max_statement_time=$timeoutSec FOR $sql";
653 } elseif ( $vendor ===
'MySQL' && version_compare( $number,
'5.7.0',
'>=' ) ) {
656 "SELECT /*+ MAX_EXECUTION_TIME($timeoutMsec)*/",
666 $conn = $this->getBindingHandle();
669 AtEase::suppressWarnings();
670 $res = $conn->query( $sql );
671 AtEase::restoreWarnings();
673 $insertId = (int)$conn->insert_id;
674 $this->lastQueryInsertId = $insertId;
675 $this->sessionLastAutoRowId = $insertId ?: $this->sessionLastAutoRowId;
679 $conn->affected_rows,
693 private function mysqlConnect( $server, $user, $password, $db ) {
694 if ( !function_exists(
'mysqli_init' ) ) {
695 throw $this->newExceptionAfterConnectError(
696 "MySQLi functions missing, have you compiled PHP with the --with-mysqli option?"
701 mysqli_report( MYSQLI_REPORT_OFF );
713 $hostAndPort = IPUtils::splitHostAndPort( $server );
714 if ( $hostAndPort ) {
715 $realServer = $hostAndPort[0];
716 if ( $hostAndPort[1] ) {
717 $port = $hostAndPort[1];
719 } elseif ( substr_count( $server,
':/' ) == 1 ) {
722 [ $realServer, $socket ] = explode(
':', $server, 2 );
724 $realServer = $server;
727 $mysqli = mysqli_init();
731 $flags = MYSQLI_CLIENT_FOUND_ROWS;
733 $flags |= MYSQLI_CLIENT_SSL;
742 if ( $this->getFlag( self::DBO_COMPRESS ) ) {
743 $flags |= MYSQLI_CLIENT_COMPRESS;
745 if ( $this->getFlag( self::DBO_PERSISTENT ) ) {
746 $realServer =
'p:' . $realServer;
749 if ( $this->utf8Mode ) {
752 $mysqli->options( MYSQLI_SET_CHARSET_NAME,
'utf8' );
754 $mysqli->options( MYSQLI_SET_CHARSET_NAME,
'binary' );
757 $mysqli->options( MYSQLI_OPT_CONNECT_TIMEOUT, $this->connectTimeout ?: 3 );
758 if ( $this->receiveTimeout ) {
759 $mysqli->options( MYSQLI_OPT_READ_TIMEOUT, $this->receiveTimeout );
763 $ok = $mysqli->real_connect( $realServer, $user, $password, $db, $port, $socket, $flags );
765 return $ok ? $mysqli :
null;
769 return ( $this->conn instanceof mysqli ) ? mysqli_close( $this->conn ) :
true;
773 return $this->sessionLastAutoRowId;
778 $this->sessionLastAutoRowId = 0;
782 if ( $this->lastEmulatedInsertId ===
null ) {
783 $conn = $this->getBindingHandle();
785 $this->lastEmulatedInsertId = (int)$conn->insert_id;
788 return $this->lastEmulatedInsertId;
795 if ( $this->conn instanceof mysqli ) {
796 return $this->conn->errno;
798 return mysqli_connect_errno();
806 private function mysqlError( $conn =
null ) {
807 if ( $conn ===
null ) {
808 return (
string)mysqli_connect_error();
814 private function mysqlRealEscapeString( $s ) {
815 $conn = $this->getBindingHandle();
817 return $conn->real_escape_string( (
string)$s );
array $params
The job parameters.
Class to handle database/schema/prefix specifications for IDatabase.