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
;
28 use InvalidArgumentException
;
33 * Database abstraction object for MySQL.
34 * Defines methods independent on used MySQL extension.
40 abstract class DatabaseMysqlBase
extends Database
{
41 /** @var MysqlMasterPos */
42 protected $lastKnownReplicaPos;
43 /** @var string Method to detect replica DB lag */
44 protected $lagDetectionMethod;
45 /** @var array Method to detect replica DB lag */
46 protected $lagDetectionOptions = [];
47 /** @var bool bool Whether to use GTID methods */
48 protected $useGTIDs = false;
49 /** @var string|null */
50 protected $sslKeyPath;
51 /** @var string|null */
52 protected $sslCertPath;
53 /** @var string|null */
55 /** @var string|null */
57 /** @var string[]|null */
58 protected $sslCiphers;
59 /** @var string sql_mode value to send on connection */
61 /** @var bool Use experimental UTF-8 transmission encoding */
64 protected $defaultBigSelects = null;
66 /** @var string|null */
67 private $serverVersion = null;
69 private $insertSelectIsSafe = null;
70 /** @var stdClass|null */
71 private $replicationInfoRow = null;
73 // Cache getServerId() for 24 hours
74 const SERVER_ID_CACHE_TTL
= 86400;
76 /** @var float Warn if lag estimates are made for transactions older than this many seconds */
77 const LAG_STALE_WARN_THRESHOLD
= 0.100;
80 * Additional $params include:
81 * - lagDetectionMethod : set to one of (Seconds_Behind_Master,pt-heartbeat).
82 * pt-heartbeat assumes the table is at heartbeat.heartbeat
83 * and uses UTC timestamps in the heartbeat.ts column.
84 * (https://www.percona.com/doc/percona-toolkit/2.2/pt-heartbeat.html)
85 * - lagDetectionOptions : if using pt-heartbeat, this can be set to an array map to change
86 * the default behavior. Normally, the heartbeat row with the server
87 * ID of this server's master will be used. Set the "conds" field to
88 * override the query conditions, e.g. ['shard' => 's1'].
89 * - useGTIDs : use GTID methods like MASTER_GTID_WAIT() when possible.
90 * - insertSelectIsSafe : force that native INSERT SELECT is or is not safe [default: null]
91 * - sslKeyPath : path to key file [default: null]
92 * - sslCertPath : path to certificate file [default: null]
93 * - sslCAFile: path to a single certificate authority PEM file [default: null]
94 * - sslCAPath : parth to certificate authority PEM directory [default: null]
95 * - sslCiphers : array list of allowable ciphers [default: null]
96 * @param array $params
98 function __construct( array $params ) {
99 $this->lagDetectionMethod
= isset( $params['lagDetectionMethod'] )
100 ?
$params['lagDetectionMethod']
101 : 'Seconds_Behind_Master';
102 $this->lagDetectionOptions
= isset( $params['lagDetectionOptions'] )
103 ?
$params['lagDetectionOptions']
105 $this->useGTIDs
= !empty( $params['useGTIDs' ] );
106 foreach ( [ 'KeyPath', 'CertPath', 'CAFile', 'CAPath', 'Ciphers' ] as $name ) {
108 if ( isset( $params[$var] ) ) {
109 $this->$var = $params[$var];
112 $this->sqlMode
= isset( $params['sqlMode'] ) ?
$params['sqlMode'] : '';
113 $this->utf8Mode
= !empty( $params['utf8Mode'] );
114 $this->insertSelectIsSafe
= isset( $params['insertSelectIsSafe'] )
115 ?
(bool)$params['insertSelectIsSafe'] : null;
117 parent
::__construct( $params );
123 public function getType() {
128 * @param string $server
129 * @param string $user
130 * @param string $password
131 * @param string $dbName
132 * @throws Exception|DBConnectionError
135 public function open( $server, $user, $password, $dbName ) {
136 # Close/unset connection handle
139 $this->server
= $server;
141 $this->password
= $password;
142 $this->dbName
= $dbName;
144 $this->installErrorHandler();
146 $this->conn
= $this->mysqlConnect( $this->server
);
147 } catch ( Exception
$ex ) {
148 $this->restoreErrorHandler();
151 $error = $this->restoreErrorHandler();
153 # Always log connection errors
154 if ( !$this->conn
) {
155 $error = $error ?
: $this->lastError();
156 $this->connLogger
->error(
157 "Error connecting to {db_server}: {error}",
158 $this->getLogContext( [
159 'method' => __METHOD__
,
163 $this->connLogger
->debug( "DB connection error\n" .
164 "Server: $server, User: $user, Password: " .
165 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
167 throw new DBConnectionError( $this, $error );
170 if ( strlen( $dbName ) ) {
171 Wikimedia\
suppressWarnings();
172 $success = $this->selectDB( $dbName );
173 Wikimedia\restoreWarnings
();
175 $error = $this->lastError();
176 $this->queryLogger
->error(
177 "Error selecting database {db_name} on server {db_server}: {error}",
178 $this->getLogContext( [
179 'method' => __METHOD__
,
183 throw new DBConnectionError( $this, "Error selecting database $dbName: $error" );
187 // Tell the server what we're communicating with
188 if ( !$this->connectInitCharset() ) {
189 $error = $this->lastError();
190 $this->queryLogger
->error(
191 "Error setting character set: {error}",
192 $this->getLogContext( [
193 'method' => __METHOD__
,
194 'error' => $this->lastError(),
197 throw new DBConnectionError( $this, "Error setting character set: $error" );
200 // Abstract over any insane MySQL defaults
201 $set = [ 'group_concat_max_len = 262144' ];
202 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
203 if ( is_string( $this->sqlMode
) ) {
204 $set[] = 'sql_mode = ' . $this->addQuotes( $this->sqlMode
);
206 // Set any custom settings defined by site config
207 // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
208 foreach ( $this->sessionVars
as $var => $val ) {
209 // Escape strings but not numbers to avoid MySQL complaining
210 if ( !is_int( $val ) && !is_float( $val ) ) {
211 $val = $this->addQuotes( $val );
213 $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
217 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
218 $success = $this->doQuery( 'SET ' . implode( ', ', $set ) );
220 $error = $this->lastError();
221 $this->queryLogger
->error(
222 'Error setting MySQL variables on server {db_server}: {error}',
223 $this->getLogContext( [
224 'method' => __METHOD__
,
228 throw new DBConnectionError( $this, "Error setting MySQL variables: $error" );
232 $this->opened
= true;
238 * Set the character set information right after connection
241 protected function connectInitCharset() {
242 if ( $this->utf8Mode
) {
243 // Tell the server we're communicating with it in UTF-8.
244 // This may engage various charset conversions.
245 return $this->mysqlSetCharset( 'utf8' );
247 return $this->mysqlSetCharset( 'binary' );
252 * Open a connection to a MySQL server
254 * @param string $realServer
255 * @return mixed Raw connection
256 * @throws DBConnectionError
258 abstract protected function mysqlConnect( $realServer );
261 * Set the character set of the MySQL link
263 * @param string $charset
266 abstract protected function mysqlSetCharset( $charset );
269 * @param ResultWrapper|resource $res
270 * @throws DBUnexpectedError
272 public function freeResult( $res ) {
273 if ( $res instanceof ResultWrapper
) {
276 Wikimedia\
suppressWarnings();
277 $ok = $this->mysqlFreeResult( $res );
278 Wikimedia\restoreWarnings
();
280 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
287 * @param resource $res Raw result
290 abstract protected function mysqlFreeResult( $res );
293 * @param ResultWrapper|resource $res
294 * @return stdClass|bool
295 * @throws DBUnexpectedError
297 public function fetchObject( $res ) {
298 if ( $res instanceof ResultWrapper
) {
301 Wikimedia\
suppressWarnings();
302 $row = $this->mysqlFetchObject( $res );
303 Wikimedia\restoreWarnings
();
305 $errno = $this->lastErrno();
306 // Unfortunately, mysql_fetch_object does not reset the last errno.
307 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
308 // these are the only errors mysql_fetch_object can cause.
309 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
310 if ( $errno == 2000 ||
$errno == 2013 ) {
311 throw new DBUnexpectedError(
313 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
321 * Fetch a result row as an object
323 * @param resource $res Raw result
326 abstract protected function mysqlFetchObject( $res );
329 * @param IResultWrapper|resource $res
331 * @throws DBUnexpectedError
333 public function fetchRow( $res ) {
334 if ( $res instanceof ResultWrapper
) {
337 Wikimedia\
suppressWarnings();
338 $row = $this->mysqlFetchArray( $res );
339 Wikimedia\restoreWarnings
();
341 $errno = $this->lastErrno();
342 // Unfortunately, mysql_fetch_array does not reset the last errno.
343 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
344 // these are the only errors mysql_fetch_array can cause.
345 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
346 if ( $errno == 2000 ||
$errno == 2013 ) {
347 throw new DBUnexpectedError(
349 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
357 * Fetch a result row as an associative and numeric array
359 * @param resource $res Raw result
362 abstract protected function mysqlFetchArray( $res );
365 * @throws DBUnexpectedError
366 * @param ResultWrapper|resource $res
369 function numRows( $res ) {
370 if ( $res instanceof ResultWrapper
) {
373 Wikimedia\
suppressWarnings();
374 $n = $this->mysqlNumRows( $res );
375 Wikimedia\restoreWarnings
();
377 // Unfortunately, mysql_num_rows does not reset the last errno.
378 // We are not checking for any errors here, since
379 // these are no errors mysql_num_rows can cause.
380 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
381 // See https://phabricator.wikimedia.org/T44430
386 * Get number of rows in result
388 * @param resource $res Raw result
391 abstract protected function mysqlNumRows( $res );
394 * @param ResultWrapper|resource $res
397 public function numFields( $res ) {
398 if ( $res instanceof ResultWrapper
) {
402 return $this->mysqlNumFields( $res );
406 * Get number of fields in result
408 * @param resource $res Raw result
411 abstract protected function mysqlNumFields( $res );
414 * @param ResultWrapper|resource $res
418 public function fieldName( $res, $n ) {
419 if ( $res instanceof ResultWrapper
) {
423 return $this->mysqlFieldName( $res, $n );
427 * Get the name of the specified field in a result
429 * @param ResultWrapper|resource $res
433 abstract protected function mysqlFieldName( $res, $n );
436 * mysql_field_type() wrapper
437 * @param ResultWrapper|resource $res
441 public function fieldType( $res, $n ) {
442 if ( $res instanceof ResultWrapper
) {
446 return $this->mysqlFieldType( $res, $n );
450 * Get the type of the specified field in a result
452 * @param ResultWrapper|resource $res
456 abstract protected function mysqlFieldType( $res, $n );
459 * @param ResultWrapper|resource $res
463 public function dataSeek( $res, $row ) {
464 if ( $res instanceof ResultWrapper
) {
468 return $this->mysqlDataSeek( $res, $row );
472 * Move internal result pointer
474 * @param ResultWrapper|resource $res
478 abstract protected function mysqlDataSeek( $res, $row );
483 public function lastError() {
485 # Even if it's non-zero, it can still be invalid
486 Wikimedia\
suppressWarnings();
487 $error = $this->mysqlError( $this->conn
);
489 $error = $this->mysqlError();
491 Wikimedia\restoreWarnings
();
493 $error = $this->mysqlError();
496 $error .= ' (' . $this->server
. ')';
503 * Returns the text of the error message from previous MySQL operation
505 * @param resource $conn Raw connection
508 abstract protected function mysqlError( $conn = null );
510 protected function wasQueryTimeout( $error, $errno ) {
511 return $errno == 2062;
515 * @param string $table
516 * @param array $uniqueIndexes
518 * @param string $fname
519 * @return ResultWrapper
521 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
522 return $this->nativeReplace( $table, $rows, $fname );
525 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
526 $row = $this->getReplicationSafetyInfo();
527 // For row-based-replication, the resulting changes will be relayed, not the query
528 if ( $row->binlog_format
=== 'ROW' ) {
531 // LIMIT requires ORDER BY on a unique key or it is non-deterministic
532 if ( isset( $selectOptions['LIMIT'] ) ) {
535 // In MySQL, an INSERT SELECT is only replication safe with row-based
536 // replication or if innodb_autoinc_lock_mode is 0. When those
537 // conditions aren't met, use non-native mode.
538 // While we could try to determine if the insert is safe anyway by
539 // checking if the target table has an auto-increment column that
540 // isn't set in $varMap, that seems unlikely to be worth the extra
543 in_array( 'NO_AUTO_COLUMNS', $insertOptions ) ||
544 (int)$row->innodb_autoinc_lock_mode
=== 0
549 * @return stdClass Process cached row
551 protected function getReplicationSafetyInfo() {
552 if ( $this->replicationInfoRow
=== null ) {
553 $this->replicationInfoRow
= $this->selectRow(
556 'innodb_autoinc_lock_mode' => '@@innodb_autoinc_lock_mode',
557 'binlog_format' => '@@binlog_format',
564 return $this->replicationInfoRow
;
568 * Estimate rows in dataset
569 * Returns estimated count, based on EXPLAIN output
570 * Takes same arguments as Database::select()
572 * @param string|array $table
573 * @param string|array $var
574 * @param string|array $conds
575 * @param string $fname
576 * @param string|array $options
577 * @param array $join_conds
580 public function estimateRowCount( $table, $var = '*', $conds = '',
581 $fname = __METHOD__
, $options = [], $join_conds = []
583 $conds = $this->normalizeConditions( $conds, $fname );
584 $column = $this->extractSingleFieldFromList( $var );
585 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
586 $conds[] = "$column IS NOT NULL";
589 $options['EXPLAIN'] = true;
590 $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
591 if ( $res === false ) {
594 if ( !$this->numRows( $res ) ) {
599 foreach ( $res as $plan ) {
600 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
606 public function tableExists( $table, $fname = __METHOD__
) {
607 // Split database and table into proper variables as Database::tableName() returns
608 // shared tables prefixed with their database, which do not work in SHOW TABLES statements
609 list( $database, , $prefix, $table ) = $this->qualifiedTableComponents( $table );
610 $tableName = "{$prefix}{$table}";
612 if ( isset( $this->sessionTempTables
[$tableName] ) ) {
613 return true; // already known to exist and won't show in SHOW TABLES anyway
616 // We can't use buildLike() here, because it specifies an escape character
617 // other than the backslash, which is the only one supported by SHOW TABLES
618 $encLike = $this->escapeLikeInternal( $tableName, '\\' );
620 // If the database has been specified (such as for shared tables), use "FROM"
621 if ( $database !== '' ) {
622 $encDatabase = $this->addIdentifierQuotes( $database );
623 $query = "SHOW TABLES FROM $encDatabase LIKE '$encLike'";
625 $query = "SHOW TABLES LIKE '$encLike'";
628 return $this->query( $query, $fname )->numRows() > 0;
632 * @param string $table
633 * @param string $field
634 * @return bool|MySQLField
636 public function fieldInfo( $table, $field ) {
637 $table = $this->tableName( $table );
638 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
642 $n = $this->mysqlNumFields( $res->result
);
643 for ( $i = 0; $i < $n; $i++
) {
644 $meta = $this->mysqlFetchField( $res->result
, $i );
645 if ( $field == $meta->name
) {
646 return new MySQLField( $meta );
654 * Get column information from a result
656 * @param resource $res Raw result
660 abstract protected function mysqlFetchField( $res, $n );
663 * Get information about an index into an object
664 * Returns false if the index does not exist
666 * @param string $table
667 * @param string $index
668 * @param string $fname
669 * @return bool|array|null False or null on failure
671 public function indexInfo( $table, $index, $fname = __METHOD__
) {
672 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
673 # SHOW INDEX should work for 3.x and up:
674 # https://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
675 $table = $this->tableName( $table );
676 $index = $this->indexName( $index );
678 $sql = 'SHOW INDEX FROM ' . $table;
679 $res = $this->query( $sql, $fname );
687 foreach ( $res as $row ) {
688 if ( $row->Key_name
== $index ) {
693 return $result ?
: false;
700 public function strencode( $s ) {
701 return $this->mysqlRealEscapeString( $s );
708 abstract protected function mysqlRealEscapeString( $s );
710 public function addQuotes( $s ) {
711 if ( is_bool( $s ) ) {
712 // Parent would transform to int, which does not play nice with MySQL type juggling.
713 // When searching for an int in a string column, the strings are cast to int, which
714 // means false would match any string not starting with a number.
715 $s = (string)(int)$s;
717 return parent
::addQuotes( $s );
721 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
726 public function addIdentifierQuotes( $s ) {
727 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
728 // Remove NUL bytes and escape backticks by doubling
729 return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
733 * @param string $name
736 public function isQuotedIdentifier( $name ) {
737 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
740 public function getLag() {
741 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
742 return $this->getLagFromPtHeartbeat();
744 return $this->getLagFromSlaveStatus();
751 protected function getLagDetectionMethod() {
752 return $this->lagDetectionMethod
;
758 protected function getLagFromSlaveStatus() {
759 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
760 $row = $res ?
$res->fetchObject() : false;
761 // If the server is not replicating, there will be no row
762 if ( $row && strval( $row->Seconds_Behind_Master
) !== '' ) {
763 return intval( $row->Seconds_Behind_Master
);
772 protected function getLagFromPtHeartbeat() {
773 $options = $this->lagDetectionOptions
;
775 $currentTrxInfo = $this->getRecordedTransactionLagStatus();
776 if ( $currentTrxInfo ) {
777 // There is an active transaction and the initial lag was already queried
778 $staleness = microtime( true ) - $currentTrxInfo['since'];
779 if ( $staleness > self
::LAG_STALE_WARN_THRESHOLD
) {
780 // Avoid returning higher and higher lag value due to snapshot age
781 // given that the isolation level will typically be REPEATABLE-READ
782 $this->queryLogger
->warning(
783 "Using cached lag value for {db_server} due to active transaction",
784 $this->getLogContext( [ 'method' => __METHOD__
, 'age' => $staleness ] )
788 return $currentTrxInfo['lag'];
791 if ( isset( $options['conds'] ) ) {
792 // Best method for multi-DC setups: use logical channel names
793 $data = $this->getHeartbeatData( $options['conds'] );
795 // Standard method: use master server ID (works with stock pt-heartbeat)
796 $masterInfo = $this->getMasterServerInfo();
797 if ( !$masterInfo ) {
798 $this->queryLogger
->error(
799 "Unable to query master of {db_server} for server ID",
800 $this->getLogContext( [
801 'method' => __METHOD__
805 return false; // could not get master server ID
808 $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
809 $data = $this->getHeartbeatData( $conds );
812 list( $time, $nowUnix ) = $data;
813 if ( $time !== null ) {
814 // @time is in ISO format like "2015-09-25T16:48:10.000510"
815 $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
816 $timeUnix = (int)$dateTime->format( 'U' ) +
$dateTime->format( 'u' ) / 1e6
;
818 return max( $nowUnix - $timeUnix, 0.0 );
821 $this->queryLogger
->error(
822 "Unable to find pt-heartbeat row for {db_server}",
823 $this->getLogContext( [
824 'method' => __METHOD__
831 protected function getMasterServerInfo() {
832 $cache = $this->srvCache
;
833 $key = $cache->makeGlobalKey(
836 // Using one key for all cluster replica DBs is preferable
837 $this->getLBInfo( 'clusterMasterHost' ) ?
: $this->getServer()
840 return $cache->getWithSetCallback(
842 $cache::TTL_INDEFINITE
,
843 function () use ( $cache, $key ) {
844 // Get and leave a lock key in place for a short period
845 if ( !$cache->lock( $key, 0, 10 ) ) {
846 return false; // avoid master connection spike slams
849 $conn = $this->getLazyMasterHandle();
851 return false; // something is misconfigured
854 // Connect to and query the master; catch errors to avoid outages
856 $res = $conn->query( 'SELECT @@server_id AS id', __METHOD__
);
857 $row = $res ?
$res->fetchObject() : false;
858 $id = $row ?
(int)$row->id
: 0;
859 } catch ( DBError
$e ) {
863 // Cache the ID if it was retrieved
864 return $id ?
[ 'serverId' => $id, 'asOf' => time() ] : false;
870 * @param array $conds WHERE clause conditions to find a row
871 * @return array (heartbeat `ts` column value or null, UNIX timestamp) for the newest beat
872 * @see https://www.percona.com/doc/percona-toolkit/2.1/pt-heartbeat.html
874 protected function getHeartbeatData( array $conds ) {
875 // Query time and trip time are not counted
876 $nowUnix = microtime( true );
877 // Do not bother starting implicit transactions here
878 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
880 $whereSQL = $this->makeList( $conds, self
::LIST_AND
);
881 // Use ORDER BY for channel based queries since that field might not be UNIQUE.
882 // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
883 // percision field is not supported in MySQL <= 5.5.
885 "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1",
888 $row = $res ?
$res->fetchObject() : false;
890 $this->restoreFlags();
893 return [ $row ?
$row->ts
: null, $nowUnix ];
896 protected function getApproximateLagStatus() {
897 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
898 // Disable caching since this is fast enough and we don't wan't
899 // to be *too* pessimistic by having both the cache TTL and the
900 // pt-heartbeat interval count as lag in getSessionLagStatus()
901 return parent
::getApproximateLagStatus();
904 $key = $this->srvCache
->makeGlobalKey( 'mysql-lag', $this->getServer() );
905 $approxLag = $this->srvCache
->get( $key );
907 $approxLag = parent
::getApproximateLagStatus();
908 $this->srvCache
->set( $key, $approxLag, 1 );
914 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
915 if ( !( $pos instanceof MySQLMasterPos
) ) {
916 throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
919 if ( $this->getLBInfo( 'is static' ) === true ) {
920 return 0; // this is a copy of a read-only dataset with no master DB
921 } elseif ( $this->lastKnownReplicaPos
&& $this->lastKnownReplicaPos
->hasReached( $pos ) ) {
922 return 0; // already reached this point for sure
925 // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
926 if ( $pos->getGTIDs() ) {
927 // Ignore GTIDs from domains exclusive to the master DB (presumably inactive)
928 $rpos = $this->getReplicaPos();
929 $gtidsWait = $rpos ? MySQLMasterPos
::getCommonDomainGTIDs( $pos, $rpos ) : [];
931 $this->queryLogger
->error(
932 "No GTIDs with the same domain between master ($pos) and replica ($rpos)",
933 $this->getLogContext( [
934 'method' => __METHOD__
,
938 return -1; // $pos is from the wrong cluster?
940 // Wait on the GTID set (MariaDB only)
941 $gtidArg = $this->addQuotes( implode( ',', $gtidsWait ) );
942 if ( strpos( $gtidArg, ':' ) !== false ) {
943 // MySQL GTIDs, e.g "source_id:transaction_id"
944 $res = $this->doQuery( "SELECT WAIT_FOR_EXECUTED_GTID_SET($gtidArg, $timeout)" );
946 // MariaDB GTIDs, e.g."domain:server:sequence"
947 $res = $this->doQuery( "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)" );
950 // Wait on the binlog coordinates
951 $encFile = $this->addQuotes( $pos->getLogFile() );
952 $encPos = intval( $pos->getLogPosition()[$pos::CORD_EVENT
] );
953 $res = $this->doQuery( "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)" );
956 $row = $res ?
$this->fetchRow( $res ) : false;
958 throw new DBExpectedError( $this, "Replication wait failed: {$this->lastError()}" );
961 // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
962 $status = ( $row[0] !== null ) ?
intval( $row[0] ) : null;
963 if ( $status === null ) {
964 if ( !$pos->getGTIDs() ) {
965 // T126436: jobs programmed to wait on master positions might be referencing
966 // binlogs with an old master hostname; this makes MASTER_POS_WAIT() return null.
967 // Try to detect this case and treat the replica DB as having reached the given
968 // position (any master switchover already requires that the new master be caught
969 // up before the switch).
970 $replicationPos = $this->getReplicaPos();
971 if ( $replicationPos && !$replicationPos->channelsMatch( $pos ) ) {
972 $this->lastKnownReplicaPos
= $replicationPos;
976 } elseif ( $status >= 0 ) {
977 // Remember that this position was reached to save queries next time
978 $this->lastKnownReplicaPos
= $pos;
985 * Get the position of the master from SHOW SLAVE STATUS
987 * @return MySQLMasterPos|bool
989 public function getReplicaPos() {
990 $now = microtime( true ); // as-of-time *before* fetching GTID variables
992 if ( $this->useGTIDs() ) {
993 // Try to use GTIDs, fallbacking to binlog positions if not possible
994 $data = $this->getServerGTIDs( __METHOD__
);
995 // Use gtid_slave_pos for MariaDB and gtid_executed for MySQL
996 foreach ( [ 'gtid_slave_pos', 'gtid_executed' ] as $name ) {
997 if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
998 return new MySQLMasterPos( $data[$name], $now );
1003 $data = $this->getServerRoleStatus( 'SLAVE', __METHOD__
);
1004 if ( $data && strlen( $data['Relay_Master_Log_File'] ) ) {
1005 return new MySQLMasterPos(
1006 "{$data['Relay_Master_Log_File']}/{$data['Exec_Master_Log_Pos']}",
1015 * Get the position of the master from SHOW MASTER STATUS
1017 * @return MySQLMasterPos|bool
1019 public function getMasterPos() {
1020 $now = microtime( true ); // as-of-time *before* fetching GTID variables
1023 if ( $this->useGTIDs() ) {
1024 // Try to use GTIDs, fallbacking to binlog positions if not possible
1025 $data = $this->getServerGTIDs( __METHOD__
);
1026 // Use gtid_binlog_pos for MariaDB and gtid_executed for MySQL
1027 foreach ( [ 'gtid_binlog_pos', 'gtid_executed' ] as $name ) {
1028 if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
1029 $pos = new MySQLMasterPos( $data[$name], $now );
1033 // Filter domains that are inactive or not relevant to the session
1035 $pos->setActiveOriginServerId( $this->getServerId() );
1036 $pos->setActiveOriginServerUUID( $this->getServerUUID() );
1037 if ( isset( $data['gtid_domain_id'] ) ) {
1038 $pos->setActiveDomain( $data['gtid_domain_id'] );
1044 $data = $this->getServerRoleStatus( 'MASTER', __METHOD__
);
1045 if ( $data && strlen( $data['File'] ) ) {
1046 $pos = new MySQLMasterPos( "{$data['File']}/{$data['Position']}", $now );
1055 * @throws DBQueryError If the variable doesn't exist for some reason
1057 protected function getServerId() {
1058 return $this->srvCache
->getWithSetCallback(
1059 $this->srvCache
->makeGlobalKey( 'mysql-server-id', $this->getServer() ),
1060 self
::SERVER_ID_CACHE_TTL
,
1062 $res = $this->query( "SELECT @@server_id AS id", __METHOD__
);
1063 return intval( $this->fetchObject( $res )->id
);
1069 * @return string|null
1071 protected function getServerUUID() {
1072 return $this->srvCache
->getWithSetCallback(
1073 $this->srvCache
->makeGlobalKey( 'mysql-server-uuid', $this->getServer() ),
1074 self
::SERVER_ID_CACHE_TTL
,
1076 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'server_uuid'" );
1077 $row = $this->fetchObject( $res );
1079 return $row ?
$row->Value
: null;
1085 * @param string $fname
1088 protected function getServerGTIDs( $fname = __METHOD__
) {
1090 // Get global-only variables like gtid_executed
1091 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_%'", $fname );
1092 foreach ( $res as $row ) {
1093 $map[$row->Variable_name
] = $row->Value
;
1095 // Get session-specific (e.g. gtid_domain_id since that is were writes will log)
1096 $res = $this->query( "SHOW SESSION VARIABLES LIKE 'gtid_%'", $fname );
1097 foreach ( $res as $row ) {
1098 $map[$row->Variable_name
] = $row->Value
;
1105 * @param string $role One of "MASTER"/"SLAVE"
1106 * @param string $fname
1107 * @return string[] Latest available server status row
1109 protected function getServerRoleStatus( $role, $fname = __METHOD__
) {
1110 return $this->query( "SHOW $role STATUS", $fname )->fetchRow() ?
: [];
1113 public function serverIsReadOnly() {
1114 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'read_only'", __METHOD__
);
1115 $row = $this->fetchObject( $res );
1117 return $row ?
( strtolower( $row->Value
) === 'on' ) : false;
1121 * @param string $index
1124 function useIndexClause( $index ) {
1125 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
1129 * @param string $index
1132 function ignoreIndexClause( $index ) {
1133 return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
1139 function lowPriorityOption() {
1140 return 'LOW_PRIORITY';
1146 public function getSoftwareLink() {
1147 // MariaDB includes its name in its version string; this is how MariaDB's version of
1148 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
1149 // in libmysql/libmysql.c).
1150 $version = $this->getServerVersion();
1151 if ( strpos( $version, 'MariaDB' ) !== false ||
strpos( $version, '-maria-' ) !== false ) {
1152 return '[{{int:version-db-mariadb-url}} MariaDB]';
1155 // Percona Server's version suffix is not very distinctive, and @@version_comment
1156 // doesn't give the necessary info for source builds, so assume the server is MySQL.
1157 // (Even Percona's version of mysql doesn't try to make the distinction.)
1158 return '[{{int:version-db-mysql-url}} MySQL]';
1164 public function getServerVersion() {
1165 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
1166 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
1167 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
1168 if ( $this->serverVersion
=== null ) {
1169 $this->serverVersion
= $this->selectField( '', 'VERSION()', '', __METHOD__
);
1171 return $this->serverVersion
;
1175 * @param array $options
1177 public function setSessionOptions( array $options ) {
1178 if ( isset( $options['connTimeout'] ) ) {
1179 $timeout = (int)$options['connTimeout'];
1180 $this->query( "SET net_read_timeout=$timeout" );
1181 $this->query( "SET net_write_timeout=$timeout" );
1186 * @param string &$sql
1187 * @param string &$newLine
1190 public function streamStatementEnd( &$sql, &$newLine ) {
1191 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
1192 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
1193 $this->delimiter
= $m[1];
1197 return parent
::streamStatementEnd( $sql, $newLine );
1201 * Check to see if a named lock is available. This is non-blocking.
1203 * @param string $lockName Name of lock to poll
1204 * @param string $method Name of method calling us
1208 public function lockIsFree( $lockName, $method ) {
1209 if ( !parent
::lockIsFree( $lockName, $method ) ) {
1210 return false; // already held
1213 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1214 $result = $this->query( "SELECT IS_FREE_LOCK($encName) AS lockstatus", $method );
1215 $row = $this->fetchObject( $result );
1217 return ( $row->lockstatus
== 1 );
1221 * @param string $lockName
1222 * @param string $method
1223 * @param int $timeout
1226 public function lock( $lockName, $method, $timeout = 5 ) {
1227 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1228 $result = $this->query( "SELECT GET_LOCK($encName, $timeout) AS lockstatus", $method );
1229 $row = $this->fetchObject( $result );
1231 if ( $row->lockstatus
== 1 ) {
1232 parent
::lock( $lockName, $method, $timeout ); // record
1236 $this->queryLogger
->info( __METHOD__
. " failed to acquire lock '{lockname}'",
1237 [ 'lockname' => $lockName ] );
1244 * https://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
1245 * @param string $lockName
1246 * @param string $method
1249 public function unlock( $lockName, $method ) {
1250 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1251 $result = $this->query( "SELECT RELEASE_LOCK($encName) as lockstatus", $method );
1252 $row = $this->fetchObject( $result );
1254 if ( $row->lockstatus
== 1 ) {
1255 parent
::unlock( $lockName, $method ); // record
1259 $this->queryLogger
->warning( __METHOD__
. " failed to release lock '$lockName'\n" );
1264 private function makeLockName( $lockName ) {
1265 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1266 // Newer version enforce a 64 char length limit.
1267 return ( strlen( $lockName ) > 64 ) ?
sha1( $lockName ) : $lockName;
1270 public function namedLocksEnqueue() {
1274 public function tableLocksHaveTransactionScope() {
1275 return false; // tied to TCP connection
1278 protected function doLockTables( array $read, array $write, $method ) {
1280 foreach ( $write as $table ) {
1281 $items[] = $this->tableName( $table ) . ' WRITE';
1283 foreach ( $read as $table ) {
1284 $items[] = $this->tableName( $table ) . ' READ';
1287 $sql = "LOCK TABLES " . implode( ',', $items );
1288 $this->query( $sql, $method );
1293 protected function doUnlockTables( $method ) {
1294 $this->query( "UNLOCK TABLES", $method );
1300 * @param bool $value
1302 public function setBigSelects( $value = true ) {
1303 if ( $value === 'default' ) {
1304 if ( $this->defaultBigSelects
=== null ) {
1305 # Function hasn't been called before so it must already be set to the default
1308 $value = $this->defaultBigSelects
;
1310 } elseif ( $this->defaultBigSelects
=== null ) {
1311 $this->defaultBigSelects
=
1312 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__
);
1314 $encValue = $value ?
'1' : '0';
1315 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
1319 * DELETE where the condition is a join. MySql uses multi-table deletes.
1320 * @param string $delTable
1321 * @param string $joinTable
1322 * @param string $delVar
1323 * @param string $joinVar
1324 * @param array|string $conds
1325 * @param bool|string $fname
1326 * @throws DBUnexpectedError
1327 * @return bool|ResultWrapper
1329 public function deleteJoin(
1330 $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
1333 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
1336 $delTable = $this->tableName( $delTable );
1337 $joinTable = $this->tableName( $joinTable );
1338 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1340 if ( $conds != '*' ) {
1341 $sql .= ' AND ' . $this->makeList( $conds, self
::LIST_AND
);
1344 return $this->query( $sql, $fname );
1348 * @param string $table
1349 * @param array $rows
1350 * @param array $uniqueIndexes
1352 * @param string $fname
1355 public function upsert( $table, array $rows, array $uniqueIndexes,
1356 array $set, $fname = __METHOD__
1358 if ( !count( $rows ) ) {
1359 return true; // nothing to do
1362 if ( !is_array( reset( $rows ) ) ) {
1366 $table = $this->tableName( $table );
1367 $columns = array_keys( $rows[0] );
1369 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1371 foreach ( $rows as $row ) {
1372 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1374 $sql .= implode( ',', $rowTuples );
1375 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, self
::LIST_SET
);
1377 return (bool)$this->query( $sql, $fname );
1381 * Determines how long the server has been up
1385 public function getServerUptime() {
1386 $vars = $this->getMysqlStatus( 'Uptime' );
1388 return (int)$vars['Uptime'];
1392 * Determines if the last failure was due to a deadlock
1396 public function wasDeadlock() {
1397 return $this->lastErrno() == 1213;
1401 * Determines if the last failure was due to a lock timeout
1405 public function wasLockTimeout() {
1406 return $this->lastErrno() == 1205;
1410 * Determines if the last failure was due to the database being read-only.
1414 public function wasReadOnlyError() {
1415 return $this->lastErrno() == 1223 ||
1416 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1419 public function wasConnectionError( $errno ) {
1420 return $errno == 2013 ||
$errno == 2006;
1423 protected function wasKnownStatementRollbackError() {
1424 $errno = $this->lastErrno();
1426 if ( $errno === 1205 ) { // lock wait timeout
1427 // Note that this is uncached to avoid stale values of SET is used
1428 $row = $this->selectRow(
1430 [ 'innodb_rollback_on_timeout' => '@@innodb_rollback_on_timeout' ],
1434 // https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
1435 // https://dev.mysql.com/doc/refman/5.5/en/innodb-parameters.html
1436 return $row->innodb_rollback_on_timeout ?
false : true;
1439 // See https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1440 return in_array( $errno, [ 1022, 1216, 1217, 1137 ], true );
1444 * @param string $oldName
1445 * @param string $newName
1446 * @param bool $temporary
1447 * @param string $fname
1450 public function duplicateTableStructure(
1451 $oldName, $newName, $temporary = false, $fname = __METHOD__
1453 $tmp = $temporary ?
'TEMPORARY ' : '';
1454 $newName = $this->addIdentifierQuotes( $newName );
1455 $oldName = $this->addIdentifierQuotes( $oldName );
1456 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1458 return $this->query( $query, $fname );
1462 * List all tables on the database
1464 * @param string $prefix Only show tables with this prefix, e.g. mw_
1465 * @param string $fname Calling function name
1468 public function listTables( $prefix = null, $fname = __METHOD__
) {
1469 $result = $this->query( "SHOW TABLES", $fname );
1473 foreach ( $result as $table ) {
1474 $vars = get_object_vars( $table );
1475 $table = array_pop( $vars );
1477 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1478 $endArray[] = $table;
1486 * @param string $tableName
1487 * @param string $fName
1488 * @return bool|ResultWrapper
1490 public function dropTable( $tableName, $fName = __METHOD__
) {
1491 if ( !$this->tableExists( $tableName, $fName ) ) {
1495 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1499 * Get status information from SHOW STATUS in an associative array
1501 * @param string $which
1504 private function getMysqlStatus( $which = "%" ) {
1505 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1508 foreach ( $res as $row ) {
1509 $status[$row->Variable_name
] = $row->Value
;
1516 * Lists VIEWs in the database
1518 * @param string $prefix Only show VIEWs with this prefix, eg.
1519 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1520 * @param string $fname Name of calling function
1524 public function listViews( $prefix = null, $fname = __METHOD__
) {
1525 // The name of the column containing the name of the VIEW
1526 $propertyName = 'Tables_in_' . $this->dbName
;
1528 // Query for the VIEWS
1529 $res = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1531 foreach ( $res as $row ) {
1532 array_push( $allViews, $row->$propertyName );
1535 if ( is_null( $prefix ) ||
$prefix === '' ) {
1539 $filteredViews = [];
1540 foreach ( $allViews as $viewName ) {
1541 // Does the name of this VIEW start with the table-prefix?
1542 if ( strpos( $viewName, $prefix ) === 0 ) {
1543 array_push( $filteredViews, $viewName );
1547 return $filteredViews;
1551 * Differentiates between a TABLE and a VIEW.
1553 * @param string $name Name of the TABLE/VIEW to test
1554 * @param string $prefix
1558 public function isView( $name, $prefix = null ) {
1559 return in_array( $name, $this->listViews( $prefix ) );
1562 protected function isTransactableQuery( $sql ) {
1563 return parent
::isTransactableQuery( $sql ) &&
1564 !preg_match( '/^SELECT\s+(GET|RELEASE|IS_FREE)_LOCK\(/', $sql );
1568 * @param string $field Field or column to cast
1571 public function buildIntegerCast( $field ) {
1572 return 'CAST( ' . $field . ' AS SIGNED )';
1576 * @return bool Whether GTID support is used (mockable for testing)
1578 protected function useGTIDs() {
1579 return $this->useGTIDs
;
1583 class_alias( DatabaseMysqlBase
::class, 'DatabaseMysqlBase' );