51 private $sessionLastAutoRowId;
73 foreach ( [
'KeyPath',
'CertPath',
'CAFile',
'CAPath',
'Ciphers' ] as $name ) {
75 if ( isset( $params[$var] ) ) {
76 $this->$var = $params[$var];
79 $this->utf8Mode = !empty( $params[
'utf8Mode'] );
80 parent::__construct( $params );
88 $params[
'topologyRole'],
91 $params[
'lagDetectionMethod'] ??
'Seconds_Behind_Master',
92 $params[
'lagDetectionOptions'] ?? [],
93 !empty( $params[
'useGTIDs' ] )
105 protected function open( $server, $user, $password, $db, $schema, $tablePrefix ) {
106 $this->
close( __METHOD__ );
108 if ( $schema !==
null ) {
114 $this->conn = $this->mysqlConnect( $server, $user, $password, $db );
115 }
catch ( RuntimeException $e ) {
121 if ( !$this->conn ) {
127 ( $db !==
'' ) ? $db :
null,
134 if ( !$this->
flagsHolder->getFlag( self::DBO_GAUGE ) ) {
136 $set[] =
'group_concat_max_len = 262144';
141 if ( !is_int( $val ) && !is_float( $val ) ) {
144 $set[] = $this->
platform->addIdentifierQuotes( $var ) .
' = ' . $val;
149 $sql =
'SET ' . implode(
', ', $set );
155 if ( $qs->res ===
false ) {
159 }
catch ( RuntimeException $e ) {
169 __CLASS__ .
": domain '{$domain->getId()}' has a schema component"
175 if ( $database ===
null ) {
186 if ( $database !== $this->
getDBname() ) {
188 $query =
new Query( $sql, self::QUERY_CHANGE_TRX,
'USE' );
189 $qs = $this->
executeQuery( $query, __METHOD__, self::QUERY_CHANGE_TRX );
190 if ( $qs->res ===
false ) {
198 $this->
platform->setCurrentDomain( $domain );
209 $error = $this->mysqlError( $this->conn );
211 $error = $this->mysqlError();
214 $error = $this->mysqlError() ?: $this->lastConnectError;
222 $row = $this->replicationReporter->getReplicationSafetyInfo( $this, $fname );
224 if ( $row->binlog_format ===
'ROW' ) {
228 if ( isset( $selectOptions[
'LIMIT'] ) ) {
239 in_array(
'NO_AUTO_COLUMNS', $insertOptions ) ||
240 (
int)$row->innodb_autoinc_lock_mode === 0
246 if ( $this->conn && $this->conn->warning_count ) {
248 $warnings = $this->conn->get_warnings();
249 $done = $warnings ===
false;
251 if ( in_array( $warnings->errno, [
263 'Insert returned unacceptable warning: ' . $warnings->message,
269 $done = !$warnings->next();
283 $conds = $this->
platform->normalizeConditions( $conds, $fname );
284 $column = $this->
platform->extractSingleFieldFromList( $var );
285 if ( is_string( $column ) && !in_array( $column, [
'*',
'1' ] ) ) {
286 $conds[] =
"$column IS NOT NULL";
289 $options[
'EXPLAIN'] =
true;
290 $res = $this->
select( $tables, $var, $conds, $fname, $options, $join_conds );
291 if ( $res ===
false ) {
294 if ( !$res->numRows() ) {
299 foreach ( $res as $plan ) {
300 $rows *= $plan->rows > 0 ? $plan->rows : 1;
308 [ $db, $pt ] = $this->platform->getDatabaseAndTableIdentifier( $table );
309 if ( isset( $this->sessionTempTables[$db][$pt] ) ) {
313 return (
bool)$this->newSelectQueryBuilder()
315 ->from(
'information_schema.tables' )
317 'table_schema' => $db,
331 "SELECT * FROM " . $this->tableName( $table ) .
" LIMIT 1",
332 self::QUERY_SILENCE_ERRORS | self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
335 $res = $this->query( $query, __METHOD__ );
340 '@phan-var MysqliResultWrapper $res';
341 return $res->getInternalFieldInfo( $field );
345 public function indexInfo( $table, $index, $fname = __METHOD__ ) {
348 'SHOW INDEX FROM ' . $this->tableName( $table ),
349 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
352 $res = $this->query( $query, $fname );
354 foreach ( $res as $row ) {
355 if ( $row->Key_name === $index ) {
356 return [
'unique' => !$row->Non_unique ];
366 'SHOW INDEX FROM ' . $this->tableName( $table ),
367 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
370 $res = $this->query( $query, $fname );
373 foreach ( $res as $row ) {
374 if ( $row->Key_name ===
'PRIMARY' ) {
375 $bySeq[(int)$row->Seq_in_index] = (
string)$row->Column_name;
381 return array_values( $bySeq );
389 return $this->mysqlRealEscapeString( $s );
395 $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
396 $query =
new Query(
"SELECT @@GLOBAL.read_only AS Value", $flags,
'SELECT' );
397 $res = $this->query( $query, __METHOD__ );
398 $row = $res->fetchObject();
400 return $row && $row->Value && $row->Value !==
'OFF';
407 [ $variant ] = $this->getMySqlServerVariant();
408 if ( $variant ===
'MariaDB' ) {
409 return '[{{int:version-db-mariadb-url}} MariaDB]';
412 return '[{{int:version-db-mysql-url}} MySQL]';
418 private function getMySqlServerVariant() {
419 $version = $this->getServerVersion();
425 $parts = explode(
'-', $version, 2 );
427 $suffix = $parts[1] ??
'';
428 if ( str_contains( $suffix,
'MariaDB' ) || str_contains( $suffix,
'-maria-' ) ) {
434 return [ $vendor, $number ];
443 $version = $this->conn->server_info;
445 str_starts_with( $version,
'5.5.5-' ) &&
446 ( str_contains( $version,
'MariaDB' ) || str_contains( $version,
'-maria-' ) )
448 $version = substr( $version, strlen(
'5.5.5-' ) );
454 $sqlAssignments = [];
456 if ( isset( $options[
'connTimeout'] ) ) {
457 $encTimeout = (int)$options[
'connTimeout'];
458 $sqlAssignments[] =
"net_read_timeout=$encTimeout";
459 $sqlAssignments[] =
"net_write_timeout=$encTimeout";
461 if ( isset( $options[
'groupConcatMaxLen'] ) ) {
462 $maxLength = (int)$options[
'groupConcatMaxLen'];
463 $sqlAssignments[] =
"group_concat_max_len=$maxLength";
466 if ( $sqlAssignments ) {
468 'SET ' . implode(
', ', $sqlAssignments ),
469 self::QUERY_CHANGE_TRX | self::QUERY_CHANGE_NONE,
472 $this->query( $query, __METHOD__ );
482 if ( preg_match(
'/^DELIMITER\s+(\S+)/i', $newLine, $m ) ) {
483 $this->delimiter = $m[1];
487 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 );
500 public function doLock(
string $lockName,
string $method,
int $timeout ) {
501 $query =
new Query( $this->platform->lockSQLText( $lockName, $timeout ), self::QUERY_CHANGE_LOCKS,
'SELECT' );
502 $res = $this->query( $query, $method );
503 $row = $res->fetchObject();
505 return ( $row->acquired !==
null ) ? (float)$row->acquired :
null;
509 public function doUnlock(
string $lockName,
string $method ) {
510 $query =
new Query( $this->platform->unlockSQLText( $lockName ), self::QUERY_CHANGE_LOCKS,
'SELECT' );
511 $res = $this->query( $query, $method );
512 $row = $res->fetchObject();
514 return ( $row->released == 1 );
521 $releaseLockFields = [];
522 foreach ( $this->sessionNamedLocks as $name => $info ) {
523 $encName = $this->addQuotes( $this->platform->makeLockName( $name ) );
524 $releaseLockFields[] =
"RELEASE_LOCK($encName)";
526 if ( $releaseLockFields ) {
527 $sql =
'SELECT ' . implode(
',', $releaseLockFields );
528 $flags = self::QUERY_CHANGE_LOCKS | self::QUERY_NO_RETRY;
529 $query =
new Query( $sql, $flags,
'SELECT' );
530 $qs = $this->executeQuery( $query, __METHOD__, $flags );
531 if ( $qs->res ===
false ) {
532 $this->reportQueryError( $qs->message, $qs->code, $sql, $fname,
true );
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 );
545 $encTable = $this->tableName( $table );
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 );
568 $encTable = $this->tableName( $table );
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 ) );
585 return in_array( $errno, [ 2013, 2006, 2003, 1927, 1053 ],
true );
594 return in_array( $errno, [ 3024, 1969, 1028 ],
true );
603 [ 3024, 1969, 1022, 1062, 1216, 1217, 1137, 1146, 1051, 1054 ],
616 $oldName, $newName, $temporary =
false, $fname = __METHOD__
618 $tmp = $temporary ?
'TEMPORARY ' :
'';
619 $newNameQuoted = $this->addIdentifierQuotes( $newName );
620 $oldNameQuoted = $this->addIdentifierQuotes( $oldName );
623 "CREATE $tmp TABLE $newNameQuoted (LIKE $oldNameQuoted)",
624 self::QUERY_PSEUDO_PERMANENT | self::QUERY_CHANGE_SCHEMA,
625 $temporary ?
'CREATE TEMPORARY' :
'CREATE',
629 return $this->query( $query, $fname );
639 public function listTables( $prefix =
null, $fname = __METHOD__ ) {
640 $qb = $this->newSelectQueryBuilder()
641 ->select(
'table_name' )
642 ->from(
'information_schema.tables' )
644 'table_schema' => $this->currentDomain->getDatabase(),
645 'table_type' =>
'BASE TABLE'
648 if ( $prefix !==
null && $prefix !==
'' ) {
649 $qb->andWhere( $this->expr(
653 return $qb->fetchFieldValues();
665 $sql = parent::selectSQLText( $tables, $vars, $conds, $fname, $options, $join_conds );
668 $timeoutMsec = intval( $options[
'MAX_EXECUTION_TIME'] ?? 0 );
669 if ( $timeoutMsec > 0 ) {
670 [ $vendor, $number ] = $this->getMySqlServerVariant();
671 if ( $vendor ===
'MariaDB' && version_compare( $number,
'10.1.2',
'>=' ) ) {
672 $timeoutSec = $timeoutMsec / 1000;
673 $sql =
"SET STATEMENT max_statement_time=$timeoutSec FOR $sql";
674 } elseif ( $vendor ===
'MySQL' && version_compare( $number,
'5.7.0',
'>=' ) ) {
677 "SELECT /*+ MAX_EXECUTION_TIME($timeoutMsec)*/",
687 $conn = $this->getBindingHandle();
691 $res = @$conn->query( $sql );
693 $insertId = (int)$conn->insert_id;
694 $this->lastQueryInsertId = $insertId;
695 $this->sessionLastAutoRowId = $insertId ?: $this->sessionLastAutoRowId;
699 $conn->affected_rows,
713 private function mysqlConnect( $server, $user, $password, $db ) {
714 if ( !function_exists(
'mysqli_init' ) ) {
715 throw $this->newExceptionAfterConnectError(
716 "MySQLi functions missing, have you compiled PHP with the --with-mysqli option?"
721 mysqli_report( MYSQLI_REPORT_OFF );
733 $hostAndPort = IPUtils::splitHostAndPort( $server );
734 if ( $hostAndPort ) {
735 $realServer = $hostAndPort[0];
736 if ( $hostAndPort[1] ) {
737 $port = $hostAndPort[1];
739 } elseif ( substr_count( $server,
':/' ) == 1 ) {
742 [ $realServer, $socket ] = explode(
':', $server, 2 );
744 $realServer = $server;
747 $mysqli = mysqli_init();
751 $flags = MYSQLI_CLIENT_FOUND_ROWS;
753 $flags |= MYSQLI_CLIENT_SSL;
762 if ( $this->getFlag( self::DBO_COMPRESS ) ) {
763 $flags |= MYSQLI_CLIENT_COMPRESS;
765 if ( $this->getFlag( self::DBO_PERSISTENT ) ) {
766 $realServer =
'p:' . $realServer;
769 if ( $this->utf8Mode ) {
772 $mysqli->options( MYSQLI_SET_CHARSET_NAME,
'utf8' );
774 $mysqli->options( MYSQLI_SET_CHARSET_NAME,
'binary' );
777 $mysqli->options( MYSQLI_OPT_CONNECT_TIMEOUT, $this->connectTimeout ?: 3 );
778 if ( $this->receiveTimeout ) {
779 $mysqli->options( MYSQLI_OPT_READ_TIMEOUT, $this->receiveTimeout );
783 $ok = $mysqli->real_connect( $realServer, $user, $password, $db, $port, $socket, $flags );
785 return $ok ? $mysqli :
null;
790 return ( $this->conn instanceof mysqli ) ? mysqli_close( $this->conn ) :
true;
795 return $this->sessionLastAutoRowId;
800 $this->sessionLastAutoRowId = 0;
805 if ( $this->lastEmulatedInsertId ===
null ) {
806 $conn = $this->getBindingHandle();
808 $this->lastEmulatedInsertId = (int)$conn->insert_id;
811 return $this->lastEmulatedInsertId;
818 if ( $this->conn instanceof mysqli ) {
819 return $this->conn->errno;
821 return mysqli_connect_errno();
829 private function mysqlError( $conn =
null ) {
830 if ( $conn ===
null ) {
831 return (
string)mysqli_connect_error();
840 private function mysqlRealEscapeString( $s ): string {
841 $conn = $this->getBindingHandle();
843 return $conn->real_escape_string( (
string)$s );
Class to handle database/schema/prefix specifications for IDatabase.