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
;
27 * Database abstraction object for MySQL.
28 * Defines methods independent on used MySQL extension.
34 abstract class DatabaseMysqlBase
extends Database
{
35 /** @var MysqlMasterPos */
36 protected $lastKnownReplicaPos;
37 /** @var string Method to detect replica DB lag */
38 protected $lagDetectionMethod;
39 /** @var array Method to detect replica DB lag */
40 protected $lagDetectionOptions = [];
41 /** @var bool bool Whether to use GTID methods */
42 protected $useGTIDs = false;
43 /** @var string|null */
44 protected $sslKeyPath;
45 /** @var string|null */
46 protected $sslCertPath;
47 /** @var string|null */
49 /** @var string[]|null */
50 protected $sslCiphers;
51 /** @var string sql_mode value to send on connection */
53 /** @var bool Use experimental UTF-8 transmission encoding */
56 /** @var string|null */
57 private $serverVersion = null;
60 * Additional $params include:
61 * - lagDetectionMethod : set to one of (Seconds_Behind_Master,pt-heartbeat).
62 * pt-heartbeat assumes the table is at heartbeat.heartbeat
63 * and uses UTC timestamps in the heartbeat.ts column.
64 * (https://www.percona.com/doc/percona-toolkit/2.2/pt-heartbeat.html)
65 * - lagDetectionOptions : if using pt-heartbeat, this can be set to an array map to change
66 * the default behavior. Normally, the heartbeat row with the server
67 * ID of this server's master will be used. Set the "conds" field to
68 * override the query conditions, e.g. ['shard' => 's1'].
69 * - useGTIDs : use GTID methods like MASTER_GTID_WAIT() when possible.
70 * - sslKeyPath : path to key file [default: null]
71 * - sslCertPath : path to certificate file [default: null]
72 * - sslCAPath : parth to certificate authority PEM files [default: null]
73 * - sslCiphers : array list of allowable ciphers [default: null]
74 * @param array $params
76 function __construct( array $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'] );
93 parent
::__construct( $params );
99 public function getType() {
104 * @param string $server
105 * @param string $user
106 * @param string $password
107 * @param string $dbName
108 * @throws Exception|DBConnectionError
111 public function open( $server, $user, $password, $dbName ) {
112 # Close/unset connection handle
115 $this->mServer
= $server;
116 $this->mUser
= $user;
117 $this->mPassword
= $password;
118 $this->mDBname
= $dbName;
120 $this->installErrorHandler();
122 $this->mConn
= $this->mysqlConnect( $this->mServer
);
123 } catch ( Exception
$ex ) {
124 $this->restoreErrorHandler();
127 $error = $this->restoreErrorHandler();
129 # Always log connection errors
130 if ( !$this->mConn
) {
132 $error = $this->lastError();
134 $this->connLogger
->error(
135 "Error connecting to {db_server}: {error}",
136 $this->getLogContext( [
137 'method' => __METHOD__
,
141 $this->connLogger
->debug( "DB connection error\n" .
142 "Server: $server, User: $user, Password: " .
143 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
145 $this->reportConnectionError( $error );
148 if ( $dbName != '' ) {
149 MediaWiki\
suppressWarnings();
150 $success = $this->selectDB( $dbName );
151 MediaWiki\restoreWarnings
();
153 $this->queryLogger
->error(
154 "Error selecting database {db_name} on server {db_server}",
155 $this->getLogContext( [
156 'method' => __METHOD__
,
159 $this->queryLogger
->debug(
160 "Error selecting database $dbName on server {$this->mServer}" );
162 $this->reportConnectionError( "Error selecting database $dbName" );
166 // Tell the server what we're communicating with
167 if ( !$this->connectInitCharset() ) {
168 $this->reportConnectionError( "Error setting character set" );
171 // Abstract over any insane MySQL defaults
172 $set = [ 'group_concat_max_len = 262144' ];
173 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
174 if ( is_string( $this->sqlMode
) ) {
175 $set[] = 'sql_mode = ' . $this->addQuotes( $this->sqlMode
);
177 // Set any custom settings defined by site config
178 // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
179 foreach ( $this->mSessionVars
as $var => $val ) {
180 // Escape strings but not numbers to avoid MySQL complaining
181 if ( !is_int( $val ) && !is_float( $val ) ) {
182 $val = $this->addQuotes( $val );
184 $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
188 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
189 $success = $this->doQuery( 'SET ' . implode( ', ', $set ) );
191 $this->queryLogger
->error(
192 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)',
193 $this->getLogContext( [
194 'method' => __METHOD__
,
197 $this->reportConnectionError(
198 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)' );
202 $this->mOpened
= true;
208 * Set the character set information right after connection
211 protected function connectInitCharset() {
212 if ( $this->utf8Mode
) {
213 // Tell the server we're communicating with it in UTF-8.
214 // This may engage various charset conversions.
215 return $this->mysqlSetCharset( 'utf8' );
217 return $this->mysqlSetCharset( 'binary' );
222 * Open a connection to a MySQL server
224 * @param string $realServer
225 * @return mixed Raw connection
226 * @throws DBConnectionError
228 abstract protected function mysqlConnect( $realServer );
231 * Set the character set of the MySQL link
233 * @param string $charset
236 abstract protected function mysqlSetCharset( $charset );
239 * @param ResultWrapper|resource $res
240 * @throws DBUnexpectedError
242 public function freeResult( $res ) {
243 if ( $res instanceof ResultWrapper
) {
246 MediaWiki\
suppressWarnings();
247 $ok = $this->mysqlFreeResult( $res );
248 MediaWiki\restoreWarnings
();
250 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
257 * @param resource $res Raw result
260 abstract protected function mysqlFreeResult( $res );
263 * @param ResultWrapper|resource $res
264 * @return stdClass|bool
265 * @throws DBUnexpectedError
267 public function fetchObject( $res ) {
268 if ( $res instanceof ResultWrapper
) {
271 MediaWiki\
suppressWarnings();
272 $row = $this->mysqlFetchObject( $res );
273 MediaWiki\restoreWarnings
();
275 $errno = $this->lastErrno();
276 // Unfortunately, mysql_fetch_object does not reset the last errno.
277 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
278 // these are the only errors mysql_fetch_object can cause.
279 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
280 if ( $errno == 2000 ||
$errno == 2013 ) {
281 throw new DBUnexpectedError(
283 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
291 * Fetch a result row as an object
293 * @param resource $res Raw result
296 abstract protected function mysqlFetchObject( $res );
299 * @param ResultWrapper|resource $res
301 * @throws DBUnexpectedError
303 public function fetchRow( $res ) {
304 if ( $res instanceof ResultWrapper
) {
307 MediaWiki\
suppressWarnings();
308 $row = $this->mysqlFetchArray( $res );
309 MediaWiki\restoreWarnings
();
311 $errno = $this->lastErrno();
312 // Unfortunately, mysql_fetch_array does not reset the last errno.
313 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
314 // these are the only errors mysql_fetch_array can cause.
315 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
316 if ( $errno == 2000 ||
$errno == 2013 ) {
317 throw new DBUnexpectedError(
319 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
327 * Fetch a result row as an associative and numeric array
329 * @param resource $res Raw result
332 abstract protected function mysqlFetchArray( $res );
335 * @throws DBUnexpectedError
336 * @param ResultWrapper|resource $res
339 function numRows( $res ) {
340 if ( $res instanceof ResultWrapper
) {
343 MediaWiki\
suppressWarnings();
344 $n = $this->mysqlNumRows( $res );
345 MediaWiki\restoreWarnings
();
347 // Unfortunately, mysql_num_rows does not reset the last errno.
348 // We are not checking for any errors here, since
349 // these are no errors mysql_num_rows can cause.
350 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
351 // See https://phabricator.wikimedia.org/T44430
356 * Get number of rows in result
358 * @param resource $res Raw result
361 abstract protected function mysqlNumRows( $res );
364 * @param ResultWrapper|resource $res
367 public function numFields( $res ) {
368 if ( $res instanceof ResultWrapper
) {
372 return $this->mysqlNumFields( $res );
376 * Get number of fields in result
378 * @param resource $res Raw result
381 abstract protected function mysqlNumFields( $res );
384 * @param ResultWrapper|resource $res
388 public function fieldName( $res, $n ) {
389 if ( $res instanceof ResultWrapper
) {
393 return $this->mysqlFieldName( $res, $n );
397 * Get the name of the specified field in a result
399 * @param ResultWrapper|resource $res
403 abstract protected function mysqlFieldName( $res, $n );
406 * mysql_field_type() wrapper
407 * @param ResultWrapper|resource $res
411 public function fieldType( $res, $n ) {
412 if ( $res instanceof ResultWrapper
) {
416 return $this->mysqlFieldType( $res, $n );
420 * Get the type of the specified field in a result
422 * @param ResultWrapper|resource $res
426 abstract protected function mysqlFieldType( $res, $n );
429 * @param ResultWrapper|resource $res
433 public function dataSeek( $res, $row ) {
434 if ( $res instanceof ResultWrapper
) {
438 return $this->mysqlDataSeek( $res, $row );
442 * Move internal result pointer
444 * @param ResultWrapper|resource $res
448 abstract protected function mysqlDataSeek( $res, $row );
453 public function lastError() {
454 if ( $this->mConn
) {
455 # Even if it's non-zero, it can still be invalid
456 MediaWiki\
suppressWarnings();
457 $error = $this->mysqlError( $this->mConn
);
459 $error = $this->mysqlError();
461 MediaWiki\restoreWarnings
();
463 $error = $this->mysqlError();
466 $error .= ' (' . $this->mServer
. ')';
473 * Returns the text of the error message from previous MySQL operation
475 * @param resource $conn Raw connection
478 abstract protected function mysqlError( $conn = null );
481 * @param string $table
482 * @param array $uniqueIndexes
484 * @param string $fname
485 * @return ResultWrapper
487 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
488 return $this->nativeReplace( $table, $rows, $fname );
492 * Estimate rows in dataset
493 * Returns estimated count, based on EXPLAIN output
494 * Takes same arguments as Database::select()
496 * @param string|array $table
497 * @param string|array $vars
498 * @param string|array $conds
499 * @param string $fname
500 * @param string|array $options
503 public function estimateRowCount( $table, $vars = '*', $conds = '',
504 $fname = __METHOD__
, $options = []
506 $options['EXPLAIN'] = true;
507 $res = $this->select( $table, $vars, $conds, $fname, $options );
508 if ( $res === false ) {
511 if ( !$this->numRows( $res ) ) {
516 foreach ( $res as $plan ) {
517 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
523 public function tableExists( $table, $fname = __METHOD__
) {
524 $table = $this->tableName( $table, 'raw' );
525 if ( isset( $this->mSessionTempTables
[$table] ) ) {
526 return true; // already known to exist and won't show in SHOW TABLES anyway
529 $encLike = $this->buildLike( $table );
531 return $this->query( "SHOW TABLES $encLike", $fname )->numRows() > 0;
535 * @param string $table
536 * @param string $field
537 * @return bool|MySQLField
539 public function fieldInfo( $table, $field ) {
540 $table = $this->tableName( $table );
541 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
545 $n = $this->mysqlNumFields( $res->result
);
546 for ( $i = 0; $i < $n; $i++
) {
547 $meta = $this->mysqlFetchField( $res->result
, $i );
548 if ( $field == $meta->name
) {
549 return new MySQLField( $meta );
557 * Get column information from a result
559 * @param resource $res Raw result
563 abstract protected function mysqlFetchField( $res, $n );
566 * Get information about an index into an object
567 * Returns false if the index does not exist
569 * @param string $table
570 * @param string $index
571 * @param string $fname
572 * @return bool|array|null False or null on failure
574 public function indexInfo( $table, $index, $fname = __METHOD__
) {
575 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
576 # SHOW INDEX should work for 3.x and up:
577 # https://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
578 $table = $this->tableName( $table );
579 $index = $this->indexName( $index );
581 $sql = 'SHOW INDEX FROM ' . $table;
582 $res = $this->query( $sql, $fname );
590 foreach ( $res as $row ) {
591 if ( $row->Key_name
== $index ) {
596 return empty( $result ) ?
false : $result;
603 public function strencode( $s ) {
604 return $this->mysqlRealEscapeString( $s );
611 abstract protected function mysqlRealEscapeString( $s );
613 public function addQuotes( $s ) {
614 if ( is_bool( $s ) ) {
615 // Parent would transform to int, which does not play nice with MySQL type juggling.
616 // When searching for an int in a string column, the strings are cast to int, which
617 // means false would match any string not starting with a number.
618 $s = (string)(int)$s;
620 return parent
::addQuotes( $s );
624 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
629 public function addIdentifierQuotes( $s ) {
630 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
631 // Remove NUL bytes and escape backticks by doubling
632 return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
636 * @param string $name
639 public function isQuotedIdentifier( $name ) {
640 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
643 public function getLag() {
644 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
645 return $this->getLagFromPtHeartbeat();
647 return $this->getLagFromSlaveStatus();
654 protected function getLagDetectionMethod() {
655 return $this->lagDetectionMethod
;
661 protected function getLagFromSlaveStatus() {
662 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
663 $row = $res ?
$res->fetchObject() : false;
664 if ( $row && strval( $row->Seconds_Behind_Master
) !== '' ) {
665 return intval( $row->Seconds_Behind_Master
);
674 protected function getLagFromPtHeartbeat() {
675 $options = $this->lagDetectionOptions
;
677 if ( isset( $options['conds'] ) ) {
678 // Best method for multi-DC setups: use logical channel names
679 $data = $this->getHeartbeatData( $options['conds'] );
681 // Standard method: use master server ID (works with stock pt-heartbeat)
682 $masterInfo = $this->getMasterServerInfo();
683 if ( !$masterInfo ) {
684 $this->queryLogger
->error(
685 "Unable to query master of {db_server} for server ID",
686 $this->getLogContext( [
687 'method' => __METHOD__
691 return false; // could not get master server ID
694 $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
695 $data = $this->getHeartbeatData( $conds );
698 list( $time, $nowUnix ) = $data;
699 if ( $time !== null ) {
700 // @time is in ISO format like "2015-09-25T16:48:10.000510"
701 $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
702 $timeUnix = (int)$dateTime->format( 'U' ) +
$dateTime->format( 'u' ) / 1e6
;
704 return max( $nowUnix - $timeUnix, 0.0 );
707 $this->queryLogger
->error(
708 "Unable to find pt-heartbeat row for {db_server}",
709 $this->getLogContext( [
710 'method' => __METHOD__
717 protected function getMasterServerInfo() {
718 $cache = $this->srvCache
;
719 $key = $cache->makeGlobalKey(
722 // Using one key for all cluster replica DBs is preferable
723 $this->getLBInfo( 'clusterMasterHost' ) ?
: $this->getServer()
726 return $cache->getWithSetCallback(
728 $cache::TTL_INDEFINITE
,
729 function () use ( $cache, $key ) {
730 // Get and leave a lock key in place for a short period
731 if ( !$cache->lock( $key, 0, 10 ) ) {
732 return false; // avoid master connection spike slams
735 $conn = $this->getLazyMasterHandle();
737 return false; // something is misconfigured
740 // Connect to and query the master; catch errors to avoid outages
742 $res = $conn->query( 'SELECT @@server_id AS id', __METHOD__
);
743 $row = $res ?
$res->fetchObject() : false;
744 $id = $row ?
(int)$row->id
: 0;
745 } catch ( DBError
$e ) {
749 // Cache the ID if it was retrieved
750 return $id ?
[ 'serverId' => $id, 'asOf' => time() ] : false;
756 * @param array $conds WHERE clause conditions to find a row
757 * @return array (heartbeat `ts` column value or null, UNIX timestamp) for the newest beat
758 * @see https://www.percona.com/doc/percona-toolkit/2.1/pt-heartbeat.html
760 protected function getHeartbeatData( array $conds ) {
761 // Do not bother starting implicit transactions here
762 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
764 $whereSQL = $this->makeList( $conds, self
::LIST_AND
);
765 // Use ORDER BY for channel based queries since that field might not be UNIQUE.
766 // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
767 // percision field is not supported in MySQL <= 5.5.
769 "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1"
771 $row = $res ?
$res->fetchObject() : false;
773 $this->restoreFlags();
776 return [ $row ?
$row->ts
: null, microtime( true ) ];
779 protected function getApproximateLagStatus() {
780 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
781 // Disable caching since this is fast enough and we don't wan't
782 // to be *too* pessimistic by having both the cache TTL and the
783 // pt-heartbeat interval count as lag in getSessionLagStatus()
784 return parent
::getApproximateLagStatus();
787 $key = $this->srvCache
->makeGlobalKey( 'mysql-lag', $this->getServer() );
788 $approxLag = $this->srvCache
->get( $key );
790 $approxLag = parent
::getApproximateLagStatus();
791 $this->srvCache
->set( $key, $approxLag, 1 );
797 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
798 if ( !( $pos instanceof MySQLMasterPos
) ) {
799 throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
802 if ( $this->getLBInfo( 'is static' ) === true ) {
803 return 0; // this is a copy of a read-only dataset with no master DB
804 } elseif ( $this->lastKnownReplicaPos
&& $this->lastKnownReplicaPos
->hasReached( $pos ) ) {
805 return 0; // already reached this point for sure
808 // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
809 if ( $this->useGTIDs
&& $pos->gtids
) {
810 // Wait on the GTID set (MariaDB only)
811 $gtidArg = $this->addQuotes( implode( ',', $pos->gtids
) );
812 $res = $this->doQuery( "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)" );
814 // Wait on the binlog coordinates
815 $encFile = $this->addQuotes( $pos->file
);
816 $encPos = intval( $pos->pos
);
817 $res = $this->doQuery( "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)" );
820 $row = $res ?
$this->fetchRow( $res ) : false;
822 throw new DBExpectedError( $this, "Failed to query MASTER_POS_WAIT()" );
825 // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
826 $status = ( $row[0] !== null ) ?
intval( $row[0] ) : null;
827 if ( $status === null ) {
828 // T126436: jobs programmed to wait on master positions might be referencing binlogs
829 // with an old master hostname. Such calls make MASTER_POS_WAIT() return null. Try
830 // to detect this and treat the replica DB as having reached the position; a proper master
831 // switchover already requires that the new master be caught up before the switch.
832 $replicationPos = $this->getReplicaPos();
833 if ( $replicationPos && !$replicationPos->channelsMatch( $pos ) ) {
834 $this->lastKnownReplicaPos
= $replicationPos;
837 } elseif ( $status >= 0 ) {
838 // Remember that this position was reached to save queries next time
839 $this->lastKnownReplicaPos
= $pos;
846 * Get the position of the master from SHOW SLAVE STATUS
848 * @return MySQLMasterPos|bool
850 public function getReplicaPos() {
851 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
852 $row = $this->fetchObject( $res );
855 $pos = isset( $row->Exec_master_log_pos
)
856 ?
$row->Exec_master_log_pos
857 : $row->Exec_Master_Log_Pos
;
858 // Also fetch the last-applied GTID set (MariaDB)
859 if ( $this->useGTIDs
) {
860 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_slave_pos'", __METHOD__
);
861 $gtidRow = $this->fetchObject( $res );
862 $gtidSet = $gtidRow ?
$gtidRow->Value
: '';
867 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos, $gtidSet );
874 * Get the position of the master from SHOW MASTER STATUS
876 * @return MySQLMasterPos|bool
878 public function getMasterPos() {
879 $res = $this->query( 'SHOW MASTER STATUS', __METHOD__
);
880 $row = $this->fetchObject( $res );
883 // Also fetch the last-written GTID set (MariaDB)
884 if ( $this->useGTIDs
) {
885 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_binlog_pos'", __METHOD__
);
886 $gtidRow = $this->fetchObject( $res );
887 $gtidSet = $gtidRow ?
$gtidRow->Value
: '';
892 return new MySQLMasterPos( $row->File
, $row->Position
, $gtidSet );
898 public function serverIsReadOnly() {
899 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'read_only'", __METHOD__
);
900 $row = $this->fetchObject( $res );
902 return $row ?
( strtolower( $row->Value
) === 'on' ) : false;
906 * @param string $index
909 function useIndexClause( $index ) {
910 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
914 * @param string $index
917 function ignoreIndexClause( $index ) {
918 return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
924 function lowPriorityOption() {
925 return 'LOW_PRIORITY';
931 public function getSoftwareLink() {
932 // MariaDB includes its name in its version string; this is how MariaDB's version of
933 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
934 // in libmysql/libmysql.c).
935 $version = $this->getServerVersion();
936 if ( strpos( $version, 'MariaDB' ) !== false ||
strpos( $version, '-maria-' ) !== false ) {
937 return '[{{int:version-db-mariadb-url}} MariaDB]';
940 // Percona Server's version suffix is not very distinctive, and @@version_comment
941 // doesn't give the necessary info for source builds, so assume the server is MySQL.
942 // (Even Percona's version of mysql doesn't try to make the distinction.)
943 return '[{{int:version-db-mysql-url}} MySQL]';
949 public function getServerVersion() {
950 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
951 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
952 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
953 if ( $this->serverVersion
=== null ) {
954 $this->serverVersion
= $this->selectField( '', 'VERSION()', '', __METHOD__
);
956 return $this->serverVersion
;
960 * @param array $options
962 public function setSessionOptions( array $options ) {
963 if ( isset( $options['connTimeout'] ) ) {
964 $timeout = (int)$options['connTimeout'];
965 $this->query( "SET net_read_timeout=$timeout" );
966 $this->query( "SET net_write_timeout=$timeout" );
972 * @param string $newLine
975 public function streamStatementEnd( &$sql, &$newLine ) {
976 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
977 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
978 $this->delimiter
= $m[1];
982 return parent
::streamStatementEnd( $sql, $newLine );
986 * Check to see if a named lock is available. This is non-blocking.
988 * @param string $lockName Name of lock to poll
989 * @param string $method Name of method calling us
993 public function lockIsFree( $lockName, $method ) {
994 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
995 $result = $this->query( "SELECT IS_FREE_LOCK($encName) AS lockstatus", $method );
996 $row = $this->fetchObject( $result );
998 return ( $row->lockstatus
== 1 );
1002 * @param string $lockName
1003 * @param string $method
1004 * @param int $timeout
1007 public function lock( $lockName, $method, $timeout = 5 ) {
1008 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1009 $result = $this->query( "SELECT GET_LOCK($encName, $timeout) AS lockstatus", $method );
1010 $row = $this->fetchObject( $result );
1012 if ( $row->lockstatus
== 1 ) {
1013 parent
::lock( $lockName, $method, $timeout ); // record
1017 $this->queryLogger
->warning( __METHOD__
. " failed to acquire lock '$lockName'\n" );
1024 * https://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
1025 * @param string $lockName
1026 * @param string $method
1029 public function unlock( $lockName, $method ) {
1030 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1031 $result = $this->query( "SELECT RELEASE_LOCK($encName) as lockstatus", $method );
1032 $row = $this->fetchObject( $result );
1034 if ( $row->lockstatus
== 1 ) {
1035 parent
::unlock( $lockName, $method ); // record
1039 $this->queryLogger
->warning( __METHOD__
. " failed to release lock '$lockName'\n" );
1044 private function makeLockName( $lockName ) {
1045 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1046 // Newer version enforce a 64 char length limit.
1047 return ( strlen( $lockName ) > 64 ) ?
sha1( $lockName ) : $lockName;
1050 public function namedLocksEnqueue() {
1055 * @param array $read
1056 * @param array $write
1057 * @param string $method
1058 * @param bool $lowPriority
1061 public function lockTables( $read, $write, $method, $lowPriority = true ) {
1064 foreach ( $write as $table ) {
1065 $tbl = $this->tableName( $table ) .
1066 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
1070 foreach ( $read as $table ) {
1071 $items[] = $this->tableName( $table ) . ' READ';
1073 $sql = "LOCK TABLES " . implode( ',', $items );
1074 $this->query( $sql, $method );
1080 * @param string $method
1083 public function unlockTables( $method ) {
1084 $this->query( "UNLOCK TABLES", $method );
1090 * @param bool $value
1092 public function setBigSelects( $value = true ) {
1093 if ( $value === 'default' ) {
1094 if ( $this->mDefaultBigSelects
=== null ) {
1095 # Function hasn't been called before so it must already be set to the default
1098 $value = $this->mDefaultBigSelects
;
1100 } elseif ( $this->mDefaultBigSelects
=== null ) {
1101 $this->mDefaultBigSelects
=
1102 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__
);
1104 $encValue = $value ?
'1' : '0';
1105 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
1109 * DELETE where the condition is a join. MySql uses multi-table deletes.
1110 * @param string $delTable
1111 * @param string $joinTable
1112 * @param string $delVar
1113 * @param string $joinVar
1114 * @param array|string $conds
1115 * @param bool|string $fname
1116 * @throws DBUnexpectedError
1117 * @return bool|ResultWrapper
1119 public function deleteJoin(
1120 $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
1123 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
1126 $delTable = $this->tableName( $delTable );
1127 $joinTable = $this->tableName( $joinTable );
1128 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1130 if ( $conds != '*' ) {
1131 $sql .= ' AND ' . $this->makeList( $conds, self
::LIST_AND
);
1134 return $this->query( $sql, $fname );
1138 * @param string $table
1139 * @param array $rows
1140 * @param array $uniqueIndexes
1142 * @param string $fname
1145 public function upsert( $table, array $rows, array $uniqueIndexes,
1146 array $set, $fname = __METHOD__
1148 if ( !count( $rows ) ) {
1149 return true; // nothing to do
1152 if ( !is_array( reset( $rows ) ) ) {
1156 $table = $this->tableName( $table );
1157 $columns = array_keys( $rows[0] );
1159 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1161 foreach ( $rows as $row ) {
1162 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1164 $sql .= implode( ',', $rowTuples );
1165 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, self
::LIST_SET
);
1167 return (bool)$this->query( $sql, $fname );
1171 * Determines how long the server has been up
1175 public function getServerUptime() {
1176 $vars = $this->getMysqlStatus( 'Uptime' );
1178 return (int)$vars['Uptime'];
1182 * Determines if the last failure was due to a deadlock
1186 public function wasDeadlock() {
1187 return $this->lastErrno() == 1213;
1191 * Determines if the last failure was due to a lock timeout
1195 public function wasLockTimeout() {
1196 return $this->lastErrno() == 1205;
1199 public function wasErrorReissuable() {
1200 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
1204 * Determines if the last failure was due to the database being read-only.
1208 public function wasReadOnlyError() {
1209 return $this->lastErrno() == 1223 ||
1210 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1213 public function wasConnectionError( $errno ) {
1214 return $errno == 2013 ||
$errno == 2006;
1218 * @param string $oldName
1219 * @param string $newName
1220 * @param bool $temporary
1221 * @param string $fname
1224 public function duplicateTableStructure(
1225 $oldName, $newName, $temporary = false, $fname = __METHOD__
1227 $tmp = $temporary ?
'TEMPORARY ' : '';
1228 $newName = $this->addIdentifierQuotes( $newName );
1229 $oldName = $this->addIdentifierQuotes( $oldName );
1230 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1232 return $this->query( $query, $fname );
1236 * List all tables on the database
1238 * @param string $prefix Only show tables with this prefix, e.g. mw_
1239 * @param string $fname Calling function name
1242 public function listTables( $prefix = null, $fname = __METHOD__
) {
1243 $result = $this->query( "SHOW TABLES", $fname );
1247 foreach ( $result as $table ) {
1248 $vars = get_object_vars( $table );
1249 $table = array_pop( $vars );
1251 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1252 $endArray[] = $table;
1260 * @param string $tableName
1261 * @param string $fName
1262 * @return bool|ResultWrapper
1264 public function dropTable( $tableName, $fName = __METHOD__
) {
1265 if ( !$this->tableExists( $tableName, $fName ) ) {
1269 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1273 * Get status information from SHOW STATUS in an associative array
1275 * @param string $which
1278 private function getMysqlStatus( $which = "%" ) {
1279 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1282 foreach ( $res as $row ) {
1283 $status[$row->Variable_name
] = $row->Value
;
1290 * Lists VIEWs in the database
1292 * @param string $prefix Only show VIEWs with this prefix, eg.
1293 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1294 * @param string $fname Name of calling function
1298 public function listViews( $prefix = null, $fname = __METHOD__
) {
1299 // The name of the column containing the name of the VIEW
1300 $propertyName = 'Tables_in_' . $this->mDBname
;
1302 // Query for the VIEWS
1303 $res = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1305 foreach ( $res as $row ) {
1306 array_push( $allViews, $row->$propertyName );
1309 if ( is_null( $prefix ) ||
$prefix === '' ) {
1313 $filteredViews = [];
1314 foreach ( $allViews as $viewName ) {
1315 // Does the name of this VIEW start with the table-prefix?
1316 if ( strpos( $viewName, $prefix ) === 0 ) {
1317 array_push( $filteredViews, $viewName );
1321 return $filteredViews;
1325 * Differentiates between a TABLE and a VIEW.
1327 * @param string $name Name of the TABLE/VIEW to test
1328 * @param string $prefix
1332 public function isView( $name, $prefix = null ) {
1333 return in_array( $name, $this->listViews( $prefix ) );