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;
68 * Additional $params include:
69 * - lagDetectionMethod : set to one of (Seconds_Behind_Master,pt-heartbeat).
70 * pt-heartbeat assumes the table is at heartbeat.heartbeat
71 * and uses UTC timestamps in the heartbeat.ts column.
72 * (https://www.percona.com/doc/percona-toolkit/2.2/pt-heartbeat.html)
73 * - lagDetectionOptions : if using pt-heartbeat, this can be set to an array map to change
74 * the default behavior. Normally, the heartbeat row with the server
75 * ID of this server's master will be used. Set the "conds" field to
76 * override the query conditions, e.g. ['shard' => 's1'].
77 * - useGTIDs : use GTID methods like MASTER_GTID_WAIT() when possible.
78 * - sslKeyPath : path to key file [default: null]
79 * - sslCertPath : path to certificate file [default: null]
80 * - sslCAFile: path to a single certificate authority PEM file [default: null]
81 * - sslCAPath : parth to certificate authority PEM directory [default: null]
82 * - sslCiphers : array list of allowable ciphers [default: null]
83 * @param array $params
85 function __construct( array $params ) {
86 $this->lagDetectionMethod
= isset( $params['lagDetectionMethod'] )
87 ?
$params['lagDetectionMethod']
88 : 'Seconds_Behind_Master';
89 $this->lagDetectionOptions
= isset( $params['lagDetectionOptions'] )
90 ?
$params['lagDetectionOptions']
92 $this->useGTIDs
= !empty( $params['useGTIDs' ] );
93 foreach ( [ 'KeyPath', 'CertPath', 'CAFile', 'CAPath', 'Ciphers' ] as $name ) {
95 if ( isset( $params[$var] ) ) {
96 $this->$var = $params[$var];
99 $this->sqlMode
= isset( $params['sqlMode'] ) ?
$params['sqlMode'] : '';
100 $this->utf8Mode
= !empty( $params['utf8Mode'] );
102 parent
::__construct( $params );
108 public function getType() {
113 * @param string $server
114 * @param string $user
115 * @param string $password
116 * @param string $dbName
117 * @throws Exception|DBConnectionError
120 public function open( $server, $user, $password, $dbName ) {
121 # Close/unset connection handle
124 $this->mServer
= $server;
125 $this->mUser
= $user;
126 $this->mPassword
= $password;
127 $this->mDBname
= $dbName;
129 $this->installErrorHandler();
131 $this->mConn
= $this->mysqlConnect( $this->mServer
);
132 } catch ( Exception
$ex ) {
133 $this->restoreErrorHandler();
136 $error = $this->restoreErrorHandler();
138 # Always log connection errors
139 if ( !$this->mConn
) {
141 $error = $this->lastError();
143 $this->connLogger
->error(
144 "Error connecting to {db_server}: {error}",
145 $this->getLogContext( [
146 'method' => __METHOD__
,
150 $this->connLogger
->debug( "DB connection error\n" .
151 "Server: $server, User: $user, Password: " .
152 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
154 $this->reportConnectionError( $error );
157 if ( $dbName != '' ) {
158 MediaWiki\
suppressWarnings();
159 $success = $this->selectDB( $dbName );
160 MediaWiki\restoreWarnings
();
162 $this->queryLogger
->error(
163 "Error selecting database {db_name} on server {db_server}",
164 $this->getLogContext( [
165 'method' => __METHOD__
,
168 $this->queryLogger
->debug(
169 "Error selecting database $dbName on server {$this->mServer}" );
171 $this->reportConnectionError( "Error selecting database $dbName" );
175 // Tell the server what we're communicating with
176 if ( !$this->connectInitCharset() ) {
177 $this->reportConnectionError( "Error setting character set" );
180 // Abstract over any insane MySQL defaults
181 $set = [ 'group_concat_max_len = 262144' ];
182 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
183 if ( is_string( $this->sqlMode
) ) {
184 $set[] = 'sql_mode = ' . $this->addQuotes( $this->sqlMode
);
186 // Set any custom settings defined by site config
187 // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
188 foreach ( $this->mSessionVars
as $var => $val ) {
189 // Escape strings but not numbers to avoid MySQL complaining
190 if ( !is_int( $val ) && !is_float( $val ) ) {
191 $val = $this->addQuotes( $val );
193 $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
197 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
198 $success = $this->doQuery( 'SET ' . implode( ', ', $set ) );
200 $this->queryLogger
->error(
201 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)',
202 $this->getLogContext( [
203 'method' => __METHOD__
,
206 $this->reportConnectionError(
207 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)' );
211 $this->mOpened
= true;
217 * Set the character set information right after connection
220 protected function connectInitCharset() {
221 if ( $this->utf8Mode
) {
222 // Tell the server we're communicating with it in UTF-8.
223 // This may engage various charset conversions.
224 return $this->mysqlSetCharset( 'utf8' );
226 return $this->mysqlSetCharset( 'binary' );
231 * Open a connection to a MySQL server
233 * @param string $realServer
234 * @return mixed Raw connection
235 * @throws DBConnectionError
237 abstract protected function mysqlConnect( $realServer );
240 * Set the character set of the MySQL link
242 * @param string $charset
245 abstract protected function mysqlSetCharset( $charset );
248 * @param ResultWrapper|resource $res
249 * @throws DBUnexpectedError
251 public function freeResult( $res ) {
252 if ( $res instanceof ResultWrapper
) {
255 MediaWiki\
suppressWarnings();
256 $ok = $this->mysqlFreeResult( $res );
257 MediaWiki\restoreWarnings
();
259 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
266 * @param resource $res Raw result
269 abstract protected function mysqlFreeResult( $res );
272 * @param ResultWrapper|resource $res
273 * @return stdClass|bool
274 * @throws DBUnexpectedError
276 public function fetchObject( $res ) {
277 if ( $res instanceof ResultWrapper
) {
280 MediaWiki\
suppressWarnings();
281 $row = $this->mysqlFetchObject( $res );
282 MediaWiki\restoreWarnings
();
284 $errno = $this->lastErrno();
285 // Unfortunately, mysql_fetch_object does not reset the last errno.
286 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
287 // these are the only errors mysql_fetch_object can cause.
288 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
289 if ( $errno == 2000 ||
$errno == 2013 ) {
290 throw new DBUnexpectedError(
292 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
300 * Fetch a result row as an object
302 * @param resource $res Raw result
305 abstract protected function mysqlFetchObject( $res );
308 * @param ResultWrapper|resource $res
310 * @throws DBUnexpectedError
312 public function fetchRow( $res ) {
313 if ( $res instanceof ResultWrapper
) {
316 MediaWiki\
suppressWarnings();
317 $row = $this->mysqlFetchArray( $res );
318 MediaWiki\restoreWarnings
();
320 $errno = $this->lastErrno();
321 // Unfortunately, mysql_fetch_array does not reset the last errno.
322 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
323 // these are the only errors mysql_fetch_array can cause.
324 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
325 if ( $errno == 2000 ||
$errno == 2013 ) {
326 throw new DBUnexpectedError(
328 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
336 * Fetch a result row as an associative and numeric array
338 * @param resource $res Raw result
341 abstract protected function mysqlFetchArray( $res );
344 * @throws DBUnexpectedError
345 * @param ResultWrapper|resource $res
348 function numRows( $res ) {
349 if ( $res instanceof ResultWrapper
) {
352 MediaWiki\
suppressWarnings();
353 $n = $this->mysqlNumRows( $res );
354 MediaWiki\restoreWarnings
();
356 // Unfortunately, mysql_num_rows does not reset the last errno.
357 // We are not checking for any errors here, since
358 // these are no errors mysql_num_rows can cause.
359 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
360 // See https://phabricator.wikimedia.org/T44430
365 * Get number of rows in result
367 * @param resource $res Raw result
370 abstract protected function mysqlNumRows( $res );
373 * @param ResultWrapper|resource $res
376 public function numFields( $res ) {
377 if ( $res instanceof ResultWrapper
) {
381 return $this->mysqlNumFields( $res );
385 * Get number of fields in result
387 * @param resource $res Raw result
390 abstract protected function mysqlNumFields( $res );
393 * @param ResultWrapper|resource $res
397 public function fieldName( $res, $n ) {
398 if ( $res instanceof ResultWrapper
) {
402 return $this->mysqlFieldName( $res, $n );
406 * Get the name of the specified field in a result
408 * @param ResultWrapper|resource $res
412 abstract protected function mysqlFieldName( $res, $n );
415 * mysql_field_type() wrapper
416 * @param ResultWrapper|resource $res
420 public function fieldType( $res, $n ) {
421 if ( $res instanceof ResultWrapper
) {
425 return $this->mysqlFieldType( $res, $n );
429 * Get the type of the specified field in a result
431 * @param ResultWrapper|resource $res
435 abstract protected function mysqlFieldType( $res, $n );
438 * @param ResultWrapper|resource $res
442 public function dataSeek( $res, $row ) {
443 if ( $res instanceof ResultWrapper
) {
447 return $this->mysqlDataSeek( $res, $row );
451 * Move internal result pointer
453 * @param ResultWrapper|resource $res
457 abstract protected function mysqlDataSeek( $res, $row );
462 public function lastError() {
463 if ( $this->mConn
) {
464 # Even if it's non-zero, it can still be invalid
465 MediaWiki\
suppressWarnings();
466 $error = $this->mysqlError( $this->mConn
);
468 $error = $this->mysqlError();
470 MediaWiki\restoreWarnings
();
472 $error = $this->mysqlError();
475 $error .= ' (' . $this->mServer
. ')';
482 * Returns the text of the error message from previous MySQL operation
484 * @param resource $conn Raw connection
487 abstract protected function mysqlError( $conn = null );
490 * @param string $table
491 * @param array $uniqueIndexes
493 * @param string $fname
494 * @return ResultWrapper
496 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
497 return $this->nativeReplace( $table, $rows, $fname );
501 * Estimate rows in dataset
502 * Returns estimated count, based on EXPLAIN output
503 * Takes same arguments as Database::select()
505 * @param string|array $table
506 * @param string|array $vars
507 * @param string|array $conds
508 * @param string $fname
509 * @param string|array $options
512 public function estimateRowCount( $table, $vars = '*', $conds = '',
513 $fname = __METHOD__
, $options = []
515 $options['EXPLAIN'] = true;
516 $res = $this->select( $table, $vars, $conds, $fname, $options );
517 if ( $res === false ) {
520 if ( !$this->numRows( $res ) ) {
525 foreach ( $res as $plan ) {
526 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
532 public function tableExists( $table, $fname = __METHOD__
) {
533 // Split database and table into proper variables as Database::tableName() returns
534 // shared tables prefixed with their database, which do not work in SHOW TABLES statements
535 list( $database, , $prefix, $table ) = $this->qualifiedTableComponents( $table );
536 $tableName = "{$prefix}{$table}";
538 if ( isset( $this->mSessionTempTables
[$tableName] ) ) {
539 return true; // already known to exist and won't show in SHOW TABLES anyway
542 // We can't use buildLike() here, because it specifies an escape character
543 // other than the backslash, which is the only one supported by SHOW TABLES
544 $encLike = $this->escapeLikeInternal( $tableName, '\\' );
546 // If the database has been specified (such as for shared tables), use "FROM"
547 if ( $database !== '' ) {
548 $encDatabase = $this->addIdentifierQuotes( $database );
549 $query = "SHOW TABLES FROM $encDatabase LIKE '$encLike'";
551 $query = "SHOW TABLES LIKE '$encLike'";
554 return $this->query( $query, $fname )->numRows() > 0;
558 * @param string $table
559 * @param string $field
560 * @return bool|MySQLField
562 public function fieldInfo( $table, $field ) {
563 $table = $this->tableName( $table );
564 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
568 $n = $this->mysqlNumFields( $res->result
);
569 for ( $i = 0; $i < $n; $i++
) {
570 $meta = $this->mysqlFetchField( $res->result
, $i );
571 if ( $field == $meta->name
) {
572 return new MySQLField( $meta );
580 * Get column information from a result
582 * @param resource $res Raw result
586 abstract protected function mysqlFetchField( $res, $n );
589 * Get information about an index into an object
590 * Returns false if the index does not exist
592 * @param string $table
593 * @param string $index
594 * @param string $fname
595 * @return bool|array|null False or null on failure
597 public function indexInfo( $table, $index, $fname = __METHOD__
) {
598 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
599 # SHOW INDEX should work for 3.x and up:
600 # https://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
601 $table = $this->tableName( $table );
602 $index = $this->indexName( $index );
604 $sql = 'SHOW INDEX FROM ' . $table;
605 $res = $this->query( $sql, $fname );
613 foreach ( $res as $row ) {
614 if ( $row->Key_name
== $index ) {
619 return empty( $result ) ?
false : $result;
626 public function strencode( $s ) {
627 return $this->mysqlRealEscapeString( $s );
634 abstract protected function mysqlRealEscapeString( $s );
636 public function addQuotes( $s ) {
637 if ( is_bool( $s ) ) {
638 // Parent would transform to int, which does not play nice with MySQL type juggling.
639 // When searching for an int in a string column, the strings are cast to int, which
640 // means false would match any string not starting with a number.
641 $s = (string)(int)$s;
643 return parent
::addQuotes( $s );
647 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
652 public function addIdentifierQuotes( $s ) {
653 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
654 // Remove NUL bytes and escape backticks by doubling
655 return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
659 * @param string $name
662 public function isQuotedIdentifier( $name ) {
663 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
666 public function getLag() {
667 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
668 return $this->getLagFromPtHeartbeat();
670 return $this->getLagFromSlaveStatus();
677 protected function getLagDetectionMethod() {
678 return $this->lagDetectionMethod
;
684 protected function getLagFromSlaveStatus() {
685 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
686 $row = $res ?
$res->fetchObject() : false;
687 if ( $row && strval( $row->Seconds_Behind_Master
) !== '' ) {
688 return intval( $row->Seconds_Behind_Master
);
697 protected function getLagFromPtHeartbeat() {
698 $options = $this->lagDetectionOptions
;
700 if ( isset( $options['conds'] ) ) {
701 // Best method for multi-DC setups: use logical channel names
702 $data = $this->getHeartbeatData( $options['conds'] );
704 // Standard method: use master server ID (works with stock pt-heartbeat)
705 $masterInfo = $this->getMasterServerInfo();
706 if ( !$masterInfo ) {
707 $this->queryLogger
->error(
708 "Unable to query master of {db_server} for server ID",
709 $this->getLogContext( [
710 'method' => __METHOD__
714 return false; // could not get master server ID
717 $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
718 $data = $this->getHeartbeatData( $conds );
721 list( $time, $nowUnix ) = $data;
722 if ( $time !== null ) {
723 // @time is in ISO format like "2015-09-25T16:48:10.000510"
724 $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
725 $timeUnix = (int)$dateTime->format( 'U' ) +
$dateTime->format( 'u' ) / 1e6
;
727 return max( $nowUnix - $timeUnix, 0.0 );
730 $this->queryLogger
->error(
731 "Unable to find pt-heartbeat row for {db_server}",
732 $this->getLogContext( [
733 'method' => __METHOD__
740 protected function getMasterServerInfo() {
741 $cache = $this->srvCache
;
742 $key = $cache->makeGlobalKey(
745 // Using one key for all cluster replica DBs is preferable
746 $this->getLBInfo( 'clusterMasterHost' ) ?
: $this->getServer()
749 return $cache->getWithSetCallback(
751 $cache::TTL_INDEFINITE
,
752 function () use ( $cache, $key ) {
753 // Get and leave a lock key in place for a short period
754 if ( !$cache->lock( $key, 0, 10 ) ) {
755 return false; // avoid master connection spike slams
758 $conn = $this->getLazyMasterHandle();
760 return false; // something is misconfigured
763 // Connect to and query the master; catch errors to avoid outages
765 $res = $conn->query( 'SELECT @@server_id AS id', __METHOD__
);
766 $row = $res ?
$res->fetchObject() : false;
767 $id = $row ?
(int)$row->id
: 0;
768 } catch ( DBError
$e ) {
772 // Cache the ID if it was retrieved
773 return $id ?
[ 'serverId' => $id, 'asOf' => time() ] : false;
779 * @param array $conds WHERE clause conditions to find a row
780 * @return array (heartbeat `ts` column value or null, UNIX timestamp) for the newest beat
781 * @see https://www.percona.com/doc/percona-toolkit/2.1/pt-heartbeat.html
783 protected function getHeartbeatData( array $conds ) {
784 // Query time and trip time are not counted
785 $nowUnix = microtime( true );
786 // Do not bother starting implicit transactions here
787 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
789 $whereSQL = $this->makeList( $conds, self
::LIST_AND
);
790 // Use ORDER BY for channel based queries since that field might not be UNIQUE.
791 // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
792 // percision field is not supported in MySQL <= 5.5.
794 "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1"
796 $row = $res ?
$res->fetchObject() : false;
798 $this->restoreFlags();
801 return [ $row ?
$row->ts
: null, $nowUnix ];
804 protected function getApproximateLagStatus() {
805 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
806 // Disable caching since this is fast enough and we don't wan't
807 // to be *too* pessimistic by having both the cache TTL and the
808 // pt-heartbeat interval count as lag in getSessionLagStatus()
809 return parent
::getApproximateLagStatus();
812 $key = $this->srvCache
->makeGlobalKey( 'mysql-lag', $this->getServer() );
813 $approxLag = $this->srvCache
->get( $key );
815 $approxLag = parent
::getApproximateLagStatus();
816 $this->srvCache
->set( $key, $approxLag, 1 );
822 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
823 if ( !( $pos instanceof MySQLMasterPos
) ) {
824 throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
827 if ( $this->getLBInfo( 'is static' ) === true ) {
828 return 0; // this is a copy of a read-only dataset with no master DB
829 } elseif ( $this->lastKnownReplicaPos
&& $this->lastKnownReplicaPos
->hasReached( $pos ) ) {
830 return 0; // already reached this point for sure
833 // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
834 if ( $this->useGTIDs
&& $pos->gtids
) {
835 // Wait on the GTID set (MariaDB only)
836 $gtidArg = $this->addQuotes( implode( ',', $pos->gtids
) );
837 $res = $this->doQuery( "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)" );
839 // Wait on the binlog coordinates
840 $encFile = $this->addQuotes( $pos->file
);
841 $encPos = intval( $pos->pos
);
842 $res = $this->doQuery( "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)" );
845 $row = $res ?
$this->fetchRow( $res ) : false;
847 throw new DBExpectedError( $this,
848 "MASTER_POS_WAIT() or MASTER_GTID_WAIT() failed: {$this->lastError()}" );
851 // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
852 $status = ( $row[0] !== null ) ?
intval( $row[0] ) : null;
853 if ( $status === null ) {
854 // T126436: jobs programmed to wait on master positions might be referencing binlogs
855 // with an old master hostname. Such calls make MASTER_POS_WAIT() return null. Try
856 // to detect this and treat the replica DB as having reached the position; a proper master
857 // switchover already requires that the new master be caught up before the switch.
858 $replicationPos = $this->getReplicaPos();
859 if ( $replicationPos && !$replicationPos->channelsMatch( $pos ) ) {
860 $this->lastKnownReplicaPos
= $replicationPos;
863 } elseif ( $status >= 0 ) {
864 // Remember that this position was reached to save queries next time
865 $this->lastKnownReplicaPos
= $pos;
872 * Get the position of the master from SHOW SLAVE STATUS
874 * @return MySQLMasterPos|bool
876 public function getReplicaPos() {
877 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
878 $row = $this->fetchObject( $res );
881 $pos = isset( $row->Exec_master_log_pos
)
882 ?
$row->Exec_master_log_pos
883 : $row->Exec_Master_Log_Pos
;
884 // Also fetch the last-applied GTID set (MariaDB)
885 if ( $this->useGTIDs
) {
886 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_slave_pos'", __METHOD__
);
887 $gtidRow = $this->fetchObject( $res );
888 $gtidSet = $gtidRow ?
$gtidRow->Value
: '';
893 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos, $gtidSet );
900 * Get the position of the master from SHOW MASTER STATUS
902 * @return MySQLMasterPos|bool
904 public function getMasterPos() {
905 $res = $this->query( 'SHOW MASTER STATUS', __METHOD__
);
906 $row = $this->fetchObject( $res );
909 // Also fetch the last-written GTID set (MariaDB)
910 if ( $this->useGTIDs
) {
911 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_binlog_pos'", __METHOD__
);
912 $gtidRow = $this->fetchObject( $res );
913 $gtidSet = $gtidRow ?
$gtidRow->Value
: '';
918 return new MySQLMasterPos( $row->File
, $row->Position
, $gtidSet );
924 public function serverIsReadOnly() {
925 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'read_only'", __METHOD__
);
926 $row = $this->fetchObject( $res );
928 return $row ?
( strtolower( $row->Value
) === 'on' ) : false;
932 * @param string $index
935 function useIndexClause( $index ) {
936 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
940 * @param string $index
943 function ignoreIndexClause( $index ) {
944 return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
950 function lowPriorityOption() {
951 return 'LOW_PRIORITY';
957 public function getSoftwareLink() {
958 // MariaDB includes its name in its version string; this is how MariaDB's version of
959 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
960 // in libmysql/libmysql.c).
961 $version = $this->getServerVersion();
962 if ( strpos( $version, 'MariaDB' ) !== false ||
strpos( $version, '-maria-' ) !== false ) {
963 return '[{{int:version-db-mariadb-url}} MariaDB]';
966 // Percona Server's version suffix is not very distinctive, and @@version_comment
967 // doesn't give the necessary info for source builds, so assume the server is MySQL.
968 // (Even Percona's version of mysql doesn't try to make the distinction.)
969 return '[{{int:version-db-mysql-url}} MySQL]';
975 public function getServerVersion() {
976 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
977 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
978 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
979 if ( $this->serverVersion
=== null ) {
980 $this->serverVersion
= $this->selectField( '', 'VERSION()', '', __METHOD__
);
982 return $this->serverVersion
;
986 * @param array $options
988 public function setSessionOptions( array $options ) {
989 if ( isset( $options['connTimeout'] ) ) {
990 $timeout = (int)$options['connTimeout'];
991 $this->query( "SET net_read_timeout=$timeout" );
992 $this->query( "SET net_write_timeout=$timeout" );
997 * @param string &$sql
998 * @param string &$newLine
1001 public function streamStatementEnd( &$sql, &$newLine ) {
1002 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
1003 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
1004 $this->delimiter
= $m[1];
1008 return parent
::streamStatementEnd( $sql, $newLine );
1012 * Check to see if a named lock is available. This is non-blocking.
1014 * @param string $lockName Name of lock to poll
1015 * @param string $method Name of method calling us
1019 public function lockIsFree( $lockName, $method ) {
1020 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1021 $result = $this->query( "SELECT IS_FREE_LOCK($encName) AS lockstatus", $method );
1022 $row = $this->fetchObject( $result );
1024 return ( $row->lockstatus
== 1 );
1028 * @param string $lockName
1029 * @param string $method
1030 * @param int $timeout
1033 public function lock( $lockName, $method, $timeout = 5 ) {
1034 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1035 $result = $this->query( "SELECT GET_LOCK($encName, $timeout) AS lockstatus", $method );
1036 $row = $this->fetchObject( $result );
1038 if ( $row->lockstatus
== 1 ) {
1039 parent
::lock( $lockName, $method, $timeout ); // record
1043 $this->queryLogger
->warning( __METHOD__
. " failed to acquire lock '$lockName'\n" );
1050 * https://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
1051 * @param string $lockName
1052 * @param string $method
1055 public function unlock( $lockName, $method ) {
1056 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1057 $result = $this->query( "SELECT RELEASE_LOCK($encName) as lockstatus", $method );
1058 $row = $this->fetchObject( $result );
1060 if ( $row->lockstatus
== 1 ) {
1061 parent
::unlock( $lockName, $method ); // record
1065 $this->queryLogger
->warning( __METHOD__
. " failed to release lock '$lockName'\n" );
1070 private function makeLockName( $lockName ) {
1071 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1072 // Newer version enforce a 64 char length limit.
1073 return ( strlen( $lockName ) > 64 ) ?
sha1( $lockName ) : $lockName;
1076 public function namedLocksEnqueue() {
1080 public function tableLocksHaveTransactionScope() {
1081 return false; // tied to TCP connection
1084 protected function doLockTables( array $read, array $write, $method ) {
1086 foreach ( $write as $table ) {
1087 $items[] = $this->tableName( $table ) . ' WRITE';
1089 foreach ( $read as $table ) {
1090 $items[] = $this->tableName( $table ) . ' READ';
1093 $sql = "LOCK TABLES " . implode( ',', $items );
1094 $this->query( $sql, $method );
1099 protected function doUnlockTables( $method ) {
1100 $this->query( "UNLOCK TABLES", $method );
1106 * @param bool $value
1108 public function setBigSelects( $value = true ) {
1109 if ( $value === 'default' ) {
1110 if ( $this->mDefaultBigSelects
=== null ) {
1111 # Function hasn't been called before so it must already be set to the default
1114 $value = $this->mDefaultBigSelects
;
1116 } elseif ( $this->mDefaultBigSelects
=== null ) {
1117 $this->mDefaultBigSelects
=
1118 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__
);
1120 $encValue = $value ?
'1' : '0';
1121 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
1125 * DELETE where the condition is a join. MySql uses multi-table deletes.
1126 * @param string $delTable
1127 * @param string $joinTable
1128 * @param string $delVar
1129 * @param string $joinVar
1130 * @param array|string $conds
1131 * @param bool|string $fname
1132 * @throws DBUnexpectedError
1133 * @return bool|ResultWrapper
1135 public function deleteJoin(
1136 $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
1139 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
1142 $delTable = $this->tableName( $delTable );
1143 $joinTable = $this->tableName( $joinTable );
1144 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1146 if ( $conds != '*' ) {
1147 $sql .= ' AND ' . $this->makeList( $conds, self
::LIST_AND
);
1150 return $this->query( $sql, $fname );
1154 * @param string $table
1155 * @param array $rows
1156 * @param array $uniqueIndexes
1158 * @param string $fname
1161 public function upsert( $table, array $rows, array $uniqueIndexes,
1162 array $set, $fname = __METHOD__
1164 if ( !count( $rows ) ) {
1165 return true; // nothing to do
1168 if ( !is_array( reset( $rows ) ) ) {
1172 $table = $this->tableName( $table );
1173 $columns = array_keys( $rows[0] );
1175 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1177 foreach ( $rows as $row ) {
1178 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1180 $sql .= implode( ',', $rowTuples );
1181 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, self
::LIST_SET
);
1183 return (bool)$this->query( $sql, $fname );
1187 * Determines how long the server has been up
1191 public function getServerUptime() {
1192 $vars = $this->getMysqlStatus( 'Uptime' );
1194 return (int)$vars['Uptime'];
1198 * Determines if the last failure was due to a deadlock
1202 public function wasDeadlock() {
1203 return $this->lastErrno() == 1213;
1207 * Determines if the last failure was due to a lock timeout
1211 public function wasLockTimeout() {
1212 return $this->lastErrno() == 1205;
1215 public function wasErrorReissuable() {
1216 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
1220 * Determines if the last failure was due to the database being read-only.
1224 public function wasReadOnlyError() {
1225 return $this->lastErrno() == 1223 ||
1226 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1229 public function wasConnectionError( $errno ) {
1230 return $errno == 2013 ||
$errno == 2006;
1234 * @param string $oldName
1235 * @param string $newName
1236 * @param bool $temporary
1237 * @param string $fname
1240 public function duplicateTableStructure(
1241 $oldName, $newName, $temporary = false, $fname = __METHOD__
1243 $tmp = $temporary ?
'TEMPORARY ' : '';
1244 $newName = $this->addIdentifierQuotes( $newName );
1245 $oldName = $this->addIdentifierQuotes( $oldName );
1246 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1248 return $this->query( $query, $fname );
1252 * List all tables on the database
1254 * @param string $prefix Only show tables with this prefix, e.g. mw_
1255 * @param string $fname Calling function name
1258 public function listTables( $prefix = null, $fname = __METHOD__
) {
1259 $result = $this->query( "SHOW TABLES", $fname );
1263 foreach ( $result as $table ) {
1264 $vars = get_object_vars( $table );
1265 $table = array_pop( $vars );
1267 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1268 $endArray[] = $table;
1276 * @param string $tableName
1277 * @param string $fName
1278 * @return bool|ResultWrapper
1280 public function dropTable( $tableName, $fName = __METHOD__
) {
1281 if ( !$this->tableExists( $tableName, $fName ) ) {
1285 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1289 * Get status information from SHOW STATUS in an associative array
1291 * @param string $which
1294 private function getMysqlStatus( $which = "%" ) {
1295 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1298 foreach ( $res as $row ) {
1299 $status[$row->Variable_name
] = $row->Value
;
1306 * Lists VIEWs in the database
1308 * @param string $prefix Only show VIEWs with this prefix, eg.
1309 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1310 * @param string $fname Name of calling function
1314 public function listViews( $prefix = null, $fname = __METHOD__
) {
1315 // The name of the column containing the name of the VIEW
1316 $propertyName = 'Tables_in_' . $this->mDBname
;
1318 // Query for the VIEWS
1319 $res = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1321 foreach ( $res as $row ) {
1322 array_push( $allViews, $row->$propertyName );
1325 if ( is_null( $prefix ) ||
$prefix === '' ) {
1329 $filteredViews = [];
1330 foreach ( $allViews as $viewName ) {
1331 // Does the name of this VIEW start with the table-prefix?
1332 if ( strpos( $viewName, $prefix ) === 0 ) {
1333 array_push( $filteredViews, $viewName );
1337 return $filteredViews;
1341 * Differentiates between a TABLE and a VIEW.
1343 * @param string $name Name of the TABLE/VIEW to test
1344 * @param string $prefix
1348 public function isView( $name, $prefix = null ) {
1349 return in_array( $name, $this->listViews( $prefix ) );
1353 * Allows for index remapping in queries where this is not consistent across DBMS
1355 * @param string $index
1358 protected function indexName( $index ) {
1360 * When SQLite indexes were introduced in r45764, it was noted that
1361 * SQLite requires index names to be unique within the whole database,
1362 * not just within a schema. As discussed in CR r45819, to avoid the
1363 * need for a schema change on existing installations, the indexes
1364 * were implicitly mapped from the new names to the old names.
1366 * This mapping can be removed if DB patches are introduced to alter
1367 * the relevant tables in existing installations. Note that because
1368 * this index mapping applies to table creation, even new installations
1369 * of MySQL have the old names (except for installations created during
1370 * a period where this mapping was inappropriately removed, see
1374 'ar_usertext_timestamp' => 'usertext_timestamp',
1375 'un_user_id' => 'user_id',
1376 'un_user_ip' => 'user_ip',
1379 if ( isset( $renamed[$index] ) ) {
1380 return $renamed[$index];
1387 class_alias( DatabaseMysqlBase
::class, 'DatabaseMysqlBase' );