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
23 namespace Wikimedia\Rdbms
;
27 use Wikimedia\AtEase\AtEase
;
28 use InvalidArgumentException
;
34 * Database abstraction object for MySQL.
35 * Defines methods independent on used MySQL extension.
41 abstract class DatabaseMysqlBase
extends Database
{
42 /** @var MysqlMasterPos */
43 protected $lastKnownReplicaPos;
44 /** @var string Method to detect replica DB lag */
45 protected $lagDetectionMethod;
46 /** @var array Method to detect replica DB lag */
47 protected $lagDetectionOptions = [];
48 /** @var bool bool Whether to use GTID methods */
49 protected $useGTIDs = false;
50 /** @var string|null */
51 protected $sslKeyPath;
52 /** @var string|null */
53 protected $sslCertPath;
54 /** @var string|null */
56 /** @var string|null */
58 /** @var string[]|null */
59 protected $sslCiphers;
60 /** @var string sql_mode value to send on connection */
62 /** @var bool Use experimental UTF-8 transmission encoding */
65 protected $defaultBigSelects = null;
68 private $insertSelectIsSafe = null;
69 /** @var stdClass|null */
70 private $replicationInfoRow = null;
72 // Cache getServerId() for 24 hours
73 const SERVER_ID_CACHE_TTL
= 86400;
75 /** @var float Warn if lag estimates are made for transactions older than this many seconds */
76 const LAG_STALE_WARN_THRESHOLD
= 0.100;
79 * Additional $params include:
80 * - lagDetectionMethod : set to one of (Seconds_Behind_Master,pt-heartbeat).
81 * pt-heartbeat assumes the table is at heartbeat.heartbeat
82 * and uses UTC timestamps in the heartbeat.ts column.
83 * (https://www.percona.com/doc/percona-toolkit/2.2/pt-heartbeat.html)
84 * - lagDetectionOptions : if using pt-heartbeat, this can be set to an array map to change
85 * the default behavior. Normally, the heartbeat row with the server
86 * ID of this server's master will be used. Set the "conds" field to
87 * override the query conditions, e.g. ['shard' => 's1'].
88 * - useGTIDs : use GTID methods like MASTER_GTID_WAIT() when possible.
89 * - insertSelectIsSafe : force that native INSERT SELECT is or is not safe [default: null]
90 * - sslKeyPath : path to key file [default: null]
91 * - sslCertPath : path to certificate file [default: null]
92 * - sslCAFile: path to a single certificate authority PEM file [default: null]
93 * - sslCAPath : parth to certificate authority PEM directory [default: null]
94 * - sslCiphers : array list of allowable ciphers [default: null]
95 * @param array $params
97 public function __construct( array $params ) {
98 $this->lagDetectionMethod
= $params['lagDetectionMethod'] ??
'Seconds_Behind_Master';
99 $this->lagDetectionOptions
= $params['lagDetectionOptions'] ??
[];
100 $this->useGTIDs
= !empty( $params['useGTIDs' ] );
101 foreach ( [ 'KeyPath', 'CertPath', 'CAFile', 'CAPath', 'Ciphers' ] as $name ) {
103 if ( isset( $params[$var] ) ) {
104 $this->$var = $params[$var];
107 $this->sqlMode
= $params['sqlMode'] ??
null;
108 $this->utf8Mode
= !empty( $params['utf8Mode'] );
109 $this->insertSelectIsSafe
= isset( $params['insertSelectIsSafe'] )
110 ?
(bool)$params['insertSelectIsSafe'] : null;
112 parent
::__construct( $params );
118 public function getType() {
122 protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix ) {
125 if ( $schema !== null ) {
126 throw $this->newExceptionAfterConnectError( "Got schema '$schema'; not supported." );
129 $this->server
= $server;
131 $this->password
= $password;
133 $this->installErrorHandler();
135 $this->conn
= $this->mysqlConnect( $this->server
, $dbName );
136 } catch ( Exception
$e ) {
137 $this->restoreErrorHandler();
138 throw $this->newExceptionAfterConnectError( $e->getMessage() );
140 $error = $this->restoreErrorHandler();
142 if ( !$this->conn
) {
143 throw $this->newExceptionAfterConnectError( $error ?
: $this->lastError() );
147 $this->currentDomain
= new DatabaseDomain(
148 strlen( $dbName ) ?
$dbName : null,
152 // Abstract over any insane MySQL defaults
153 $set = [ 'group_concat_max_len = 262144' ];
154 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
155 if ( is_string( $this->sqlMode
) ) {
156 $set[] = 'sql_mode = ' . $this->addQuotes( $this->sqlMode
);
158 // Set any custom settings defined by site config
159 // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
160 foreach ( $this->connectionVariables
as $var => $val ) {
161 // Escape strings but not numbers to avoid MySQL complaining
162 if ( !is_int( $val ) && !is_float( $val ) ) {
163 $val = $this->addQuotes( $val );
165 $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
170 'SET ' . implode( ', ', $set ),
172 self
::QUERY_IGNORE_DBO_TRX | self
::QUERY_NO_RETRY
175 } catch ( Exception
$e ) {
176 throw $this->newExceptionAfterConnectError( $e->getMessage() );
180 protected function doSelectDomain( DatabaseDomain
$domain ) {
181 if ( $domain->getSchema() !== null ) {
182 throw new DBExpectedError(
184 __CLASS__
. ": domain '{$domain->getId()}' has a schema component"
188 $database = $domain->getDatabase();
189 // A null database means "don't care" so leave it as is and update the table prefix
190 if ( $database === null ) {
191 $this->currentDomain
= new DatabaseDomain(
192 $this->currentDomain
->getDatabase(),
194 $domain->getTablePrefix()
200 if ( $database !== $this->getDBname() ) {
201 $sql = 'USE ' . $this->addIdentifierQuotes( $database );
202 list( $res, $err, $errno ) =
203 $this->executeQuery( $sql, __METHOD__
, self
::QUERY_IGNORE_DBO_TRX
);
205 if ( $res === false ) {
206 $this->reportQueryError( $err, $errno, $sql, __METHOD__
);
207 return false; // unreachable
211 // Update that domain fields on success (no exception thrown)
212 $this->currentDomain
= $domain;
218 * Open a connection to a MySQL server
220 * @param string $realServer
221 * @param string|null $dbName
222 * @return mixed|null Driver connection handle
223 * @throws DBConnectionError
225 abstract protected function mysqlConnect( $realServer, $dbName );
228 * @param IResultWrapper|resource $res
229 * @throws DBUnexpectedError
231 public function freeResult( $res ) {
232 AtEase
::suppressWarnings();
233 $ok = $this->mysqlFreeResult( ResultWrapper
::unwrap( $res ) );
234 AtEase
::restoreWarnings();
236 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
243 * @param resource $res Raw result
246 abstract protected function mysqlFreeResult( $res );
249 * @param IResultWrapper|resource $res
250 * @return stdClass|bool
251 * @throws DBUnexpectedError
253 public function fetchObject( $res ) {
254 AtEase
::suppressWarnings();
255 $row = $this->mysqlFetchObject( ResultWrapper
::unwrap( $res ) );
256 AtEase
::restoreWarnings();
258 $errno = $this->lastErrno();
259 // Unfortunately, mysql_fetch_object does not reset the last errno.
260 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
261 // these are the only errors mysql_fetch_object can cause.
262 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
263 if ( $errno == 2000 ||
$errno == 2013 ) {
264 throw new DBUnexpectedError(
266 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
274 * Fetch a result row as an object
276 * @param resource $res Raw result
279 abstract protected function mysqlFetchObject( $res );
282 * @param IResultWrapper|resource $res
284 * @throws DBUnexpectedError
286 public function fetchRow( $res ) {
287 AtEase
::suppressWarnings();
288 $row = $this->mysqlFetchArray( ResultWrapper
::unwrap( $res ) );
289 AtEase
::restoreWarnings();
291 $errno = $this->lastErrno();
292 // Unfortunately, mysql_fetch_array does not reset the last errno.
293 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
294 // these are the only errors mysql_fetch_array can cause.
295 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
296 if ( $errno == 2000 ||
$errno == 2013 ) {
297 throw new DBUnexpectedError(
299 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
307 * Fetch a result row as an associative and numeric array
309 * @param resource $res Raw result
310 * @return array|false
312 abstract protected function mysqlFetchArray( $res );
315 * @throws DBUnexpectedError
316 * @param IResultWrapper|resource $res
319 function numRows( $res ) {
320 if ( is_bool( $res ) ) {
323 AtEase
::suppressWarnings();
324 $n = $this->mysqlNumRows( ResultWrapper
::unwrap( $res ) );
325 AtEase
::restoreWarnings();
328 // Unfortunately, mysql_num_rows does not reset the last errno.
329 // We are not checking for any errors here, since
330 // there are no errors mysql_num_rows can cause.
331 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
332 // See https://phabricator.wikimedia.org/T44430
337 * Get number of rows in result
339 * @param resource $res Raw result
342 abstract protected function mysqlNumRows( $res );
345 * @param IResultWrapper|resource $res
348 public function numFields( $res ) {
349 return $this->mysqlNumFields( ResultWrapper
::unwrap( $res ) );
353 * Get number of fields in result
355 * @param resource $res Raw result
358 abstract protected function mysqlNumFields( $res );
361 * @param IResultWrapper|resource $res
365 public function fieldName( $res, $n ) {
366 return $this->mysqlFieldName( ResultWrapper
::unwrap( $res ), $n );
370 * Get the name of the specified field in a result
372 * @param IResultWrapper|resource $res
376 abstract protected function mysqlFieldName( $res, $n );
379 * mysql_field_type() wrapper
380 * @param IResultWrapper|resource $res
384 public function fieldType( $res, $n ) {
385 return $this->mysqlFieldType( ResultWrapper
::unwrap( $res ), $n );
389 * Get the type of the specified field in a result
391 * @param IResultWrapper|resource $res
395 abstract protected function mysqlFieldType( $res, $n );
398 * @param IResultWrapper|resource $res
402 public function dataSeek( $res, $row ) {
403 return $this->mysqlDataSeek( ResultWrapper
::unwrap( $res ), $row );
407 * Move internal result pointer
409 * @param IResultWrapper|resource $res
413 abstract protected function mysqlDataSeek( $res, $row );
418 public function lastError() {
420 # Even if it's non-zero, it can still be invalid
421 AtEase
::suppressWarnings();
422 $error = $this->mysqlError( $this->conn
);
424 $error = $this->mysqlError();
426 AtEase
::restoreWarnings();
428 $error = $this->mysqlError();
431 $error .= ' (' . $this->server
. ')';
438 * Returns the text of the error message from previous MySQL operation
440 * @param resource|null $conn Raw connection
443 abstract protected function mysqlError( $conn = null );
445 protected function wasQueryTimeout( $error, $errno ) {
446 // https://dev.mysql.com/doc/refman/8.0/en/client-error-reference.html
447 // https://phabricator.wikimedia.org/T170638
448 return in_array( $errno, [ 2062, 3024 ] );
451 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
452 $this->nativeReplace( $table, $rows, $fname );
455 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
456 $row = $this->getReplicationSafetyInfo();
457 // For row-based-replication, the resulting changes will be relayed, not the query
458 if ( $row->binlog_format
=== 'ROW' ) {
461 // LIMIT requires ORDER BY on a unique key or it is non-deterministic
462 if ( isset( $selectOptions['LIMIT'] ) ) {
465 // In MySQL, an INSERT SELECT is only replication safe with row-based
466 // replication or if innodb_autoinc_lock_mode is 0. When those
467 // conditions aren't met, use non-native mode.
468 // While we could try to determine if the insert is safe anyway by
469 // checking if the target table has an auto-increment column that
470 // isn't set in $varMap, that seems unlikely to be worth the extra
473 in_array( 'NO_AUTO_COLUMNS', $insertOptions ) ||
474 (int)$row->innodb_autoinc_lock_mode
=== 0
479 * @return stdClass Process cached row
481 protected function getReplicationSafetyInfo() {
482 if ( $this->replicationInfoRow
=== null ) {
483 $this->replicationInfoRow
= $this->selectRow(
486 'innodb_autoinc_lock_mode' => '@@innodb_autoinc_lock_mode',
487 'binlog_format' => '@@binlog_format',
494 return $this->replicationInfoRow
;
498 * Estimate rows in dataset
499 * Returns estimated count, based on EXPLAIN output
500 * Takes same arguments as Database::select()
502 * @param string|array $table
503 * @param string|array $var
504 * @param string|array $conds
505 * @param string $fname
506 * @param string|array $options
507 * @param array $join_conds
510 public function estimateRowCount( $table, $var = '*', $conds = '',
511 $fname = __METHOD__
, $options = [], $join_conds = []
513 $conds = $this->normalizeConditions( $conds, $fname );
514 $column = $this->extractSingleFieldFromList( $var );
515 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
516 $conds[] = "$column IS NOT NULL";
519 $options['EXPLAIN'] = true;
520 $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
521 if ( $res === false ) {
524 if ( !$this->numRows( $res ) ) {
529 foreach ( $res as $plan ) {
530 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
536 public function tableExists( $table, $fname = __METHOD__
) {
537 // Split database and table into proper variables as Database::tableName() returns
538 // shared tables prefixed with their database, which do not work in SHOW TABLES statements
539 list( $database, , $prefix, $table ) = $this->qualifiedTableComponents( $table );
540 $tableName = "{$prefix}{$table}";
542 if ( isset( $this->sessionTempTables
[$tableName] ) ) {
543 return true; // already known to exist and won't show in SHOW TABLES anyway
546 // We can't use buildLike() here, because it specifies an escape character
547 // other than the backslash, which is the only one supported by SHOW TABLES
548 $encLike = $this->escapeLikeInternal( $tableName, '\\' );
550 // If the database has been specified (such as for shared tables), use "FROM"
551 if ( $database !== '' ) {
552 $encDatabase = $this->addIdentifierQuotes( $database );
553 $query = "SHOW TABLES FROM $encDatabase LIKE '$encLike'";
555 $query = "SHOW TABLES LIKE '$encLike'";
558 return $this->query( $query, $fname )->numRows() > 0;
562 * @param string $table
563 * @param string $field
564 * @return bool|MySQLField
566 public function fieldInfo( $table, $field ) {
567 $table = $this->tableName( $table );
568 $flags = self
::QUERY_SILENCE_ERRORS
;
569 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, $flags );
573 $n = $this->mysqlNumFields( ResultWrapper
::unwrap( $res ) );
574 for ( $i = 0; $i < $n; $i++
) {
575 $meta = $this->mysqlFetchField( ResultWrapper
::unwrap( $res ), $i );
576 if ( $field == $meta->name
) {
577 return new MySQLField( $meta );
585 * Get column information from a result
587 * @param resource $res Raw result
591 abstract protected function mysqlFetchField( $res, $n );
594 * Get information about an index into an object
595 * Returns false if the index does not exist
597 * @param string $table
598 * @param string $index
599 * @param string $fname
600 * @return bool|array|null False or null on failure
602 public function indexInfo( $table, $index, $fname = __METHOD__
) {
603 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
604 # SHOW INDEX should work for 3.x and up:
605 # https://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
606 $table = $this->tableName( $table );
607 $index = $this->indexName( $index );
609 $sql = 'SHOW INDEX FROM ' . $table;
610 $res = $this->query( $sql, $fname );
618 foreach ( $res as $row ) {
619 if ( $row->Key_name
== $index ) {
624 return $result ?
: false;
631 public function strencode( $s ) {
632 return $this->mysqlRealEscapeString( $s );
639 abstract protected function mysqlRealEscapeString( $s );
641 public function addQuotes( $s ) {
642 if ( is_bool( $s ) ) {
643 // Parent would transform to int, which does not play nice with MySQL type juggling.
644 // When searching for an int in a string column, the strings are cast to int, which
645 // means false would match any string not starting with a number.
646 $s = (string)(int)$s;
648 return parent
::addQuotes( $s );
652 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
657 public function addIdentifierQuotes( $s ) {
658 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
659 // Remove NUL bytes and escape backticks by doubling
660 return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
664 * @param string $name
667 public function isQuotedIdentifier( $name ) {
668 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
671 protected function doGetLag() {
672 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
673 return $this->getLagFromPtHeartbeat();
675 return $this->getLagFromSlaveStatus();
682 protected function getLagDetectionMethod() {
683 return $this->lagDetectionMethod
;
689 protected function getLagFromSlaveStatus() {
690 $flags = self
::QUERY_SILENCE_ERRORS | self
::QUERY_IGNORE_DBO_TRX
;
691 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
, $flags );
692 $row = $res ?
$res->fetchObject() : false;
693 // If the server is not replicating, there will be no row
694 if ( $row && strval( $row->Seconds_Behind_Master
) !== '' ) {
695 return intval( $row->Seconds_Behind_Master
);
704 protected function getLagFromPtHeartbeat() {
705 $options = $this->lagDetectionOptions
;
707 $currentTrxInfo = $this->getRecordedTransactionLagStatus();
708 if ( $currentTrxInfo ) {
709 // There is an active transaction and the initial lag was already queried
710 $staleness = microtime( true ) - $currentTrxInfo['since'];
711 if ( $staleness > self
::LAG_STALE_WARN_THRESHOLD
) {
712 // Avoid returning higher and higher lag value due to snapshot age
713 // given that the isolation level will typically be REPEATABLE-READ
714 $this->queryLogger
->warning(
715 "Using cached lag value for {db_server} due to active transaction",
716 $this->getLogContext( [
717 'method' => __METHOD__
,
719 'trace' => ( new RuntimeException() )->getTraceAsString()
724 return $currentTrxInfo['lag'];
727 if ( isset( $options['conds'] ) ) {
728 // Best method for multi-DC setups: use logical channel names
729 $data = $this->getHeartbeatData( $options['conds'] );
731 // Standard method: use master server ID (works with stock pt-heartbeat)
732 $masterInfo = $this->getMasterServerInfo();
733 if ( !$masterInfo ) {
734 $this->queryLogger
->error(
735 "Unable to query master of {db_server} for server ID",
736 $this->getLogContext( [
737 'method' => __METHOD__
741 return false; // could not get master server ID
744 $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
745 $data = $this->getHeartbeatData( $conds );
748 list( $time, $nowUnix ) = $data;
749 if ( $time !== null ) {
750 // @time is in ISO format like "2015-09-25T16:48:10.000510"
751 $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
752 $timeUnix = (int)$dateTime->format( 'U' ) +
$dateTime->format( 'u' ) / 1e6
;
754 return max( $nowUnix - $timeUnix, 0.0 );
757 $this->queryLogger
->error(
758 "Unable to find pt-heartbeat row for {db_server}",
759 $this->getLogContext( [
760 'method' => __METHOD__
767 protected function getMasterServerInfo() {
768 $cache = $this->srvCache
;
769 $key = $cache->makeGlobalKey(
772 // Using one key for all cluster replica DBs is preferable
773 $this->getLBInfo( 'clusterMasterHost' ) ?
: $this->getServer()
777 return $cache->getWithSetCallback(
779 $cache::TTL_INDEFINITE
,
780 function () use ( $cache, $key, $fname ) {
781 // Get and leave a lock key in place for a short period
782 if ( !$cache->lock( $key, 0, 10 ) ) {
783 return false; // avoid master connection spike slams
786 $conn = $this->getLazyMasterHandle();
788 return false; // something is misconfigured
791 // Connect to and query the master; catch errors to avoid outages
793 $flags = self
::QUERY_SILENCE_ERRORS | self
::QUERY_IGNORE_DBO_TRX
;
794 $res = $conn->query( 'SELECT @@server_id AS id', $fname, $flags );
795 $row = $res ?
$res->fetchObject() : false;
796 $id = $row ?
(int)$row->id
: 0;
797 } catch ( DBError
$e ) {
801 // Cache the ID if it was retrieved
802 return $id ?
[ 'serverId' => $id, 'asOf' => time() ] : false;
808 * @param array $conds WHERE clause conditions to find a row
809 * @return array (heartbeat `ts` column value or null, UNIX timestamp) for the newest beat
810 * @see https://www.percona.com/doc/percona-toolkit/2.1/pt-heartbeat.html
812 protected function getHeartbeatData( array $conds ) {
813 // Query time and trip time are not counted
814 $nowUnix = microtime( true );
815 $whereSQL = $this->makeList( $conds, self
::LIST_AND
);
816 // Use ORDER BY for channel based queries since that field might not be UNIQUE.
817 // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
818 // percision field is not supported in MySQL <= 5.5.
820 "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1",
822 self
::QUERY_SILENCE_ERRORS | self
::QUERY_IGNORE_DBO_TRX
824 $row = $res ?
$res->fetchObject() : false;
826 return [ $row ?
$row->ts
: null, $nowUnix ];
829 protected function getApproximateLagStatus() {
830 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
831 // Disable caching since this is fast enough and we don't wan't
832 // to be *too* pessimistic by having both the cache TTL and the
833 // pt-heartbeat interval count as lag in getSessionLagStatus()
834 return parent
::getApproximateLagStatus();
837 $key = $this->srvCache
->makeGlobalKey( 'mysql-lag', $this->getServer() );
838 $approxLag = $this->srvCache
->get( $key );
840 $approxLag = parent
::getApproximateLagStatus();
841 $this->srvCache
->set( $key, $approxLag, 1 );
847 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
848 if ( !( $pos instanceof MySQLMasterPos
) ) {
849 throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
852 if ( $this->getLBInfo( 'is static' ) === true ) {
853 return 0; // this is a copy of a read-only dataset with no master DB
854 } elseif ( $this->lastKnownReplicaPos
&& $this->lastKnownReplicaPos
->hasReached( $pos ) ) {
855 return 0; // already reached this point for sure
858 // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
859 if ( $pos->getGTIDs() ) {
860 // Ignore GTIDs from domains exclusive to the master DB (presumably inactive)
861 $rpos = $this->getReplicaPos();
862 $gtidsWait = $rpos ? MySQLMasterPos
::getCommonDomainGTIDs( $pos, $rpos ) : [];
864 $this->queryLogger
->error(
865 "No GTIDs with the same domain between master ($pos) and replica ($rpos)",
866 $this->getLogContext( [
867 'method' => __METHOD__
,
871 return -1; // $pos is from the wrong cluster?
873 // Wait on the GTID set (MariaDB only)
874 $gtidArg = $this->addQuotes( implode( ',', $gtidsWait ) );
875 if ( strpos( $gtidArg, ':' ) !== false ) {
876 // MySQL GTIDs, e.g "source_id:transaction_id"
877 $sql = "SELECT WAIT_FOR_EXECUTED_GTID_SET($gtidArg, $timeout)";
879 // MariaDB GTIDs, e.g."domain:server:sequence"
880 $sql = "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)";
883 // Wait on the binlog coordinates
884 $encFile = $this->addQuotes( $pos->getLogFile() );
885 $encPos = intval( $pos->getLogPosition()[$pos::CORD_EVENT
] );
886 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
889 list( $res, $err ) = $this->executeQuery( $sql, __METHOD__
, self
::QUERY_IGNORE_DBO_TRX
);
890 $row = $res ?
$this->fetchRow( $res ) : false;
892 throw new DBExpectedError( $this, "Replication wait failed: {$err}" );
895 // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
896 $status = ( $row[0] !== null ) ?
intval( $row[0] ) : null;
897 if ( $status === null ) {
898 if ( !$pos->getGTIDs() ) {
899 // T126436: jobs programmed to wait on master positions might be referencing
900 // binlogs with an old master hostname; this makes MASTER_POS_WAIT() return null.
901 // Try to detect this case and treat the replica DB as having reached the given
902 // position (any master switchover already requires that the new master be caught
903 // up before the switch).
904 $replicationPos = $this->getReplicaPos();
905 if ( $replicationPos && !$replicationPos->channelsMatch( $pos ) ) {
906 $this->lastKnownReplicaPos
= $replicationPos;
910 } elseif ( $status >= 0 ) {
911 // Remember that this position was reached to save queries next time
912 $this->lastKnownReplicaPos
= $pos;
919 * Get the position of the master from SHOW SLAVE STATUS
921 * @return MySQLMasterPos|bool
923 public function getReplicaPos() {
924 $now = microtime( true ); // as-of-time *before* fetching GTID variables
926 if ( $this->useGTIDs() ) {
927 // Try to use GTIDs, fallbacking to binlog positions if not possible
928 $data = $this->getServerGTIDs( __METHOD__
);
929 // Use gtid_slave_pos for MariaDB and gtid_executed for MySQL
930 foreach ( [ 'gtid_slave_pos', 'gtid_executed' ] as $name ) {
931 if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
932 return new MySQLMasterPos( $data[$name], $now );
937 $data = $this->getServerRoleStatus( 'SLAVE', __METHOD__
);
938 if ( $data && strlen( $data['Relay_Master_Log_File'] ) ) {
939 return new MySQLMasterPos(
940 "{$data['Relay_Master_Log_File']}/{$data['Exec_Master_Log_Pos']}",
949 * Get the position of the master from SHOW MASTER STATUS
951 * @return MySQLMasterPos|bool
953 public function getMasterPos() {
954 $now = microtime( true ); // as-of-time *before* fetching GTID variables
957 if ( $this->useGTIDs() ) {
958 // Try to use GTIDs, fallbacking to binlog positions if not possible
959 $data = $this->getServerGTIDs( __METHOD__
);
960 // Use gtid_binlog_pos for MariaDB and gtid_executed for MySQL
961 foreach ( [ 'gtid_binlog_pos', 'gtid_executed' ] as $name ) {
962 if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
963 $pos = new MySQLMasterPos( $data[$name], $now );
967 // Filter domains that are inactive or not relevant to the session
969 $pos->setActiveOriginServerId( $this->getServerId() );
970 $pos->setActiveOriginServerUUID( $this->getServerUUID() );
971 if ( isset( $data['gtid_domain_id'] ) ) {
972 $pos->setActiveDomain( $data['gtid_domain_id'] );
978 $data = $this->getServerRoleStatus( 'MASTER', __METHOD__
);
979 if ( $data && strlen( $data['File'] ) ) {
980 $pos = new MySQLMasterPos( "{$data['File']}/{$data['Position']}", $now );
989 * @throws DBQueryError If the variable doesn't exist for some reason
991 protected function getServerId() {
993 return $this->srvCache
->getWithSetCallback(
994 $this->srvCache
->makeGlobalKey( 'mysql-server-id', $this->getServer() ),
995 self
::SERVER_ID_CACHE_TTL
,
996 function () use ( $fname ) {
997 $flags = self
::QUERY_IGNORE_DBO_TRX
;
998 $res = $this->query( "SELECT @@server_id AS id", $fname, $flags );
1000 return intval( $this->fetchObject( $res )->id
);
1006 * @return string|null
1008 protected function getServerUUID() {
1009 $fname = __METHOD__
;
1010 return $this->srvCache
->getWithSetCallback(
1011 $this->srvCache
->makeGlobalKey( 'mysql-server-uuid', $this->getServer() ),
1012 self
::SERVER_ID_CACHE_TTL
,
1013 function () use ( $fname ) {
1014 $flags = self
::QUERY_IGNORE_DBO_TRX
;
1015 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'server_uuid'", $fname, $flags );
1016 $row = $this->fetchObject( $res );
1018 return $row ?
$row->Value
: null;
1024 * @param string $fname
1027 protected function getServerGTIDs( $fname = __METHOD__
) {
1030 $flags = self
::QUERY_IGNORE_DBO_TRX
;
1031 // Get global-only variables like gtid_executed
1032 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_%'", $fname, $flags );
1033 foreach ( $res as $row ) {
1034 $map[$row->Variable_name
] = $row->Value
;
1036 // Get session-specific (e.g. gtid_domain_id since that is were writes will log)
1037 $res = $this->query( "SHOW SESSION VARIABLES LIKE 'gtid_%'", $fname, $flags );
1038 foreach ( $res as $row ) {
1039 $map[$row->Variable_name
] = $row->Value
;
1046 * @param string $role One of "MASTER"/"SLAVE"
1047 * @param string $fname
1048 * @return string[] Latest available server status row
1050 protected function getServerRoleStatus( $role, $fname = __METHOD__
) {
1051 $flags = self
::QUERY_IGNORE_DBO_TRX
;
1053 return $this->query( "SHOW $role STATUS", $fname, $flags )->fetchRow() ?
: [];
1056 public function serverIsReadOnly() {
1057 // Avoid SHOW to avoid internal temporary tables
1058 $flags = self
::QUERY_IGNORE_DBO_TRX | self
::QUERY_SILENCE_ERRORS
;
1059 $res = $this->query( "SELECT @@GLOBAL.read_only AS Value", __METHOD__
, $flags );
1060 $row = $this->fetchObject( $res );
1062 return $row ?
(bool)$row->Value
: false;
1066 * @param string $index
1069 function useIndexClause( $index ) {
1070 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
1074 * @param string $index
1077 function ignoreIndexClause( $index ) {
1078 return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
1084 public function getSoftwareLink() {
1085 // MariaDB includes its name in its version string; this is how MariaDB's version of
1086 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
1087 // in libmysql/libmysql.c).
1088 $version = $this->getServerVersion();
1089 if ( strpos( $version, 'MariaDB' ) !== false ||
strpos( $version, '-maria-' ) !== false ) {
1090 return '[{{int:version-db-mariadb-url}} MariaDB]';
1093 // Percona Server's version suffix is not very distinctive, and @@version_comment
1094 // doesn't give the necessary info for source builds, so assume the server is MySQL.
1095 // (Even Percona's version of mysql doesn't try to make the distinction.)
1096 return '[{{int:version-db-mysql-url}} MySQL]';
1102 public function getServerVersion() {
1103 $cache = $this->srvCache
;
1104 $fname = __METHOD__
;
1106 return $cache->getWithSetCallback(
1107 $cache->makeGlobalKey( 'mysql-server-version', $this->getServer() ),
1109 function () use ( $fname ) {
1110 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
1111 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
1112 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
1113 return $this->selectField( '', 'VERSION()', '', $fname );
1119 * @param array $options
1121 public function setSessionOptions( array $options ) {
1122 if ( isset( $options['connTimeout'] ) ) {
1123 $flags = self
::QUERY_IGNORE_DBO_TRX
;
1124 $timeout = (int)$options['connTimeout'];
1125 $this->query( "SET net_read_timeout=$timeout", __METHOD__
, $flags );
1126 $this->query( "SET net_write_timeout=$timeout", __METHOD__
, $flags );
1131 * @param string &$sql
1132 * @param string &$newLine
1135 public function streamStatementEnd( &$sql, &$newLine ) {
1136 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
1137 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
1138 $this->delimiter
= $m[1];
1142 return parent
::streamStatementEnd( $sql, $newLine );
1146 * Check to see if a named lock is available. This is non-blocking.
1148 * @param string $lockName Name of lock to poll
1149 * @param string $method Name of method calling us
1153 public function lockIsFree( $lockName, $method ) {
1154 if ( !parent
::lockIsFree( $lockName, $method ) ) {
1155 return false; // already held
1158 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1160 $flags = self
::QUERY_IGNORE_DBO_TRX
;
1161 $res = $this->query( "SELECT IS_FREE_LOCK($encName) AS lockstatus", $method, $flags );
1162 $row = $this->fetchObject( $res );
1164 return ( $row->lockstatus
== 1 );
1168 * @param string $lockName
1169 * @param string $method
1170 * @param int $timeout
1173 public function lock( $lockName, $method, $timeout = 5 ) {
1174 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1176 $flags = self
::QUERY_IGNORE_DBO_TRX
;
1177 $res = $this->query( "SELECT GET_LOCK($encName, $timeout) AS lockstatus", $method, $flags );
1178 $row = $this->fetchObject( $res );
1180 if ( $row->lockstatus
== 1 ) {
1181 parent
::lock( $lockName, $method, $timeout ); // record
1185 $this->queryLogger
->info( __METHOD__
. " failed to acquire lock '{lockname}'",
1186 [ 'lockname' => $lockName ] );
1193 * https://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
1194 * @param string $lockName
1195 * @param string $method
1198 public function unlock( $lockName, $method ) {
1199 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1201 $flags = self
::QUERY_IGNORE_DBO_TRX
;
1202 $res = $this->query( "SELECT RELEASE_LOCK($encName) as lockstatus", $method, $flags );
1203 $row = $this->fetchObject( $res );
1205 if ( $row->lockstatus
== 1 ) {
1206 parent
::unlock( $lockName, $method ); // record
1210 $this->queryLogger
->warning( __METHOD__
. " failed to release lock '$lockName'\n" );
1215 private function makeLockName( $lockName ) {
1216 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1217 // Newer version enforce a 64 char length limit.
1218 return ( strlen( $lockName ) > 64 ) ?
sha1( $lockName ) : $lockName;
1221 public function namedLocksEnqueue() {
1225 public function tableLocksHaveTransactionScope() {
1226 return false; // tied to TCP connection
1229 protected function doLockTables( array $read, array $write, $method ) {
1231 foreach ( $write as $table ) {
1232 $items[] = $this->tableName( $table ) . ' WRITE';
1234 foreach ( $read as $table ) {
1235 $items[] = $this->tableName( $table ) . ' READ';
1238 $sql = "LOCK TABLES " . implode( ',', $items );
1239 $this->query( $sql, $method, self
::QUERY_IGNORE_DBO_TRX
);
1244 protected function doUnlockTables( $method ) {
1245 $this->query( "UNLOCK TABLES", $method, self
::QUERY_IGNORE_DBO_TRX
);
1251 * @param bool $value
1253 public function setBigSelects( $value = true ) {
1254 if ( $value === 'default' ) {
1255 if ( $this->defaultBigSelects
=== null ) {
1256 # Function hasn't been called before so it must already be set to the default
1259 $value = $this->defaultBigSelects
;
1261 } elseif ( $this->defaultBigSelects
=== null ) {
1262 $this->defaultBigSelects
=
1263 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__
);
1265 $encValue = $value ?
'1' : '0';
1266 $this->query( "SET sql_big_selects=$encValue", __METHOD__
, self
::QUERY_IGNORE_DBO_TRX
);
1270 * DELETE where the condition is a join. MySql uses multi-table deletes.
1271 * @param string $delTable
1272 * @param string $joinTable
1273 * @param string $delVar
1274 * @param string $joinVar
1275 * @param array|string $conds
1276 * @param bool|string $fname
1277 * @throws DBUnexpectedError
1279 public function deleteJoin(
1280 $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
1283 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
1286 $delTable = $this->tableName( $delTable );
1287 $joinTable = $this->tableName( $joinTable );
1288 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1290 if ( $conds != '*' ) {
1291 $sql .= ' AND ' . $this->makeList( $conds, self
::LIST_AND
);
1294 $this->query( $sql, $fname );
1297 public function upsert(
1298 $table, array $rows, $uniqueIndexes, array $set, $fname = __METHOD__
1300 if ( $rows === [] ) {
1301 return true; // nothing to do
1304 if ( !is_array( reset( $rows ) ) ) {
1308 $table = $this->tableName( $table );
1309 $columns = array_keys( $rows[0] );
1311 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1313 foreach ( $rows as $row ) {
1314 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1316 $sql .= implode( ',', $rowTuples );
1317 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, self
::LIST_SET
);
1319 $this->query( $sql, $fname );
1325 * Determines how long the server has been up
1329 public function getServerUptime() {
1330 $vars = $this->getMysqlStatus( 'Uptime' );
1332 return (int)$vars['Uptime'];
1336 * Determines if the last failure was due to a deadlock
1340 public function wasDeadlock() {
1341 return $this->lastErrno() == 1213;
1345 * Determines if the last failure was due to a lock timeout
1349 public function wasLockTimeout() {
1350 return $this->lastErrno() == 1205;
1354 * Determines if the last failure was due to the database being read-only.
1358 public function wasReadOnlyError() {
1359 return $this->lastErrno() == 1223 ||
1360 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1363 public function wasConnectionError( $errno ) {
1364 return $errno == 2013 ||
$errno == 2006;
1367 protected function wasKnownStatementRollbackError() {
1368 $errno = $this->lastErrno();
1370 if ( $errno === 1205 ) { // lock wait timeout
1371 // Note that this is uncached to avoid stale values of SET is used
1372 $row = $this->selectRow(
1374 [ 'innodb_rollback_on_timeout' => '@@innodb_rollback_on_timeout' ],
1378 // https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
1379 // https://dev.mysql.com/doc/refman/5.5/en/innodb-parameters.html
1380 return $row->innodb_rollback_on_timeout ?
false : true;
1383 // See https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1384 return in_array( $errno, [ 1022, 1062, 1216, 1217, 1137, 1146, 1051, 1054 ], true );
1388 * @param string $oldName
1389 * @param string $newName
1390 * @param bool $temporary
1391 * @param string $fname
1394 public function duplicateTableStructure(
1395 $oldName, $newName, $temporary = false, $fname = __METHOD__
1397 $tmp = $temporary ?
'TEMPORARY ' : '';
1398 $newName = $this->addIdentifierQuotes( $newName );
1399 $oldName = $this->addIdentifierQuotes( $oldName );
1400 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1402 return $this->query( $query, $fname, $this::QUERY_PSEUDO_PERMANENT
);
1406 * List all tables on the database
1408 * @param string|null $prefix Only show tables with this prefix, e.g. mw_
1409 * @param string $fname Calling function name
1412 public function listTables( $prefix = null, $fname = __METHOD__
) {
1413 $result = $this->query( "SHOW TABLES", $fname );
1417 foreach ( $result as $table ) {
1418 $vars = get_object_vars( $table );
1419 $table = array_pop( $vars );
1421 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1422 $endArray[] = $table;
1430 * @param string $tableName
1431 * @param string $fName
1432 * @return bool|IResultWrapper
1434 public function dropTable( $tableName, $fName = __METHOD__
) {
1435 if ( !$this->tableExists( $tableName, $fName ) ) {
1439 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1443 * Get status information from SHOW STATUS in an associative array
1445 * @param string $which
1448 private function getMysqlStatus( $which = "%" ) {
1449 $flags = self
::QUERY_IGNORE_DBO_TRX
;
1450 $res = $this->query( "SHOW STATUS LIKE '{$which}'", __METHOD__
, $flags );
1453 foreach ( $res as $row ) {
1454 $status[$row->Variable_name
] = $row->Value
;
1461 * Lists VIEWs in the database
1463 * @param string|null $prefix Only show VIEWs with this prefix, eg.
1464 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1465 * @param string $fname Name of calling function
1469 public function listViews( $prefix = null, $fname = __METHOD__
) {
1470 // The name of the column containing the name of the VIEW
1471 $propertyName = 'Tables_in_' . $this->getDBname();
1473 // Query for the VIEWS
1474 $res = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1476 foreach ( $res as $row ) {
1477 array_push( $allViews, $row->$propertyName );
1480 if ( is_null( $prefix ) ||
$prefix === '' ) {
1484 $filteredViews = [];
1485 foreach ( $allViews as $viewName ) {
1486 // Does the name of this VIEW start with the table-prefix?
1487 if ( strpos( $viewName, $prefix ) === 0 ) {
1488 array_push( $filteredViews, $viewName );
1492 return $filteredViews;
1496 * Differentiates between a TABLE and a VIEW.
1498 * @param string $name Name of the TABLE/VIEW to test
1499 * @param string|null $prefix
1503 public function isView( $name, $prefix = null ) {
1504 return in_array( $name, $this->listViews( $prefix ) );
1507 protected function isTransactableQuery( $sql ) {
1508 return parent
::isTransactableQuery( $sql ) &&
1509 !preg_match( '/^SELECT\s+(GET|RELEASE|IS_FREE)_LOCK\(/', $sql );
1512 public function buildStringCast( $field ) {
1513 return "CAST( $field AS BINARY )";
1517 * @param string $field Field or column to cast
1520 public function buildIntegerCast( $field ) {
1521 return 'CAST( ' . $field . ' AS SIGNED )';
1525 * @return bool Whether GTID support is used (mockable for testing)
1527 protected function useGTIDs() {
1528 return $this->useGTIDs
;
1533 * @deprecated since 1.29
1535 class_alias( DatabaseMysqlBase
::class, 'DatabaseMysqlBase' );