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 $encLike = $this->buildLike( $table );
533 return $this->query( "SHOW TABLES $encLike", $fname )->numRows() > 0;
537 * @param string $table
538 * @param string $field
539 * @return bool|MySQLField
541 public function fieldInfo( $table, $field ) {
542 $table = $this->tableName( $table );
543 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
547 $n = $this->mysqlNumFields( $res->result
);
548 for ( $i = 0; $i < $n; $i++
) {
549 $meta = $this->mysqlFetchField( $res->result
, $i );
550 if ( $field == $meta->name
) {
551 return new MySQLField( $meta );
559 * Get column information from a result
561 * @param resource $res Raw result
565 abstract protected function mysqlFetchField( $res, $n );
568 * Get information about an index into an object
569 * Returns false if the index does not exist
571 * @param string $table
572 * @param string $index
573 * @param string $fname
574 * @return bool|array|null False or null on failure
576 public function indexInfo( $table, $index, $fname = __METHOD__
) {
577 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
578 # SHOW INDEX should work for 3.x and up:
579 # https://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
580 $table = $this->tableName( $table );
581 $index = $this->indexName( $index );
583 $sql = 'SHOW INDEX FROM ' . $table;
584 $res = $this->query( $sql, $fname );
592 foreach ( $res as $row ) {
593 if ( $row->Key_name
== $index ) {
598 return empty( $result ) ?
false : $result;
605 public function strencode( $s ) {
606 return $this->mysqlRealEscapeString( $s );
613 abstract protected function mysqlRealEscapeString( $s );
615 public function addQuotes( $s ) {
616 if ( is_bool( $s ) ) {
617 // Parent would transform to int, which does not play nice with MySQL type juggling.
618 // When searching for an int in a string column, the strings are cast to int, which
619 // means false would match any string not starting with a number.
620 $s = (string)(int)$s;
622 return parent
::addQuotes( $s );
626 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
631 public function addIdentifierQuotes( $s ) {
632 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
633 // Remove NUL bytes and escape backticks by doubling
634 return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
638 * @param string $name
641 public function isQuotedIdentifier( $name ) {
642 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
645 public function getLag() {
646 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
647 return $this->getLagFromPtHeartbeat();
649 return $this->getLagFromSlaveStatus();
656 protected function getLagDetectionMethod() {
657 return $this->lagDetectionMethod
;
663 protected function getLagFromSlaveStatus() {
664 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
665 $row = $res ?
$res->fetchObject() : false;
666 if ( $row && strval( $row->Seconds_Behind_Master
) !== '' ) {
667 return intval( $row->Seconds_Behind_Master
);
676 protected function getLagFromPtHeartbeat() {
677 $options = $this->lagDetectionOptions
;
679 if ( isset( $options['conds'] ) ) {
680 // Best method for multi-DC setups: use logical channel names
681 $data = $this->getHeartbeatData( $options['conds'] );
683 // Standard method: use master server ID (works with stock pt-heartbeat)
684 $masterInfo = $this->getMasterServerInfo();
685 if ( !$masterInfo ) {
686 $this->queryLogger
->error(
687 "Unable to query master of {db_server} for server ID",
688 $this->getLogContext( [
689 'method' => __METHOD__
693 return false; // could not get master server ID
696 $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
697 $data = $this->getHeartbeatData( $conds );
700 list( $time, $nowUnix ) = $data;
701 if ( $time !== null ) {
702 // @time is in ISO format like "2015-09-25T16:48:10.000510"
703 $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
704 $timeUnix = (int)$dateTime->format( 'U' ) +
$dateTime->format( 'u' ) / 1e6
;
706 return max( $nowUnix - $timeUnix, 0.0 );
709 $this->queryLogger
->error(
710 "Unable to find pt-heartbeat row for {db_server}",
711 $this->getLogContext( [
712 'method' => __METHOD__
719 protected function getMasterServerInfo() {
720 $cache = $this->srvCache
;
721 $key = $cache->makeGlobalKey(
724 // Using one key for all cluster replica DBs is preferable
725 $this->getLBInfo( 'clusterMasterHost' ) ?
: $this->getServer()
728 return $cache->getWithSetCallback(
730 $cache::TTL_INDEFINITE
,
731 function () use ( $cache, $key ) {
732 // Get and leave a lock key in place for a short period
733 if ( !$cache->lock( $key, 0, 10 ) ) {
734 return false; // avoid master connection spike slams
737 $conn = $this->getLazyMasterHandle();
739 return false; // something is misconfigured
742 // Connect to and query the master; catch errors to avoid outages
744 $res = $conn->query( 'SELECT @@server_id AS id', __METHOD__
);
745 $row = $res ?
$res->fetchObject() : false;
746 $id = $row ?
(int)$row->id
: 0;
747 } catch ( DBError
$e ) {
751 // Cache the ID if it was retrieved
752 return $id ?
[ 'serverId' => $id, 'asOf' => time() ] : false;
758 * @param array $conds WHERE clause conditions to find a row
759 * @return array (heartbeat `ts` column value or null, UNIX timestamp) for the newest beat
760 * @see https://www.percona.com/doc/percona-toolkit/2.1/pt-heartbeat.html
762 protected function getHeartbeatData( array $conds ) {
763 // Do not bother starting implicit transactions here
764 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
766 $whereSQL = $this->makeList( $conds, self
::LIST_AND
);
767 // Use ORDER BY for channel based queries since that field might not be UNIQUE.
768 // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
769 // percision field is not supported in MySQL <= 5.5.
771 "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1"
773 $row = $res ?
$res->fetchObject() : false;
775 $this->restoreFlags();
778 return [ $row ?
$row->ts
: null, microtime( true ) ];
781 protected function getApproximateLagStatus() {
782 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
783 // Disable caching since this is fast enough and we don't wan't
784 // to be *too* pessimistic by having both the cache TTL and the
785 // pt-heartbeat interval count as lag in getSessionLagStatus()
786 return parent
::getApproximateLagStatus();
789 $key = $this->srvCache
->makeGlobalKey( 'mysql-lag', $this->getServer() );
790 $approxLag = $this->srvCache
->get( $key );
792 $approxLag = parent
::getApproximateLagStatus();
793 $this->srvCache
->set( $key, $approxLag, 1 );
799 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
800 if ( !( $pos instanceof MySQLMasterPos
) ) {
801 throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
804 if ( $this->getLBInfo( 'is static' ) === true ) {
805 return 0; // this is a copy of a read-only dataset with no master DB
806 } elseif ( $this->lastKnownReplicaPos
&& $this->lastKnownReplicaPos
->hasReached( $pos ) ) {
807 return 0; // already reached this point for sure
810 // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
811 if ( $this->useGTIDs
&& $pos->gtids
) {
812 // Wait on the GTID set (MariaDB only)
813 $gtidArg = $this->addQuotes( implode( ',', $pos->gtids
) );
814 $res = $this->doQuery( "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)" );
816 // Wait on the binlog coordinates
817 $encFile = $this->addQuotes( $pos->file
);
818 $encPos = intval( $pos->pos
);
819 $res = $this->doQuery( "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)" );
822 $row = $res ?
$this->fetchRow( $res ) : false;
824 throw new DBExpectedError( $this, "Failed to query MASTER_POS_WAIT()" );
827 // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
828 $status = ( $row[0] !== null ) ?
intval( $row[0] ) : null;
829 if ( $status === null ) {
830 // T126436: jobs programmed to wait on master positions might be referencing binlogs
831 // with an old master hostname. Such calls make MASTER_POS_WAIT() return null. Try
832 // to detect this and treat the replica DB as having reached the position; a proper master
833 // switchover already requires that the new master be caught up before the switch.
834 $replicationPos = $this->getReplicaPos();
835 if ( $replicationPos && !$replicationPos->channelsMatch( $pos ) ) {
836 $this->lastKnownReplicaPos
= $replicationPos;
839 } elseif ( $status >= 0 ) {
840 // Remember that this position was reached to save queries next time
841 $this->lastKnownReplicaPos
= $pos;
848 * Get the position of the master from SHOW SLAVE STATUS
850 * @return MySQLMasterPos|bool
852 public function getReplicaPos() {
853 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
854 $row = $this->fetchObject( $res );
857 $pos = isset( $row->Exec_master_log_pos
)
858 ?
$row->Exec_master_log_pos
859 : $row->Exec_Master_Log_Pos
;
860 // Also fetch the last-applied GTID set (MariaDB)
861 if ( $this->useGTIDs
) {
862 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_slave_pos'", __METHOD__
);
863 $gtidRow = $this->fetchObject( $res );
864 $gtidSet = $gtidRow ?
$gtidRow->Value
: '';
869 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos, $gtidSet );
876 * Get the position of the master from SHOW MASTER STATUS
878 * @return MySQLMasterPos|bool
880 public function getMasterPos() {
881 $res = $this->query( 'SHOW MASTER STATUS', __METHOD__
);
882 $row = $this->fetchObject( $res );
885 // Also fetch the last-written GTID set (MariaDB)
886 if ( $this->useGTIDs
) {
887 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_binlog_pos'", __METHOD__
);
888 $gtidRow = $this->fetchObject( $res );
889 $gtidSet = $gtidRow ?
$gtidRow->Value
: '';
894 return new MySQLMasterPos( $row->File
, $row->Position
, $gtidSet );
900 public function serverIsReadOnly() {
901 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'read_only'", __METHOD__
);
902 $row = $this->fetchObject( $res );
904 return $row ?
( strtolower( $row->Value
) === 'on' ) : false;
908 * @param string $index
911 function useIndexClause( $index ) {
912 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
916 * @param string $index
919 function ignoreIndexClause( $index ) {
920 return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
926 function lowPriorityOption() {
927 return 'LOW_PRIORITY';
933 public function getSoftwareLink() {
934 // MariaDB includes its name in its version string; this is how MariaDB's version of
935 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
936 // in libmysql/libmysql.c).
937 $version = $this->getServerVersion();
938 if ( strpos( $version, 'MariaDB' ) !== false ||
strpos( $version, '-maria-' ) !== false ) {
939 return '[{{int:version-db-mariadb-url}} MariaDB]';
942 // Percona Server's version suffix is not very distinctive, and @@version_comment
943 // doesn't give the necessary info for source builds, so assume the server is MySQL.
944 // (Even Percona's version of mysql doesn't try to make the distinction.)
945 return '[{{int:version-db-mysql-url}} MySQL]';
951 public function getServerVersion() {
952 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
953 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
954 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
955 if ( $this->serverVersion
=== null ) {
956 $this->serverVersion
= $this->selectField( '', 'VERSION()', '', __METHOD__
);
958 return $this->serverVersion
;
962 * @param array $options
964 public function setSessionOptions( array $options ) {
965 if ( isset( $options['connTimeout'] ) ) {
966 $timeout = (int)$options['connTimeout'];
967 $this->query( "SET net_read_timeout=$timeout" );
968 $this->query( "SET net_write_timeout=$timeout" );
974 * @param string $newLine
977 public function streamStatementEnd( &$sql, &$newLine ) {
978 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
979 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
980 $this->delimiter
= $m[1];
984 return parent
::streamStatementEnd( $sql, $newLine );
988 * Check to see if a named lock is available. This is non-blocking.
990 * @param string $lockName Name of lock to poll
991 * @param string $method Name of method calling us
995 public function lockIsFree( $lockName, $method ) {
996 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
997 $result = $this->query( "SELECT IS_FREE_LOCK($encName) AS lockstatus", $method );
998 $row = $this->fetchObject( $result );
1000 return ( $row->lockstatus
== 1 );
1004 * @param string $lockName
1005 * @param string $method
1006 * @param int $timeout
1009 public function lock( $lockName, $method, $timeout = 5 ) {
1010 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1011 $result = $this->query( "SELECT GET_LOCK($encName, $timeout) AS lockstatus", $method );
1012 $row = $this->fetchObject( $result );
1014 if ( $row->lockstatus
== 1 ) {
1015 parent
::lock( $lockName, $method, $timeout ); // record
1019 $this->queryLogger
->warning( __METHOD__
. " failed to acquire lock '$lockName'\n" );
1026 * https://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
1027 * @param string $lockName
1028 * @param string $method
1031 public function unlock( $lockName, $method ) {
1032 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1033 $result = $this->query( "SELECT RELEASE_LOCK($encName) as lockstatus", $method );
1034 $row = $this->fetchObject( $result );
1036 if ( $row->lockstatus
== 1 ) {
1037 parent
::unlock( $lockName, $method ); // record
1041 $this->queryLogger
->warning( __METHOD__
. " failed to release lock '$lockName'\n" );
1046 private function makeLockName( $lockName ) {
1047 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1048 // Newer version enforce a 64 char length limit.
1049 return ( strlen( $lockName ) > 64 ) ?
sha1( $lockName ) : $lockName;
1052 public function namedLocksEnqueue() {
1057 * @param array $read
1058 * @param array $write
1059 * @param string $method
1060 * @param bool $lowPriority
1063 public function lockTables( $read, $write, $method, $lowPriority = true ) {
1066 foreach ( $write as $table ) {
1067 $tbl = $this->tableName( $table ) .
1068 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
1072 foreach ( $read as $table ) {
1073 $items[] = $this->tableName( $table ) . ' READ';
1075 $sql = "LOCK TABLES " . implode( ',', $items );
1076 $this->query( $sql, $method );
1082 * @param string $method
1085 public function unlockTables( $method ) {
1086 $this->query( "UNLOCK TABLES", $method );
1092 * @param bool $value
1094 public function setBigSelects( $value = true ) {
1095 if ( $value === 'default' ) {
1096 if ( $this->mDefaultBigSelects
=== null ) {
1097 # Function hasn't been called before so it must already be set to the default
1100 $value = $this->mDefaultBigSelects
;
1102 } elseif ( $this->mDefaultBigSelects
=== null ) {
1103 $this->mDefaultBigSelects
=
1104 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__
);
1106 $encValue = $value ?
'1' : '0';
1107 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
1111 * DELETE where the condition is a join. MySql uses multi-table deletes.
1112 * @param string $delTable
1113 * @param string $joinTable
1114 * @param string $delVar
1115 * @param string $joinVar
1116 * @param array|string $conds
1117 * @param bool|string $fname
1118 * @throws DBUnexpectedError
1119 * @return bool|ResultWrapper
1121 public function deleteJoin(
1122 $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
1125 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
1128 $delTable = $this->tableName( $delTable );
1129 $joinTable = $this->tableName( $joinTable );
1130 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1132 if ( $conds != '*' ) {
1133 $sql .= ' AND ' . $this->makeList( $conds, self
::LIST_AND
);
1136 return $this->query( $sql, $fname );
1140 * @param string $table
1141 * @param array $rows
1142 * @param array $uniqueIndexes
1144 * @param string $fname
1147 public function upsert( $table, array $rows, array $uniqueIndexes,
1148 array $set, $fname = __METHOD__
1150 if ( !count( $rows ) ) {
1151 return true; // nothing to do
1154 if ( !is_array( reset( $rows ) ) ) {
1158 $table = $this->tableName( $table );
1159 $columns = array_keys( $rows[0] );
1161 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1163 foreach ( $rows as $row ) {
1164 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1166 $sql .= implode( ',', $rowTuples );
1167 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, self
::LIST_SET
);
1169 return (bool)$this->query( $sql, $fname );
1173 * Determines how long the server has been up
1177 public function getServerUptime() {
1178 $vars = $this->getMysqlStatus( 'Uptime' );
1180 return (int)$vars['Uptime'];
1184 * Determines if the last failure was due to a deadlock
1188 public function wasDeadlock() {
1189 return $this->lastErrno() == 1213;
1193 * Determines if the last failure was due to a lock timeout
1197 public function wasLockTimeout() {
1198 return $this->lastErrno() == 1205;
1201 public function wasErrorReissuable() {
1202 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
1206 * Determines if the last failure was due to the database being read-only.
1210 public function wasReadOnlyError() {
1211 return $this->lastErrno() == 1223 ||
1212 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1215 public function wasConnectionError( $errno ) {
1216 return $errno == 2013 ||
$errno == 2006;
1220 * @param string $oldName
1221 * @param string $newName
1222 * @param bool $temporary
1223 * @param string $fname
1226 public function duplicateTableStructure(
1227 $oldName, $newName, $temporary = false, $fname = __METHOD__
1229 $tmp = $temporary ?
'TEMPORARY ' : '';
1230 $newName = $this->addIdentifierQuotes( $newName );
1231 $oldName = $this->addIdentifierQuotes( $oldName );
1232 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1234 return $this->query( $query, $fname );
1238 * List all tables on the database
1240 * @param string $prefix Only show tables with this prefix, e.g. mw_
1241 * @param string $fname Calling function name
1244 public function listTables( $prefix = null, $fname = __METHOD__
) {
1245 $result = $this->query( "SHOW TABLES", $fname );
1249 foreach ( $result as $table ) {
1250 $vars = get_object_vars( $table );
1251 $table = array_pop( $vars );
1253 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1254 $endArray[] = $table;
1262 * @param string $tableName
1263 * @param string $fName
1264 * @return bool|ResultWrapper
1266 public function dropTable( $tableName, $fName = __METHOD__
) {
1267 if ( !$this->tableExists( $tableName, $fName ) ) {
1271 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1275 * Get status information from SHOW STATUS in an associative array
1277 * @param string $which
1280 private function getMysqlStatus( $which = "%" ) {
1281 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1284 foreach ( $res as $row ) {
1285 $status[$row->Variable_name
] = $row->Value
;
1292 * Lists VIEWs in the database
1294 * @param string $prefix Only show VIEWs with this prefix, eg.
1295 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1296 * @param string $fname Name of calling function
1300 public function listViews( $prefix = null, $fname = __METHOD__
) {
1301 // The name of the column containing the name of the VIEW
1302 $propertyName = 'Tables_in_' . $this->mDBname
;
1304 // Query for the VIEWS
1305 $res = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1307 foreach ( $res as $row ) {
1308 array_push( $allViews, $row->$propertyName );
1311 if ( is_null( $prefix ) ||
$prefix === '' ) {
1315 $filteredViews = [];
1316 foreach ( $allViews as $viewName ) {
1317 // Does the name of this VIEW start with the table-prefix?
1318 if ( strpos( $viewName, $prefix ) === 0 ) {
1319 array_push( $filteredViews, $viewName );
1323 return $filteredViews;
1327 * Differentiates between a TABLE and a VIEW.
1329 * @param string $name Name of the TABLE/VIEW to test
1330 * @param string $prefix
1334 public function isView( $name, $prefix = null ) {
1335 return in_array( $name, $this->listViews( $prefix ) );