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 Database
{
33 /** @var MysqlMasterPos */
34 protected $lastKnownSlavePos;
35 /** @var string Method to detect slave lag */
36 protected $lagDetectionMethod;
37 /** @var array Method to detect slave lag */
38 protected $lagDetectionOptions = [];
40 /** @var string|null */
41 private $serverVersion = null;
44 * Additional $params include:
45 * - lagDetectionMethod : set to one of (Seconds_Behind_Master,pt-heartbeat).
46 * pt-heartbeat assumes the table is at heartbeat.heartbeat
47 * and uses UTC timestamps in the heartbeat.ts column.
48 * (https://www.percona.com/doc/percona-toolkit/2.2/pt-heartbeat.html)
49 * - lagDetectionOptions : if using pt-heartbeat, this can be set to an array map to change
50 * the default behavior. Normally, the heartbeat row with the server
51 * ID of this server's master will be used. Set the "conds" field to
52 * override the query conditions, e.g. ['shard' => 's1'].
53 * @param array $params
55 function __construct( array $params ) {
56 parent
::__construct( $params );
58 $this->lagDetectionMethod
= isset( $params['lagDetectionMethod'] )
59 ?
$params['lagDetectionMethod']
60 : 'Seconds_Behind_Master';
61 $this->lagDetectionOptions
= isset( $params['lagDetectionOptions'] )
62 ?
$params['lagDetectionOptions']
74 * @param string $server
76 * @param string $password
77 * @param string $dbName
78 * @throws Exception|DBConnectionError
81 function open( $server, $user, $password, $dbName ) {
82 global $wgAllDBsAreLocalhost, $wgSQLMode;
84 # Close/unset connection handle
87 # Debugging hack -- fake cluster
88 $realServer = $wgAllDBsAreLocalhost ?
'localhost' : $server;
89 $this->mServer
= $server;
91 $this->mPassword
= $password;
92 $this->mDBname
= $dbName;
94 $this->installErrorHandler();
96 $this->mConn
= $this->mysqlConnect( $realServer );
97 } catch ( Exception
$ex ) {
98 $this->restoreErrorHandler();
101 $error = $this->restoreErrorHandler();
103 # Always log connection errors
104 if ( !$this->mConn
) {
106 $error = $this->lastError();
109 "Error connecting to {db_server}: {error}",
110 $this->getLogContext( [
111 'method' => __METHOD__
,
115 wfDebug( "DB connection error\n" .
116 "Server: $server, User: $user, Password: " .
117 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
119 $this->reportConnectionError( $error );
122 if ( $dbName != '' ) {
123 MediaWiki\
suppressWarnings();
124 $success = $this->selectDB( $dbName );
125 MediaWiki\restoreWarnings
();
128 "Error selecting database {db_name} on server {db_server}",
129 $this->getLogContext( [
130 'method' => __METHOD__
,
133 wfDebug( "Error selecting database $dbName on server {$this->mServer} " .
134 "from client host " . wfHostname() . "\n" );
136 $this->reportConnectionError( "Error selecting database $dbName" );
140 // Tell the server what we're communicating with
141 if ( !$this->connectInitCharset() ) {
142 $this->reportConnectionError( "Error setting character set" );
145 // Abstract over any insane MySQL defaults
146 $set = [ 'group_concat_max_len = 262144' ];
147 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
148 if ( is_string( $wgSQLMode ) ) {
149 $set[] = 'sql_mode = ' . $this->addQuotes( $wgSQLMode );
151 // Set any custom settings defined by site config
152 // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
153 foreach ( $this->mSessionVars
as $var => $val ) {
154 // Escape strings but not numbers to avoid MySQL complaining
155 if ( !is_int( $val ) && !is_float( $val ) ) {
156 $val = $this->addQuotes( $val );
158 $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
162 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
163 $success = $this->doQuery( 'SET ' . implode( ', ', $set ) );
166 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)',
167 $this->getLogContext( [
168 'method' => __METHOD__
,
171 $this->reportConnectionError(
172 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)' );
176 $this->mOpened
= true;
182 * Set the character set information right after connection
185 protected function connectInitCharset() {
189 // Tell the server we're communicating with it in UTF-8.
190 // This may engage various charset conversions.
191 return $this->mysqlSetCharset( 'utf8' );
193 return $this->mysqlSetCharset( 'binary' );
198 * Open a connection to a MySQL server
200 * @param string $realServer
201 * @return mixed Raw connection
202 * @throws DBConnectionError
204 abstract protected function mysqlConnect( $realServer );
207 * Set the character set of the MySQL link
209 * @param string $charset
212 abstract protected function mysqlSetCharset( $charset );
215 * @param ResultWrapper|resource $res
216 * @throws DBUnexpectedError
218 function freeResult( $res ) {
219 if ( $res instanceof ResultWrapper
) {
222 MediaWiki\
suppressWarnings();
223 $ok = $this->mysqlFreeResult( $res );
224 MediaWiki\restoreWarnings
();
226 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
233 * @param resource $res Raw result
236 abstract protected function mysqlFreeResult( $res );
239 * @param ResultWrapper|resource $res
240 * @return stdClass|bool
241 * @throws DBUnexpectedError
243 function fetchObject( $res ) {
244 if ( $res instanceof ResultWrapper
) {
247 MediaWiki\
suppressWarnings();
248 $row = $this->mysqlFetchObject( $res );
249 MediaWiki\restoreWarnings
();
251 $errno = $this->lastErrno();
252 // Unfortunately, mysql_fetch_object does not reset the last errno.
253 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
254 // these are the only errors mysql_fetch_object can cause.
255 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
256 if ( $errno == 2000 ||
$errno == 2013 ) {
257 throw new DBUnexpectedError(
259 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
267 * Fetch a result row as an object
269 * @param resource $res Raw result
272 abstract protected function mysqlFetchObject( $res );
275 * @param ResultWrapper|resource $res
277 * @throws DBUnexpectedError
279 function fetchRow( $res ) {
280 if ( $res instanceof ResultWrapper
) {
283 MediaWiki\
suppressWarnings();
284 $row = $this->mysqlFetchArray( $res );
285 MediaWiki\restoreWarnings
();
287 $errno = $this->lastErrno();
288 // Unfortunately, mysql_fetch_array does not reset the last errno.
289 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
290 // these are the only errors mysql_fetch_array can cause.
291 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
292 if ( $errno == 2000 ||
$errno == 2013 ) {
293 throw new DBUnexpectedError(
295 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
303 * Fetch a result row as an associative and numeric array
305 * @param resource $res Raw result
308 abstract protected function mysqlFetchArray( $res );
311 * @throws DBUnexpectedError
312 * @param ResultWrapper|resource $res
315 function numRows( $res ) {
316 if ( $res instanceof ResultWrapper
) {
319 MediaWiki\
suppressWarnings();
320 $n = $this->mysqlNumRows( $res );
321 MediaWiki\restoreWarnings
();
323 // Unfortunately, mysql_num_rows does not reset the last errno.
324 // We are not checking for any errors here, since
325 // these are no errors mysql_num_rows can cause.
326 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
327 // See https://phabricator.wikimedia.org/T44430
332 * Get number of rows in result
334 * @param resource $res Raw result
337 abstract protected function mysqlNumRows( $res );
340 * @param ResultWrapper|resource $res
343 function numFields( $res ) {
344 if ( $res instanceof ResultWrapper
) {
348 return $this->mysqlNumFields( $res );
352 * Get number of fields in result
354 * @param resource $res Raw result
357 abstract protected function mysqlNumFields( $res );
360 * @param ResultWrapper|resource $res
364 function fieldName( $res, $n ) {
365 if ( $res instanceof ResultWrapper
) {
369 return $this->mysqlFieldName( $res, $n );
373 * Get the name of the specified field in a result
375 * @param ResultWrapper|resource $res
379 abstract protected function mysqlFieldName( $res, $n );
382 * mysql_field_type() wrapper
383 * @param ResultWrapper|resource $res
387 public function fieldType( $res, $n ) {
388 if ( $res instanceof ResultWrapper
) {
392 return $this->mysqlFieldType( $res, $n );
396 * Get the type of the specified field in a result
398 * @param ResultWrapper|resource $res
402 abstract protected function mysqlFieldType( $res, $n );
405 * @param ResultWrapper|resource $res
409 function dataSeek( $res, $row ) {
410 if ( $res instanceof ResultWrapper
) {
414 return $this->mysqlDataSeek( $res, $row );
418 * Move internal result pointer
420 * @param ResultWrapper|resource $res
424 abstract protected function mysqlDataSeek( $res, $row );
429 function lastError() {
430 if ( $this->mConn
) {
431 # Even if it's non-zero, it can still be invalid
432 MediaWiki\
suppressWarnings();
433 $error = $this->mysqlError( $this->mConn
);
435 $error = $this->mysqlError();
437 MediaWiki\restoreWarnings
();
439 $error = $this->mysqlError();
442 $error .= ' (' . $this->mServer
. ')';
449 * Returns the text of the error message from previous MySQL operation
451 * @param resource $conn Raw connection
454 abstract protected function mysqlError( $conn = null );
457 * @param string $table
458 * @param array $uniqueIndexes
460 * @param string $fname
461 * @return ResultWrapper
463 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
464 return $this->nativeReplace( $table, $rows, $fname );
468 * Estimate rows in dataset
469 * Returns estimated count, based on EXPLAIN output
470 * Takes same arguments as Database::select()
472 * @param string|array $table
473 * @param string|array $vars
474 * @param string|array $conds
475 * @param string $fname
476 * @param string|array $options
479 public function estimateRowCount( $table, $vars = '*', $conds = '',
480 $fname = __METHOD__
, $options = []
482 $options['EXPLAIN'] = true;
483 $res = $this->select( $table, $vars, $conds, $fname, $options );
484 if ( $res === false ) {
487 if ( !$this->numRows( $res ) ) {
492 foreach ( $res as $plan ) {
493 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
500 * @param string $table
501 * @param string $field
502 * @return bool|MySQLField
504 function fieldInfo( $table, $field ) {
505 $table = $this->tableName( $table );
506 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
510 $n = $this->mysqlNumFields( $res->result
);
511 for ( $i = 0; $i < $n; $i++
) {
512 $meta = $this->mysqlFetchField( $res->result
, $i );
513 if ( $field == $meta->name
) {
514 return new MySQLField( $meta );
522 * Get column information from a result
524 * @param resource $res Raw result
528 abstract protected function mysqlFetchField( $res, $n );
531 * Get information about an index into an object
532 * Returns false if the index does not exist
534 * @param string $table
535 * @param string $index
536 * @param string $fname
537 * @return bool|array|null False or null on failure
539 function indexInfo( $table, $index, $fname = __METHOD__
) {
540 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
541 # SHOW INDEX should work for 3.x and up:
542 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
543 $table = $this->tableName( $table );
544 $index = $this->indexName( $index );
546 $sql = 'SHOW INDEX FROM ' . $table;
547 $res = $this->query( $sql, $fname );
555 foreach ( $res as $row ) {
556 if ( $row->Key_name
== $index ) {
561 return empty( $result ) ?
false : $result;
568 function strencode( $s ) {
569 $sQuoted = $this->mysqlRealEscapeString( $s );
571 if ( $sQuoted === false ) {
573 $sQuoted = $this->mysqlRealEscapeString( $s );
583 abstract protected function mysqlRealEscapeString( $s );
586 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
591 public function addIdentifierQuotes( $s ) {
592 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
593 // Remove NUL bytes and escape backticks by doubling
594 return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
598 * @param string $name
601 public function isQuotedIdentifier( $name ) {
602 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
609 $ping = $this->mysqlPing();
611 // Connection was good or lost but reconnected...
612 // @note: mysqlnd (php 5.6+) does not support this (PHP bug 52561)
616 // Try a full disconnect/reconnect cycle if ping() failed
617 $this->closeConnection();
618 $this->mOpened
= false;
619 $this->mConn
= false;
620 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
626 * Ping a server connection or reconnect if there is no connection
630 abstract protected function mysqlPing();
633 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
634 return $this->getLagFromPtHeartbeat();
636 return $this->getLagFromSlaveStatus();
643 protected function getLagDetectionMethod() {
644 return $this->lagDetectionMethod
;
650 protected function getLagFromSlaveStatus() {
651 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
652 $row = $res ?
$res->fetchObject() : false;
653 if ( $row && strval( $row->Seconds_Behind_Master
) !== '' ) {
654 return intval( $row->Seconds_Behind_Master
);
663 protected function getLagFromPtHeartbeat() {
664 $options = $this->lagDetectionOptions
;
666 if ( isset( $options['conds'] ) ) {
667 // Best method for multi-DC setups: use logical channel names
668 $data = $this->getHeartbeatData( $options['conds'] );
670 // Standard method: use master server ID (works with stock pt-heartbeat)
671 $masterInfo = $this->getMasterServerInfo();
672 if ( !$masterInfo ) {
674 "Unable to query master of {db_server} for server ID",
675 $this->getLogContext( [
676 'method' => __METHOD__
680 return false; // could not get master server ID
683 $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
684 $data = $this->getHeartbeatData( $conds );
687 list( $time, $nowUnix ) = $data;
688 if ( $time !== null ) {
689 // @time is in ISO format like "2015-09-25T16:48:10.000510"
690 $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
691 $timeUnix = (int)$dateTime->format( 'U' ) +
$dateTime->format( 'u' ) / 1e6
;
693 return max( $nowUnix - $timeUnix, 0.0 );
697 "Unable to find pt-heartbeat row for {db_server}",
698 $this->getLogContext( [
699 'method' => __METHOD__
706 protected function getMasterServerInfo() {
707 $cache = $this->srvCache
;
708 $key = $cache->makeGlobalKey(
711 // Using one key for all cluster slaves is preferable
712 $this->getLBInfo( 'clusterMasterHost' ) ?
: $this->getServer()
715 return $cache->getWithSetCallback(
717 $cache::TTL_INDEFINITE
,
718 function () use ( $cache, $key ) {
719 // Get and leave a lock key in place for a short period
720 if ( !$cache->lock( $key, 0, 10 ) ) {
721 return false; // avoid master connection spike slams
724 $conn = $this->getLazyMasterHandle();
726 return false; // something is misconfigured
729 // Connect to and query the master; catch errors to avoid outages
731 $res = $conn->query( 'SELECT @@server_id AS id', __METHOD__
);
732 $row = $res ?
$res->fetchObject() : false;
733 $id = $row ?
(int)$row->id
: 0;
734 } catch ( DBError
$e ) {
738 // Cache the ID if it was retrieved
739 return $id ?
[ 'serverId' => $id, 'asOf' => time() ] : false;
745 * @param array $conds WHERE clause conditions to find a row
746 * @return array (heartbeat `ts` column value or null, UNIX timestamp) for the newest beat
747 * @see https://www.percona.com/doc/percona-toolkit/2.1/pt-heartbeat.html
749 protected function getHeartbeatData( array $conds ) {
750 $whereSQL = $this->makeList( $conds, LIST_AND
);
751 // Use ORDER BY for channel based queries since that field might not be UNIQUE.
752 // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
753 // percision field is not supported in MySQL <= 5.5.
755 "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1"
757 $row = $res ?
$res->fetchObject() : false;
759 return [ $row ?
$row->ts
: null, microtime( true ) ];
762 public function getApproximateLagStatus() {
763 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
764 // Disable caching since this is fast enough and we don't wan't
765 // to be *too* pessimistic by having both the cache TTL and the
766 // pt-heartbeat interval count as lag in getSessionLagStatus()
767 return parent
::getApproximateLagStatus();
770 $key = $this->srvCache
->makeGlobalKey( 'mysql-lag', $this->getServer() );
771 $approxLag = $this->srvCache
->get( $key );
773 $approxLag = parent
::getApproximateLagStatus();
774 $this->srvCache
->set( $key, $approxLag, 1 );
780 function masterPosWait( DBMasterPos
$pos, $timeout ) {
781 if ( !( $pos instanceof MySQLMasterPos
) ) {
782 throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
785 if ( $this->getLBInfo( 'is static' ) === true ) {
786 return 0; // this is a copy of a read-only dataset with no master DB
787 } elseif ( $this->lastKnownSlavePos
&& $this->lastKnownSlavePos
->hasReached( $pos ) ) {
788 return 0; // already reached this point for sure
791 # Commit any open transactions
792 $this->commit( __METHOD__
, 'flush' );
794 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
795 $encFile = $this->addQuotes( $pos->file
);
796 $encPos = intval( $pos->pos
);
797 $res = $this->doQuery( "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)" );
799 $row = $res ?
$this->fetchRow( $res ) : false;
801 throw new DBExpectedError( $this, "Failed to query MASTER_POS_WAIT()" );
804 // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
805 $status = ( $row[0] !== null ) ?
intval( $row[0] ) : null;
806 if ( $status === null ) {
807 // T126436: jobs programmed to wait on master positions might be referencing binlogs
808 // with an old master hostname. Such calls make MASTER_POS_WAIT() return null. Try
809 // to detect this and treat the slave as having reached the position; a proper master
810 // switchover already requires that the new master be caught up before the switch.
811 $slavePos = $this->getSlavePos();
812 if ( $slavePos && !$slavePos->channelsMatch( $pos ) ) {
813 $this->lastKnownSlavePos
= $slavePos;
816 } elseif ( $status >= 0 ) {
817 // Remember that this position was reached to save queries next time
818 $this->lastKnownSlavePos
= $pos;
825 * Get the position of the master from SHOW SLAVE STATUS
827 * @return MySQLMasterPos|bool
829 function getSlavePos() {
830 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
831 $row = $this->fetchObject( $res );
834 $pos = isset( $row->Exec_master_log_pos
)
835 ?
$row->Exec_master_log_pos
836 : $row->Exec_Master_Log_Pos
;
838 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
845 * Get the position of the master from SHOW MASTER STATUS
847 * @return MySQLMasterPos|bool
849 function getMasterPos() {
850 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
851 $row = $this->fetchObject( $res );
854 return new MySQLMasterPos( $row->File
, $row->Position
);
861 * @param string $index
864 function useIndexClause( $index ) {
865 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
871 function lowPriorityOption() {
872 return 'LOW_PRIORITY';
878 public function getSoftwareLink() {
879 // MariaDB includes its name in its version string; this is how MariaDB's version of
880 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
881 // in libmysql/libmysql.c).
882 $version = $this->getServerVersion();
883 if ( strpos( $version, 'MariaDB' ) !== false ||
strpos( $version, '-maria-' ) !== false ) {
884 return '[{{int:version-db-mariadb-url}} MariaDB]';
887 // Percona Server's version suffix is not very distinctive, and @@version_comment
888 // doesn't give the necessary info for source builds, so assume the server is MySQL.
889 // (Even Percona's version of mysql doesn't try to make the distinction.)
890 return '[{{int:version-db-mysql-url}} MySQL]';
896 public function getServerVersion() {
897 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
898 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
899 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
900 if ( $this->serverVersion
=== null ) {
901 $this->serverVersion
= $this->selectField( '', 'VERSION()', '', __METHOD__
);
903 return $this->serverVersion
;
907 * @param array $options
909 public function setSessionOptions( array $options ) {
910 if ( isset( $options['connTimeout'] ) ) {
911 $timeout = (int)$options['connTimeout'];
912 $this->query( "SET net_read_timeout=$timeout" );
913 $this->query( "SET net_write_timeout=$timeout" );
919 * @param string $newLine
922 public function streamStatementEnd( &$sql, &$newLine ) {
923 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
924 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
925 $this->delimiter
= $m[1];
929 return parent
::streamStatementEnd( $sql, $newLine );
933 * Check to see if a named lock is available. This is non-blocking.
935 * @param string $lockName Name of lock to poll
936 * @param string $method Name of method calling us
940 public function lockIsFree( $lockName, $method ) {
941 $lockName = $this->addQuotes( $this->makeLockName( $lockName ) );
942 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
943 $row = $this->fetchObject( $result );
945 return ( $row->lockstatus
== 1 );
949 * @param string $lockName
950 * @param string $method
951 * @param int $timeout
954 public function lock( $lockName, $method, $timeout = 5 ) {
955 $lockName = $this->addQuotes( $this->makeLockName( $lockName ) );
956 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
957 $row = $this->fetchObject( $result );
959 if ( $row->lockstatus
== 1 ) {
960 parent
::lock( $lockName, $method, $timeout ); // record
964 wfDebug( __METHOD__
. " failed to acquire lock\n" );
971 * http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
972 * @param string $lockName
973 * @param string $method
976 public function unlock( $lockName, $method ) {
977 $lockName = $this->addQuotes( $this->makeLockName( $lockName ) );
978 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
979 $row = $this->fetchObject( $result );
981 if ( $row->lockstatus
== 1 ) {
982 parent
::unlock( $lockName, $method ); // record
986 wfDebug( __METHOD__
. " failed to release lock\n" );
991 private function makeLockName( $lockName ) {
992 // http://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
993 // Newer version enforce a 64 char length limit.
994 return ( strlen( $lockName ) > 64 ) ?
sha1( $lockName ) : $lockName;
997 public function namedLocksEnqueue() {
1002 * @param array $read
1003 * @param array $write
1004 * @param string $method
1005 * @param bool $lowPriority
1008 public function lockTables( $read, $write, $method, $lowPriority = true ) {
1011 foreach ( $write as $table ) {
1012 $tbl = $this->tableName( $table ) .
1013 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
1017 foreach ( $read as $table ) {
1018 $items[] = $this->tableName( $table ) . ' READ';
1020 $sql = "LOCK TABLES " . implode( ',', $items );
1021 $this->query( $sql, $method );
1027 * @param string $method
1030 public function unlockTables( $method ) {
1031 $this->query( "UNLOCK TABLES", $method );
1037 * Get search engine class. All subclasses of this
1038 * need to implement this if they wish to use searching.
1042 public function getSearchEngine() {
1043 return 'SearchMySQL';
1047 * @param bool $value
1049 public function setBigSelects( $value = true ) {
1050 if ( $value === 'default' ) {
1051 if ( $this->mDefaultBigSelects
=== null ) {
1052 # Function hasn't been called before so it must already be set to the default
1055 $value = $this->mDefaultBigSelects
;
1057 } elseif ( $this->mDefaultBigSelects
=== null ) {
1058 $this->mDefaultBigSelects
=
1059 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__
);
1061 $encValue = $value ?
'1' : '0';
1062 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
1066 * DELETE where the condition is a join. MySql uses multi-table deletes.
1067 * @param string $delTable
1068 * @param string $joinTable
1069 * @param string $delVar
1070 * @param string $joinVar
1071 * @param array|string $conds
1072 * @param bool|string $fname
1073 * @throws DBUnexpectedError
1074 * @return bool|ResultWrapper
1076 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
) {
1078 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
1081 $delTable = $this->tableName( $delTable );
1082 $joinTable = $this->tableName( $joinTable );
1083 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1085 if ( $conds != '*' ) {
1086 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1089 return $this->query( $sql, $fname );
1093 * @param string $table
1094 * @param array $rows
1095 * @param array $uniqueIndexes
1097 * @param string $fname
1100 public function upsert( $table, array $rows, array $uniqueIndexes,
1101 array $set, $fname = __METHOD__
1103 if ( !count( $rows ) ) {
1104 return true; // nothing to do
1107 if ( !is_array( reset( $rows ) ) ) {
1111 $table = $this->tableName( $table );
1112 $columns = array_keys( $rows[0] );
1114 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1116 foreach ( $rows as $row ) {
1117 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1119 $sql .= implode( ',', $rowTuples );
1120 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, LIST_SET
);
1122 return (bool)$this->query( $sql, $fname );
1126 * Determines how long the server has been up
1130 function getServerUptime() {
1131 $vars = $this->getMysqlStatus( 'Uptime' );
1133 return (int)$vars['Uptime'];
1137 * Determines if the last failure was due to a deadlock
1141 function wasDeadlock() {
1142 return $this->lastErrno() == 1213;
1146 * Determines if the last failure was due to a lock timeout
1150 function wasLockTimeout() {
1151 return $this->lastErrno() == 1205;
1155 * Determines if the last query error was something that should be dealt
1156 * with by pinging the connection and reissuing the query
1160 function wasErrorReissuable() {
1161 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
1165 * Determines if the last failure was due to the database being read-only.
1169 function wasReadOnlyError() {
1170 return $this->lastErrno() == 1223 ||
1171 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1174 function wasConnectionError( $errno ) {
1175 return $errno == 2013 ||
$errno == 2006;
1179 * Get the underlying binding handle, mConn
1181 * Makes sure that mConn is set (disconnects and ping() failure can unset it).
1182 * This catches broken callers than catch and ignore disconnection exceptions.
1183 * Unlike checking isOpen(), this is safe to call inside of open().
1185 * @return resource|object
1186 * @throws DBUnexpectedError
1189 protected function getBindingHandle() {
1190 if ( !$this->mConn
) {
1191 throw new DBUnexpectedError(
1193 'DB connection was already closed or the connection dropped.'
1197 return $this->mConn
;
1201 * @param string $oldName
1202 * @param string $newName
1203 * @param bool $temporary
1204 * @param string $fname
1207 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
1208 $tmp = $temporary ?
'TEMPORARY ' : '';
1209 $newName = $this->addIdentifierQuotes( $newName );
1210 $oldName = $this->addIdentifierQuotes( $oldName );
1211 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1213 return $this->query( $query, $fname );
1217 * List all tables on the database
1219 * @param string $prefix Only show tables with this prefix, e.g. mw_
1220 * @param string $fname Calling function name
1223 function listTables( $prefix = null, $fname = __METHOD__
) {
1224 $result = $this->query( "SHOW TABLES", $fname );
1228 foreach ( $result as $table ) {
1229 $vars = get_object_vars( $table );
1230 $table = array_pop( $vars );
1232 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1233 $endArray[] = $table;
1241 * @param string $tableName
1242 * @param string $fName
1243 * @return bool|ResultWrapper
1245 public function dropTable( $tableName, $fName = __METHOD__
) {
1246 if ( !$this->tableExists( $tableName, $fName ) ) {
1250 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1256 protected function getDefaultSchemaVars() {
1257 $vars = parent
::getDefaultSchemaVars();
1258 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
1259 $vars['wgDBTableOptions'] = str_replace(
1262 $vars['wgDBTableOptions']
1269 * Get status information from SHOW STATUS in an associative array
1271 * @param string $which
1274 function getMysqlStatus( $which = "%" ) {
1275 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1278 foreach ( $res as $row ) {
1279 $status[$row->Variable_name
] = $row->Value
;
1286 * Lists VIEWs in the database
1288 * @param string $prefix Only show VIEWs with this prefix, eg.
1289 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1290 * @param string $fname Name of calling function
1294 public function listViews( $prefix = null, $fname = __METHOD__
) {
1296 if ( !isset( $this->allViews
) ) {
1298 // The name of the column containing the name of the VIEW
1299 $propertyName = 'Tables_in_' . $this->mDBname
;
1301 // Query for the VIEWS
1302 $result = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1303 $this->allViews
= [];
1304 while ( ( $row = $this->fetchRow( $result ) ) !== false ) {
1305 array_push( $this->allViews
, $row[$propertyName] );
1309 if ( is_null( $prefix ) ||
$prefix === '' ) {
1310 return $this->allViews
;
1313 $filteredViews = [];
1314 foreach ( $this->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 ) );
1341 class MySQLField
implements Field
{
1342 private $name, $tablename, $default, $max_length, $nullable,
1343 $is_pk, $is_unique, $is_multiple, $is_key, $type, $binary,
1344 $is_numeric, $is_blob, $is_unsigned, $is_zerofill;
1346 function __construct( $info ) {
1347 $this->name
= $info->name
;
1348 $this->tablename
= $info->table
;
1349 $this->default = $info->def
;
1350 $this->max_length
= $info->max_length
;
1351 $this->nullable
= !$info->not_null
;
1352 $this->is_pk
= $info->primary_key
;
1353 $this->is_unique
= $info->unique_key
;
1354 $this->is_multiple
= $info->multiple_key
;
1355 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
1356 $this->type
= $info->type
;
1357 $this->binary
= isset( $info->binary
) ?
$info->binary
: false;
1358 $this->is_numeric
= isset( $info->numeric ) ?
$info->numeric : false;
1359 $this->is_blob
= isset( $info->blob
) ?
$info->blob
: false;
1360 $this->is_unsigned
= isset( $info->unsigned
) ?
$info->unsigned
: false;
1361 $this->is_zerofill
= isset( $info->zerofill
) ?
$info->zerofill
: false;
1374 function tableName() {
1375 return $this->tablename
;
1388 function isNullable() {
1389 return $this->nullable
;
1392 function defaultValue() {
1393 return $this->default;
1400 return $this->is_key
;
1406 function isMultipleKey() {
1407 return $this->is_multiple
;
1413 function isBinary() {
1414 return $this->binary
;
1420 function isNumeric() {
1421 return $this->is_numeric
;
1428 return $this->is_blob
;
1434 function isUnsigned() {
1435 return $this->is_unsigned
;
1441 function isZerofill() {
1442 return $this->is_zerofill
;
1446 class MySQLMasterPos
implements DBMasterPos
{
1449 /** @var int Position */
1451 /** @var float UNIX timestamp */
1452 public $asOfTime = 0.0;
1454 function __construct( $file, $pos ) {
1455 $this->file
= $file;
1457 $this->asOfTime
= microtime( true );
1460 function asOfTime() {
1461 return $this->asOfTime
;
1464 function hasReached( DBMasterPos
$pos ) {
1465 if ( !( $pos instanceof self
) ) {
1466 throw new InvalidArgumentException( "Position not an instance of " . __CLASS__
);
1469 $thisPos = $this->getCoordinates();
1470 $thatPos = $pos->getCoordinates();
1472 return ( $thisPos && $thatPos && $thisPos >= $thatPos );
1475 function channelsMatch( DBMasterPos
$pos ) {
1476 if ( !( $pos instanceof self
) ) {
1477 throw new InvalidArgumentException( "Position not an instance of " . __CLASS__
);
1480 $thisBinlog = $this->getBinlogName();
1481 $thatBinlog = $pos->getBinlogName();
1483 return ( $thisBinlog !== false && $thisBinlog === $thatBinlog );
1486 function __toString() {
1487 // e.g db1034-bin.000976/843431247
1488 return "{$this->file}/{$this->pos}";
1492 * @return string|bool
1494 protected function getBinlogName() {
1496 if ( preg_match( '!^(.+)\.(\d+)/(\d+)$!', (string)$this, $m ) ) {
1504 * @return array|bool (int, int)
1506 protected function getCoordinates() {
1508 if ( preg_match( '!\.(\d+)/(\d+)$!', (string)$this, $m ) ) {
1509 return [ (int)$m[1], (int)$m[2] ];