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
;
31 use DBUnexpectedError
;
32 use DBConnectionError
;
37 * Database abstraction object for MySQL.
38 * Defines methods independent on used MySQL extension.
44 abstract class DatabaseMysqlBase
extends Database
{
45 /** @var MysqlMasterPos */
46 protected $lastKnownReplicaPos;
47 /** @var string Method to detect replica DB lag */
48 protected $lagDetectionMethod;
49 /** @var array Method to detect replica DB lag */
50 protected $lagDetectionOptions = [];
51 /** @var bool bool Whether to use GTID methods */
52 protected $useGTIDs = false;
53 /** @var string|null */
54 protected $sslKeyPath;
55 /** @var string|null */
56 protected $sslCertPath;
57 /** @var string|null */
59 /** @var string[]|null */
60 protected $sslCiphers;
61 /** @var string sql_mode value to send on connection */
63 /** @var bool Use experimental UTF-8 transmission encoding */
66 /** @var string|null */
67 private $serverVersion = 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 * - sslKeyPath : path to key file [default: null]
81 * - sslCertPath : path to certificate file [default: null]
82 * - sslCAPath : parth to certificate authority PEM files [default: null]
83 * - sslCiphers : array list of allowable ciphers [default: null]
84 * @param array $params
86 function __construct( array $params ) {
87 $this->lagDetectionMethod
= isset( $params['lagDetectionMethod'] )
88 ?
$params['lagDetectionMethod']
89 : 'Seconds_Behind_Master';
90 $this->lagDetectionOptions
= isset( $params['lagDetectionOptions'] )
91 ?
$params['lagDetectionOptions']
93 $this->useGTIDs
= !empty( $params['useGTIDs' ] );
94 foreach ( [ 'KeyPath', 'CertPath', 'CAPath', 'Ciphers' ] as $name ) {
96 if ( isset( $params[$var] ) ) {
97 $this->$var = $params[$var];
100 $this->sqlMode
= isset( $params['sqlMode'] ) ?
$params['sqlMode'] : '';
101 $this->utf8Mode
= !empty( $params['utf8Mode'] );
103 parent
::__construct( $params );
109 public function getType() {
114 * @param string $server
115 * @param string $user
116 * @param string $password
117 * @param string $dbName
118 * @throws Exception|DBConnectionError
121 public function open( $server, $user, $password, $dbName ) {
122 # Close/unset connection handle
125 $this->mServer
= $server;
126 $this->mUser
= $user;
127 $this->mPassword
= $password;
128 $this->mDBname
= $dbName;
130 $this->installErrorHandler();
132 $this->mConn
= $this->mysqlConnect( $this->mServer
);
133 } catch ( Exception
$ex ) {
134 $this->restoreErrorHandler();
137 $error = $this->restoreErrorHandler();
139 # Always log connection errors
140 if ( !$this->mConn
) {
142 $error = $this->lastError();
144 $this->connLogger
->error(
145 "Error connecting to {db_server}: {error}",
146 $this->getLogContext( [
147 'method' => __METHOD__
,
151 $this->connLogger
->debug( "DB connection error\n" .
152 "Server: $server, User: $user, Password: " .
153 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
155 $this->reportConnectionError( $error );
158 if ( $dbName != '' ) {
159 MediaWiki\
suppressWarnings();
160 $success = $this->selectDB( $dbName );
161 MediaWiki\restoreWarnings
();
163 $this->queryLogger
->error(
164 "Error selecting database {db_name} on server {db_server}",
165 $this->getLogContext( [
166 'method' => __METHOD__
,
169 $this->queryLogger
->debug(
170 "Error selecting database $dbName on server {$this->mServer}" );
172 $this->reportConnectionError( "Error selecting database $dbName" );
176 // Tell the server what we're communicating with
177 if ( !$this->connectInitCharset() ) {
178 $this->reportConnectionError( "Error setting character set" );
181 // Abstract over any insane MySQL defaults
182 $set = [ 'group_concat_max_len = 262144' ];
183 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
184 if ( is_string( $this->sqlMode
) ) {
185 $set[] = 'sql_mode = ' . $this->addQuotes( $this->sqlMode
);
187 // Set any custom settings defined by site config
188 // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
189 foreach ( $this->mSessionVars
as $var => $val ) {
190 // Escape strings but not numbers to avoid MySQL complaining
191 if ( !is_int( $val ) && !is_float( $val ) ) {
192 $val = $this->addQuotes( $val );
194 $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
198 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
199 $success = $this->doQuery( 'SET ' . implode( ', ', $set ) );
201 $this->queryLogger
->error(
202 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)',
203 $this->getLogContext( [
204 'method' => __METHOD__
,
207 $this->reportConnectionError(
208 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)' );
212 $this->mOpened
= true;
218 * Set the character set information right after connection
221 protected function connectInitCharset() {
222 if ( $this->utf8Mode
) {
223 // Tell the server we're communicating with it in UTF-8.
224 // This may engage various charset conversions.
225 return $this->mysqlSetCharset( 'utf8' );
227 return $this->mysqlSetCharset( 'binary' );
232 * Open a connection to a MySQL server
234 * @param string $realServer
235 * @return mixed Raw connection
236 * @throws DBConnectionError
238 abstract protected function mysqlConnect( $realServer );
241 * Set the character set of the MySQL link
243 * @param string $charset
246 abstract protected function mysqlSetCharset( $charset );
249 * @param ResultWrapper|resource $res
250 * @throws DBUnexpectedError
252 public function freeResult( $res ) {
253 if ( $res instanceof ResultWrapper
) {
256 MediaWiki\
suppressWarnings();
257 $ok = $this->mysqlFreeResult( $res );
258 MediaWiki\restoreWarnings
();
260 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
267 * @param resource $res Raw result
270 abstract protected function mysqlFreeResult( $res );
273 * @param ResultWrapper|resource $res
274 * @return stdClass|bool
275 * @throws DBUnexpectedError
277 public function fetchObject( $res ) {
278 if ( $res instanceof ResultWrapper
) {
281 MediaWiki\
suppressWarnings();
282 $row = $this->mysqlFetchObject( $res );
283 MediaWiki\restoreWarnings
();
285 $errno = $this->lastErrno();
286 // Unfortunately, mysql_fetch_object does not reset the last errno.
287 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
288 // these are the only errors mysql_fetch_object can cause.
289 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
290 if ( $errno == 2000 ||
$errno == 2013 ) {
291 throw new DBUnexpectedError(
293 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
301 * Fetch a result row as an object
303 * @param resource $res Raw result
306 abstract protected function mysqlFetchObject( $res );
309 * @param ResultWrapper|resource $res
311 * @throws DBUnexpectedError
313 public function fetchRow( $res ) {
314 if ( $res instanceof ResultWrapper
) {
317 MediaWiki\
suppressWarnings();
318 $row = $this->mysqlFetchArray( $res );
319 MediaWiki\restoreWarnings
();
321 $errno = $this->lastErrno();
322 // Unfortunately, mysql_fetch_array does not reset the last errno.
323 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
324 // these are the only errors mysql_fetch_array can cause.
325 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
326 if ( $errno == 2000 ||
$errno == 2013 ) {
327 throw new DBUnexpectedError(
329 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
337 * Fetch a result row as an associative and numeric array
339 * @param resource $res Raw result
342 abstract protected function mysqlFetchArray( $res );
345 * @throws DBUnexpectedError
346 * @param ResultWrapper|resource $res
349 function numRows( $res ) {
350 if ( $res instanceof ResultWrapper
) {
353 MediaWiki\
suppressWarnings();
354 $n = $this->mysqlNumRows( $res );
355 MediaWiki\restoreWarnings
();
357 // Unfortunately, mysql_num_rows does not reset the last errno.
358 // We are not checking for any errors here, since
359 // these are no errors mysql_num_rows can cause.
360 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
361 // See https://phabricator.wikimedia.org/T44430
366 * Get number of rows in result
368 * @param resource $res Raw result
371 abstract protected function mysqlNumRows( $res );
374 * @param ResultWrapper|resource $res
377 public function numFields( $res ) {
378 if ( $res instanceof ResultWrapper
) {
382 return $this->mysqlNumFields( $res );
386 * Get number of fields in result
388 * @param resource $res Raw result
391 abstract protected function mysqlNumFields( $res );
394 * @param ResultWrapper|resource $res
398 public function fieldName( $res, $n ) {
399 if ( $res instanceof ResultWrapper
) {
403 return $this->mysqlFieldName( $res, $n );
407 * Get the name of the specified field in a result
409 * @param ResultWrapper|resource $res
413 abstract protected function mysqlFieldName( $res, $n );
416 * mysql_field_type() wrapper
417 * @param ResultWrapper|resource $res
421 public function fieldType( $res, $n ) {
422 if ( $res instanceof ResultWrapper
) {
426 return $this->mysqlFieldType( $res, $n );
430 * Get the type of the specified field in a result
432 * @param ResultWrapper|resource $res
436 abstract protected function mysqlFieldType( $res, $n );
439 * @param ResultWrapper|resource $res
443 public function dataSeek( $res, $row ) {
444 if ( $res instanceof ResultWrapper
) {
448 return $this->mysqlDataSeek( $res, $row );
452 * Move internal result pointer
454 * @param ResultWrapper|resource $res
458 abstract protected function mysqlDataSeek( $res, $row );
463 public function lastError() {
464 if ( $this->mConn
) {
465 # Even if it's non-zero, it can still be invalid
466 MediaWiki\
suppressWarnings();
467 $error = $this->mysqlError( $this->mConn
);
469 $error = $this->mysqlError();
471 MediaWiki\restoreWarnings
();
473 $error = $this->mysqlError();
476 $error .= ' (' . $this->mServer
. ')';
483 * Returns the text of the error message from previous MySQL operation
485 * @param resource $conn Raw connection
488 abstract protected function mysqlError( $conn = null );
491 * @param string $table
492 * @param array $uniqueIndexes
494 * @param string $fname
495 * @return ResultWrapper
497 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
498 return $this->nativeReplace( $table, $rows, $fname );
502 * Estimate rows in dataset
503 * Returns estimated count, based on EXPLAIN output
504 * Takes same arguments as Database::select()
506 * @param string|array $table
507 * @param string|array $vars
508 * @param string|array $conds
509 * @param string $fname
510 * @param string|array $options
513 public function estimateRowCount( $table, $vars = '*', $conds = '',
514 $fname = __METHOD__
, $options = []
516 $options['EXPLAIN'] = true;
517 $res = $this->select( $table, $vars, $conds, $fname, $options );
518 if ( $res === false ) {
521 if ( !$this->numRows( $res ) ) {
526 foreach ( $res as $plan ) {
527 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
533 public function tableExists( $table, $fname = __METHOD__
) {
534 $table = $this->tableName( $table, 'raw' );
535 if ( isset( $this->mSessionTempTables
[$table] ) ) {
536 return true; // already known to exist and won't show in SHOW TABLES anyway
539 $encLike = $this->buildLike( $table );
541 return $this->query( "SHOW TABLES $encLike", $fname )->numRows() > 0;
545 * @param string $table
546 * @param string $field
547 * @return bool|MySQLField
549 public function fieldInfo( $table, $field ) {
550 $table = $this->tableName( $table );
551 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
555 $n = $this->mysqlNumFields( $res->result
);
556 for ( $i = 0; $i < $n; $i++
) {
557 $meta = $this->mysqlFetchField( $res->result
, $i );
558 if ( $field == $meta->name
) {
559 return new MySQLField( $meta );
567 * Get column information from a result
569 * @param resource $res Raw result
573 abstract protected function mysqlFetchField( $res, $n );
576 * Get information about an index into an object
577 * Returns false if the index does not exist
579 * @param string $table
580 * @param string $index
581 * @param string $fname
582 * @return bool|array|null False or null on failure
584 public function indexInfo( $table, $index, $fname = __METHOD__
) {
585 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
586 # SHOW INDEX should work for 3.x and up:
587 # https://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
588 $table = $this->tableName( $table );
589 $index = $this->indexName( $index );
591 $sql = 'SHOW INDEX FROM ' . $table;
592 $res = $this->query( $sql, $fname );
600 foreach ( $res as $row ) {
601 if ( $row->Key_name
== $index ) {
606 return empty( $result ) ?
false : $result;
613 public function strencode( $s ) {
614 return $this->mysqlRealEscapeString( $s );
621 abstract protected function mysqlRealEscapeString( $s );
623 public function addQuotes( $s ) {
624 if ( is_bool( $s ) ) {
625 // Parent would transform to int, which does not play nice with MySQL type juggling.
626 // When searching for an int in a string column, the strings are cast to int, which
627 // means false would match any string not starting with a number.
628 $s = (string)(int)$s;
630 return parent
::addQuotes( $s );
634 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
639 public function addIdentifierQuotes( $s ) {
640 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
641 // Remove NUL bytes and escape backticks by doubling
642 return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
646 * @param string $name
649 public function isQuotedIdentifier( $name ) {
650 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
653 public function getLag() {
654 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
655 return $this->getLagFromPtHeartbeat();
657 return $this->getLagFromSlaveStatus();
664 protected function getLagDetectionMethod() {
665 return $this->lagDetectionMethod
;
671 protected function getLagFromSlaveStatus() {
672 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
673 $row = $res ?
$res->fetchObject() : false;
674 if ( $row && strval( $row->Seconds_Behind_Master
) !== '' ) {
675 return intval( $row->Seconds_Behind_Master
);
684 protected function getLagFromPtHeartbeat() {
685 $options = $this->lagDetectionOptions
;
687 if ( isset( $options['conds'] ) ) {
688 // Best method for multi-DC setups: use logical channel names
689 $data = $this->getHeartbeatData( $options['conds'] );
691 // Standard method: use master server ID (works with stock pt-heartbeat)
692 $masterInfo = $this->getMasterServerInfo();
693 if ( !$masterInfo ) {
694 $this->queryLogger
->error(
695 "Unable to query master of {db_server} for server ID",
696 $this->getLogContext( [
697 'method' => __METHOD__
701 return false; // could not get master server ID
704 $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
705 $data = $this->getHeartbeatData( $conds );
708 list( $time, $nowUnix ) = $data;
709 if ( $time !== null ) {
710 // @time is in ISO format like "2015-09-25T16:48:10.000510"
711 $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
712 $timeUnix = (int)$dateTime->format( 'U' ) +
$dateTime->format( 'u' ) / 1e6
;
714 return max( $nowUnix - $timeUnix, 0.0 );
717 $this->queryLogger
->error(
718 "Unable to find pt-heartbeat row for {db_server}",
719 $this->getLogContext( [
720 'method' => __METHOD__
727 protected function getMasterServerInfo() {
728 $cache = $this->srvCache
;
729 $key = $cache->makeGlobalKey(
732 // Using one key for all cluster replica DBs is preferable
733 $this->getLBInfo( 'clusterMasterHost' ) ?
: $this->getServer()
736 return $cache->getWithSetCallback(
738 $cache::TTL_INDEFINITE
,
739 function () use ( $cache, $key ) {
740 // Get and leave a lock key in place for a short period
741 if ( !$cache->lock( $key, 0, 10 ) ) {
742 return false; // avoid master connection spike slams
745 $conn = $this->getLazyMasterHandle();
747 return false; // something is misconfigured
750 // Connect to and query the master; catch errors to avoid outages
752 $res = $conn->query( 'SELECT @@server_id AS id', __METHOD__
);
753 $row = $res ?
$res->fetchObject() : false;
754 $id = $row ?
(int)$row->id
: 0;
755 } catch ( DBError
$e ) {
759 // Cache the ID if it was retrieved
760 return $id ?
[ 'serverId' => $id, 'asOf' => time() ] : false;
766 * @param array $conds WHERE clause conditions to find a row
767 * @return array (heartbeat `ts` column value or null, UNIX timestamp) for the newest beat
768 * @see https://www.percona.com/doc/percona-toolkit/2.1/pt-heartbeat.html
770 protected function getHeartbeatData( array $conds ) {
771 // Do not bother starting implicit transactions here
772 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
774 $whereSQL = $this->makeList( $conds, self
::LIST_AND
);
775 // Use ORDER BY for channel based queries since that field might not be UNIQUE.
776 // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
777 // percision field is not supported in MySQL <= 5.5.
779 "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1"
781 $row = $res ?
$res->fetchObject() : false;
783 $this->restoreFlags();
786 return [ $row ?
$row->ts
: null, microtime( true ) ];
789 protected function getApproximateLagStatus() {
790 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
791 // Disable caching since this is fast enough and we don't wan't
792 // to be *too* pessimistic by having both the cache TTL and the
793 // pt-heartbeat interval count as lag in getSessionLagStatus()
794 return parent
::getApproximateLagStatus();
797 $key = $this->srvCache
->makeGlobalKey( 'mysql-lag', $this->getServer() );
798 $approxLag = $this->srvCache
->get( $key );
800 $approxLag = parent
::getApproximateLagStatus();
801 $this->srvCache
->set( $key, $approxLag, 1 );
807 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
808 if ( !( $pos instanceof MySQLMasterPos
) ) {
809 throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
812 if ( $this->getLBInfo( 'is static' ) === true ) {
813 return 0; // this is a copy of a read-only dataset with no master DB
814 } elseif ( $this->lastKnownReplicaPos
&& $this->lastKnownReplicaPos
->hasReached( $pos ) ) {
815 return 0; // already reached this point for sure
818 // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
819 if ( $this->useGTIDs
&& $pos->gtids
) {
820 // Wait on the GTID set (MariaDB only)
821 $gtidArg = $this->addQuotes( implode( ',', $pos->gtids
) );
822 $res = $this->doQuery( "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)" );
824 // Wait on the binlog coordinates
825 $encFile = $this->addQuotes( $pos->file
);
826 $encPos = intval( $pos->pos
);
827 $res = $this->doQuery( "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)" );
830 $row = $res ?
$this->fetchRow( $res ) : false;
832 throw new DBExpectedError( $this,
833 "MASTER_POS_WAIT() or MASTER_GTID_WAIT() failed: {$this->lastError()}" );
836 // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
837 $status = ( $row[0] !== null ) ?
intval( $row[0] ) : null;
838 if ( $status === null ) {
839 // T126436: jobs programmed to wait on master positions might be referencing binlogs
840 // with an old master hostname. Such calls make MASTER_POS_WAIT() return null. Try
841 // to detect this and treat the replica DB as having reached the position; a proper master
842 // switchover already requires that the new master be caught up before the switch.
843 $replicationPos = $this->getReplicaPos();
844 if ( $replicationPos && !$replicationPos->channelsMatch( $pos ) ) {
845 $this->lastKnownReplicaPos
= $replicationPos;
848 } elseif ( $status >= 0 ) {
849 // Remember that this position was reached to save queries next time
850 $this->lastKnownReplicaPos
= $pos;
857 * Get the position of the master from SHOW SLAVE STATUS
859 * @return MySQLMasterPos|bool
861 public function getReplicaPos() {
862 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
863 $row = $this->fetchObject( $res );
866 $pos = isset( $row->Exec_master_log_pos
)
867 ?
$row->Exec_master_log_pos
868 : $row->Exec_Master_Log_Pos
;
869 // Also fetch the last-applied GTID set (MariaDB)
870 if ( $this->useGTIDs
) {
871 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_slave_pos'", __METHOD__
);
872 $gtidRow = $this->fetchObject( $res );
873 $gtidSet = $gtidRow ?
$gtidRow->Value
: '';
878 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos, $gtidSet );
885 * Get the position of the master from SHOW MASTER STATUS
887 * @return MySQLMasterPos|bool
889 public function getMasterPos() {
890 $res = $this->query( 'SHOW MASTER STATUS', __METHOD__
);
891 $row = $this->fetchObject( $res );
894 // Also fetch the last-written GTID set (MariaDB)
895 if ( $this->useGTIDs
) {
896 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_binlog_pos'", __METHOD__
);
897 $gtidRow = $this->fetchObject( $res );
898 $gtidSet = $gtidRow ?
$gtidRow->Value
: '';
903 return new MySQLMasterPos( $row->File
, $row->Position
, $gtidSet );
909 public function serverIsReadOnly() {
910 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'read_only'", __METHOD__
);
911 $row = $this->fetchObject( $res );
913 return $row ?
( strtolower( $row->Value
) === 'on' ) : false;
917 * @param string $index
920 function useIndexClause( $index ) {
921 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
925 * @param string $index
928 function ignoreIndexClause( $index ) {
929 return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
935 function lowPriorityOption() {
936 return 'LOW_PRIORITY';
942 public function getSoftwareLink() {
943 // MariaDB includes its name in its version string; this is how MariaDB's version of
944 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
945 // in libmysql/libmysql.c).
946 $version = $this->getServerVersion();
947 if ( strpos( $version, 'MariaDB' ) !== false ||
strpos( $version, '-maria-' ) !== false ) {
948 return '[{{int:version-db-mariadb-url}} MariaDB]';
951 // Percona Server's version suffix is not very distinctive, and @@version_comment
952 // doesn't give the necessary info for source builds, so assume the server is MySQL.
953 // (Even Percona's version of mysql doesn't try to make the distinction.)
954 return '[{{int:version-db-mysql-url}} MySQL]';
960 public function getServerVersion() {
961 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
962 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
963 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
964 if ( $this->serverVersion
=== null ) {
965 $this->serverVersion
= $this->selectField( '', 'VERSION()', '', __METHOD__
);
967 return $this->serverVersion
;
971 * @param array $options
973 public function setSessionOptions( array $options ) {
974 if ( isset( $options['connTimeout'] ) ) {
975 $timeout = (int)$options['connTimeout'];
976 $this->query( "SET net_read_timeout=$timeout" );
977 $this->query( "SET net_write_timeout=$timeout" );
983 * @param string $newLine
986 public function streamStatementEnd( &$sql, &$newLine ) {
987 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
988 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
989 $this->delimiter
= $m[1];
993 return parent
::streamStatementEnd( $sql, $newLine );
997 * Check to see if a named lock is available. This is non-blocking.
999 * @param string $lockName Name of lock to poll
1000 * @param string $method Name of method calling us
1004 public function lockIsFree( $lockName, $method ) {
1005 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1006 $result = $this->query( "SELECT IS_FREE_LOCK($encName) AS lockstatus", $method );
1007 $row = $this->fetchObject( $result );
1009 return ( $row->lockstatus
== 1 );
1013 * @param string $lockName
1014 * @param string $method
1015 * @param int $timeout
1018 public function lock( $lockName, $method, $timeout = 5 ) {
1019 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1020 $result = $this->query( "SELECT GET_LOCK($encName, $timeout) AS lockstatus", $method );
1021 $row = $this->fetchObject( $result );
1023 if ( $row->lockstatus
== 1 ) {
1024 parent
::lock( $lockName, $method, $timeout ); // record
1028 $this->queryLogger
->warning( __METHOD__
. " failed to acquire lock '$lockName'\n" );
1035 * https://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
1036 * @param string $lockName
1037 * @param string $method
1040 public function unlock( $lockName, $method ) {
1041 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1042 $result = $this->query( "SELECT RELEASE_LOCK($encName) as lockstatus", $method );
1043 $row = $this->fetchObject( $result );
1045 if ( $row->lockstatus
== 1 ) {
1046 parent
::unlock( $lockName, $method ); // record
1050 $this->queryLogger
->warning( __METHOD__
. " failed to release lock '$lockName'\n" );
1055 private function makeLockName( $lockName ) {
1056 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1057 // Newer version enforce a 64 char length limit.
1058 return ( strlen( $lockName ) > 64 ) ?
sha1( $lockName ) : $lockName;
1061 public function namedLocksEnqueue() {
1065 public function tableLocksHaveTransactionScope() {
1066 return false; // tied to TCP connection
1069 protected function doLockTables( array $read, array $write, $method ) {
1071 foreach ( $write as $table ) {
1072 $items[] = $this->tableName( $table ) . ' WRITE';
1074 foreach ( $read as $table ) {
1075 $items[] = $this->tableName( $table ) . ' READ';
1078 $sql = "LOCK TABLES " . implode( ',', $items );
1079 $this->query( $sql, $method );
1084 protected function doUnlockTables( $method ) {
1085 $this->query( "UNLOCK TABLES", $method );
1091 * @param bool $value
1093 public function setBigSelects( $value = true ) {
1094 if ( $value === 'default' ) {
1095 if ( $this->mDefaultBigSelects
=== null ) {
1096 # Function hasn't been called before so it must already be set to the default
1099 $value = $this->mDefaultBigSelects
;
1101 } elseif ( $this->mDefaultBigSelects
=== null ) {
1102 $this->mDefaultBigSelects
=
1103 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__
);
1105 $encValue = $value ?
'1' : '0';
1106 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
1110 * DELETE where the condition is a join. MySql uses multi-table deletes.
1111 * @param string $delTable
1112 * @param string $joinTable
1113 * @param string $delVar
1114 * @param string $joinVar
1115 * @param array|string $conds
1116 * @param bool|string $fname
1117 * @throws DBUnexpectedError
1118 * @return bool|ResultWrapper
1120 public function deleteJoin(
1121 $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
1124 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
1127 $delTable = $this->tableName( $delTable );
1128 $joinTable = $this->tableName( $joinTable );
1129 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1131 if ( $conds != '*' ) {
1132 $sql .= ' AND ' . $this->makeList( $conds, self
::LIST_AND
);
1135 return $this->query( $sql, $fname );
1139 * @param string $table
1140 * @param array $rows
1141 * @param array $uniqueIndexes
1143 * @param string $fname
1146 public function upsert( $table, array $rows, array $uniqueIndexes,
1147 array $set, $fname = __METHOD__
1149 if ( !count( $rows ) ) {
1150 return true; // nothing to do
1153 if ( !is_array( reset( $rows ) ) ) {
1157 $table = $this->tableName( $table );
1158 $columns = array_keys( $rows[0] );
1160 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1162 foreach ( $rows as $row ) {
1163 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1165 $sql .= implode( ',', $rowTuples );
1166 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, self
::LIST_SET
);
1168 return (bool)$this->query( $sql, $fname );
1172 * Determines how long the server has been up
1176 public function getServerUptime() {
1177 $vars = $this->getMysqlStatus( 'Uptime' );
1179 return (int)$vars['Uptime'];
1183 * Determines if the last failure was due to a deadlock
1187 public function wasDeadlock() {
1188 return $this->lastErrno() == 1213;
1192 * Determines if the last failure was due to a lock timeout
1196 public function wasLockTimeout() {
1197 return $this->lastErrno() == 1205;
1200 public function wasErrorReissuable() {
1201 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
1205 * Determines if the last failure was due to the database being read-only.
1209 public function wasReadOnlyError() {
1210 return $this->lastErrno() == 1223 ||
1211 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1214 public function wasConnectionError( $errno ) {
1215 return $errno == 2013 ||
$errno == 2006;
1219 * @param string $oldName
1220 * @param string $newName
1221 * @param bool $temporary
1222 * @param string $fname
1225 public function duplicateTableStructure(
1226 $oldName, $newName, $temporary = false, $fname = __METHOD__
1228 $tmp = $temporary ?
'TEMPORARY ' : '';
1229 $newName = $this->addIdentifierQuotes( $newName );
1230 $oldName = $this->addIdentifierQuotes( $oldName );
1231 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1233 return $this->query( $query, $fname );
1237 * List all tables on the database
1239 * @param string $prefix Only show tables with this prefix, e.g. mw_
1240 * @param string $fname Calling function name
1243 public function listTables( $prefix = null, $fname = __METHOD__
) {
1244 $result = $this->query( "SHOW TABLES", $fname );
1248 foreach ( $result as $table ) {
1249 $vars = get_object_vars( $table );
1250 $table = array_pop( $vars );
1252 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1253 $endArray[] = $table;
1261 * @param string $tableName
1262 * @param string $fName
1263 * @return bool|ResultWrapper
1265 public function dropTable( $tableName, $fName = __METHOD__
) {
1266 if ( !$this->tableExists( $tableName, $fName ) ) {
1270 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1274 * Get status information from SHOW STATUS in an associative array
1276 * @param string $which
1279 private function getMysqlStatus( $which = "%" ) {
1280 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1283 foreach ( $res as $row ) {
1284 $status[$row->Variable_name
] = $row->Value
;
1291 * Lists VIEWs in the database
1293 * @param string $prefix Only show VIEWs with this prefix, eg.
1294 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1295 * @param string $fname Name of calling function
1299 public function listViews( $prefix = null, $fname = __METHOD__
) {
1300 // The name of the column containing the name of the VIEW
1301 $propertyName = 'Tables_in_' . $this->mDBname
;
1303 // Query for the VIEWS
1304 $res = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1306 foreach ( $res as $row ) {
1307 array_push( $allViews, $row->$propertyName );
1310 if ( is_null( $prefix ) ||
$prefix === '' ) {
1314 $filteredViews = [];
1315 foreach ( $allViews as $viewName ) {
1316 // Does the name of this VIEW start with the table-prefix?
1317 if ( strpos( $viewName, $prefix ) === 0 ) {
1318 array_push( $filteredViews, $viewName );
1322 return $filteredViews;
1326 * Differentiates between a TABLE and a VIEW.
1328 * @param string $name Name of the TABLE/VIEW to test
1329 * @param string $prefix
1333 public function isView( $name, $prefix = null ) {
1334 return in_array( $name, $this->listViews( $prefix ) );
1338 * Allows for index remapping in queries where this is not consistent across DBMS
1340 * @param string $index
1343 protected function indexName( $index ) {
1345 * When SQLite indexes were introduced in r45764, it was noted that
1346 * SQLite requires index names to be unique within the whole database,
1347 * not just within a schema. As discussed in CR r45819, to avoid the
1348 * need for a schema change on existing installations, the indexes
1349 * were implicitly mapped from the new names to the old names.
1351 * This mapping can be removed if DB patches are introduced to alter
1352 * the relevant tables in existing installations. Note that because
1353 * this index mapping applies to table creation, even new installations
1354 * of MySQL have the old names (except for installations created during
1355 * a period where this mapping was inappropriately removed, see
1359 'ar_usertext_timestamp' => 'usertext_timestamp',
1360 'un_user_id' => 'user_id',
1361 'un_user_ip' => 'user_ip',
1364 if ( isset( $renamed[$index] ) ) {
1365 return $renamed[$index];
1372 class_alias( DatabaseMysqlBase
::class, 'DatabaseMysqlBase' );