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 use Wikimedia\Rdbms\DBMasterPos
;
24 use Wikimedia\Rdbms\MySQLMasterPos
;
25 use Wikimedia\Rdbms\MySQLField
;
26 use Wikimedia\Rdbms\ResultWrapper
;
29 * Database abstraction object for MySQL.
30 * Defines methods independent on used MySQL extension.
36 abstract class DatabaseMysqlBase
extends Database
{
37 /** @var MysqlMasterPos */
38 protected $lastKnownReplicaPos;
39 /** @var string Method to detect replica DB lag */
40 protected $lagDetectionMethod;
41 /** @var array Method to detect replica DB lag */
42 protected $lagDetectionOptions = [];
43 /** @var bool bool Whether to use GTID methods */
44 protected $useGTIDs = false;
45 /** @var string|null */
46 protected $sslKeyPath;
47 /** @var string|null */
48 protected $sslCertPath;
49 /** @var string|null */
51 /** @var string[]|null */
52 protected $sslCiphers;
53 /** @var string sql_mode value to send on connection */
55 /** @var bool Use experimental UTF-8 transmission encoding */
58 /** @var string|null */
59 private $serverVersion = null;
62 * Additional $params include:
63 * - lagDetectionMethod : set to one of (Seconds_Behind_Master,pt-heartbeat).
64 * pt-heartbeat assumes the table is at heartbeat.heartbeat
65 * and uses UTC timestamps in the heartbeat.ts column.
66 * (https://www.percona.com/doc/percona-toolkit/2.2/pt-heartbeat.html)
67 * - lagDetectionOptions : if using pt-heartbeat, this can be set to an array map to change
68 * the default behavior. Normally, the heartbeat row with the server
69 * ID of this server's master will be used. Set the "conds" field to
70 * override the query conditions, e.g. ['shard' => 's1'].
71 * - useGTIDs : use GTID methods like MASTER_GTID_WAIT() when possible.
72 * - sslKeyPath : path to key file [default: null]
73 * - sslCertPath : path to certificate file [default: null]
74 * - sslCAPath : parth to certificate authority PEM files [default: null]
75 * - sslCiphers : array list of allowable ciphers [default: null]
76 * @param array $params
78 function __construct( array $params ) {
79 $this->lagDetectionMethod
= isset( $params['lagDetectionMethod'] )
80 ?
$params['lagDetectionMethod']
81 : 'Seconds_Behind_Master';
82 $this->lagDetectionOptions
= isset( $params['lagDetectionOptions'] )
83 ?
$params['lagDetectionOptions']
85 $this->useGTIDs
= !empty( $params['useGTIDs' ] );
86 foreach ( [ 'KeyPath', 'CertPath', 'CAPath', 'Ciphers' ] as $name ) {
88 if ( isset( $params[$var] ) ) {
89 $this->$var = $params[$var];
92 $this->sqlMode
= isset( $params['sqlMode'] ) ?
$params['sqlMode'] : '';
93 $this->utf8Mode
= !empty( $params['utf8Mode'] );
95 parent
::__construct( $params );
101 public function getType() {
106 * @param string $server
107 * @param string $user
108 * @param string $password
109 * @param string $dbName
110 * @throws Exception|DBConnectionError
113 public function open( $server, $user, $password, $dbName ) {
114 # Close/unset connection handle
117 $this->mServer
= $server;
118 $this->mUser
= $user;
119 $this->mPassword
= $password;
120 $this->mDBname
= $dbName;
122 $this->installErrorHandler();
124 $this->mConn
= $this->mysqlConnect( $this->mServer
);
125 } catch ( Exception
$ex ) {
126 $this->restoreErrorHandler();
129 $error = $this->restoreErrorHandler();
131 # Always log connection errors
132 if ( !$this->mConn
) {
134 $error = $this->lastError();
136 $this->connLogger
->error(
137 "Error connecting to {db_server}: {error}",
138 $this->getLogContext( [
139 'method' => __METHOD__
,
143 $this->connLogger
->debug( "DB connection error\n" .
144 "Server: $server, User: $user, Password: " .
145 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
147 $this->reportConnectionError( $error );
150 if ( $dbName != '' ) {
151 MediaWiki\
suppressWarnings();
152 $success = $this->selectDB( $dbName );
153 MediaWiki\restoreWarnings
();
155 $this->queryLogger
->error(
156 "Error selecting database {db_name} on server {db_server}",
157 $this->getLogContext( [
158 'method' => __METHOD__
,
161 $this->queryLogger
->debug(
162 "Error selecting database $dbName on server {$this->mServer}" );
164 $this->reportConnectionError( "Error selecting database $dbName" );
168 // Tell the server what we're communicating with
169 if ( !$this->connectInitCharset() ) {
170 $this->reportConnectionError( "Error setting character set" );
173 // Abstract over any insane MySQL defaults
174 $set = [ 'group_concat_max_len = 262144' ];
175 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
176 if ( is_string( $this->sqlMode
) ) {
177 $set[] = 'sql_mode = ' . $this->addQuotes( $this->sqlMode
);
179 // Set any custom settings defined by site config
180 // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
181 foreach ( $this->mSessionVars
as $var => $val ) {
182 // Escape strings but not numbers to avoid MySQL complaining
183 if ( !is_int( $val ) && !is_float( $val ) ) {
184 $val = $this->addQuotes( $val );
186 $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
190 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
191 $success = $this->doQuery( 'SET ' . implode( ', ', $set ) );
193 $this->queryLogger
->error(
194 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)',
195 $this->getLogContext( [
196 'method' => __METHOD__
,
199 $this->reportConnectionError(
200 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)' );
204 $this->mOpened
= true;
210 * Set the character set information right after connection
213 protected function connectInitCharset() {
214 if ( $this->utf8Mode
) {
215 // Tell the server we're communicating with it in UTF-8.
216 // This may engage various charset conversions.
217 return $this->mysqlSetCharset( 'utf8' );
219 return $this->mysqlSetCharset( 'binary' );
224 * Open a connection to a MySQL server
226 * @param string $realServer
227 * @return mixed Raw connection
228 * @throws DBConnectionError
230 abstract protected function mysqlConnect( $realServer );
233 * Set the character set of the MySQL link
235 * @param string $charset
238 abstract protected function mysqlSetCharset( $charset );
241 * @param ResultWrapper|resource $res
242 * @throws DBUnexpectedError
244 public function freeResult( $res ) {
245 if ( $res instanceof ResultWrapper
) {
248 MediaWiki\
suppressWarnings();
249 $ok = $this->mysqlFreeResult( $res );
250 MediaWiki\restoreWarnings
();
252 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
259 * @param resource $res Raw result
262 abstract protected function mysqlFreeResult( $res );
265 * @param ResultWrapper|resource $res
266 * @return stdClass|bool
267 * @throws DBUnexpectedError
269 public function fetchObject( $res ) {
270 if ( $res instanceof ResultWrapper
) {
273 MediaWiki\
suppressWarnings();
274 $row = $this->mysqlFetchObject( $res );
275 MediaWiki\restoreWarnings
();
277 $errno = $this->lastErrno();
278 // Unfortunately, mysql_fetch_object does not reset the last errno.
279 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
280 // these are the only errors mysql_fetch_object can cause.
281 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
282 if ( $errno == 2000 ||
$errno == 2013 ) {
283 throw new DBUnexpectedError(
285 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
293 * Fetch a result row as an object
295 * @param resource $res Raw result
298 abstract protected function mysqlFetchObject( $res );
301 * @param ResultWrapper|resource $res
303 * @throws DBUnexpectedError
305 public function fetchRow( $res ) {
306 if ( $res instanceof ResultWrapper
) {
309 MediaWiki\
suppressWarnings();
310 $row = $this->mysqlFetchArray( $res );
311 MediaWiki\restoreWarnings
();
313 $errno = $this->lastErrno();
314 // Unfortunately, mysql_fetch_array does not reset the last errno.
315 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
316 // these are the only errors mysql_fetch_array can cause.
317 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
318 if ( $errno == 2000 ||
$errno == 2013 ) {
319 throw new DBUnexpectedError(
321 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
329 * Fetch a result row as an associative and numeric array
331 * @param resource $res Raw result
334 abstract protected function mysqlFetchArray( $res );
337 * @throws DBUnexpectedError
338 * @param ResultWrapper|resource $res
341 function numRows( $res ) {
342 if ( $res instanceof ResultWrapper
) {
345 MediaWiki\
suppressWarnings();
346 $n = $this->mysqlNumRows( $res );
347 MediaWiki\restoreWarnings
();
349 // Unfortunately, mysql_num_rows does not reset the last errno.
350 // We are not checking for any errors here, since
351 // these are no errors mysql_num_rows can cause.
352 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
353 // See https://phabricator.wikimedia.org/T44430
358 * Get number of rows in result
360 * @param resource $res Raw result
363 abstract protected function mysqlNumRows( $res );
366 * @param ResultWrapper|resource $res
369 public function numFields( $res ) {
370 if ( $res instanceof ResultWrapper
) {
374 return $this->mysqlNumFields( $res );
378 * Get number of fields in result
380 * @param resource $res Raw result
383 abstract protected function mysqlNumFields( $res );
386 * @param ResultWrapper|resource $res
390 public function fieldName( $res, $n ) {
391 if ( $res instanceof ResultWrapper
) {
395 return $this->mysqlFieldName( $res, $n );
399 * Get the name of the specified field in a result
401 * @param ResultWrapper|resource $res
405 abstract protected function mysqlFieldName( $res, $n );
408 * mysql_field_type() wrapper
409 * @param ResultWrapper|resource $res
413 public function fieldType( $res, $n ) {
414 if ( $res instanceof ResultWrapper
) {
418 return $this->mysqlFieldType( $res, $n );
422 * Get the type of the specified field in a result
424 * @param ResultWrapper|resource $res
428 abstract protected function mysqlFieldType( $res, $n );
431 * @param ResultWrapper|resource $res
435 public function dataSeek( $res, $row ) {
436 if ( $res instanceof ResultWrapper
) {
440 return $this->mysqlDataSeek( $res, $row );
444 * Move internal result pointer
446 * @param ResultWrapper|resource $res
450 abstract protected function mysqlDataSeek( $res, $row );
455 public function lastError() {
456 if ( $this->mConn
) {
457 # Even if it's non-zero, it can still be invalid
458 MediaWiki\
suppressWarnings();
459 $error = $this->mysqlError( $this->mConn
);
461 $error = $this->mysqlError();
463 MediaWiki\restoreWarnings
();
465 $error = $this->mysqlError();
468 $error .= ' (' . $this->mServer
. ')';
475 * Returns the text of the error message from previous MySQL operation
477 * @param resource $conn Raw connection
480 abstract protected function mysqlError( $conn = null );
483 * @param string $table
484 * @param array $uniqueIndexes
486 * @param string $fname
487 * @return ResultWrapper
489 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
490 return $this->nativeReplace( $table, $rows, $fname );
494 * Estimate rows in dataset
495 * Returns estimated count, based on EXPLAIN output
496 * Takes same arguments as Database::select()
498 * @param string|array $table
499 * @param string|array $vars
500 * @param string|array $conds
501 * @param string $fname
502 * @param string|array $options
505 public function estimateRowCount( $table, $vars = '*', $conds = '',
506 $fname = __METHOD__
, $options = []
508 $options['EXPLAIN'] = true;
509 $res = $this->select( $table, $vars, $conds, $fname, $options );
510 if ( $res === false ) {
513 if ( !$this->numRows( $res ) ) {
518 foreach ( $res as $plan ) {
519 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
525 public function tableExists( $table, $fname = __METHOD__
) {
526 $table = $this->tableName( $table, 'raw' );
527 if ( isset( $this->mSessionTempTables
[$table] ) ) {
528 return true; // already known to exist and won't show in SHOW TABLES anyway
531 // We can't use buildLike() here, because it specifies an escape character
532 // other than the backslash, which is the only one supported by SHOW TABLES
533 $encLike = $this->escapeLikeInternal( $table, '\\' );
535 return $this->query( "SHOW TABLES LIKE '$encLike'", $fname )->numRows() > 0;
539 * @param string $table
540 * @param string $field
541 * @return bool|MySQLField
543 public function fieldInfo( $table, $field ) {
544 $table = $this->tableName( $table );
545 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
549 $n = $this->mysqlNumFields( $res->result
);
550 for ( $i = 0; $i < $n; $i++
) {
551 $meta = $this->mysqlFetchField( $res->result
, $i );
552 if ( $field == $meta->name
) {
553 return new MySQLField( $meta );
561 * Get column information from a result
563 * @param resource $res Raw result
567 abstract protected function mysqlFetchField( $res, $n );
570 * Get information about an index into an object
571 * Returns false if the index does not exist
573 * @param string $table
574 * @param string $index
575 * @param string $fname
576 * @return bool|array|null False or null on failure
578 public function indexInfo( $table, $index, $fname = __METHOD__
) {
579 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
580 # SHOW INDEX should work for 3.x and up:
581 # https://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
582 $table = $this->tableName( $table );
583 $index = $this->indexName( $index );
585 $sql = 'SHOW INDEX FROM ' . $table;
586 $res = $this->query( $sql, $fname );
594 foreach ( $res as $row ) {
595 if ( $row->Key_name
== $index ) {
600 return empty( $result ) ?
false : $result;
607 public function strencode( $s ) {
608 return $this->mysqlRealEscapeString( $s );
615 abstract protected function mysqlRealEscapeString( $s );
617 public function addQuotes( $s ) {
618 if ( is_bool( $s ) ) {
619 // Parent would transform to int, which does not play nice with MySQL type juggling.
620 // When searching for an int in a string column, the strings are cast to int, which
621 // means false would match any string not starting with a number.
622 $s = (string)(int)$s;
624 return parent
::addQuotes( $s );
628 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
633 public function addIdentifierQuotes( $s ) {
634 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
635 // Remove NUL bytes and escape backticks by doubling
636 return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
640 * @param string $name
643 public function isQuotedIdentifier( $name ) {
644 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
647 public function getLag() {
648 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
649 return $this->getLagFromPtHeartbeat();
651 return $this->getLagFromSlaveStatus();
658 protected function getLagDetectionMethod() {
659 return $this->lagDetectionMethod
;
665 protected function getLagFromSlaveStatus() {
666 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
667 $row = $res ?
$res->fetchObject() : false;
668 if ( $row && strval( $row->Seconds_Behind_Master
) !== '' ) {
669 return intval( $row->Seconds_Behind_Master
);
678 protected function getLagFromPtHeartbeat() {
679 $options = $this->lagDetectionOptions
;
681 if ( isset( $options['conds'] ) ) {
682 // Best method for multi-DC setups: use logical channel names
683 $data = $this->getHeartbeatData( $options['conds'] );
685 // Standard method: use master server ID (works with stock pt-heartbeat)
686 $masterInfo = $this->getMasterServerInfo();
687 if ( !$masterInfo ) {
688 $this->queryLogger
->error(
689 "Unable to query master of {db_server} for server ID",
690 $this->getLogContext( [
691 'method' => __METHOD__
695 return false; // could not get master server ID
698 $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
699 $data = $this->getHeartbeatData( $conds );
702 list( $time, $nowUnix ) = $data;
703 if ( $time !== null ) {
704 // @time is in ISO format like "2015-09-25T16:48:10.000510"
705 $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
706 $timeUnix = (int)$dateTime->format( 'U' ) +
$dateTime->format( 'u' ) / 1e6
;
708 return max( $nowUnix - $timeUnix, 0.0 );
711 $this->queryLogger
->error(
712 "Unable to find pt-heartbeat row for {db_server}",
713 $this->getLogContext( [
714 'method' => __METHOD__
721 protected function getMasterServerInfo() {
722 $cache = $this->srvCache
;
723 $key = $cache->makeGlobalKey(
726 // Using one key for all cluster replica DBs is preferable
727 $this->getLBInfo( 'clusterMasterHost' ) ?
: $this->getServer()
730 return $cache->getWithSetCallback(
732 $cache::TTL_INDEFINITE
,
733 function () use ( $cache, $key ) {
734 // Get and leave a lock key in place for a short period
735 if ( !$cache->lock( $key, 0, 10 ) ) {
736 return false; // avoid master connection spike slams
739 $conn = $this->getLazyMasterHandle();
741 return false; // something is misconfigured
744 // Connect to and query the master; catch errors to avoid outages
746 $res = $conn->query( 'SELECT @@server_id AS id', __METHOD__
);
747 $row = $res ?
$res->fetchObject() : false;
748 $id = $row ?
(int)$row->id
: 0;
749 } catch ( DBError
$e ) {
753 // Cache the ID if it was retrieved
754 return $id ?
[ 'serverId' => $id, 'asOf' => time() ] : false;
760 * @param array $conds WHERE clause conditions to find a row
761 * @return array (heartbeat `ts` column value or null, UNIX timestamp) for the newest beat
762 * @see https://www.percona.com/doc/percona-toolkit/2.1/pt-heartbeat.html
764 protected function getHeartbeatData( array $conds ) {
765 // Do not bother starting implicit transactions here
766 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
768 $whereSQL = $this->makeList( $conds, self
::LIST_AND
);
769 // Use ORDER BY for channel based queries since that field might not be UNIQUE.
770 // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
771 // percision field is not supported in MySQL <= 5.5.
773 "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1"
775 $row = $res ?
$res->fetchObject() : false;
777 $this->restoreFlags();
780 return [ $row ?
$row->ts
: null, microtime( true ) ];
783 protected function getApproximateLagStatus() {
784 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
785 // Disable caching since this is fast enough and we don't wan't
786 // to be *too* pessimistic by having both the cache TTL and the
787 // pt-heartbeat interval count as lag in getSessionLagStatus()
788 return parent
::getApproximateLagStatus();
791 $key = $this->srvCache
->makeGlobalKey( 'mysql-lag', $this->getServer() );
792 $approxLag = $this->srvCache
->get( $key );
794 $approxLag = parent
::getApproximateLagStatus();
795 $this->srvCache
->set( $key, $approxLag, 1 );
801 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
802 if ( !( $pos instanceof MySQLMasterPos
) ) {
803 throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
806 if ( $this->getLBInfo( 'is static' ) === true ) {
807 return 0; // this is a copy of a read-only dataset with no master DB
808 } elseif ( $this->lastKnownReplicaPos
&& $this->lastKnownReplicaPos
->hasReached( $pos ) ) {
809 return 0; // already reached this point for sure
812 // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
813 if ( $this->useGTIDs
&& $pos->gtids
) {
814 // Wait on the GTID set (MariaDB only)
815 $gtidArg = $this->addQuotes( implode( ',', $pos->gtids
) );
816 $res = $this->doQuery( "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)" );
818 // Wait on the binlog coordinates
819 $encFile = $this->addQuotes( $pos->file
);
820 $encPos = intval( $pos->pos
);
821 $res = $this->doQuery( "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)" );
824 $row = $res ?
$this->fetchRow( $res ) : false;
826 throw new DBExpectedError( $this,
827 "MASTER_POS_WAIT() or MASTER_GTID_WAIT() failed: {$this->lastError()}" );
830 // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
831 $status = ( $row[0] !== null ) ?
intval( $row[0] ) : null;
832 if ( $status === null ) {
833 // T126436: jobs programmed to wait on master positions might be referencing binlogs
834 // with an old master hostname. Such calls make MASTER_POS_WAIT() return null. Try
835 // to detect this and treat the replica DB as having reached the position; a proper master
836 // switchover already requires that the new master be caught up before the switch.
837 $replicationPos = $this->getReplicaPos();
838 if ( $replicationPos && !$replicationPos->channelsMatch( $pos ) ) {
839 $this->lastKnownReplicaPos
= $replicationPos;
842 } elseif ( $status >= 0 ) {
843 // Remember that this position was reached to save queries next time
844 $this->lastKnownReplicaPos
= $pos;
851 * Get the position of the master from SHOW SLAVE STATUS
853 * @return MySQLMasterPos|bool
855 public function getReplicaPos() {
856 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
857 $row = $this->fetchObject( $res );
860 $pos = isset( $row->Exec_master_log_pos
)
861 ?
$row->Exec_master_log_pos
862 : $row->Exec_Master_Log_Pos
;
863 // Also fetch the last-applied GTID set (MariaDB)
864 if ( $this->useGTIDs
) {
865 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_slave_pos'", __METHOD__
);
866 $gtidRow = $this->fetchObject( $res );
867 $gtidSet = $gtidRow ?
$gtidRow->Value
: '';
872 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos, $gtidSet );
879 * Get the position of the master from SHOW MASTER STATUS
881 * @return MySQLMasterPos|bool
883 public function getMasterPos() {
884 $res = $this->query( 'SHOW MASTER STATUS', __METHOD__
);
885 $row = $this->fetchObject( $res );
888 // Also fetch the last-written GTID set (MariaDB)
889 if ( $this->useGTIDs
) {
890 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_binlog_pos'", __METHOD__
);
891 $gtidRow = $this->fetchObject( $res );
892 $gtidSet = $gtidRow ?
$gtidRow->Value
: '';
897 return new MySQLMasterPos( $row->File
, $row->Position
, $gtidSet );
903 public function serverIsReadOnly() {
904 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'read_only'", __METHOD__
);
905 $row = $this->fetchObject( $res );
907 return $row ?
( strtolower( $row->Value
) === 'on' ) : false;
911 * @param string $index
914 function useIndexClause( $index ) {
915 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
919 * @param string $index
922 function ignoreIndexClause( $index ) {
923 return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
929 function lowPriorityOption() {
930 return 'LOW_PRIORITY';
936 public function getSoftwareLink() {
937 // MariaDB includes its name in its version string; this is how MariaDB's version of
938 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
939 // in libmysql/libmysql.c).
940 $version = $this->getServerVersion();
941 if ( strpos( $version, 'MariaDB' ) !== false ||
strpos( $version, '-maria-' ) !== false ) {
942 return '[{{int:version-db-mariadb-url}} MariaDB]';
945 // Percona Server's version suffix is not very distinctive, and @@version_comment
946 // doesn't give the necessary info for source builds, so assume the server is MySQL.
947 // (Even Percona's version of mysql doesn't try to make the distinction.)
948 return '[{{int:version-db-mysql-url}} MySQL]';
954 public function getServerVersion() {
955 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
956 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
957 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
958 if ( $this->serverVersion
=== null ) {
959 $this->serverVersion
= $this->selectField( '', 'VERSION()', '', __METHOD__
);
961 return $this->serverVersion
;
965 * @param array $options
967 public function setSessionOptions( array $options ) {
968 if ( isset( $options['connTimeout'] ) ) {
969 $timeout = (int)$options['connTimeout'];
970 $this->query( "SET net_read_timeout=$timeout" );
971 $this->query( "SET net_write_timeout=$timeout" );
977 * @param string $newLine
980 public function streamStatementEnd( &$sql, &$newLine ) {
981 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
982 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
983 $this->delimiter
= $m[1];
987 return parent
::streamStatementEnd( $sql, $newLine );
991 * Check to see if a named lock is available. This is non-blocking.
993 * @param string $lockName Name of lock to poll
994 * @param string $method Name of method calling us
998 public function lockIsFree( $lockName, $method ) {
999 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1000 $result = $this->query( "SELECT IS_FREE_LOCK($encName) AS lockstatus", $method );
1001 $row = $this->fetchObject( $result );
1003 return ( $row->lockstatus
== 1 );
1007 * @param string $lockName
1008 * @param string $method
1009 * @param int $timeout
1012 public function lock( $lockName, $method, $timeout = 5 ) {
1013 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1014 $result = $this->query( "SELECT GET_LOCK($encName, $timeout) AS lockstatus", $method );
1015 $row = $this->fetchObject( $result );
1017 if ( $row->lockstatus
== 1 ) {
1018 parent
::lock( $lockName, $method, $timeout ); // record
1022 $this->queryLogger
->warning( __METHOD__
. " failed to acquire lock '$lockName'\n" );
1029 * https://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
1030 * @param string $lockName
1031 * @param string $method
1034 public function unlock( $lockName, $method ) {
1035 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1036 $result = $this->query( "SELECT RELEASE_LOCK($encName) as lockstatus", $method );
1037 $row = $this->fetchObject( $result );
1039 if ( $row->lockstatus
== 1 ) {
1040 parent
::unlock( $lockName, $method ); // record
1044 $this->queryLogger
->warning( __METHOD__
. " failed to release lock '$lockName'\n" );
1049 private function makeLockName( $lockName ) {
1050 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1051 // Newer version enforce a 64 char length limit.
1052 return ( strlen( $lockName ) > 64 ) ?
sha1( $lockName ) : $lockName;
1055 public function namedLocksEnqueue() {
1060 * @param array $read
1061 * @param array $write
1062 * @param string $method
1063 * @param bool $lowPriority
1066 public function lockTables( $read, $write, $method, $lowPriority = true ) {
1069 foreach ( $write as $table ) {
1070 $tbl = $this->tableName( $table ) .
1071 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
1075 foreach ( $read as $table ) {
1076 $items[] = $this->tableName( $table ) . ' READ';
1078 $sql = "LOCK TABLES " . implode( ',', $items );
1079 $this->query( $sql, $method );
1085 * @param string $method
1088 public function unlockTables( $method ) {
1089 $this->query( "UNLOCK TABLES", $method );
1095 * @param bool $value
1097 public function setBigSelects( $value = true ) {
1098 if ( $value === 'default' ) {
1099 if ( $this->mDefaultBigSelects
=== null ) {
1100 # Function hasn't been called before so it must already be set to the default
1103 $value = $this->mDefaultBigSelects
;
1105 } elseif ( $this->mDefaultBigSelects
=== null ) {
1106 $this->mDefaultBigSelects
=
1107 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__
);
1109 $encValue = $value ?
'1' : '0';
1110 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
1114 * DELETE where the condition is a join. MySql uses multi-table deletes.
1115 * @param string $delTable
1116 * @param string $joinTable
1117 * @param string $delVar
1118 * @param string $joinVar
1119 * @param array|string $conds
1120 * @param bool|string $fname
1121 * @throws DBUnexpectedError
1122 * @return bool|ResultWrapper
1124 public function deleteJoin(
1125 $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
1128 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
1131 $delTable = $this->tableName( $delTable );
1132 $joinTable = $this->tableName( $joinTable );
1133 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1135 if ( $conds != '*' ) {
1136 $sql .= ' AND ' . $this->makeList( $conds, self
::LIST_AND
);
1139 return $this->query( $sql, $fname );
1143 * @param string $table
1144 * @param array $rows
1145 * @param array $uniqueIndexes
1147 * @param string $fname
1150 public function upsert( $table, array $rows, array $uniqueIndexes,
1151 array $set, $fname = __METHOD__
1153 if ( !count( $rows ) ) {
1154 return true; // nothing to do
1157 if ( !is_array( reset( $rows ) ) ) {
1161 $table = $this->tableName( $table );
1162 $columns = array_keys( $rows[0] );
1164 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1166 foreach ( $rows as $row ) {
1167 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1169 $sql .= implode( ',', $rowTuples );
1170 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, self
::LIST_SET
);
1172 return (bool)$this->query( $sql, $fname );
1176 * Determines how long the server has been up
1180 public function getServerUptime() {
1181 $vars = $this->getMysqlStatus( 'Uptime' );
1183 return (int)$vars['Uptime'];
1187 * Determines if the last failure was due to a deadlock
1191 public function wasDeadlock() {
1192 return $this->lastErrno() == 1213;
1196 * Determines if the last failure was due to a lock timeout
1200 public function wasLockTimeout() {
1201 return $this->lastErrno() == 1205;
1204 public function wasErrorReissuable() {
1205 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
1209 * Determines if the last failure was due to the database being read-only.
1213 public function wasReadOnlyError() {
1214 return $this->lastErrno() == 1223 ||
1215 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1218 public function wasConnectionError( $errno ) {
1219 return $errno == 2013 ||
$errno == 2006;
1223 * @param string $oldName
1224 * @param string $newName
1225 * @param bool $temporary
1226 * @param string $fname
1229 public function duplicateTableStructure(
1230 $oldName, $newName, $temporary = false, $fname = __METHOD__
1232 $tmp = $temporary ?
'TEMPORARY ' : '';
1233 $newName = $this->addIdentifierQuotes( $newName );
1234 $oldName = $this->addIdentifierQuotes( $oldName );
1235 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1237 return $this->query( $query, $fname );
1241 * List all tables on the database
1243 * @param string $prefix Only show tables with this prefix, e.g. mw_
1244 * @param string $fname Calling function name
1247 public function listTables( $prefix = null, $fname = __METHOD__
) {
1248 $result = $this->query( "SHOW TABLES", $fname );
1252 foreach ( $result as $table ) {
1253 $vars = get_object_vars( $table );
1254 $table = array_pop( $vars );
1256 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1257 $endArray[] = $table;
1265 * @param string $tableName
1266 * @param string $fName
1267 * @return bool|ResultWrapper
1269 public function dropTable( $tableName, $fName = __METHOD__
) {
1270 if ( !$this->tableExists( $tableName, $fName ) ) {
1274 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1278 * Get status information from SHOW STATUS in an associative array
1280 * @param string $which
1283 private function getMysqlStatus( $which = "%" ) {
1284 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1287 foreach ( $res as $row ) {
1288 $status[$row->Variable_name
] = $row->Value
;
1295 * Lists VIEWs in the database
1297 * @param string $prefix Only show VIEWs with this prefix, eg.
1298 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1299 * @param string $fname Name of calling function
1303 public function listViews( $prefix = null, $fname = __METHOD__
) {
1304 // The name of the column containing the name of the VIEW
1305 $propertyName = 'Tables_in_' . $this->mDBname
;
1307 // Query for the VIEWS
1308 $res = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1310 foreach ( $res as $row ) {
1311 array_push( $allViews, $row->$propertyName );
1314 if ( is_null( $prefix ) ||
$prefix === '' ) {
1318 $filteredViews = [];
1319 foreach ( $allViews as $viewName ) {
1320 // Does the name of this VIEW start with the table-prefix?
1321 if ( strpos( $viewName, $prefix ) === 0 ) {
1322 array_push( $filteredViews, $viewName );
1326 return $filteredViews;
1330 * Differentiates between a TABLE and a VIEW.
1332 * @param string $name Name of the TABLE/VIEW to test
1333 * @param string $prefix
1337 public function isView( $name, $prefix = null ) {
1338 return in_array( $name, $this->listViews( $prefix ) );