25use Wikimedia\AtEase\AtEase;
64 private $sessionLastAutoRowId;
86 foreach ( [
'KeyPath',
'CertPath',
'CAFile',
'CAPath',
'Ciphers' ] as $name ) {
88 if ( isset( $params[$var] ) ) {
89 $this->$var = $params[$var];
92 $this->utf8Mode = !empty( $params[
'utf8Mode'] );
93 parent::__construct( $params );
101 $params[
'topologyRole'],
104 $params[
'lagDetectionMethod'] ??
'Seconds_Behind_Master',
105 $params[
'lagDetectionOptions'] ?? [],
106 !empty( $params[
'useGTIDs' ] )
117 protected function open( $server, $user, $password, $db, $schema, $tablePrefix ) {
118 $this->
close( __METHOD__ );
120 if ( $schema !==
null ) {
126 $this->conn = $this->mysqlConnect( $server, $user, $password, $db );
127 }
catch ( RuntimeException $e ) {
133 if ( !$this->conn ) {
139 $db && strlen( $db ) ? $db :
null,
143 $this->platform->setPrefix( $tablePrefix );
146 if ( !$this->flagsHolder->getFlag( self::DBO_GAUGE ) ) {
148 $set[] =
'group_concat_max_len = 262144';
151 foreach ( $this->connectionVariables as $var => $val ) {
153 if ( !is_int( $val ) && !is_float( $val ) ) {
156 $set[] = $this->platform->addIdentifierQuotes( $var ) .
' = ' . $val;
161 $sql =
'SET ' . implode(
', ', $set );
162 $flags = self::QUERY_NO_RETRY | self::QUERY_CHANGE_TRX;
163 $query =
new Query( $sql, $flags,
'SET' );
166 $qs = $this->
executeQuery( $query, __METHOD__, $flags );
167 if ( $qs->res ===
false ) {
171 }
catch ( RuntimeException $e ) {
180 __CLASS__ .
": domain '{$domain->getId()}' has a schema component"
186 if ( $database ===
null ) {
188 $this->currentDomain->getDatabase(),
197 if ( $database !== $this->
getDBname() ) {
199 $query =
new Query( $sql, self::QUERY_CHANGE_TRX,
'USE' );
200 $qs = $this->
executeQuery( $query, __METHOD__, self::QUERY_CHANGE_TRX );
201 if ( $qs->res ===
false ) {
208 $this->currentDomain = $domain;
220 $error = $this->mysqlError( $this->conn );
222 $error = $this->mysqlError();
232 $row = $this->replicationReporter->getReplicationSafetyInfo( $this );
234 if ( $row->binlog_format ===
'ROW' ) {
238 if ( isset( $selectOptions[
'LIMIT'] ) ) {
249 in_array(
'NO_AUTO_COLUMNS', $insertOptions ) ||
250 (
int)$row->innodb_autoinc_lock_mode === 0
275 $conds = $this->platform->normalizeConditions( $conds, $fname );
276 $column = $this->platform->extractSingleFieldFromList( $var );
277 if ( is_string( $column ) && !in_array( $column, [
'*',
'1' ] ) ) {
278 $conds[] =
"$column IS NOT NULL";
281 $options[
'EXPLAIN'] =
true;
282 $res = $this->
select( $tables, $var, $conds, $fname, $options, $join_conds );
283 if ( $res ===
false ) {
286 if ( !$res->numRows() ) {
291 foreach ( $res as $plan ) {
292 $rows *= $plan->rows > 0 ? $plan->rows : 1;
301 [ $database, , $prefix, $table ] = $this->platform->qualifiedTableComponents( $table );
302 $tableName =
"{$prefix}{$table}";
304 if ( isset( $this->sessionTempTables[$tableName] ) ) {
311 $encLike = $this->platform->escapeLikeInternal( $tableName,
'\\' );
314 if ( $database !==
'' ) {
315 $encDatabase = $this->platform->addIdentifierQuotes( $database );
316 $sql =
"SHOW TABLES FROM $encDatabase LIKE '$encLike'";
318 $sql =
"SHOW TABLES LIKE '$encLike'";
321 $query =
new Query( $sql, self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
'SHOW', $table );
322 $res = $this->
query( $query, $fname );
324 return $res->numRows() > 0;
334 "SELECT * FROM " . $this->
tableName( $table ) .
" LIMIT 1",
335 self::QUERY_SILENCE_ERRORS | self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
339 $res = $this->
query( $query, __METHOD__ );
344 '@phan-var MysqliResultWrapper $res';
345 return $res->getInternalFieldInfo( $field );
357 public function indexInfo( $table, $index, $fname = __METHOD__ ) {
359 $index = $this->platform->indexName( $index );
361 'SHOW INDEX FROM ' . $this->
tableName( $table ),
362 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
366 $res = $this->
query( $query, $fname );
374 foreach ( $res as $row ) {
375 if ( $row->Key_name == $index ) {
380 return $result ?:
false;
388 return $this->mysqlRealEscapeString( $s );
393 $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
394 $query =
new Query(
"SELECT @@GLOBAL.read_only AS Value", $flags,
'SELECT' );
395 $res = $this->
query( $query, __METHOD__ );
396 $row = $res->fetchObject();
398 return $row && (bool)$row->Value;
405 [ $variant ] = $this->getMySqlServerVariant();
406 if ( $variant ===
'MariaDB' ) {
407 return '[{{int:version-db-mariadb-url}} MariaDB]';
410 return '[{{int:version-db-mysql-url}} MySQL]';
416 private function getMySqlServerVariant() {
423 $parts = explode(
'-', $version, 2 );
425 $suffix = $parts[1] ??
'';
426 if ( strpos( $suffix,
'MariaDB' ) !==
false || strpos( $suffix,
'-maria-' ) !==
false ) {
432 return [ $vendor, $number ];
441 $version = $this->conn->server_info;
443 str_starts_with( $version,
'5.5.5-' ) &&
444 ( str_contains( $version,
'MariaDB' ) || str_contains( $version,
'-maria-' ) )
446 $version = substr( $version, strlen(
'5.5.5-' ) );
455 $sqlAssignments = [];
457 if ( isset( $options[
'connTimeout'] ) ) {
458 $encTimeout = (int)$options[
'connTimeout'];
459 $sqlAssignments[] =
"net_read_timeout=$encTimeout";
460 $sqlAssignments[] =
"net_write_timeout=$encTimeout";
462 if ( isset( $options[
'groupConcatMaxLen'] ) ) {
463 $maxLength = (int)$options[
'groupConcatMaxLen'];
464 $sqlAssignments[] =
"group_concat_max_len=$maxLength";
467 if ( $sqlAssignments ) {
469 'SET ' . implode(
', ', $sqlAssignments ),
470 self::QUERY_CHANGE_TRX | self::QUERY_CHANGE_NONE,
473 $this->
query( $query, __METHOD__ );
483 if ( preg_match(
'/^DELIMITER\s+(\S+)/i', $newLine, $m ) ) {
484 $this->delimiter = $m[1];
488 return parent::streamStatementEnd( $sql, $newLine );
492 $query =
new Query( $this->platform->lockIsFreeSQLText( $lockName ), self::QUERY_CHANGE_LOCKS,
'SELECT' );
493 $res = $this->
query( $query, $method );
494 $row = $res->fetchObject();
496 return ( $row->unlocked == 1 );
499 public function doLock(
string $lockName,
string $method,
int $timeout ) {
500 $query =
new Query( $this->platform->lockSQLText( $lockName, $timeout ), self::QUERY_CHANGE_LOCKS,
'SELECT' );
501 $res = $this->
query( $query, $method );
502 $row = $res->fetchObject();
504 return ( $row->acquired !==
null ) ? (float)$row->acquired :
null;
507 public function doUnlock(
string $lockName,
string $method ) {
508 $query =
new Query( $this->platform->unlockSQLText( $lockName ), self::QUERY_CHANGE_LOCKS,
'SELECT' );
509 $res = $this->
query( $query, $method );
510 $row = $res->fetchObject();
512 return ( $row->released == 1 );
522 $releaseLockFields = [];
523 foreach ( $this->sessionNamedLocks as $name => $info ) {
524 $encName = $this->
addQuotes( $this->platform->makeLockName( $name ) );
525 $releaseLockFields[] =
"RELEASE_LOCK($encName)";
527 if ( $releaseLockFields ) {
528 $sql =
'SELECT ' . implode(
',', $releaseLockFields );
529 $flags = self::QUERY_CHANGE_LOCKS | self::QUERY_NO_RETRY;
530 $query =
new Query( $sql, $flags,
'SELECT' );
531 $qs = $this->
executeQuery( $query, __METHOD__, $flags );
532 if ( $qs->res ===
false ) {
538 public function upsert( $table, array $rows, $uniqueKeys, array $set, $fname = __METHOD__ ) {
539 $identityKey = $this->platform->normalizeUpsertParams( $uniqueKeys, $rows );
543 $this->platform->assertValidUpsertSetArray( $set, $identityKey, $rows );
546 [ $sqlColumns, $sqlTuples ] = $this->platform->makeInsertLists( $rows );
547 $sqlColumnAssignments = $this->
makeList( $set, self::LIST_SET );
553 "INSERT INTO $encTable " .
554 "($sqlColumns) VALUES $sqlTuples " .
555 "ON DUPLICATE KEY UPDATE $sqlColumnAssignments";
556 $query =
new Query( $sql, self::QUERY_CHANGE_ROWS,
'INSERT', $table );
557 $this->
query( $query, $fname );
559 $this->lastQueryAffectedRows = min( $this->lastQueryAffectedRows, count( $rows ) );
563 public function replace( $table, $uniqueKeys, $rows, $fname = __METHOD__ ) {
564 $this->platform->normalizeUpsertParams( $uniqueKeys, $rows );
569 [ $sqlColumns, $sqlTuples ] = $this->platform->makeInsertLists( $rows );
571 $sql =
"REPLACE INTO $encTable ($sqlColumns) VALUES $sqlTuples";
574 $query =
new Query( $sql, self::QUERY_CHANGE_ROWS,
'REPLACE', $table );
575 $this->
query( $query, $fname );
577 $this->lastQueryAffectedRows = min( $this->lastQueryAffectedRows, count( $rows ) );
596 ( $this->
lastErrno() == 1290 && strpos( $this->
lastError(),
'--read-only' ) !== false );
603 return in_array( $errno, [ 2013, 2006, 2003, 1927, 1053 ],
true );
610 return in_array( $errno, [ 3024, 2062, 1969, 1028 ],
true );
618 [ 3024, 1969, 1022, 1062, 1216, 1217, 1137, 1146, 1051, 1054 ],
631 $oldName, $newName, $temporary =
false, $fname = __METHOD__
633 $tmp = $temporary ?
'TEMPORARY ' :
'';
638 "CREATE $tmp TABLE $newNameQuoted (LIKE $oldNameQuoted)",
639 self::QUERY_PSEUDO_PERMANENT | self::QUERY_CHANGE_SCHEMA,
641 [ $oldName, $newName ]
643 return $this->
query( $query, $fname );
653 public function listTables( $prefix =
null, $fname = __METHOD__ ) {
654 $query =
new Query(
"SHOW TABLES", self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
'SHOW' );
655 $result = $this->
query( $query, $fname );
659 foreach ( $result as $table ) {
660 $vars = get_object_vars( $table );
661 $table = array_pop( $vars );
663 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
664 $endArray[] = $table;
680 public function listViews( $prefix =
null, $fname = __METHOD__ ) {
682 $propertyName =
'Tables_in_' . $this->
getDBname();
684 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"',
685 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
689 $res = $this->
query( $query, $fname );
692 foreach ( $res as $row ) {
693 $allViews[] = $row->$propertyName;
696 if ( $prefix ===
null || $prefix ===
'' ) {
701 foreach ( $allViews as $viewName ) {
703 if ( strpos( $viewName, $prefix ) === 0 ) {
704 $filteredViews[] = $viewName;
708 return $filteredViews;
719 $sql = parent::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
722 $timeoutMsec = intval( $options[
'MAX_EXECUTION_TIME'] ?? 0 );
723 if ( $timeoutMsec > 0 ) {
724 [ $vendor, $number ] = $this->getMySqlServerVariant();
725 if ( $vendor ===
'MariaDB' && version_compare( $number,
'10.1.2',
'>=' ) ) {
726 $timeoutSec = $timeoutMsec / 1000;
727 $sql =
"SET STATEMENT max_statement_time=$timeoutSec FOR $sql";
728 } elseif ( $vendor ===
'MySQL' && version_compare( $number,
'5.7.0',
'>=' ) ) {
731 "SELECT /*+ MAX_EXECUTION_TIME($timeoutMsec)*/",
744 AtEase::suppressWarnings();
745 $res =
$conn->query( $sql );
746 AtEase::restoreWarnings();
748 $insertId = (int)
$conn->insert_id;
749 $this->lastQueryInsertId = $insertId;
750 $this->sessionLastAutoRowId = $insertId ?: $this->sessionLastAutoRowId;
754 $conn->affected_rows,
768 private function mysqlConnect( $server, $user, $password, $db ) {
769 if ( !function_exists(
'mysqli_init' ) ) {
770 throw $this->newExceptionAfterConnectError(
771 "MySQLi functions missing, have you compiled PHP with the --with-mysqli option?"
776 mysqli_report( MYSQLI_REPORT_OFF );
788 $hostAndPort = IPUtils::splitHostAndPort( $server );
789 if ( $hostAndPort ) {
790 $realServer = $hostAndPort[0];
791 if ( $hostAndPort[1] ) {
792 $port = $hostAndPort[1];
794 } elseif ( substr_count( $server,
':/' ) == 1 ) {
797 [ $realServer, $socket ] = explode(
':', $server, 2 );
799 $realServer = $server;
802 $mysqli = mysqli_init();
806 $flags = MYSQLI_CLIENT_FOUND_ROWS;
808 $flags |= MYSQLI_CLIENT_SSL;
817 if ( $this->getFlag( self::DBO_COMPRESS ) ) {
818 $flags |= MYSQLI_CLIENT_COMPRESS;
820 if ( $this->getFlag( self::DBO_PERSISTENT ) ) {
821 $realServer =
'p:' . $realServer;
824 if ( $this->utf8Mode ) {
827 $mysqli->options( MYSQLI_SET_CHARSET_NAME,
'utf8' );
829 $mysqli->options( MYSQLI_SET_CHARSET_NAME,
'binary' );
832 $mysqli->options( MYSQLI_OPT_CONNECT_TIMEOUT, $this->connectTimeout ?: 3 );
833 if ( $this->receiveTimeout ) {
834 $mysqli->options( MYSQLI_OPT_READ_TIMEOUT, $this->receiveTimeout );
838 $ok = $mysqli->real_connect( $realServer, $user, $password, $db, $port, $socket, $flags );
840 return $ok ? $mysqli :
null;
844 return ( $this->conn instanceof mysqli ) ? mysqli_close( $this->conn ) :
true;
848 return $this->sessionLastAutoRowId;
853 $this->sessionLastAutoRowId = 0;
857 if ( $this->lastEmulatedInsertId ===
null ) {
858 $conn = $this->getBindingHandle();
860 $this->lastEmulatedInsertId = (int)$conn->insert_id;
863 return $this->lastEmulatedInsertId;
870 if ( $this->conn instanceof mysqli ) {
871 return $this->conn->errno;
873 return mysqli_connect_errno();
881 private function mysqlError( $conn =
null ) {
882 if ( $conn ===
null ) {
883 return (
string)mysqli_connect_error();
889 private function mysqlRealEscapeString( $s ) {
890 $conn = $this->getBindingHandle();
892 return $conn->real_escape_string( (
string)$s );
899class_alias( DatabaseMySQL::class,
'DatabaseMysqlBase' );
904class_alias( DatabaseMySQL::class,
'DatabaseMysqli' );
Class to handle database/schema/prefix specifications for IDatabase.