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
25 * Database abstraction object for MySQL.
26 * Defines methods independent on used MySQL extension.
32 abstract class DatabaseMysqlBase
extends DatabaseBase
{
33 /** @var MysqlMasterPos */
34 protected $lastKnownReplicaPos;
35 /** @var string Method to detect replica DB lag */
36 protected $lagDetectionMethod;
37 /** @var array Method to detect replica DB lag */
38 protected $lagDetectionOptions = [];
39 /** @var bool bool Whether to use GTID methods */
40 protected $useGTIDs = false;
41 /** @var string|null */
42 protected $sslKeyPath;
43 /** @var string|null */
44 protected $sslCertPath;
45 /** @var string|null */
47 /** @var string[]|null */
48 protected $sslCiphers;
49 /** @var string sql_mode value to send on connection */
51 /** @var bool Use experimental UTF-8 transmission encoding */
54 /** @var string|null */
55 private $serverVersion = null;
58 * Additional $params include:
59 * - lagDetectionMethod : set to one of (Seconds_Behind_Master,pt-heartbeat).
60 * pt-heartbeat assumes the table is at heartbeat.heartbeat
61 * and uses UTC timestamps in the heartbeat.ts column.
62 * (https://www.percona.com/doc/percona-toolkit/2.2/pt-heartbeat.html)
63 * - lagDetectionOptions : if using pt-heartbeat, this can be set to an array map to change
64 * the default behavior. Normally, the heartbeat row with the server
65 * ID of this server's master will be used. Set the "conds" field to
66 * override the query conditions, e.g. ['shard' => 's1'].
67 * - useGTIDs : use GTID methods like MASTER_GTID_WAIT() when possible.
68 * - sslKeyPath : path to key file [default: null]
69 * - sslCertPath : path to certificate file [default: null]
70 * - sslCAPath : parth to certificate authority PEM files [default: null]
71 * - sslCiphers : array list of allowable ciphers [default: null]
72 * @param array $params
74 function __construct( array $params ) {
75 parent
::__construct( $params );
77 $this->lagDetectionMethod
= isset( $params['lagDetectionMethod'] )
78 ?
$params['lagDetectionMethod']
79 : 'Seconds_Behind_Master';
80 $this->lagDetectionOptions
= isset( $params['lagDetectionOptions'] )
81 ?
$params['lagDetectionOptions']
83 $this->useGTIDs
= !empty( $params['useGTIDs' ] );
84 foreach ( [ 'KeyPath', 'CertPath', 'CAPath', 'Ciphers' ] as $name ) {
86 if ( isset( $params[$var] ) ) {
87 $this->$var = $params[$var];
90 $this->sqlMode
= isset( $params['sqlMode'] ) ?
$params['sqlMode'] : '';
91 $this->utf8Mode
= !empty( $params['utf8Mode'] );
102 * @param string $server
103 * @param string $user
104 * @param string $password
105 * @param string $dbName
106 * @throws Exception|DBConnectionError
109 function open( $server, $user, $password, $dbName ) {
110 # Close/unset connection handle
113 $this->mServer
= $server;
114 $this->mUser
= $user;
115 $this->mPassword
= $password;
116 $this->mDBname
= $dbName;
118 $this->installErrorHandler();
120 $this->mConn
= $this->mysqlConnect( $this->mServer
);
121 } catch ( Exception
$ex ) {
122 $this->restoreErrorHandler();
125 $error = $this->restoreErrorHandler();
127 # Always log connection errors
128 if ( !$this->mConn
) {
130 $error = $this->lastError();
132 $this->queryLogger
->error(
133 "Error connecting to {db_server}: {error}",
134 $this->getLogContext( [
135 'method' => __METHOD__
,
139 $this->queryLogger
->debug( "DB connection error\n" .
140 "Server: $server, User: $user, Password: " .
141 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
143 $this->reportConnectionError( $error );
146 if ( $dbName != '' ) {
147 MediaWiki\
suppressWarnings();
148 $success = $this->selectDB( $dbName );
149 MediaWiki\restoreWarnings
();
151 $this->queryLogger
->error(
152 "Error selecting database {db_name} on server {db_server}",
153 $this->getLogContext( [
154 'method' => __METHOD__
,
157 $this->queryLogger
->debug(
158 "Error selecting database $dbName on server {$this->mServer}" );
160 $this->reportConnectionError( "Error selecting database $dbName" );
164 // Tell the server what we're communicating with
165 if ( !$this->connectInitCharset() ) {
166 $this->reportConnectionError( "Error setting character set" );
169 // Abstract over any insane MySQL defaults
170 $set = [ 'group_concat_max_len = 262144' ];
171 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
172 if ( is_string( $this->sqlMode
) ) {
173 $set[] = 'sql_mode = ' . $this->addQuotes( $this->sqlMode
);
175 // Set any custom settings defined by site config
176 // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
177 foreach ( $this->mSessionVars
as $var => $val ) {
178 // Escape strings but not numbers to avoid MySQL complaining
179 if ( !is_int( $val ) && !is_float( $val ) ) {
180 $val = $this->addQuotes( $val );
182 $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
186 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
187 $success = $this->doQuery( 'SET ' . implode( ', ', $set ) );
189 $this->queryLogger
->error(
190 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)',
191 $this->getLogContext( [
192 'method' => __METHOD__
,
195 $this->reportConnectionError(
196 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)' );
200 $this->mOpened
= true;
206 * Set the character set information right after connection
209 protected function connectInitCharset() {
210 if ( $this->utf8Mode
) {
211 // Tell the server we're communicating with it in UTF-8.
212 // This may engage various charset conversions.
213 return $this->mysqlSetCharset( 'utf8' );
215 return $this->mysqlSetCharset( 'binary' );
220 * Open a connection to a MySQL server
222 * @param string $realServer
223 * @return mixed Raw connection
224 * @throws DBConnectionError
226 abstract protected function mysqlConnect( $realServer );
229 * Set the character set of the MySQL link
231 * @param string $charset
234 abstract protected function mysqlSetCharset( $charset );
237 * @param ResultWrapper|resource $res
238 * @throws DBUnexpectedError
240 function freeResult( $res ) {
241 if ( $res instanceof ResultWrapper
) {
244 MediaWiki\
suppressWarnings();
245 $ok = $this->mysqlFreeResult( $res );
246 MediaWiki\restoreWarnings
();
248 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
255 * @param resource $res Raw result
258 abstract protected function mysqlFreeResult( $res );
261 * @param ResultWrapper|resource $res
262 * @return stdClass|bool
263 * @throws DBUnexpectedError
265 function fetchObject( $res ) {
266 if ( $res instanceof ResultWrapper
) {
269 MediaWiki\
suppressWarnings();
270 $row = $this->mysqlFetchObject( $res );
271 MediaWiki\restoreWarnings
();
273 $errno = $this->lastErrno();
274 // Unfortunately, mysql_fetch_object does not reset the last errno.
275 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
276 // these are the only errors mysql_fetch_object can cause.
277 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
278 if ( $errno == 2000 ||
$errno == 2013 ) {
279 throw new DBUnexpectedError(
281 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
289 * Fetch a result row as an object
291 * @param resource $res Raw result
294 abstract protected function mysqlFetchObject( $res );
297 * @param ResultWrapper|resource $res
299 * @throws DBUnexpectedError
301 function fetchRow( $res ) {
302 if ( $res instanceof ResultWrapper
) {
305 MediaWiki\
suppressWarnings();
306 $row = $this->mysqlFetchArray( $res );
307 MediaWiki\restoreWarnings
();
309 $errno = $this->lastErrno();
310 // Unfortunately, mysql_fetch_array does not reset the last errno.
311 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
312 // these are the only errors mysql_fetch_array can cause.
313 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
314 if ( $errno == 2000 ||
$errno == 2013 ) {
315 throw new DBUnexpectedError(
317 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
325 * Fetch a result row as an associative and numeric array
327 * @param resource $res Raw result
330 abstract protected function mysqlFetchArray( $res );
333 * @throws DBUnexpectedError
334 * @param ResultWrapper|resource $res
337 function numRows( $res ) {
338 if ( $res instanceof ResultWrapper
) {
341 MediaWiki\
suppressWarnings();
342 $n = $this->mysqlNumRows( $res );
343 MediaWiki\restoreWarnings
();
345 // Unfortunately, mysql_num_rows does not reset the last errno.
346 // We are not checking for any errors here, since
347 // these are no errors mysql_num_rows can cause.
348 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
349 // See https://phabricator.wikimedia.org/T44430
354 * Get number of rows in result
356 * @param resource $res Raw result
359 abstract protected function mysqlNumRows( $res );
362 * @param ResultWrapper|resource $res
365 function numFields( $res ) {
366 if ( $res instanceof ResultWrapper
) {
370 return $this->mysqlNumFields( $res );
374 * Get number of fields in result
376 * @param resource $res Raw result
379 abstract protected function mysqlNumFields( $res );
382 * @param ResultWrapper|resource $res
386 function fieldName( $res, $n ) {
387 if ( $res instanceof ResultWrapper
) {
391 return $this->mysqlFieldName( $res, $n );
395 * Get the name of the specified field in a result
397 * @param ResultWrapper|resource $res
401 abstract protected function mysqlFieldName( $res, $n );
404 * mysql_field_type() wrapper
405 * @param ResultWrapper|resource $res
409 public function fieldType( $res, $n ) {
410 if ( $res instanceof ResultWrapper
) {
414 return $this->mysqlFieldType( $res, $n );
418 * Get the type of the specified field in a result
420 * @param ResultWrapper|resource $res
424 abstract protected function mysqlFieldType( $res, $n );
427 * @param ResultWrapper|resource $res
431 function dataSeek( $res, $row ) {
432 if ( $res instanceof ResultWrapper
) {
436 return $this->mysqlDataSeek( $res, $row );
440 * Move internal result pointer
442 * @param ResultWrapper|resource $res
446 abstract protected function mysqlDataSeek( $res, $row );
451 function lastError() {
452 if ( $this->mConn
) {
453 # Even if it's non-zero, it can still be invalid
454 MediaWiki\
suppressWarnings();
455 $error = $this->mysqlError( $this->mConn
);
457 $error = $this->mysqlError();
459 MediaWiki\restoreWarnings
();
461 $error = $this->mysqlError();
464 $error .= ' (' . $this->mServer
. ')';
471 * Returns the text of the error message from previous MySQL operation
473 * @param resource $conn Raw connection
476 abstract protected function mysqlError( $conn = null );
479 * @param string $table
480 * @param array $uniqueIndexes
482 * @param string $fname
483 * @return ResultWrapper
485 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
486 return $this->nativeReplace( $table, $rows, $fname );
490 * Estimate rows in dataset
491 * Returns estimated count, based on EXPLAIN output
492 * Takes same arguments as Database::select()
494 * @param string|array $table
495 * @param string|array $vars
496 * @param string|array $conds
497 * @param string $fname
498 * @param string|array $options
501 public function estimateRowCount( $table, $vars = '*', $conds = '',
502 $fname = __METHOD__
, $options = []
504 $options['EXPLAIN'] = true;
505 $res = $this->select( $table, $vars, $conds, $fname, $options );
506 if ( $res === false ) {
509 if ( !$this->numRows( $res ) ) {
514 foreach ( $res as $plan ) {
515 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
521 function tableExists( $table, $fname = __METHOD__
) {
522 $table = $this->tableName( $table, 'raw' );
523 $encLike = $this->buildLike( $table );
525 return $this->query( "SHOW TABLES $encLike", $fname )->numRows() > 0;
529 * @param string $table
530 * @param string $field
531 * @return bool|MySQLField
533 function fieldInfo( $table, $field ) {
534 $table = $this->tableName( $table );
535 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
539 $n = $this->mysqlNumFields( $res->result
);
540 for ( $i = 0; $i < $n; $i++
) {
541 $meta = $this->mysqlFetchField( $res->result
, $i );
542 if ( $field == $meta->name
) {
543 return new MySQLField( $meta );
551 * Get column information from a result
553 * @param resource $res Raw result
557 abstract protected function mysqlFetchField( $res, $n );
560 * Get information about an index into an object
561 * Returns false if the index does not exist
563 * @param string $table
564 * @param string $index
565 * @param string $fname
566 * @return bool|array|null False or null on failure
568 function indexInfo( $table, $index, $fname = __METHOD__
) {
569 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
570 # SHOW INDEX should work for 3.x and up:
571 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
572 $table = $this->tableName( $table );
573 $index = $this->indexName( $index );
575 $sql = 'SHOW INDEX FROM ' . $table;
576 $res = $this->query( $sql, $fname );
584 foreach ( $res as $row ) {
585 if ( $row->Key_name
== $index ) {
590 return empty( $result ) ?
false : $result;
597 function strencode( $s ) {
598 return $this->mysqlRealEscapeString( $s );
605 abstract protected function mysqlRealEscapeString( $s );
608 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
613 public function addIdentifierQuotes( $s ) {
614 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
615 // Remove NUL bytes and escape backticks by doubling
616 return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
620 * @param string $name
623 public function isQuotedIdentifier( $name ) {
624 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
628 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
629 return $this->getLagFromPtHeartbeat();
631 return $this->getLagFromSlaveStatus();
638 protected function getLagDetectionMethod() {
639 return $this->lagDetectionMethod
;
645 protected function getLagFromSlaveStatus() {
646 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
647 $row = $res ?
$res->fetchObject() : false;
648 if ( $row && strval( $row->Seconds_Behind_Master
) !== '' ) {
649 return intval( $row->Seconds_Behind_Master
);
658 protected function getLagFromPtHeartbeat() {
659 $options = $this->lagDetectionOptions
;
661 if ( isset( $options['conds'] ) ) {
662 // Best method for multi-DC setups: use logical channel names
663 $data = $this->getHeartbeatData( $options['conds'] );
665 // Standard method: use master server ID (works with stock pt-heartbeat)
666 $masterInfo = $this->getMasterServerInfo();
667 if ( !$masterInfo ) {
668 $this->queryLogger
->error(
669 "Unable to query master of {db_server} for server ID",
670 $this->getLogContext( [
671 'method' => __METHOD__
675 return false; // could not get master server ID
678 $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
679 $data = $this->getHeartbeatData( $conds );
682 list( $time, $nowUnix ) = $data;
683 if ( $time !== null ) {
684 // @time is in ISO format like "2015-09-25T16:48:10.000510"
685 $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
686 $timeUnix = (int)$dateTime->format( 'U' ) +
$dateTime->format( 'u' ) / 1e6
;
688 return max( $nowUnix - $timeUnix, 0.0 );
691 $this->queryLogger
->error(
692 "Unable to find pt-heartbeat row for {db_server}",
693 $this->getLogContext( [
694 'method' => __METHOD__
701 protected function getMasterServerInfo() {
702 $cache = $this->srvCache
;
703 $key = $cache->makeGlobalKey(
706 // Using one key for all cluster replica DBs is preferable
707 $this->getLBInfo( 'clusterMasterHost' ) ?
: $this->getServer()
710 return $cache->getWithSetCallback(
712 $cache::TTL_INDEFINITE
,
713 function () use ( $cache, $key ) {
714 // Get and leave a lock key in place for a short period
715 if ( !$cache->lock( $key, 0, 10 ) ) {
716 return false; // avoid master connection spike slams
719 $conn = $this->getLazyMasterHandle();
721 return false; // something is misconfigured
724 // Connect to and query the master; catch errors to avoid outages
726 $res = $conn->query( 'SELECT @@server_id AS id', __METHOD__
);
727 $row = $res ?
$res->fetchObject() : false;
728 $id = $row ?
(int)$row->id
: 0;
729 } catch ( DBError
$e ) {
733 // Cache the ID if it was retrieved
734 return $id ?
[ 'serverId' => $id, 'asOf' => time() ] : false;
740 * @param array $conds WHERE clause conditions to find a row
741 * @return array (heartbeat `ts` column value or null, UNIX timestamp) for the newest beat
742 * @see https://www.percona.com/doc/percona-toolkit/2.1/pt-heartbeat.html
744 protected function getHeartbeatData( array $conds ) {
745 $whereSQL = $this->makeList( $conds, self
::LIST_AND
);
746 // Use ORDER BY for channel based queries since that field might not be UNIQUE.
747 // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
748 // percision field is not supported in MySQL <= 5.5.
750 "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1"
752 $row = $res ?
$res->fetchObject() : false;
754 return [ $row ?
$row->ts
: null, microtime( true ) ];
757 public function getApproximateLagStatus() {
758 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
759 // Disable caching since this is fast enough and we don't wan't
760 // to be *too* pessimistic by having both the cache TTL and the
761 // pt-heartbeat interval count as lag in getSessionLagStatus()
762 return parent
::getApproximateLagStatus();
765 $key = $this->srvCache
->makeGlobalKey( 'mysql-lag', $this->getServer() );
766 $approxLag = $this->srvCache
->get( $key );
768 $approxLag = parent
::getApproximateLagStatus();
769 $this->srvCache
->set( $key, $approxLag, 1 );
775 function masterPosWait( DBMasterPos
$pos, $timeout ) {
776 if ( !( $pos instanceof MySQLMasterPos
) ) {
777 throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
780 if ( $this->getLBInfo( 'is static' ) === true ) {
781 return 0; // this is a copy of a read-only dataset with no master DB
782 } elseif ( $this->lastKnownReplicaPos
&& $this->lastKnownReplicaPos
->hasReached( $pos ) ) {
783 return 0; // already reached this point for sure
786 // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
787 if ( $this->useGTIDs
&& $pos->gtids
) {
788 // Wait on the GTID set (MariaDB only)
789 $gtidArg = $this->addQuotes( implode( ',', $pos->gtids
) );
790 $res = $this->doQuery( "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)" );
792 // Wait on the binlog coordinates
793 $encFile = $this->addQuotes( $pos->file
);
794 $encPos = intval( $pos->pos
);
795 $res = $this->doQuery( "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)" );
798 $row = $res ?
$this->fetchRow( $res ) : false;
800 throw new DBExpectedError( $this, "Failed to query MASTER_POS_WAIT()" );
803 // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
804 $status = ( $row[0] !== null ) ?
intval( $row[0] ) : null;
805 if ( $status === null ) {
806 // T126436: jobs programmed to wait on master positions might be referencing binlogs
807 // with an old master hostname. Such calls make MASTER_POS_WAIT() return null. Try
808 // to detect this and treat the replica DB as having reached the position; a proper master
809 // switchover already requires that the new master be caught up before the switch.
810 $replicationPos = $this->getSlavePos();
811 if ( $replicationPos && !$replicationPos->channelsMatch( $pos ) ) {
812 $this->lastKnownReplicaPos
= $replicationPos;
815 } elseif ( $status >= 0 ) {
816 // Remember that this position was reached to save queries next time
817 $this->lastKnownReplicaPos
= $pos;
824 * Get the position of the master from SHOW SLAVE STATUS
826 * @return MySQLMasterPos|bool
828 function getSlavePos() {
829 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
830 $row = $this->fetchObject( $res );
833 $pos = isset( $row->Exec_master_log_pos
)
834 ?
$row->Exec_master_log_pos
835 : $row->Exec_Master_Log_Pos
;
836 // Also fetch the last-applied GTID set (MariaDB)
837 if ( $this->useGTIDs
) {
838 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_slave_pos'", __METHOD__
);
839 $gtidRow = $this->fetchObject( $res );
840 $gtidSet = $gtidRow ?
$gtidRow->Value
: '';
845 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos, $gtidSet );
852 * Get the position of the master from SHOW MASTER STATUS
854 * @return MySQLMasterPos|bool
856 function getMasterPos() {
857 $res = $this->query( 'SHOW MASTER STATUS', __METHOD__
);
858 $row = $this->fetchObject( $res );
861 // Also fetch the last-written GTID set (MariaDB)
862 if ( $this->useGTIDs
) {
863 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_binlog_pos'", __METHOD__
);
864 $gtidRow = $this->fetchObject( $res );
865 $gtidSet = $gtidRow ?
$gtidRow->Value
: '';
870 return new MySQLMasterPos( $row->File
, $row->Position
, $gtidSet );
876 public function serverIsReadOnly() {
877 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'read_only'", __METHOD__
);
878 $row = $this->fetchObject( $res );
880 return $row ?
( strtolower( $row->Value
) === 'on' ) : false;
884 * @param string $index
887 function useIndexClause( $index ) {
888 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
892 * @param string $index
895 function ignoreIndexClause( $index ) {
896 return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
902 function lowPriorityOption() {
903 return 'LOW_PRIORITY';
909 public function getSoftwareLink() {
910 // MariaDB includes its name in its version string; this is how MariaDB's version of
911 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
912 // in libmysql/libmysql.c).
913 $version = $this->getServerVersion();
914 if ( strpos( $version, 'MariaDB' ) !== false ||
strpos( $version, '-maria-' ) !== false ) {
915 return '[{{int:version-db-mariadb-url}} MariaDB]';
918 // Percona Server's version suffix is not very distinctive, and @@version_comment
919 // doesn't give the necessary info for source builds, so assume the server is MySQL.
920 // (Even Percona's version of mysql doesn't try to make the distinction.)
921 return '[{{int:version-db-mysql-url}} MySQL]';
927 public function getServerVersion() {
928 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
929 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
930 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
931 if ( $this->serverVersion
=== null ) {
932 $this->serverVersion
= $this->selectField( '', 'VERSION()', '', __METHOD__
);
934 return $this->serverVersion
;
938 * @param array $options
940 public function setSessionOptions( array $options ) {
941 if ( isset( $options['connTimeout'] ) ) {
942 $timeout = (int)$options['connTimeout'];
943 $this->query( "SET net_read_timeout=$timeout" );
944 $this->query( "SET net_write_timeout=$timeout" );
950 * @param string $newLine
953 public function streamStatementEnd( &$sql, &$newLine ) {
954 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
955 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
956 $this->delimiter
= $m[1];
960 return parent
::streamStatementEnd( $sql, $newLine );
964 * Check to see if a named lock is available. This is non-blocking.
966 * @param string $lockName Name of lock to poll
967 * @param string $method Name of method calling us
971 public function lockIsFree( $lockName, $method ) {
972 $lockName = $this->addQuotes( $this->makeLockName( $lockName ) );
973 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
974 $row = $this->fetchObject( $result );
976 return ( $row->lockstatus
== 1 );
980 * @param string $lockName
981 * @param string $method
982 * @param int $timeout
985 public function lock( $lockName, $method, $timeout = 5 ) {
986 $lockName = $this->addQuotes( $this->makeLockName( $lockName ) );
987 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
988 $row = $this->fetchObject( $result );
990 if ( $row->lockstatus
== 1 ) {
991 parent
::lock( $lockName, $method, $timeout ); // record
995 $this->queryLogger
->warning( __METHOD__
. " failed to acquire lock '$lockName'\n" );
1002 * http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
1003 * @param string $lockName
1004 * @param string $method
1007 public function unlock( $lockName, $method ) {
1008 $lockName = $this->addQuotes( $this->makeLockName( $lockName ) );
1009 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
1010 $row = $this->fetchObject( $result );
1012 if ( $row->lockstatus
== 1 ) {
1013 parent
::unlock( $lockName, $method ); // record
1017 $this->queryLogger
->warning( __METHOD__
. " failed to release lock '$lockName'\n" );
1022 private function makeLockName( $lockName ) {
1023 // http://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1024 // Newer version enforce a 64 char length limit.
1025 return ( strlen( $lockName ) > 64 ) ?
sha1( $lockName ) : $lockName;
1028 public function namedLocksEnqueue() {
1033 * @param array $read
1034 * @param array $write
1035 * @param string $method
1036 * @param bool $lowPriority
1039 public function lockTables( $read, $write, $method, $lowPriority = true ) {
1042 foreach ( $write as $table ) {
1043 $tbl = $this->tableName( $table ) .
1044 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
1048 foreach ( $read as $table ) {
1049 $items[] = $this->tableName( $table ) . ' READ';
1051 $sql = "LOCK TABLES " . implode( ',', $items );
1052 $this->query( $sql, $method );
1058 * @param string $method
1061 public function unlockTables( $method ) {
1062 $this->query( "UNLOCK TABLES", $method );
1068 * @param bool $value
1070 public function setBigSelects( $value = true ) {
1071 if ( $value === 'default' ) {
1072 if ( $this->mDefaultBigSelects
=== null ) {
1073 # Function hasn't been called before so it must already be set to the default
1076 $value = $this->mDefaultBigSelects
;
1078 } elseif ( $this->mDefaultBigSelects
=== null ) {
1079 $this->mDefaultBigSelects
=
1080 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__
);
1082 $encValue = $value ?
'1' : '0';
1083 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
1087 * DELETE where the condition is a join. MySql uses multi-table deletes.
1088 * @param string $delTable
1089 * @param string $joinTable
1090 * @param string $delVar
1091 * @param string $joinVar
1092 * @param array|string $conds
1093 * @param bool|string $fname
1094 * @throws DBUnexpectedError
1095 * @return bool|ResultWrapper
1097 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
) {
1099 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
1102 $delTable = $this->tableName( $delTable );
1103 $joinTable = $this->tableName( $joinTable );
1104 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1106 if ( $conds != '*' ) {
1107 $sql .= ' AND ' . $this->makeList( $conds, self
::LIST_AND
);
1110 return $this->query( $sql, $fname );
1114 * @param string $table
1115 * @param array $rows
1116 * @param array $uniqueIndexes
1118 * @param string $fname
1121 public function upsert( $table, array $rows, array $uniqueIndexes,
1122 array $set, $fname = __METHOD__
1124 if ( !count( $rows ) ) {
1125 return true; // nothing to do
1128 if ( !is_array( reset( $rows ) ) ) {
1132 $table = $this->tableName( $table );
1133 $columns = array_keys( $rows[0] );
1135 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1137 foreach ( $rows as $row ) {
1138 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1140 $sql .= implode( ',', $rowTuples );
1141 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, self
::LIST_SET
);
1143 return (bool)$this->query( $sql, $fname );
1147 * Determines how long the server has been up
1151 function getServerUptime() {
1152 $vars = $this->getMysqlStatus( 'Uptime' );
1154 return (int)$vars['Uptime'];
1158 * Determines if the last failure was due to a deadlock
1162 function wasDeadlock() {
1163 return $this->lastErrno() == 1213;
1167 * Determines if the last failure was due to a lock timeout
1171 function wasLockTimeout() {
1172 return $this->lastErrno() == 1205;
1175 function wasErrorReissuable() {
1176 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
1180 * Determines if the last failure was due to the database being read-only.
1184 function wasReadOnlyError() {
1185 return $this->lastErrno() == 1223 ||
1186 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1189 function wasConnectionError( $errno ) {
1190 return $errno == 2013 ||
$errno == 2006;
1194 * Get the underlying binding handle, mConn
1196 * Makes sure that mConn is set (disconnects and ping() failure can unset it).
1197 * This catches broken callers than catch and ignore disconnection exceptions.
1198 * Unlike checking isOpen(), this is safe to call inside of open().
1200 * @return resource|object
1201 * @throws DBUnexpectedError
1204 protected function getBindingHandle() {
1205 if ( !$this->mConn
) {
1206 throw new DBUnexpectedError(
1208 'DB connection was already closed or the connection dropped.'
1212 return $this->mConn
;
1216 * @param string $oldName
1217 * @param string $newName
1218 * @param bool $temporary
1219 * @param string $fname
1222 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
1223 $tmp = $temporary ?
'TEMPORARY ' : '';
1224 $newName = $this->addIdentifierQuotes( $newName );
1225 $oldName = $this->addIdentifierQuotes( $oldName );
1226 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1228 return $this->query( $query, $fname );
1232 * List all tables on the database
1234 * @param string $prefix Only show tables with this prefix, e.g. mw_
1235 * @param string $fname Calling function name
1238 function listTables( $prefix = null, $fname = __METHOD__
) {
1239 $result = $this->query( "SHOW TABLES", $fname );
1243 foreach ( $result as $table ) {
1244 $vars = get_object_vars( $table );
1245 $table = array_pop( $vars );
1247 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1248 $endArray[] = $table;
1256 * @param string $tableName
1257 * @param string $fName
1258 * @return bool|ResultWrapper
1260 public function dropTable( $tableName, $fName = __METHOD__
) {
1261 if ( !$this->tableExists( $tableName, $fName ) ) {
1265 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1271 protected function getDefaultSchemaVars() {
1272 $vars = parent
::getDefaultSchemaVars();
1273 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
1274 $vars['wgDBTableOptions'] = str_replace(
1277 $vars['wgDBTableOptions']
1284 * Get status information from SHOW STATUS in an associative array
1286 * @param string $which
1289 function getMysqlStatus( $which = "%" ) {
1290 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1293 foreach ( $res as $row ) {
1294 $status[$row->Variable_name
] = $row->Value
;
1301 * Lists VIEWs in the database
1303 * @param string $prefix Only show VIEWs with this prefix, eg.
1304 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1305 * @param string $fname Name of calling function
1309 public function listViews( $prefix = null, $fname = __METHOD__
) {
1311 if ( !isset( $this->allViews
) ) {
1313 // The name of the column containing the name of the VIEW
1314 $propertyName = 'Tables_in_' . $this->mDBname
;
1316 // Query for the VIEWS
1317 $result = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1318 $this->allViews
= [];
1319 while ( ( $row = $this->fetchRow( $result ) ) !== false ) {
1320 array_push( $this->allViews
, $row[$propertyName] );
1324 if ( is_null( $prefix ) ||
$prefix === '' ) {
1325 return $this->allViews
;
1328 $filteredViews = [];
1329 foreach ( $this->allViews
as $viewName ) {
1330 // Does the name of this VIEW start with the table-prefix?
1331 if ( strpos( $viewName, $prefix ) === 0 ) {
1332 array_push( $filteredViews, $viewName );
1336 return $filteredViews;
1340 * Differentiates between a TABLE and a VIEW.
1342 * @param string $name Name of the TABLE/VIEW to test
1343 * @param string $prefix
1347 public function isView( $name, $prefix = null ) {
1348 return in_array( $name, $this->listViews( $prefix ) );