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 /** @var string|null */
65 private $serverVersion = null;
67 private $insertSelectIsSafe = null;
70 * Additional $params include:
71 * - lagDetectionMethod : set to one of (Seconds_Behind_Master,pt-heartbeat).
72 * pt-heartbeat assumes the table is at heartbeat.heartbeat
73 * and uses UTC timestamps in the heartbeat.ts column.
74 * (https://www.percona.com/doc/percona-toolkit/2.2/pt-heartbeat.html)
75 * - lagDetectionOptions : if using pt-heartbeat, this can be set to an array map to change
76 * the default behavior. Normally, the heartbeat row with the server
77 * ID of this server's master will be used. Set the "conds" field to
78 * override the query conditions, e.g. ['shard' => 's1'].
79 * - useGTIDs : use GTID methods like MASTER_GTID_WAIT() when possible.
80 * - insertSelectIsSafe : force that native INSERT SELECT is or is not safe [default: null]
81 * - sslKeyPath : path to key file [default: null]
82 * - sslCertPath : path to certificate file [default: null]
83 * - sslCAFile: path to a single certificate authority PEM file [default: null]
84 * - sslCAPath : parth to certificate authority PEM directory [default: null]
85 * - sslCiphers : array list of allowable ciphers [default: null]
86 * @param array $params
88 function __construct( array $params ) {
89 $this->lagDetectionMethod
= isset( $params['lagDetectionMethod'] )
90 ?
$params['lagDetectionMethod']
91 : 'Seconds_Behind_Master';
92 $this->lagDetectionOptions
= isset( $params['lagDetectionOptions'] )
93 ?
$params['lagDetectionOptions']
95 $this->useGTIDs
= !empty( $params['useGTIDs' ] );
96 foreach ( [ 'KeyPath', 'CertPath', 'CAFile', 'CAPath', 'Ciphers' ] as $name ) {
98 if ( isset( $params[$var] ) ) {
99 $this->$var = $params[$var];
102 $this->sqlMode
= isset( $params['sqlMode'] ) ?
$params['sqlMode'] : '';
103 $this->utf8Mode
= !empty( $params['utf8Mode'] );
104 $this->insertSelectIsSafe
= isset( $params['insertSelectIsSafe'] )
105 ?
(bool)$params['insertSelectIsSafe'] : null;
107 parent
::__construct( $params );
113 public function getType() {
118 * @param string $server
119 * @param string $user
120 * @param string $password
121 * @param string $dbName
122 * @throws Exception|DBConnectionError
125 public function open( $server, $user, $password, $dbName ) {
126 # Close/unset connection handle
129 $this->mServer
= $server;
130 $this->mUser
= $user;
131 $this->mPassword
= $password;
132 $this->mDBname
= $dbName;
134 $this->installErrorHandler();
136 $this->mConn
= $this->mysqlConnect( $this->mServer
);
137 } catch ( Exception
$ex ) {
138 $this->restoreErrorHandler();
141 $error = $this->restoreErrorHandler();
143 # Always log connection errors
144 if ( !$this->mConn
) {
146 $error = $this->lastError();
148 $this->connLogger
->error(
149 "Error connecting to {db_server}: {error}",
150 $this->getLogContext( [
151 'method' => __METHOD__
,
155 $this->connLogger
->debug( "DB connection error\n" .
156 "Server: $server, User: $user, Password: " .
157 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
159 $this->reportConnectionError( $error );
162 if ( strlen( $dbName ) ) {
163 Wikimedia\
suppressWarnings();
164 $success = $this->selectDB( $dbName );
165 Wikimedia\restoreWarnings
();
167 $this->queryLogger
->error(
168 "Error selecting database {db_name} on server {db_server}",
169 $this->getLogContext( [
170 'method' => __METHOD__
,
173 $this->queryLogger
->debug(
174 "Error selecting database $dbName on server {$this->mServer}" );
176 $this->reportConnectionError( "Error selecting database $dbName" );
180 // Tell the server what we're communicating with
181 if ( !$this->connectInitCharset() ) {
182 $this->reportConnectionError( "Error setting character set" );
185 // Abstract over any insane MySQL defaults
186 $set = [ 'group_concat_max_len = 262144' ];
187 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
188 if ( is_string( $this->sqlMode
) ) {
189 $set[] = 'sql_mode = ' . $this->addQuotes( $this->sqlMode
);
191 // Set any custom settings defined by site config
192 // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
193 foreach ( $this->mSessionVars
as $var => $val ) {
194 // Escape strings but not numbers to avoid MySQL complaining
195 if ( !is_int( $val ) && !is_float( $val ) ) {
196 $val = $this->addQuotes( $val );
198 $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
202 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
203 $success = $this->doQuery( 'SET ' . implode( ', ', $set ) );
205 $this->queryLogger
->error(
206 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)',
207 $this->getLogContext( [
208 'method' => __METHOD__
,
211 $this->reportConnectionError(
212 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)' );
216 $this->mOpened
= true;
222 * Set the character set information right after connection
225 protected function connectInitCharset() {
226 if ( $this->utf8Mode
) {
227 // Tell the server we're communicating with it in UTF-8.
228 // This may engage various charset conversions.
229 return $this->mysqlSetCharset( 'utf8' );
231 return $this->mysqlSetCharset( 'binary' );
236 * Open a connection to a MySQL server
238 * @param string $realServer
239 * @return mixed Raw connection
240 * @throws DBConnectionError
242 abstract protected function mysqlConnect( $realServer );
245 * Set the character set of the MySQL link
247 * @param string $charset
250 abstract protected function mysqlSetCharset( $charset );
253 * @param ResultWrapper|resource $res
254 * @throws DBUnexpectedError
256 public function freeResult( $res ) {
257 if ( $res instanceof ResultWrapper
) {
260 Wikimedia\
suppressWarnings();
261 $ok = $this->mysqlFreeResult( $res );
262 Wikimedia\restoreWarnings
();
264 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
271 * @param resource $res Raw result
274 abstract protected function mysqlFreeResult( $res );
277 * @param ResultWrapper|resource $res
278 * @return stdClass|bool
279 * @throws DBUnexpectedError
281 public function fetchObject( $res ) {
282 if ( $res instanceof ResultWrapper
) {
285 Wikimedia\
suppressWarnings();
286 $row = $this->mysqlFetchObject( $res );
287 Wikimedia\restoreWarnings
();
289 $errno = $this->lastErrno();
290 // Unfortunately, mysql_fetch_object does not reset the last errno.
291 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
292 // these are the only errors mysql_fetch_object can cause.
293 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
294 if ( $errno == 2000 ||
$errno == 2013 ) {
295 throw new DBUnexpectedError(
297 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
305 * Fetch a result row as an object
307 * @param resource $res Raw result
310 abstract protected function mysqlFetchObject( $res );
313 * @param ResultWrapper|resource $res
315 * @throws DBUnexpectedError
317 public function fetchRow( $res ) {
318 if ( $res instanceof ResultWrapper
) {
321 Wikimedia\
suppressWarnings();
322 $row = $this->mysqlFetchArray( $res );
323 Wikimedia\restoreWarnings
();
325 $errno = $this->lastErrno();
326 // Unfortunately, mysql_fetch_array does not reset the last errno.
327 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
328 // these are the only errors mysql_fetch_array can cause.
329 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
330 if ( $errno == 2000 ||
$errno == 2013 ) {
331 throw new DBUnexpectedError(
333 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
341 * Fetch a result row as an associative and numeric array
343 * @param resource $res Raw result
346 abstract protected function mysqlFetchArray( $res );
349 * @throws DBUnexpectedError
350 * @param ResultWrapper|resource $res
353 function numRows( $res ) {
354 if ( $res instanceof ResultWrapper
) {
357 Wikimedia\
suppressWarnings();
358 $n = $this->mysqlNumRows( $res );
359 Wikimedia\restoreWarnings
();
361 // Unfortunately, mysql_num_rows does not reset the last errno.
362 // We are not checking for any errors here, since
363 // these are no errors mysql_num_rows can cause.
364 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
365 // See https://phabricator.wikimedia.org/T44430
370 * Get number of rows in result
372 * @param resource $res Raw result
375 abstract protected function mysqlNumRows( $res );
378 * @param ResultWrapper|resource $res
381 public function numFields( $res ) {
382 if ( $res instanceof ResultWrapper
) {
386 return $this->mysqlNumFields( $res );
390 * Get number of fields in result
392 * @param resource $res Raw result
395 abstract protected function mysqlNumFields( $res );
398 * @param ResultWrapper|resource $res
402 public function fieldName( $res, $n ) {
403 if ( $res instanceof ResultWrapper
) {
407 return $this->mysqlFieldName( $res, $n );
411 * Get the name of the specified field in a result
413 * @param ResultWrapper|resource $res
417 abstract protected function mysqlFieldName( $res, $n );
420 * mysql_field_type() wrapper
421 * @param ResultWrapper|resource $res
425 public function fieldType( $res, $n ) {
426 if ( $res instanceof ResultWrapper
) {
430 return $this->mysqlFieldType( $res, $n );
434 * Get the type of the specified field in a result
436 * @param ResultWrapper|resource $res
440 abstract protected function mysqlFieldType( $res, $n );
443 * @param ResultWrapper|resource $res
447 public function dataSeek( $res, $row ) {
448 if ( $res instanceof ResultWrapper
) {
452 return $this->mysqlDataSeek( $res, $row );
456 * Move internal result pointer
458 * @param ResultWrapper|resource $res
462 abstract protected function mysqlDataSeek( $res, $row );
467 public function lastError() {
468 if ( $this->mConn
) {
469 # Even if it's non-zero, it can still be invalid
470 Wikimedia\
suppressWarnings();
471 $error = $this->mysqlError( $this->mConn
);
473 $error = $this->mysqlError();
475 Wikimedia\restoreWarnings
();
477 $error = $this->mysqlError();
480 $error .= ' (' . $this->mServer
. ')';
487 * Returns the text of the error message from previous MySQL operation
489 * @param resource $conn Raw connection
492 abstract protected function mysqlError( $conn = null );
494 protected function wasQueryTimeout( $error, $errno ) {
495 return $errno == 2062;
499 * @param string $table
500 * @param array $uniqueIndexes
502 * @param string $fname
503 * @return ResultWrapper
505 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
506 return $this->nativeReplace( $table, $rows, $fname );
509 protected function nativeInsertSelect(
510 $destTable, $srcTable, $varMap, $conds,
511 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
513 if ( $this->insertSelectIsSafe
=== null ) {
514 // In MySQL, an INSERT SELECT is only replication safe with row-based
515 // replication or if innodb_autoinc_lock_mode is 0. When those
516 // conditions aren't met, use non-native mode.
517 // While we could try to determine if the insert is safe anyway by
518 // checking if the target table has an auto-increment column that
519 // isn't set in $varMap, that seems unlikely to be worth the extra
521 $row = $this->selectRow(
524 'innodb_autoinc_lock_mode' => '@@innodb_autoinc_lock_mode',
525 'binlog_format' => '@@binlog_format',
530 $this->insertSelectIsSafe
= $row->binlog_format
=== 'ROW' ||
531 (int)$row->innodb_autoinc_lock_mode
=== 0;
534 if ( !$this->insertSelectIsSafe
) {
535 return $this->nonNativeInsertSelect(
546 return parent
::nativeInsertSelect(
560 * Estimate rows in dataset
561 * Returns estimated count, based on EXPLAIN output
562 * Takes same arguments as Database::select()
564 * @param string|array $table
565 * @param string|array $vars
566 * @param string|array $conds
567 * @param string $fname
568 * @param string|array $options
571 public function estimateRowCount( $table, $vars = '*', $conds = '',
572 $fname = __METHOD__
, $options = []
574 $options['EXPLAIN'] = true;
575 $res = $this->select( $table, $vars, $conds, $fname, $options );
576 if ( $res === false ) {
579 if ( !$this->numRows( $res ) ) {
584 foreach ( $res as $plan ) {
585 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
591 public function tableExists( $table, $fname = __METHOD__
) {
592 // Split database and table into proper variables as Database::tableName() returns
593 // shared tables prefixed with their database, which do not work in SHOW TABLES statements
594 list( $database, , $prefix, $table ) = $this->qualifiedTableComponents( $table );
595 $tableName = "{$prefix}{$table}";
597 if ( isset( $this->mSessionTempTables
[$tableName] ) ) {
598 return true; // already known to exist and won't show in SHOW TABLES anyway
601 // We can't use buildLike() here, because it specifies an escape character
602 // other than the backslash, which is the only one supported by SHOW TABLES
603 $encLike = $this->escapeLikeInternal( $tableName, '\\' );
605 // If the database has been specified (such as for shared tables), use "FROM"
606 if ( $database !== '' ) {
607 $encDatabase = $this->addIdentifierQuotes( $database );
608 $query = "SHOW TABLES FROM $encDatabase LIKE '$encLike'";
610 $query = "SHOW TABLES LIKE '$encLike'";
613 return $this->query( $query, $fname )->numRows() > 0;
617 * @param string $table
618 * @param string $field
619 * @return bool|MySQLField
621 public function fieldInfo( $table, $field ) {
622 $table = $this->tableName( $table );
623 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
627 $n = $this->mysqlNumFields( $res->result
);
628 for ( $i = 0; $i < $n; $i++
) {
629 $meta = $this->mysqlFetchField( $res->result
, $i );
630 if ( $field == $meta->name
) {
631 return new MySQLField( $meta );
639 * Get column information from a result
641 * @param resource $res Raw result
645 abstract protected function mysqlFetchField( $res, $n );
648 * Get information about an index into an object
649 * Returns false if the index does not exist
651 * @param string $table
652 * @param string $index
653 * @param string $fname
654 * @return bool|array|null False or null on failure
656 public function indexInfo( $table, $index, $fname = __METHOD__
) {
657 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
658 # SHOW INDEX should work for 3.x and up:
659 # https://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
660 $table = $this->tableName( $table );
661 $index = $this->indexName( $index );
663 $sql = 'SHOW INDEX FROM ' . $table;
664 $res = $this->query( $sql, $fname );
672 foreach ( $res as $row ) {
673 if ( $row->Key_name
== $index ) {
678 return empty( $result ) ?
false : $result;
685 public function strencode( $s ) {
686 return $this->mysqlRealEscapeString( $s );
693 abstract protected function mysqlRealEscapeString( $s );
695 public function addQuotes( $s ) {
696 if ( is_bool( $s ) ) {
697 // Parent would transform to int, which does not play nice with MySQL type juggling.
698 // When searching for an int in a string column, the strings are cast to int, which
699 // means false would match any string not starting with a number.
700 $s = (string)(int)$s;
702 return parent
::addQuotes( $s );
706 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
711 public function addIdentifierQuotes( $s ) {
712 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
713 // Remove NUL bytes and escape backticks by doubling
714 return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
718 * @param string $name
721 public function isQuotedIdentifier( $name ) {
722 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
725 public function getLag() {
726 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
727 return $this->getLagFromPtHeartbeat();
729 return $this->getLagFromSlaveStatus();
736 protected function getLagDetectionMethod() {
737 return $this->lagDetectionMethod
;
743 protected function getLagFromSlaveStatus() {
744 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
745 $row = $res ?
$res->fetchObject() : false;
746 if ( $row && strval( $row->Seconds_Behind_Master
) !== '' ) {
747 return intval( $row->Seconds_Behind_Master
);
756 protected function getLagFromPtHeartbeat() {
757 $options = $this->lagDetectionOptions
;
759 if ( isset( $options['conds'] ) ) {
760 // Best method for multi-DC setups: use logical channel names
761 $data = $this->getHeartbeatData( $options['conds'] );
763 // Standard method: use master server ID (works with stock pt-heartbeat)
764 $masterInfo = $this->getMasterServerInfo();
765 if ( !$masterInfo ) {
766 $this->queryLogger
->error(
767 "Unable to query master of {db_server} for server ID",
768 $this->getLogContext( [
769 'method' => __METHOD__
773 return false; // could not get master server ID
776 $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
777 $data = $this->getHeartbeatData( $conds );
780 list( $time, $nowUnix ) = $data;
781 if ( $time !== null ) {
782 // @time is in ISO format like "2015-09-25T16:48:10.000510"
783 $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
784 $timeUnix = (int)$dateTime->format( 'U' ) +
$dateTime->format( 'u' ) / 1e6
;
786 return max( $nowUnix - $timeUnix, 0.0 );
789 $this->queryLogger
->error(
790 "Unable to find pt-heartbeat row for {db_server}",
791 $this->getLogContext( [
792 'method' => __METHOD__
799 protected function getMasterServerInfo() {
800 $cache = $this->srvCache
;
801 $key = $cache->makeGlobalKey(
804 // Using one key for all cluster replica DBs is preferable
805 $this->getLBInfo( 'clusterMasterHost' ) ?
: $this->getServer()
808 return $cache->getWithSetCallback(
810 $cache::TTL_INDEFINITE
,
811 function () use ( $cache, $key ) {
812 // Get and leave a lock key in place for a short period
813 if ( !$cache->lock( $key, 0, 10 ) ) {
814 return false; // avoid master connection spike slams
817 $conn = $this->getLazyMasterHandle();
819 return false; // something is misconfigured
822 // Connect to and query the master; catch errors to avoid outages
824 $res = $conn->query( 'SELECT @@server_id AS id', __METHOD__
);
825 $row = $res ?
$res->fetchObject() : false;
826 $id = $row ?
(int)$row->id
: 0;
827 } catch ( DBError
$e ) {
831 // Cache the ID if it was retrieved
832 return $id ?
[ 'serverId' => $id, 'asOf' => time() ] : false;
838 * @param array $conds WHERE clause conditions to find a row
839 * @return array (heartbeat `ts` column value or null, UNIX timestamp) for the newest beat
840 * @see https://www.percona.com/doc/percona-toolkit/2.1/pt-heartbeat.html
842 protected function getHeartbeatData( array $conds ) {
843 // Query time and trip time are not counted
844 $nowUnix = microtime( true );
845 // Do not bother starting implicit transactions here
846 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
848 $whereSQL = $this->makeList( $conds, self
::LIST_AND
);
849 // Use ORDER BY for channel based queries since that field might not be UNIQUE.
850 // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
851 // percision field is not supported in MySQL <= 5.5.
853 "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1"
855 $row = $res ?
$res->fetchObject() : false;
857 $this->restoreFlags();
860 return [ $row ?
$row->ts
: null, $nowUnix ];
863 protected function getApproximateLagStatus() {
864 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
865 // Disable caching since this is fast enough and we don't wan't
866 // to be *too* pessimistic by having both the cache TTL and the
867 // pt-heartbeat interval count as lag in getSessionLagStatus()
868 return parent
::getApproximateLagStatus();
871 $key = $this->srvCache
->makeGlobalKey( 'mysql-lag', $this->getServer() );
872 $approxLag = $this->srvCache
->get( $key );
874 $approxLag = parent
::getApproximateLagStatus();
875 $this->srvCache
->set( $key, $approxLag, 1 );
881 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
882 if ( !( $pos instanceof MySQLMasterPos
) ) {
883 throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
886 if ( $this->getLBInfo( 'is static' ) === true ) {
887 return 0; // this is a copy of a read-only dataset with no master DB
888 } elseif ( $this->lastKnownReplicaPos
&& $this->lastKnownReplicaPos
->hasReached( $pos ) ) {
889 return 0; // already reached this point for sure
892 // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
894 // Wait on the GTID set (MariaDB only)
895 $gtidArg = $this->addQuotes( implode( ',', $pos->gtids
) );
896 $res = $this->doQuery( "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)" );
898 // Wait on the binlog coordinates
899 $encFile = $this->addQuotes( $pos->getLogFile() );
900 $encPos = intval( $pos->pos
[1] );
901 $res = $this->doQuery( "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)" );
904 $row = $res ?
$this->fetchRow( $res ) : false;
906 throw new DBExpectedError( $this,
907 "MASTER_POS_WAIT() or MASTER_GTID_WAIT() failed: {$this->lastError()}" );
910 // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
911 $status = ( $row[0] !== null ) ?
intval( $row[0] ) : null;
912 if ( $status === null ) {
913 if ( !$pos->gtids
) {
914 // T126436: jobs programmed to wait on master positions might be referencing
915 // binlogs with an old master hostname; this makes MASTER_POS_WAIT() return null.
916 // Try to detect this case and treat the replica DB as having reached the given
917 // position (any master switchover already requires that the new master be caught
918 // up before the switch).
919 $replicationPos = $this->getReplicaPos();
920 if ( $replicationPos && !$replicationPos->channelsMatch( $pos ) ) {
921 $this->lastKnownReplicaPos
= $replicationPos;
925 } elseif ( $status >= 0 ) {
926 // Remember that this position was reached to save queries next time
927 $this->lastKnownReplicaPos
= $pos;
934 * Get the position of the master from SHOW SLAVE STATUS
936 * @return MySQLMasterPos|bool
938 public function getReplicaPos() {
939 $now = microtime( true );
941 if ( $this->useGTIDs
) {
942 $res = $this->query( "SELECT @@global.gtid_slave_pos AS Value", __METHOD__
);
943 $gtidRow = $this->fetchObject( $res );
944 if ( $gtidRow && strlen( $gtidRow->Value
) ) {
945 return new MySQLMasterPos( $gtidRow->Value
, $now );
949 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
950 $row = $this->fetchObject( $res );
951 if ( $row && strlen( $row->Relay_Master_Log_File
) ) {
952 return new MySQLMasterPos(
953 "{$row->Relay_Master_Log_File}/{$row->Exec_Master_Log_Pos}",
962 * Get the position of the master from SHOW MASTER STATUS
964 * @return MySQLMasterPos|bool
966 public function getMasterPos() {
967 $now = microtime( true );
969 if ( $this->useGTIDs
) {
970 $res = $this->query( "SELECT @@global.gtid_binlog_pos AS Value", __METHOD__
);
971 $gtidRow = $this->fetchObject( $res );
972 if ( $gtidRow && strlen( $gtidRow->Value
) ) {
973 return new MySQLMasterPos( $gtidRow->Value
, $now );
977 $res = $this->query( 'SHOW MASTER STATUS', __METHOD__
);
978 $row = $this->fetchObject( $res );
979 if ( $row && strlen( $row->File
) ) {
980 return new MySQLMasterPos( "{$row->File}/{$row->Position}", $now );
986 public function serverIsReadOnly() {
987 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'read_only'", __METHOD__
);
988 $row = $this->fetchObject( $res );
990 return $row ?
( strtolower( $row->Value
) === 'on' ) : false;
994 * @param string $index
997 function useIndexClause( $index ) {
998 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
1002 * @param string $index
1005 function ignoreIndexClause( $index ) {
1006 return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
1012 function lowPriorityOption() {
1013 return 'LOW_PRIORITY';
1019 public function getSoftwareLink() {
1020 // MariaDB includes its name in its version string; this is how MariaDB's version of
1021 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
1022 // in libmysql/libmysql.c).
1023 $version = $this->getServerVersion();
1024 if ( strpos( $version, 'MariaDB' ) !== false ||
strpos( $version, '-maria-' ) !== false ) {
1025 return '[{{int:version-db-mariadb-url}} MariaDB]';
1028 // Percona Server's version suffix is not very distinctive, and @@version_comment
1029 // doesn't give the necessary info for source builds, so assume the server is MySQL.
1030 // (Even Percona's version of mysql doesn't try to make the distinction.)
1031 return '[{{int:version-db-mysql-url}} MySQL]';
1037 public function getServerVersion() {
1038 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
1039 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
1040 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
1041 if ( $this->serverVersion
=== null ) {
1042 $this->serverVersion
= $this->selectField( '', 'VERSION()', '', __METHOD__
);
1044 return $this->serverVersion
;
1048 * @param array $options
1050 public function setSessionOptions( array $options ) {
1051 if ( isset( $options['connTimeout'] ) ) {
1052 $timeout = (int)$options['connTimeout'];
1053 $this->query( "SET net_read_timeout=$timeout" );
1054 $this->query( "SET net_write_timeout=$timeout" );
1059 * @param string &$sql
1060 * @param string &$newLine
1063 public function streamStatementEnd( &$sql, &$newLine ) {
1064 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
1065 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
1066 $this->delimiter
= $m[1];
1070 return parent
::streamStatementEnd( $sql, $newLine );
1074 * Check to see if a named lock is available. This is non-blocking.
1076 * @param string $lockName Name of lock to poll
1077 * @param string $method Name of method calling us
1081 public function lockIsFree( $lockName, $method ) {
1082 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1083 $result = $this->query( "SELECT IS_FREE_LOCK($encName) AS lockstatus", $method );
1084 $row = $this->fetchObject( $result );
1086 return ( $row->lockstatus
== 1 );
1090 * @param string $lockName
1091 * @param string $method
1092 * @param int $timeout
1095 public function lock( $lockName, $method, $timeout = 5 ) {
1096 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1097 $result = $this->query( "SELECT GET_LOCK($encName, $timeout) AS lockstatus", $method );
1098 $row = $this->fetchObject( $result );
1100 if ( $row->lockstatus
== 1 ) {
1101 parent
::lock( $lockName, $method, $timeout ); // record
1105 $this->queryLogger
->info( __METHOD__
. " failed to acquire lock '{lockname}'",
1106 [ 'lockname' => $lockName ] );
1113 * https://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
1114 * @param string $lockName
1115 * @param string $method
1118 public function unlock( $lockName, $method ) {
1119 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1120 $result = $this->query( "SELECT RELEASE_LOCK($encName) as lockstatus", $method );
1121 $row = $this->fetchObject( $result );
1123 if ( $row->lockstatus
== 1 ) {
1124 parent
::unlock( $lockName, $method ); // record
1128 $this->queryLogger
->warning( __METHOD__
. " failed to release lock '$lockName'\n" );
1133 private function makeLockName( $lockName ) {
1134 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1135 // Newer version enforce a 64 char length limit.
1136 return ( strlen( $lockName ) > 64 ) ?
sha1( $lockName ) : $lockName;
1139 public function namedLocksEnqueue() {
1143 public function tableLocksHaveTransactionScope() {
1144 return false; // tied to TCP connection
1147 protected function doLockTables( array $read, array $write, $method ) {
1149 foreach ( $write as $table ) {
1150 $items[] = $this->tableName( $table ) . ' WRITE';
1152 foreach ( $read as $table ) {
1153 $items[] = $this->tableName( $table ) . ' READ';
1156 $sql = "LOCK TABLES " . implode( ',', $items );
1157 $this->query( $sql, $method );
1162 protected function doUnlockTables( $method ) {
1163 $this->query( "UNLOCK TABLES", $method );
1169 * @param bool $value
1171 public function setBigSelects( $value = true ) {
1172 if ( $value === 'default' ) {
1173 if ( $this->mDefaultBigSelects
=== null ) {
1174 # Function hasn't been called before so it must already be set to the default
1177 $value = $this->mDefaultBigSelects
;
1179 } elseif ( $this->mDefaultBigSelects
=== null ) {
1180 $this->mDefaultBigSelects
=
1181 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__
);
1183 $encValue = $value ?
'1' : '0';
1184 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
1188 * DELETE where the condition is a join. MySql uses multi-table deletes.
1189 * @param string $delTable
1190 * @param string $joinTable
1191 * @param string $delVar
1192 * @param string $joinVar
1193 * @param array|string $conds
1194 * @param bool|string $fname
1195 * @throws DBUnexpectedError
1196 * @return bool|ResultWrapper
1198 public function deleteJoin(
1199 $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
1202 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
1205 $delTable = $this->tableName( $delTable );
1206 $joinTable = $this->tableName( $joinTable );
1207 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1209 if ( $conds != '*' ) {
1210 $sql .= ' AND ' . $this->makeList( $conds, self
::LIST_AND
);
1213 return $this->query( $sql, $fname );
1217 * @param string $table
1218 * @param array $rows
1219 * @param array $uniqueIndexes
1221 * @param string $fname
1224 public function upsert( $table, array $rows, array $uniqueIndexes,
1225 array $set, $fname = __METHOD__
1227 if ( !count( $rows ) ) {
1228 return true; // nothing to do
1231 if ( !is_array( reset( $rows ) ) ) {
1235 $table = $this->tableName( $table );
1236 $columns = array_keys( $rows[0] );
1238 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1240 foreach ( $rows as $row ) {
1241 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1243 $sql .= implode( ',', $rowTuples );
1244 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, self
::LIST_SET
);
1246 return (bool)$this->query( $sql, $fname );
1250 * Determines how long the server has been up
1254 public function getServerUptime() {
1255 $vars = $this->getMysqlStatus( 'Uptime' );
1257 return (int)$vars['Uptime'];
1261 * Determines if the last failure was due to a deadlock
1265 public function wasDeadlock() {
1266 return $this->lastErrno() == 1213;
1270 * Determines if the last failure was due to a lock timeout
1274 public function wasLockTimeout() {
1275 return $this->lastErrno() == 1205;
1278 public function wasErrorReissuable() {
1279 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
1283 * Determines if the last failure was due to the database being read-only.
1287 public function wasReadOnlyError() {
1288 return $this->lastErrno() == 1223 ||
1289 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1292 public function wasConnectionError( $errno ) {
1293 return $errno == 2013 ||
$errno == 2006;
1297 * @param string $oldName
1298 * @param string $newName
1299 * @param bool $temporary
1300 * @param string $fname
1303 public function duplicateTableStructure(
1304 $oldName, $newName, $temporary = false, $fname = __METHOD__
1306 $tmp = $temporary ?
'TEMPORARY ' : '';
1307 $newName = $this->addIdentifierQuotes( $newName );
1308 $oldName = $this->addIdentifierQuotes( $oldName );
1309 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1311 return $this->query( $query, $fname );
1315 * List all tables on the database
1317 * @param string $prefix Only show tables with this prefix, e.g. mw_
1318 * @param string $fname Calling function name
1321 public function listTables( $prefix = null, $fname = __METHOD__
) {
1322 $result = $this->query( "SHOW TABLES", $fname );
1326 foreach ( $result as $table ) {
1327 $vars = get_object_vars( $table );
1328 $table = array_pop( $vars );
1330 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1331 $endArray[] = $table;
1339 * @param string $tableName
1340 * @param string $fName
1341 * @return bool|ResultWrapper
1343 public function dropTable( $tableName, $fName = __METHOD__
) {
1344 if ( !$this->tableExists( $tableName, $fName ) ) {
1348 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1352 * Get status information from SHOW STATUS in an associative array
1354 * @param string $which
1357 private function getMysqlStatus( $which = "%" ) {
1358 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1361 foreach ( $res as $row ) {
1362 $status[$row->Variable_name
] = $row->Value
;
1369 * Lists VIEWs in the database
1371 * @param string $prefix Only show VIEWs with this prefix, eg.
1372 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1373 * @param string $fname Name of calling function
1377 public function listViews( $prefix = null, $fname = __METHOD__
) {
1378 // The name of the column containing the name of the VIEW
1379 $propertyName = 'Tables_in_' . $this->mDBname
;
1381 // Query for the VIEWS
1382 $res = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1384 foreach ( $res as $row ) {
1385 array_push( $allViews, $row->$propertyName );
1388 if ( is_null( $prefix ) ||
$prefix === '' ) {
1392 $filteredViews = [];
1393 foreach ( $allViews as $viewName ) {
1394 // Does the name of this VIEW start with the table-prefix?
1395 if ( strpos( $viewName, $prefix ) === 0 ) {
1396 array_push( $filteredViews, $viewName );
1400 return $filteredViews;
1404 * Differentiates between a TABLE and a VIEW.
1406 * @param string $name Name of the TABLE/VIEW to test
1407 * @param string $prefix
1411 public function isView( $name, $prefix = null ) {
1412 return in_array( $name, $this->listViews( $prefix ) );
1416 * Allows for index remapping in queries where this is not consistent across DBMS
1418 * @param string $index
1421 protected function indexName( $index ) {
1423 * When SQLite indexes were introduced in r45764, it was noted that
1424 * SQLite requires index names to be unique within the whole database,
1425 * not just within a schema. As discussed in CR r45819, to avoid the
1426 * need for a schema change on existing installations, the indexes
1427 * were implicitly mapped from the new names to the old names.
1429 * This mapping can be removed if DB patches are introduced to alter
1430 * the relevant tables in existing installations. Note that because
1431 * this index mapping applies to table creation, even new installations
1432 * of MySQL have the old names (except for installations created during
1433 * a period where this mapping was inappropriately removed, see
1437 'ar_usertext_timestamp' => 'usertext_timestamp',
1438 'un_user_id' => 'user_id',
1439 'un_user_ip' => 'user_ip',
1442 if ( isset( $renamed[$index] ) ) {
1443 return $renamed[$index];
1450 class_alias( DatabaseMysqlBase
::class, 'DatabaseMysqlBase' );