25use Wikimedia\AtEase\AtEase;
66 private $sessionLastAutoRowId;
88 foreach ( [
'KeyPath',
'CertPath',
'CAFile',
'CAPath',
'Ciphers' ] as $name ) {
90 if ( isset( $params[$var] ) ) {
91 $this->$var = $params[$var];
94 $this->utf8Mode = !empty( $params[
'utf8Mode'] );
95 parent::__construct( $params );
103 $params[
'topologyRole'],
106 $params[
'lagDetectionMethod'] ??
'Seconds_Behind_Master',
107 $params[
'lagDetectionOptions'] ?? [],
108 !empty( $params[
'useGTIDs' ] )
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;
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__ ) {
356 'SHOW INDEX FROM ' . $this->tableName( $table ),
357 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
360 $res = $this->query( $query, $fname );
362 foreach ( $res as $row ) {
363 if ( $row->Key_name === $index ) {
364 return [
'unique' => !$row->Non_unique ];
376 return $this->mysqlRealEscapeString( $s );
381 $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
382 $query =
new Query(
"SELECT @@GLOBAL.read_only AS Value", $flags,
'SELECT' );
383 $res = $this->query( $query, __METHOD__ );
384 $row = $res->fetchObject();
386 return $row && (bool)$row->Value;
393 [ $variant ] = $this->getMySqlServerVariant();
394 if ( $variant ===
'MariaDB' ) {
395 return '[{{int:version-db-mariadb-url}} MariaDB]';
398 return '[{{int:version-db-mysql-url}} MySQL]';
404 private function getMySqlServerVariant() {
405 $version = $this->getServerVersion();
411 $parts = explode(
'-', $version, 2 );
413 $suffix = $parts[1] ??
'';
414 if ( strpos( $suffix,
'MariaDB' ) !==
false || strpos( $suffix,
'-maria-' ) !==
false ) {
420 return [ $vendor, $number ];
429 $version = $this->conn->server_info;
431 str_starts_with( $version,
'5.5.5-' ) &&
432 ( str_contains( $version,
'MariaDB' ) || str_contains( $version,
'-maria-' ) )
434 $version = substr( $version, strlen(
'5.5.5-' ) );
440 $sqlAssignments = [];
442 if ( isset( $options[
'connTimeout'] ) ) {
443 $encTimeout = (int)$options[
'connTimeout'];
444 $sqlAssignments[] =
"net_read_timeout=$encTimeout";
445 $sqlAssignments[] =
"net_write_timeout=$encTimeout";
447 if ( isset( $options[
'groupConcatMaxLen'] ) ) {
448 $maxLength = (int)$options[
'groupConcatMaxLen'];
449 $sqlAssignments[] =
"group_concat_max_len=$maxLength";
452 if ( $sqlAssignments ) {
454 'SET ' . implode(
', ', $sqlAssignments ),
455 self::QUERY_CHANGE_TRX | self::QUERY_CHANGE_NONE,
458 $this->query( $query, __METHOD__ );
468 if ( preg_match(
'/^DELIMITER\s+(\S+)/i', $newLine, $m ) ) {
469 $this->delimiter = $m[1];
473 return parent::streamStatementEnd( $sql, $newLine );
477 $query =
new Query( $this->platform->lockIsFreeSQLText( $lockName ), self::QUERY_CHANGE_LOCKS,
'SELECT' );
478 $res = $this->query( $query, $method );
479 $row = $res->fetchObject();
481 return ( $row->unlocked == 1 );
484 public function doLock(
string $lockName,
string $method,
int $timeout ) {
485 $query =
new Query( $this->platform->lockSQLText( $lockName, $timeout ), self::QUERY_CHANGE_LOCKS,
'SELECT' );
486 $res = $this->query( $query, $method );
487 $row = $res->fetchObject();
489 return ( $row->acquired !==
null ) ? (float)$row->acquired :
null;
492 public function doUnlock(
string $lockName,
string $method ) {
493 $query =
new Query( $this->platform->unlockSQLText( $lockName ), self::QUERY_CHANGE_LOCKS,
'SELECT' );
494 $res = $this->query( $query, $method );
495 $row = $res->fetchObject();
497 return ( $row->released == 1 );
503 $releaseLockFields = [];
504 foreach ( $this->sessionNamedLocks as $name => $info ) {
505 $encName = $this->addQuotes( $this->platform->makeLockName( $name ) );
506 $releaseLockFields[] =
"RELEASE_LOCK($encName)";
508 if ( $releaseLockFields ) {
509 $sql =
'SELECT ' . implode(
',', $releaseLockFields );
510 $flags = self::QUERY_CHANGE_LOCKS | self::QUERY_NO_RETRY;
511 $query =
new Query( $sql, $flags,
'SELECT' );
512 $qs = $this->executeQuery( $query, __METHOD__, $flags );
513 if ( $qs->res ===
false ) {
514 $this->reportQueryError( $qs->message, $qs->code, $sql, $fname,
true );
519 public function upsert( $table, array $rows, $uniqueKeys, array $set, $fname = __METHOD__ ) {
520 $identityKey = $this->platform->normalizeUpsertParams( $uniqueKeys, $rows );
524 $this->platform->assertValidUpsertSetArray( $set, $identityKey, $rows );
526 $encTable = $this->tableName( $table );
527 [ $sqlColumns, $sqlTuples ] = $this->platform->makeInsertLists( $rows );
528 $sqlColumnAssignments = $this->makeList( $set, self::LIST_SET );
534 "INSERT INTO $encTable " .
535 "($sqlColumns) VALUES $sqlTuples " .
536 "ON DUPLICATE KEY UPDATE $sqlColumnAssignments";
537 $query =
new Query( $sql, self::QUERY_CHANGE_ROWS,
'INSERT', $table );
538 $this->query( $query, $fname );
540 $this->lastQueryAffectedRows = min( $this->lastQueryAffectedRows, count( $rows ) );
543 public function replace( $table, $uniqueKeys, $rows, $fname = __METHOD__ ) {
544 $this->platform->normalizeUpsertParams( $uniqueKeys, $rows );
548 $encTable = $this->tableName( $table );
549 [ $sqlColumns, $sqlTuples ] = $this->platform->makeInsertLists( $rows );
551 $sql =
"REPLACE INTO $encTable ($sqlColumns) VALUES $sqlTuples";
554 $query =
new Query( $sql, self::QUERY_CHANGE_ROWS,
'REPLACE', $table );
555 $this->query( $query, $fname );
557 $this->lastQueryAffectedRows = min( $this->lastQueryAffectedRows, count( $rows ) );
564 return in_array( $errno, [ 2013, 2006, 2003, 1927, 1053 ],
true );
571 return in_array( $errno, [ 3024, 2062, 1969, 1028 ],
true );
579 [ 3024, 1969, 1022, 1062, 1216, 1217, 1137, 1146, 1051, 1054 ],
592 $oldName, $newName, $temporary =
false, $fname = __METHOD__
594 $tmp = $temporary ?
'TEMPORARY ' :
'';
595 $newNameQuoted = $this->addIdentifierQuotes( $newName );
596 $oldNameQuoted = $this->addIdentifierQuotes( $oldName );
599 "CREATE $tmp TABLE $newNameQuoted (LIKE $oldNameQuoted)",
600 self::QUERY_PSEUDO_PERMANENT | self::QUERY_CHANGE_SCHEMA,
601 $temporary ?
'CREATE TEMPORARY' :
'CREATE',
605 return $this->query( $query, $fname );
615 public function listTables( $prefix =
null, $fname = __METHOD__ ) {
616 $qb = $this->newSelectQueryBuilder()
617 ->select(
'table_name' )
618 ->from(
'information_schema.tables' )
620 'table_schema' => $this->currentDomain->getDatabase(),
621 'table_type' =>
'BASE TABLE'
624 if ( $prefix !==
null && $prefix !==
'' ) {
625 $qb->andWhere( $this->expr(
629 return $qb->fetchFieldValues();
640 $sql = parent::selectSQLText( $tables, $vars, $conds, $fname, $options, $join_conds );
643 $timeoutMsec = intval( $options[
'MAX_EXECUTION_TIME'] ?? 0 );
644 if ( $timeoutMsec > 0 ) {
645 [ $vendor, $number ] = $this->getMySqlServerVariant();
646 if ( $vendor ===
'MariaDB' && version_compare( $number,
'10.1.2',
'>=' ) ) {
647 $timeoutSec = $timeoutMsec / 1000;
648 $sql =
"SET STATEMENT max_statement_time=$timeoutSec FOR $sql";
649 } elseif ( $vendor ===
'MySQL' && version_compare( $number,
'5.7.0',
'>=' ) ) {
652 "SELECT /*+ MAX_EXECUTION_TIME($timeoutMsec)*/",
662 $conn = $this->getBindingHandle();
665 AtEase::suppressWarnings();
666 $res = $conn->query( $sql );
667 AtEase::restoreWarnings();
669 $insertId = (int)$conn->insert_id;
670 $this->lastQueryInsertId = $insertId;
671 $this->sessionLastAutoRowId = $insertId ?: $this->sessionLastAutoRowId;
675 $conn->affected_rows,
689 private function mysqlConnect( $server, $user, $password, $db ) {
690 if ( !function_exists(
'mysqli_init' ) ) {
691 throw $this->newExceptionAfterConnectError(
692 "MySQLi functions missing, have you compiled PHP with the --with-mysqli option?"
697 mysqli_report( MYSQLI_REPORT_OFF );
709 $hostAndPort = IPUtils::splitHostAndPort( $server );
710 if ( $hostAndPort ) {
711 $realServer = $hostAndPort[0];
712 if ( $hostAndPort[1] ) {
713 $port = $hostAndPort[1];
715 } elseif ( substr_count( $server,
':/' ) == 1 ) {
718 [ $realServer, $socket ] = explode(
':', $server, 2 );
720 $realServer = $server;
723 $mysqli = mysqli_init();
727 $flags = MYSQLI_CLIENT_FOUND_ROWS;
729 $flags |= MYSQLI_CLIENT_SSL;
738 if ( $this->getFlag( self::DBO_COMPRESS ) ) {
739 $flags |= MYSQLI_CLIENT_COMPRESS;
741 if ( $this->getFlag( self::DBO_PERSISTENT ) ) {
742 $realServer =
'p:' . $realServer;
745 if ( $this->utf8Mode ) {
748 $mysqli->options( MYSQLI_SET_CHARSET_NAME,
'utf8' );
750 $mysqli->options( MYSQLI_SET_CHARSET_NAME,
'binary' );
753 $mysqli->options( MYSQLI_OPT_CONNECT_TIMEOUT, $this->connectTimeout ?: 3 );
754 if ( $this->receiveTimeout ) {
755 $mysqli->options( MYSQLI_OPT_READ_TIMEOUT, $this->receiveTimeout );
759 $ok = $mysqli->real_connect( $realServer, $user, $password, $db, $port, $socket, $flags );
761 return $ok ? $mysqli :
null;
765 return ( $this->conn instanceof mysqli ) ? mysqli_close( $this->conn ) :
true;
769 return $this->sessionLastAutoRowId;
774 $this->sessionLastAutoRowId = 0;
778 if ( $this->lastEmulatedInsertId ===
null ) {
779 $conn = $this->getBindingHandle();
781 $this->lastEmulatedInsertId = (int)$conn->insert_id;
784 return $this->lastEmulatedInsertId;
791 if ( $this->conn instanceof mysqli ) {
792 return $this->conn->errno;
794 return mysqli_connect_errno();
802 private function mysqlError( $conn =
null ) {
803 if ( $conn ===
null ) {
804 return (
string)mysqli_connect_error();
813 private function mysqlRealEscapeString( $s ): string {
814 $conn = $this->getBindingHandle();
816 return $conn->real_escape_string( (
string)$s );
Class to handle database/schema/prefix specifications for IDatabase.