IDatabase: Rename masterPosWait to primaryPosWait
[mediawiki.git] / includes / libs / rdbms / database / DatabaseMysqlBase.php
blob726e9e96e6bf6620a9c23cc451521d689272b3a0
1 <?php
2 /**
3 * This is the MySQL database abstraction layer.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @ingroup Database
23 namespace Wikimedia\Rdbms;
25 use InvalidArgumentException;
26 use mysqli_result;
27 use RuntimeException;
28 use stdClass;
29 use Wikimedia\AtEase\AtEase;
31 /**
32 * Database abstraction object for MySQL.
33 * Defines methods independent on used MySQL extension.
35 * TODO: This could probably be merged with DatabaseMysqli.
36 * The split was created to support a transition from the old "mysql" extension
37 * to mysqli, and there may be an argument for retaining it in order to support
38 * some future transition to something else, but it's complexity and YAGNI.
40 * @ingroup Database
41 * @since 1.22
42 * @see Database
44 abstract class DatabaseMysqlBase extends Database {
45 /** @var MySQLPrimaryPos */
46 protected $lastKnownReplicaPos;
47 /** @var string Method to detect replica DB lag */
48 protected $lagDetectionMethod;
49 /** @var array Method to detect replica DB lag */
50 protected $lagDetectionOptions = [];
51 /** @var bool bool Whether to use GTID methods */
52 protected $useGTIDs = false;
53 /** @var string|null */
54 protected $sslKeyPath;
55 /** @var string|null */
56 protected $sslCertPath;
57 /** @var string|null */
58 protected $sslCAFile;
59 /** @var string|null */
60 protected $sslCAPath;
61 /**
62 * Open SSL cipher list string
63 * @see https://www.openssl.org/docs/man1.0.2/man1/ciphers.html
64 * @var string|null
66 protected $sslCiphers;
67 /** @var string sql_mode value to send on connection */
68 protected $sqlMode;
69 /** @var bool Use experimental UTF-8 transmission encoding */
70 protected $utf8Mode;
71 /** @var bool|null */
72 protected $defaultBigSelects;
74 /** @var bool|null */
75 private $insertSelectIsSafe;
76 /** @var stdClass|null */
77 private $replicationInfoRow;
79 // Cache getServerId() for 24 hours
80 private const SERVER_ID_CACHE_TTL = 86400;
82 /** @var float Warn if lag estimates are made for transactions older than this many seconds */
83 private const LAG_STALE_WARN_THRESHOLD = 0.100;
85 /**
86 * Additional $params include:
87 * - lagDetectionMethod : set to one of (Seconds_Behind_Master,pt-heartbeat).
88 * pt-heartbeat assumes the table is at heartbeat.heartbeat
89 * and uses UTC timestamps in the heartbeat.ts column.
90 * (https://www.percona.com/doc/percona-toolkit/2.2/pt-heartbeat.html)
91 * - lagDetectionOptions : if using pt-heartbeat, this can be set to an array map to change
92 * the default behavior. Normally, the heartbeat row with the server
93 * ID of this server's primary DB will be used. Set the "conds" field to
94 * override the query conditions, e.g. ['shard' => 's1'].
95 * - useGTIDs : use GTID methods like MASTER_GTID_WAIT() when possible.
96 * - insertSelectIsSafe : force that native INSERT SELECT is or is not safe [default: null]
97 * - sslKeyPath : path to key file [default: null]
98 * - sslCertPath : path to certificate file [default: null]
99 * - sslCAFile: path to a single certificate authority PEM file [default: null]
100 * - sslCAPath : parth to certificate authority PEM directory [default: null]
101 * - sslCiphers : array list of allowable ciphers [default: null]
102 * @param array $params
104 public function __construct( array $params ) {
105 $this->lagDetectionMethod = $params['lagDetectionMethod'] ?? 'Seconds_Behind_Master';
106 $this->lagDetectionOptions = $params['lagDetectionOptions'] ?? [];
107 $this->useGTIDs = !empty( $params['useGTIDs' ] );
108 foreach ( [ 'KeyPath', 'CertPath', 'CAFile', 'CAPath', 'Ciphers' ] as $name ) {
109 $var = "ssl{$name}";
110 if ( isset( $params[$var] ) ) {
111 $this->$var = $params[$var];
114 $this->sqlMode = $params['sqlMode'] ?? null;
115 $this->utf8Mode = !empty( $params['utf8Mode'] );
116 $this->insertSelectIsSafe = isset( $params['insertSelectIsSafe'] )
117 ? (bool)$params['insertSelectIsSafe'] : null;
119 parent::__construct( $params );
123 * @return string
125 public function getType() {
126 return 'mysql';
129 protected function open( $server, $user, $password, $db, $schema, $tablePrefix ) {
130 $this->close( __METHOD__ );
132 if ( $schema !== null ) {
133 throw $this->newExceptionAfterConnectError( "Got schema '$schema'; not supported." );
136 $this->installErrorHandler();
137 try {
138 $this->conn = $this->mysqlConnect( $server, $user, $password, $db );
139 } catch ( RuntimeException $e ) {
140 $this->restoreErrorHandler();
141 throw $this->newExceptionAfterConnectError( $e->getMessage() );
143 $error = $this->restoreErrorHandler();
145 if ( !$this->conn ) {
146 throw $this->newExceptionAfterConnectError( $error ?: $this->lastError() );
149 try {
150 $this->currentDomain = new DatabaseDomain(
151 strlen( $db ) ? $db : null,
152 null,
153 $tablePrefix
155 // Abstract over any insane MySQL defaults
156 $set = [ 'group_concat_max_len = 262144' ];
157 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
158 if ( is_string( $this->sqlMode ) ) {
159 $set[] = 'sql_mode = ' . $this->addQuotes( $this->sqlMode );
161 // Set any custom settings defined by site config
162 // https://dev.mysql.com/doc/refman/5.7/en/innodb-parameters.html
163 foreach ( $this->connectionVariables as $var => $val ) {
164 // Escape strings but not numbers to avoid MySQL complaining
165 if ( !is_int( $val ) && !is_float( $val ) ) {
166 $val = $this->addQuotes( $val );
168 $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
171 // @phan-suppress-next-next-line PhanRedundantCondition
172 // If kept for safety and to avoid broken query
173 if ( $set ) {
174 $this->query(
175 'SET ' . implode( ', ', $set ),
176 __METHOD__,
177 self::QUERY_IGNORE_DBO_TRX | self::QUERY_NO_RETRY | self::QUERY_CHANGE_TRX
180 } catch ( RuntimeException $e ) {
181 throw $this->newExceptionAfterConnectError( $e->getMessage() );
185 protected function doSelectDomain( DatabaseDomain $domain ) {
186 if ( $domain->getSchema() !== null ) {
187 throw new DBExpectedError(
188 $this,
189 __CLASS__ . ": domain '{$domain->getId()}' has a schema component"
193 $database = $domain->getDatabase();
194 // A null database means "don't care" so leave it as is and update the table prefix
195 if ( $database === null ) {
196 $this->currentDomain = new DatabaseDomain(
197 $this->currentDomain->getDatabase(),
198 null,
199 $domain->getTablePrefix()
202 return true;
205 if ( $database !== $this->getDBname() ) {
206 $sql = 'USE ' . $this->addIdentifierQuotes( $database );
207 list( $res, $err, $errno ) =
208 $this->executeQuery( $sql, __METHOD__, self::QUERY_IGNORE_DBO_TRX );
210 if ( $res === false ) {
211 $this->reportQueryError( $err, $errno, $sql, __METHOD__ );
212 return false; // unreachable
216 // Update that domain fields on success (no exception thrown)
217 $this->currentDomain = $domain;
219 return true;
223 * Open a connection to a MySQL server
225 * @param string|null $server
226 * @param string|null $user
227 * @param string|null $password
228 * @param string|null $db
229 * @return mixed|null Driver connection handle
230 * @throws DBConnectionError
232 abstract protected function mysqlConnect( $server, $user, $password, $db );
235 * mysql_field_type() wrapper
237 * Not part of the interface and apparently not called by anything.
239 * @deprecated since 1.37
241 * @param MysqliResultWrapper $res
242 * @param int $n
243 * @return string
245 public function fieldType( $res, $n ) {
246 wfDeprecated( __METHOD__, '1.37' );
247 return $this->mysqlFieldType( $res->getInternalResult(), $n );
251 * Get the type of the specified field in a result
253 * @deprecated since 1.37
255 * @param mysqli_result $res
256 * @param int $n
257 * @return string
259 abstract protected function mysqlFieldType( $res, $n );
262 * @return string
264 public function lastError() {
265 if ( $this->conn ) {
266 # Even if it's non-zero, it can still be invalid
267 AtEase::suppressWarnings();
268 $error = $this->mysqlError( $this->conn );
269 if ( !$error ) {
270 $error = $this->mysqlError();
272 AtEase::restoreWarnings();
273 } else {
274 $error = $this->mysqlError();
276 if ( $error ) {
277 $error .= ' (' . $this->getServerName() . ')';
280 return $error;
284 * Returns the text of the error message from previous MySQL operation
286 * @param resource|null $conn Raw connection
287 * @return string
289 abstract protected function mysqlError( $conn = null );
291 protected function wasQueryTimeout( $error, $errno ) {
292 // https://dev.mysql.com/doc/refman/8.0/en/client-error-reference.html
293 // https://phabricator.wikimedia.org/T170638
294 return in_array( $errno, [ 2062, 3024 ] );
297 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
298 $row = $this->getReplicationSafetyInfo();
299 // For row-based-replication, the resulting changes will be relayed, not the query
300 if ( $row->binlog_format === 'ROW' ) {
301 return true;
303 // LIMIT requires ORDER BY on a unique key or it is non-deterministic
304 if ( isset( $selectOptions['LIMIT'] ) ) {
305 return false;
307 // In MySQL, an INSERT SELECT is only replication safe with row-based
308 // replication or if innodb_autoinc_lock_mode is 0. When those
309 // conditions aren't met, use non-native mode.
310 // While we could try to determine if the insert is safe anyway by
311 // checking if the target table has an auto-increment column that
312 // isn't set in $varMap, that seems unlikely to be worth the extra
313 // complexity.
314 return (
315 in_array( 'NO_AUTO_COLUMNS', $insertOptions ) ||
316 (int)$row->innodb_autoinc_lock_mode === 0
321 * @return stdClass Process cached row
323 protected function getReplicationSafetyInfo() {
324 if ( $this->replicationInfoRow === null ) {
325 $this->replicationInfoRow = $this->selectRow(
326 false,
328 'innodb_autoinc_lock_mode' => '@@innodb_autoinc_lock_mode',
329 'binlog_format' => '@@binlog_format',
332 __METHOD__
336 return $this->replicationInfoRow;
340 * Estimate rows in dataset
341 * Returns estimated count, based on EXPLAIN output
342 * Takes same arguments as Database::select()
344 * @param string|array $tables
345 * @param string|array $var
346 * @param string|array $conds
347 * @param string $fname
348 * @param string|array $options
349 * @param array $join_conds
350 * @return bool|int
352 public function estimateRowCount(
353 $tables,
354 $var = '*',
355 $conds = '',
356 $fname = __METHOD__,
357 $options = [],
358 $join_conds = []
360 $conds = $this->normalizeConditions( $conds, $fname );
361 $column = $this->extractSingleFieldFromList( $var );
362 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
363 $conds[] = "$column IS NOT NULL";
366 $options['EXPLAIN'] = true;
367 $res = $this->select( $tables, $var, $conds, $fname, $options, $join_conds );
368 if ( $res === false ) {
369 return false;
371 if ( !$this->numRows( $res ) ) {
372 return 0;
375 $rows = 1;
376 foreach ( $res as $plan ) {
377 $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
380 return (int)$rows;
383 public function tableExists( $table, $fname = __METHOD__ ) {
384 // Split database and table into proper variables as Database::tableName() returns
385 // shared tables prefixed with their database, which do not work in SHOW TABLES statements
386 list( $database, , $prefix, $table ) = $this->qualifiedTableComponents( $table );
387 $tableName = "{$prefix}{$table}";
389 if ( isset( $this->sessionTempTables[$tableName] ) ) {
390 return true; // already known to exist and won't show in SHOW TABLES anyway
393 // We can't use buildLike() here, because it specifies an escape character
394 // other than the backslash, which is the only one supported by SHOW TABLES
395 $encLike = $this->escapeLikeInternal( $tableName, '\\' );
397 // If the database has been specified (such as for shared tables), use "FROM"
398 if ( $database !== '' ) {
399 $encDatabase = $this->addIdentifierQuotes( $database );
400 $sql = "SHOW TABLES FROM $encDatabase LIKE '$encLike'";
401 } else {
402 $sql = "SHOW TABLES LIKE '$encLike'";
405 $res = $this->query(
406 $sql,
407 $fname,
408 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
411 return $res->numRows() > 0;
415 * @param string $table
416 * @param string $field
417 * @return bool|MySQLField
419 public function fieldInfo( $table, $field ) {
420 $res = $this->query(
421 "SELECT * FROM " . $this->tableName( $table ) . " LIMIT 1",
422 __METHOD__,
423 self::QUERY_SILENCE_ERRORS | self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
425 if ( !$res ) {
426 return false;
428 /** @var MysqliResultWrapper $res */
429 '@phan-var MysqliResultWrapper $res';
430 return $res->getInternalFieldInfo( $field );
434 * Get information about an index into an object
435 * Returns false if the index does not exist
437 * @param string $table
438 * @param string $index
439 * @param string $fname
440 * @return bool|array|null False or null on failure
442 public function indexInfo( $table, $index, $fname = __METHOD__ ) {
443 # https://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
444 $index = $this->indexName( $index );
446 $res = $this->query(
447 'SHOW INDEX FROM ' . $this->tableName( $table ),
448 $fname,
449 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
452 if ( !$res ) {
453 return null;
456 $result = [];
458 foreach ( $res as $row ) {
459 if ( $row->Key_name == $index ) {
460 $result[] = $row;
464 return $result ?: false;
468 * @param string $s
469 * @return string
471 public function strencode( $s ) {
472 return $this->mysqlRealEscapeString( $s );
476 * @param string $s
477 * @return mixed
479 abstract protected function mysqlRealEscapeString( $s );
482 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
484 * @param string $s
485 * @return string
487 public function addIdentifierQuotes( $s ) {
488 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
489 // Remove NUL bytes and escape backticks by doubling
490 return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
494 * @param string $name
495 * @return bool
497 public function isQuotedIdentifier( $name ) {
498 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
501 protected function doGetLag() {
502 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
503 return $this->getLagFromPtHeartbeat();
504 } else {
505 return $this->getLagFromSlaveStatus();
510 * @return string
512 protected function getLagDetectionMethod() {
513 return $this->lagDetectionMethod;
517 * @return int|false Second of lag
519 protected function getLagFromSlaveStatus() {
520 $res = $this->query(
521 'SHOW SLAVE STATUS',
522 __METHOD__,
523 self::QUERY_SILENCE_ERRORS | self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
525 $row = $res ? $res->fetchObject() : false;
526 // If the server is not replicating, there will be no row
527 if ( $row && strval( $row->Seconds_Behind_Master ) !== '' ) {
528 // https://mariadb.com/kb/en/delayed-replication/
529 // https://dev.mysql.com/doc/refman/5.6/en/replication-delayed.html
530 return intval( $row->Seconds_Behind_Master + ( $row->SQL_Remaining_Delay ?? 0 ) );
533 return false;
537 * @return float|false Seconds of lag
539 protected function getLagFromPtHeartbeat() {
540 $options = $this->lagDetectionOptions;
542 $currentTrxInfo = $this->getRecordedTransactionLagStatus();
543 if ( $currentTrxInfo ) {
544 // There is an active transaction and the initial lag was already queried
545 $staleness = microtime( true ) - $currentTrxInfo['since'];
546 if ( $staleness > self::LAG_STALE_WARN_THRESHOLD ) {
547 // Avoid returning higher and higher lag value due to snapshot age
548 // given that the isolation level will typically be REPEATABLE-READ
549 $this->queryLogger->warning(
550 "Using cached lag value for {db_server} due to active transaction",
551 $this->getLogContext( [
552 'method' => __METHOD__,
553 'age' => $staleness,
554 'exception' => new RuntimeException()
559 return $currentTrxInfo['lag'];
562 if ( isset( $options['conds'] ) ) {
563 // Best method for multi-DC setups: use logical channel names
564 $ago = $this->fetchSecondsSinceHeartbeat( $options['conds'] );
565 } else {
566 // Standard method: use primary server ID (works with stock pt-heartbeat)
567 $masterInfo = $this->getMasterServerInfo();
568 if ( !$masterInfo ) {
569 $this->queryLogger->error(
570 "Unable to query primary of {db_server} for server ID",
571 $this->getLogContext( [
572 'method' => __METHOD__
576 return false; // could not get primary server ID
579 $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
580 $ago = $this->fetchSecondsSinceHeartbeat( $conds );
583 if ( $ago !== null ) {
584 return max( $ago, 0.0 );
587 $this->queryLogger->error(
588 "Unable to find pt-heartbeat row for {db_server}",
589 $this->getLogContext( [
590 'method' => __METHOD__
594 return false;
597 protected function getMasterServerInfo() {
598 $cache = $this->srvCache;
599 $key = $cache->makeGlobalKey(
600 'mysql',
601 'master-info',
602 // Using one key for all cluster replica DBs is preferable
603 $this->topologyRootMaster ?? $this->getServerName()
605 $fname = __METHOD__;
607 return $cache->getWithSetCallback(
608 $key,
609 $cache::TTL_INDEFINITE,
610 function () use ( $cache, $key, $fname ) {
611 // Get and leave a lock key in place for a short period
612 if ( !$cache->lock( $key, 0, 10 ) ) {
613 return false; // avoid primary DB connection spike slams
616 $conn = $this->getLazyMasterHandle();
617 if ( !$conn ) {
618 return false; // something is misconfigured
621 $flags = self::QUERY_SILENCE_ERRORS | self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
622 // Connect to and query the primary DB; catch errors to avoid outages
623 try {
624 $res = $conn->query( 'SELECT @@server_id AS id', $fname, $flags );
625 $row = $res ? $res->fetchObject() : false;
626 $id = $row ? (int)$row->id : 0;
627 } catch ( DBError $e ) {
628 $id = 0;
631 // Cache the ID if it was retrieved
632 return $id ? [ 'serverId' => $id, 'asOf' => time() ] : false;
638 * @param array $conds WHERE clause conditions to find a row
639 * @return float|null Elapsed seconds since the newest beat or null if none was found
640 * @see https://www.percona.com/doc/percona-toolkit/2.1/pt-heartbeat.html
642 protected function fetchSecondsSinceHeartbeat( array $conds ) {
643 $whereSQL = $this->makeList( $conds, self::LIST_AND );
644 // User mysql server time so that query time and trip time are not counted.
645 // Use ORDER BY for channel based queries since that field might not be UNIQUE.
646 $res = $this->query(
647 "SELECT TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6)) AS us_ago " .
648 "FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1",
649 __METHOD__,
650 self::QUERY_SILENCE_ERRORS | self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
652 $row = $res ? $res->fetchObject() : false;
654 return $row ? ( $row->us_ago / 1e6 ) : null;
657 protected function getApproximateLagStatus() {
658 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
659 // Disable caching since this is fast enough and we don't wan't
660 // to be *too* pessimistic by having both the cache TTL and the
661 // pt-heartbeat interval count as lag in getSessionLagStatus()
662 return parent::getApproximateLagStatus();
665 $key = $this->srvCache->makeGlobalKey( 'mysql-lag', $this->getServerName() );
666 $approxLag = $this->srvCache->get( $key );
667 if ( !$approxLag ) {
668 $approxLag = parent::getApproximateLagStatus();
669 $this->srvCache->set( $key, $approxLag, 1 );
672 return $approxLag;
675 public function primaryPosWait( DBPrimaryPos $pos, $timeout ) {
676 if ( !( $pos instanceof MySQLPrimaryPos ) ) {
677 throw new InvalidArgumentException( "Position not an instance of MySQLPrimaryPos" );
680 if ( $this->topologyRole === self::ROLE_STATIC_CLONE ) {
681 $this->queryLogger->debug(
682 "Bypassed replication wait; database has a static dataset",
683 $this->getLogContext( [ 'method' => __METHOD__, 'raw_pos' => $pos ] )
686 return 0; // this is a copy of a read-only dataset with no primary DB
687 } elseif ( $this->lastKnownReplicaPos && $this->lastKnownReplicaPos->hasReached( $pos ) ) {
688 $this->queryLogger->debug(
689 "Bypassed replication wait; replication known to have reached {raw_pos}",
690 $this->getLogContext( [ 'method' => __METHOD__, 'raw_pos' => $pos ] )
693 return 0; // already reached this point for sure
696 // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
697 if ( $pos->getGTIDs() ) {
698 // Get the GTIDs from this replica server too see the domains (channels)
699 $refPos = $this->getReplicaPos();
700 if ( !$refPos ) {
701 $this->queryLogger->error(
702 "Could not get replication position on replica DB to compare to {raw_pos}",
703 $this->getLogContext( [ 'method' => __METHOD__, 'raw_pos' => $pos ] )
706 return -1; // this is the primary DB itself?
708 // GTIDs with domains (channels) that are active and are present on the replica
709 $gtidsWait = $pos::getRelevantActiveGTIDs( $pos, $refPos );
710 if ( !$gtidsWait ) {
711 $this->queryLogger->error(
712 "No active GTIDs in {raw_pos} share a domain with those in {current_pos}",
713 $this->getLogContext( [
714 'method' => __METHOD__,
715 'raw_pos' => $pos,
716 'current_pos' => $refPos
720 return -1; // $pos is from the wrong cluster?
722 // Wait on the GTID set
723 $gtidArg = $this->addQuotes( implode( ',', $gtidsWait ) );
724 if ( strpos( $gtidArg, ':' ) !== false ) {
725 // MySQL GTIDs, e.g "source_id:transaction_id"
726 $sql = "SELECT WAIT_FOR_EXECUTED_GTID_SET($gtidArg, $timeout)";
727 } else {
728 // MariaDB GTIDs, e.g."domain:server:sequence"
729 $sql = "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)";
731 $waitPos = implode( ',', $gtidsWait );
732 } else {
733 // Wait on the binlog coordinates
734 $encFile = $this->addQuotes( $pos->getLogFile() );
735 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
736 $encPos = intval( $pos->getLogPosition()[$pos::CORD_EVENT] );
737 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
738 $waitPos = $pos->__toString();
741 $start = microtime( true );
742 $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
743 $res = $this->query( $sql, __METHOD__, $flags );
744 $row = $this->fetchRow( $res );
745 $seconds = max( microtime( true ) - $start, 0 );
747 // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
748 $status = ( $row[0] !== null ) ? intval( $row[0] ) : null;
749 if ( $status === null ) {
750 $this->replLogger->error(
751 "An error occurred while waiting for replication to reach {wait_pos}",
752 $this->getLogContext( [
753 'raw_pos' => $pos,
754 'wait_pos' => $waitPos,
755 'sql' => $sql,
756 'seconds_waited' => $seconds,
757 'exception' => new RuntimeException()
760 } elseif ( $status < 0 ) {
761 $this->replLogger->error(
762 "Timed out waiting for replication to reach {wait_pos}",
763 $this->getLogContext( [
764 'raw_pos' => $pos,
765 'wait_pos' => $waitPos,
766 'timeout' => $timeout,
767 'sql' => $sql,
768 'seconds_waited' => $seconds,
769 'exception' => new RuntimeException()
772 } elseif ( $status >= 0 ) {
773 $this->replLogger->debug(
774 "Replication has reached {wait_pos}",
775 $this->getLogContext( [
776 'raw_pos' => $pos,
777 'wait_pos' => $waitPos,
778 'seconds_waited' => $seconds,
781 // Remember that this position was reached to save queries next time
782 $this->lastKnownReplicaPos = $pos;
785 return $status;
789 * Get the position of the primary DB from SHOW SLAVE STATUS
791 * @return MySQLPrimaryPos|bool
793 public function getReplicaPos() {
794 $now = microtime( true ); // as-of-time *before* fetching GTID variables
796 if ( $this->useGTIDs() ) {
797 // Try to use GTIDs, fallbacking to binlog positions if not possible
798 $data = $this->getServerGTIDs( __METHOD__ );
799 // Use gtid_slave_pos for MariaDB and gtid_executed for MySQL
800 foreach ( [ 'gtid_slave_pos', 'gtid_executed' ] as $name ) {
801 if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
802 return new MySQLPrimaryPos( $data[$name], $now );
807 $data = $this->getServerRoleStatus( 'SLAVE', __METHOD__ );
808 if ( $data && strlen( $data['Relay_Master_Log_File'] ) ) {
809 return new MySQLPrimaryPos(
810 "{$data['Relay_Master_Log_File']}/{$data['Exec_Master_Log_Pos']}",
811 $now
815 return false;
819 * Get the position of the primary DB from SHOW MASTER STATUS
821 * @return MySQLPrimaryPos|bool
823 public function getPrimaryPos() {
824 $now = microtime( true ); // as-of-time *before* fetching GTID variables
826 $pos = false;
827 if ( $this->useGTIDs() ) {
828 // Try to use GTIDs, fallbacking to binlog positions if not possible
829 $data = $this->getServerGTIDs( __METHOD__ );
830 // Use gtid_binlog_pos for MariaDB and gtid_executed for MySQL
831 foreach ( [ 'gtid_binlog_pos', 'gtid_executed' ] as $name ) {
832 if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
833 $pos = new MySQLPrimaryPos( $data[$name], $now );
834 break;
837 // Filter domains that are inactive or not relevant to the session
838 if ( $pos ) {
839 $pos->setActiveOriginServerId( $this->getServerId() );
840 $pos->setActiveOriginServerUUID( $this->getServerUUID() );
841 if ( isset( $data['gtid_domain_id'] ) ) {
842 $pos->setActiveDomain( $data['gtid_domain_id'] );
847 if ( !$pos ) {
848 $data = $this->getServerRoleStatus( 'MASTER', __METHOD__ );
849 if ( $data && strlen( $data['File'] ) ) {
850 $pos = new MySQLPrimaryPos( "{$data['File']}/{$data['Position']}", $now );
854 return $pos;
857 public function getMasterPos() {
858 // wfDeprecated( __METHOD__, '1.37' );
859 return $this->getPrimaryPos();
863 * @inheritDoc
864 * @return string|null 32 bit integer ID; null if not applicable or unknown
866 public function getTopologyBasedServerId() {
867 return $this->getServerId();
871 * @return string Value of server_id (32-bit integer, unique to the replication topology)
872 * @throws DBQueryError
874 protected function getServerId() {
875 $fname = __METHOD__;
876 return $this->srvCache->getWithSetCallback(
877 $this->srvCache->makeGlobalKey( 'mysql-server-id', $this->getServerName() ),
878 self::SERVER_ID_CACHE_TTL,
879 function () use ( $fname ) {
880 $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
881 $res = $this->query( "SELECT @@server_id AS id", $fname, $flags );
883 return $this->fetchObject( $res )->id;
889 * @return string|null Value of server_uuid (hyphenated 128-bit hex string, globally unique)
890 * @throws DBQueryError
892 protected function getServerUUID() {
893 $fname = __METHOD__;
894 return $this->srvCache->getWithSetCallback(
895 $this->srvCache->makeGlobalKey( 'mysql-server-uuid', $this->getServerName() ),
896 self::SERVER_ID_CACHE_TTL,
897 function () use ( $fname ) {
898 $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
899 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'server_uuid'", $fname, $flags );
900 $row = $this->fetchObject( $res );
902 return $row ? $row->Value : null;
908 * @param string $fname
909 * @return string[]
911 protected function getServerGTIDs( $fname = __METHOD__ ) {
912 $map = [];
914 $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
916 // Get global-only variables like gtid_executed
917 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_%'", $fname, $flags );
918 foreach ( $res as $row ) {
919 $map[$row->Variable_name] = $row->Value;
921 // Get session-specific (e.g. gtid_domain_id since that is were writes will log)
922 $res = $this->query( "SHOW SESSION VARIABLES LIKE 'gtid_%'", $fname, $flags );
923 foreach ( $res as $row ) {
924 $map[$row->Variable_name] = $row->Value;
927 return $map;
931 * @param string $role One of "MASTER"/"SLAVE"
932 * @param string $fname
933 * @return string[] Latest available server status row
935 protected function getServerRoleStatus( $role, $fname = __METHOD__ ) {
936 $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
937 $res = $this->query( "SHOW $role STATUS", $fname, $flags );
939 return $res->fetchRow() ?: [];
942 public function serverIsReadOnly() {
943 // Avoid SHOW to avoid internal temporary tables
944 $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
945 $res = $this->query( "SELECT @@GLOBAL.read_only AS Value", __METHOD__, $flags );
946 $row = $this->fetchObject( $res );
948 return $row ? (bool)$row->Value : false;
952 * @param string $index
953 * @return string
955 public function useIndexClause( $index ) {
956 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
960 * @param string $index
961 * @return string
963 public function ignoreIndexClause( $index ) {
964 return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
968 * @return string
970 public function getSoftwareLink() {
971 list( $variant ) = $this->getMySqlServerVariant();
972 if ( $variant === 'MariaDB' ) {
973 return '[{{int:version-db-mariadb-url}} MariaDB]';
976 return '[{{int:version-db-mysql-url}} MySQL]';
980 * @return string[] (one of ("MariaDB","MySQL"), x.y.z version string)
982 protected function getMySqlServerVariant() {
983 $version = $this->getServerVersion();
985 // MariaDB includes its name in its version string; this is how MariaDB's version of
986 // the mysql command-line client identifies MariaDB servers.
987 // https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_version
988 // https://mariadb.com/kb/en/version/
989 $parts = explode( '-', $version, 2 );
990 $number = $parts[0];
991 $suffix = $parts[1] ?? '';
992 if ( strpos( $suffix, 'MariaDB' ) !== false || strpos( $suffix, '-maria-' ) !== false ) {
993 $vendor = 'MariaDB';
994 } else {
995 $vendor = 'MySQL';
998 return [ $vendor, $number ];
1002 * @return string
1004 public function getServerVersion() {
1005 $cache = $this->srvCache;
1006 $fname = __METHOD__;
1008 return $cache->getWithSetCallback(
1009 $cache->makeGlobalKey( 'mysql-server-version', $this->getServerName() ),
1010 $cache::TTL_HOUR,
1011 function () use ( $fname ) {
1012 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
1013 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
1014 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
1015 return $this->selectField( '', 'VERSION()', '', $fname );
1021 * @param array $options
1023 public function setSessionOptions( array $options ) {
1024 if ( isset( $options['connTimeout'] ) ) {
1025 $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_TRX;
1026 $timeout = (int)$options['connTimeout'];
1027 $this->query( "SET net_read_timeout=$timeout", __METHOD__, $flags );
1028 $this->query( "SET net_write_timeout=$timeout", __METHOD__, $flags );
1033 * @param string &$sql
1034 * @param string &$newLine
1035 * @return bool
1037 public function streamStatementEnd( &$sql, &$newLine ) {
1038 if ( preg_match( '/^DELIMITER\s+(\S+)/i', $newLine, $m ) ) {
1039 $this->delimiter = $m[1];
1040 $newLine = '';
1043 return parent::streamStatementEnd( $sql, $newLine );
1046 public function doLockIsFree( string $lockName, string $method ) {
1047 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1049 $res = $this->query(
1050 "SELECT IS_FREE_LOCK($encName) AS unlocked",
1051 $method,
1052 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
1054 $row = $this->fetchObject( $res );
1056 return ( $row->unlocked == 1 );
1059 public function doLock( string $lockName, string $method, int $timeout ) {
1060 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1061 // Unlike NOW(), SYSDATE() gets the time at invokation rather than query start.
1062 // The precision argument is silently ignored for MySQL < 5.6 and MariaDB < 5.3.
1063 // https://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html#function_sysdate
1064 // https://dev.mysql.com/doc/refman/5.6/en/fractional-seconds.html
1065 $res = $this->query(
1066 "SELECT IF(GET_LOCK($encName,$timeout),UNIX_TIMESTAMP(SYSDATE(6)),NULL) AS acquired",
1067 $method,
1068 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
1070 $row = $this->fetchObject( $res );
1072 return ( $row->acquired !== null ) ? (float)$row->acquired : null;
1075 public function doUnlock( string $lockName, string $method ) {
1076 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1078 $res = $this->query(
1079 "SELECT RELEASE_LOCK($encName) AS released",
1080 $method,
1081 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
1083 $row = $this->fetchObject( $res );
1085 return ( $row->released == 1 );
1088 private function makeLockName( $lockName ) {
1089 // https://dev.mysql.com/doc/refman/5.7/en/locking-functions.html#function_get-lock
1090 // MySQL 5.7+ enforces a 64 char length limit.
1091 return ( strlen( $lockName ) > 64 ) ? sha1( $lockName ) : $lockName;
1094 public function namedLocksEnqueue() {
1095 return true;
1098 public function tableLocksHaveTransactionScope() {
1099 return false; // tied to TCP connection
1102 protected function doLockTables( array $read, array $write, $method ) {
1103 $items = [];
1104 foreach ( $write as $table ) {
1105 $items[] = $this->tableName( $table ) . ' WRITE';
1107 foreach ( $read as $table ) {
1108 $items[] = $this->tableName( $table ) . ' READ';
1111 $this->query(
1112 "LOCK TABLES " . implode( ',', $items ),
1113 $method,
1114 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_ROWS
1117 return true;
1120 protected function doUnlockTables( $method ) {
1121 $this->query(
1122 "UNLOCK TABLES",
1123 $method,
1124 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_ROWS
1127 return true;
1131 * @param bool $value
1133 public function setBigSelects( $value = true ) {
1134 if ( $value === 'default' ) {
1135 if ( $this->defaultBigSelects === null ) {
1136 # Function hasn't been called before so it must already be set to the default
1137 return;
1138 } else {
1139 $value = $this->defaultBigSelects;
1141 } elseif ( $this->defaultBigSelects === null ) {
1142 $this->defaultBigSelects =
1143 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__ );
1146 $this->query(
1147 "SET sql_big_selects=" . ( $value ? '1' : '0' ),
1148 __METHOD__,
1149 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_TRX
1154 * DELETE where the condition is a join. MySql uses multi-table deletes.
1155 * @param string $delTable
1156 * @param string $joinTable
1157 * @param string $delVar
1158 * @param string $joinVar
1159 * @param array|string $conds
1160 * @param bool|string $fname
1161 * @throws DBUnexpectedError
1163 public function deleteJoin(
1164 $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
1166 if ( !$conds ) {
1167 throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
1170 $delTable = $this->tableName( $delTable );
1171 $joinTable = $this->tableName( $joinTable );
1172 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1174 if ( $conds != '*' ) {
1175 $sql .= ' AND ' . $this->makeList( $conds, self::LIST_AND );
1178 $this->query( $sql, $fname, self::QUERY_CHANGE_ROWS );
1181 protected function doUpsert(
1182 string $table,
1183 array $rows,
1184 array $identityKey,
1185 array $set,
1186 string $fname
1188 $encTable = $this->tableName( $table );
1189 list( $sqlColumns, $sqlTuples ) = $this->makeInsertLists( $rows );
1190 $sqlColumnAssignments = $this->makeList( $set, self::LIST_SET );
1192 $sql =
1193 "INSERT INTO $encTable ($sqlColumns) VALUES $sqlTuples " .
1194 "ON DUPLICATE KEY UPDATE $sqlColumnAssignments";
1196 $this->query( $sql, $fname, self::QUERY_CHANGE_ROWS );
1199 protected function doReplace( $table, array $identityKey, array $rows, $fname ) {
1200 $encTable = $this->tableName( $table );
1201 list( $sqlColumns, $sqlTuples ) = $this->makeInsertLists( $rows );
1203 $sql = "REPLACE INTO $encTable ($sqlColumns) VALUES $sqlTuples";
1205 $this->query( $sql, $fname, self::QUERY_CHANGE_ROWS );
1209 * Determines how long the server has been up
1211 * @return int
1213 public function getServerUptime() {
1214 $vars = $this->getMysqlStatus( 'Uptime' );
1216 return (int)$vars['Uptime'];
1220 * Determines if the last failure was due to a deadlock
1222 * @return bool
1224 public function wasDeadlock() {
1225 return $this->lastErrno() == 1213;
1229 * Determines if the last failure was due to a lock timeout
1231 * @return bool
1233 public function wasLockTimeout() {
1234 return $this->lastErrno() == 1205;
1238 * Determines if the last failure was due to the database being read-only.
1240 * @return bool
1242 public function wasReadOnlyError() {
1243 return $this->lastErrno() == 1223 ||
1244 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1247 public function wasConnectionError( $errno ) {
1248 return $errno == 2013 || $errno == 2006;
1251 protected function wasKnownStatementRollbackError() {
1252 $errno = $this->lastErrno();
1254 if ( $errno === 1205 ) { // lock wait timeout
1255 // Note that this is uncached to avoid stale values of SET is used
1256 $res = $this->query(
1257 "SELECT @@innodb_rollback_on_timeout AS Value",
1258 __METHOD__,
1259 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
1261 $row = $res ? $res->fetchObject() : false;
1262 // https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
1263 // https://dev.mysql.com/doc/refman/5.5/en/innodb-parameters.html
1264 return ( $row && !$row->Value );
1267 // See https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1268 return in_array( $errno, [ 1022, 1062, 1216, 1217, 1137, 1146, 1051, 1054 ], true );
1272 * @param string $oldName
1273 * @param string $newName
1274 * @param bool $temporary
1275 * @param string $fname
1276 * @return bool
1278 public function duplicateTableStructure(
1279 $oldName, $newName, $temporary = false, $fname = __METHOD__
1281 $tmp = $temporary ? 'TEMPORARY ' : '';
1282 $newName = $this->addIdentifierQuotes( $newName );
1283 $oldName = $this->addIdentifierQuotes( $oldName );
1285 return $this->query(
1286 "CREATE $tmp TABLE $newName (LIKE $oldName)",
1287 $fname,
1288 self::QUERY_PSEUDO_PERMANENT | self::QUERY_CHANGE_SCHEMA
1293 * List all tables on the database
1295 * @param string|null $prefix Only show tables with this prefix, e.g. mw_
1296 * @param string $fname Calling function name
1297 * @return array
1299 public function listTables( $prefix = null, $fname = __METHOD__ ) {
1300 $result = $this->query(
1301 "SHOW TABLES",
1302 $fname,
1303 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
1306 $endArray = [];
1308 foreach ( $result as $table ) {
1309 $vars = get_object_vars( $table );
1310 $table = array_pop( $vars );
1312 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1313 $endArray[] = $table;
1317 return $endArray;
1321 * Get status information from SHOW STATUS in an associative array
1323 * @param string $which
1324 * @return array
1326 private function getMysqlStatus( $which = "%" ) {
1327 $res = $this->query(
1328 "SHOW STATUS LIKE '{$which}'",
1329 __METHOD__,
1330 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
1333 $status = [];
1334 foreach ( $res as $row ) {
1335 $status[$row->Variable_name] = $row->Value;
1338 return $status;
1342 * Lists VIEWs in the database
1344 * @param string|null $prefix Only show VIEWs with this prefix, eg.
1345 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1346 * @param string $fname Name of calling function
1347 * @return array
1348 * @since 1.22
1350 public function listViews( $prefix = null, $fname = __METHOD__ ) {
1351 // The name of the column containing the name of the VIEW
1352 $propertyName = 'Tables_in_' . $this->getDBname();
1354 // Query for the VIEWS
1355 $res = $this->query(
1356 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"',
1357 $fname,
1358 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
1361 $allViews = [];
1362 foreach ( $res as $row ) {
1363 array_push( $allViews, $row->$propertyName );
1366 if ( $prefix === null || $prefix === '' ) {
1367 return $allViews;
1370 $filteredViews = [];
1371 foreach ( $allViews as $viewName ) {
1372 // Does the name of this VIEW start with the table-prefix?
1373 if ( strpos( $viewName, $prefix ) === 0 ) {
1374 array_push( $filteredViews, $viewName );
1378 return $filteredViews;
1382 * Differentiates between a TABLE and a VIEW.
1384 * @param string $name Name of the TABLE/VIEW to test
1385 * @param string|null $prefix
1386 * @return bool
1387 * @since 1.22
1389 public function isView( $name, $prefix = null ) {
1390 return in_array( $name, $this->listViews( $prefix, __METHOD__ ) );
1393 protected function isTransactableQuery( $sql ) {
1394 return parent::isTransactableQuery( $sql ) &&
1395 !preg_match( '/^SELECT\s+(GET|RELEASE|IS_FREE)_LOCK\(/', $sql );
1398 public function buildStringCast( $field ) {
1399 return "CAST( $field AS BINARY )";
1403 * @param string $field Field or column to cast
1404 * @return string
1406 public function buildIntegerCast( $field ) {
1407 return 'CAST( ' . $field . ' AS SIGNED )';
1411 * @return bool Whether GTID support is used (mockable for testing)
1413 protected function useGTIDs() {
1414 return $this->useGTIDs;
1419 * @deprecated since 1.29
1421 class_alias( DatabaseMysqlBase::class, 'DatabaseMysqlBase' );