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 namespace Wikimedia\Rdbms
;
28 use InvalidArgumentException
;
33 * Database abstraction object for MySQL.
34 * Defines methods independent on used MySQL extension.
40 abstract class DatabaseMysqlBase
extends Database
{
41 /** @var MysqlMasterPos */
42 protected $lastKnownReplicaPos;
43 /** @var string Method to detect replica DB lag */
44 protected $lagDetectionMethod;
45 /** @var array Method to detect replica DB lag */
46 protected $lagDetectionOptions = [];
47 /** @var bool bool Whether to use GTID methods */
48 protected $useGTIDs = false;
49 /** @var string|null */
50 protected $sslKeyPath;
51 /** @var string|null */
52 protected $sslCertPath;
53 /** @var string|null */
55 /** @var string[]|null */
56 protected $sslCiphers;
57 /** @var string sql_mode value to send on connection */
59 /** @var bool Use experimental UTF-8 transmission encoding */
62 /** @var string|null */
63 private $serverVersion = null;
66 * Additional $params include:
67 * - lagDetectionMethod : set to one of (Seconds_Behind_Master,pt-heartbeat).
68 * pt-heartbeat assumes the table is at heartbeat.heartbeat
69 * and uses UTC timestamps in the heartbeat.ts column.
70 * (https://www.percona.com/doc/percona-toolkit/2.2/pt-heartbeat.html)
71 * - lagDetectionOptions : if using pt-heartbeat, this can be set to an array map to change
72 * the default behavior. Normally, the heartbeat row with the server
73 * ID of this server's master will be used. Set the "conds" field to
74 * override the query conditions, e.g. ['shard' => 's1'].
75 * - useGTIDs : use GTID methods like MASTER_GTID_WAIT() when possible.
76 * - sslKeyPath : path to key file [default: null]
77 * - sslCertPath : path to certificate file [default: null]
78 * - sslCAPath : parth to certificate authority PEM files [default: null]
79 * - sslCiphers : array list of allowable ciphers [default: null]
80 * @param array $params
82 function __construct( array $params ) {
83 $this->lagDetectionMethod
= isset( $params['lagDetectionMethod'] )
84 ?
$params['lagDetectionMethod']
85 : 'Seconds_Behind_Master';
86 $this->lagDetectionOptions
= isset( $params['lagDetectionOptions'] )
87 ?
$params['lagDetectionOptions']
89 $this->useGTIDs
= !empty( $params['useGTIDs' ] );
90 foreach ( [ 'KeyPath', 'CertPath', 'CAPath', 'Ciphers' ] as $name ) {
92 if ( isset( $params[$var] ) ) {
93 $this->$var = $params[$var];
96 $this->sqlMode
= isset( $params['sqlMode'] ) ?
$params['sqlMode'] : '';
97 $this->utf8Mode
= !empty( $params['utf8Mode'] );
99 parent
::__construct( $params );
105 public function getType() {
110 * @param string $server
111 * @param string $user
112 * @param string $password
113 * @param string $dbName
114 * @throws Exception|DBConnectionError
117 public function open( $server, $user, $password, $dbName ) {
118 # Close/unset connection handle
121 $this->mServer
= $server;
122 $this->mUser
= $user;
123 $this->mPassword
= $password;
124 $this->mDBname
= $dbName;
126 $this->installErrorHandler();
128 $this->mConn
= $this->mysqlConnect( $this->mServer
);
129 } catch ( Exception
$ex ) {
130 $this->restoreErrorHandler();
133 $error = $this->restoreErrorHandler();
135 # Always log connection errors
136 if ( !$this->mConn
) {
138 $error = $this->lastError();
140 $this->connLogger
->error(
141 "Error connecting to {db_server}: {error}",
142 $this->getLogContext( [
143 'method' => __METHOD__
,
147 $this->connLogger
->debug( "DB connection error\n" .
148 "Server: $server, User: $user, Password: " .
149 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
151 $this->reportConnectionError( $error );
154 if ( $dbName != '' ) {
155 MediaWiki\
suppressWarnings();
156 $success = $this->selectDB( $dbName );
157 MediaWiki\restoreWarnings
();
159 $this->queryLogger
->error(
160 "Error selecting database {db_name} on server {db_server}",
161 $this->getLogContext( [
162 'method' => __METHOD__
,
165 $this->queryLogger
->debug(
166 "Error selecting database $dbName on server {$this->mServer}" );
168 $this->reportConnectionError( "Error selecting database $dbName" );
172 // Tell the server what we're communicating with
173 if ( !$this->connectInitCharset() ) {
174 $this->reportConnectionError( "Error setting character set" );
177 // Abstract over any insane MySQL defaults
178 $set = [ 'group_concat_max_len = 262144' ];
179 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
180 if ( is_string( $this->sqlMode
) ) {
181 $set[] = 'sql_mode = ' . $this->addQuotes( $this->sqlMode
);
183 // Set any custom settings defined by site config
184 // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
185 foreach ( $this->mSessionVars
as $var => $val ) {
186 // Escape strings but not numbers to avoid MySQL complaining
187 if ( !is_int( $val ) && !is_float( $val ) ) {
188 $val = $this->addQuotes( $val );
190 $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
194 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
195 $success = $this->doQuery( 'SET ' . implode( ', ', $set ) );
197 $this->queryLogger
->error(
198 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)',
199 $this->getLogContext( [
200 'method' => __METHOD__
,
203 $this->reportConnectionError(
204 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)' );
208 $this->mOpened
= true;
214 * Set the character set information right after connection
217 protected function connectInitCharset() {
218 if ( $this->utf8Mode
) {
219 // Tell the server we're communicating with it in UTF-8.
220 // This may engage various charset conversions.
221 return $this->mysqlSetCharset( 'utf8' );
223 return $this->mysqlSetCharset( 'binary' );
228 * Open a connection to a MySQL server
230 * @param string $realServer
231 * @return mixed Raw connection
232 * @throws DBConnectionError
234 abstract protected function mysqlConnect( $realServer );
237 * Set the character set of the MySQL link
239 * @param string $charset
242 abstract protected function mysqlSetCharset( $charset );
245 * @param ResultWrapper|resource $res
246 * @throws DBUnexpectedError
248 public function freeResult( $res ) {
249 if ( $res instanceof ResultWrapper
) {
252 MediaWiki\
suppressWarnings();
253 $ok = $this->mysqlFreeResult( $res );
254 MediaWiki\restoreWarnings
();
256 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
263 * @param resource $res Raw result
266 abstract protected function mysqlFreeResult( $res );
269 * @param ResultWrapper|resource $res
270 * @return stdClass|bool
271 * @throws DBUnexpectedError
273 public function fetchObject( $res ) {
274 if ( $res instanceof ResultWrapper
) {
277 MediaWiki\
suppressWarnings();
278 $row = $this->mysqlFetchObject( $res );
279 MediaWiki\restoreWarnings
();
281 $errno = $this->lastErrno();
282 // Unfortunately, mysql_fetch_object does not reset the last errno.
283 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
284 // these are the only errors mysql_fetch_object can cause.
285 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
286 if ( $errno == 2000 ||
$errno == 2013 ) {
287 throw new DBUnexpectedError(
289 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
297 * Fetch a result row as an object
299 * @param resource $res Raw result
302 abstract protected function mysqlFetchObject( $res );
305 * @param ResultWrapper|resource $res
307 * @throws DBUnexpectedError
309 public function fetchRow( $res ) {
310 if ( $res instanceof ResultWrapper
) {
313 MediaWiki\
suppressWarnings();
314 $row = $this->mysqlFetchArray( $res );
315 MediaWiki\restoreWarnings
();
317 $errno = $this->lastErrno();
318 // Unfortunately, mysql_fetch_array does not reset the last errno.
319 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
320 // these are the only errors mysql_fetch_array can cause.
321 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
322 if ( $errno == 2000 ||
$errno == 2013 ) {
323 throw new DBUnexpectedError(
325 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
333 * Fetch a result row as an associative and numeric array
335 * @param resource $res Raw result
338 abstract protected function mysqlFetchArray( $res );
341 * @throws DBUnexpectedError
342 * @param ResultWrapper|resource $res
345 function numRows( $res ) {
346 if ( $res instanceof ResultWrapper
) {
349 MediaWiki\
suppressWarnings();
350 $n = $this->mysqlNumRows( $res );
351 MediaWiki\restoreWarnings
();
353 // Unfortunately, mysql_num_rows does not reset the last errno.
354 // We are not checking for any errors here, since
355 // these are no errors mysql_num_rows can cause.
356 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
357 // See https://phabricator.wikimedia.org/T44430
362 * Get number of rows in result
364 * @param resource $res Raw result
367 abstract protected function mysqlNumRows( $res );
370 * @param ResultWrapper|resource $res
373 public function numFields( $res ) {
374 if ( $res instanceof ResultWrapper
) {
378 return $this->mysqlNumFields( $res );
382 * Get number of fields in result
384 * @param resource $res Raw result
387 abstract protected function mysqlNumFields( $res );
390 * @param ResultWrapper|resource $res
394 public function fieldName( $res, $n ) {
395 if ( $res instanceof ResultWrapper
) {
399 return $this->mysqlFieldName( $res, $n );
403 * Get the name of the specified field in a result
405 * @param ResultWrapper|resource $res
409 abstract protected function mysqlFieldName( $res, $n );
412 * mysql_field_type() wrapper
413 * @param ResultWrapper|resource $res
417 public function fieldType( $res, $n ) {
418 if ( $res instanceof ResultWrapper
) {
422 return $this->mysqlFieldType( $res, $n );
426 * Get the type of the specified field in a result
428 * @param ResultWrapper|resource $res
432 abstract protected function mysqlFieldType( $res, $n );
435 * @param ResultWrapper|resource $res
439 public function dataSeek( $res, $row ) {
440 if ( $res instanceof ResultWrapper
) {
444 return $this->mysqlDataSeek( $res, $row );
448 * Move internal result pointer
450 * @param ResultWrapper|resource $res
454 abstract protected function mysqlDataSeek( $res, $row );
459 public function lastError() {
460 if ( $this->mConn
) {
461 # Even if it's non-zero, it can still be invalid
462 MediaWiki\
suppressWarnings();
463 $error = $this->mysqlError( $this->mConn
);
465 $error = $this->mysqlError();
467 MediaWiki\restoreWarnings
();
469 $error = $this->mysqlError();
472 $error .= ' (' . $this->mServer
. ')';
479 * Returns the text of the error message from previous MySQL operation
481 * @param resource $conn Raw connection
484 abstract protected function mysqlError( $conn = null );
487 * @param string $table
488 * @param array $uniqueIndexes
490 * @param string $fname
491 * @return ResultWrapper
493 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
494 return $this->nativeReplace( $table, $rows, $fname );
498 * Estimate rows in dataset
499 * Returns estimated count, based on EXPLAIN output
500 * Takes same arguments as Database::select()
502 * @param string|array $table
503 * @param string|array $vars
504 * @param string|array $conds
505 * @param string $fname
506 * @param string|array $options
509 public function estimateRowCount( $table, $vars = '*', $conds = '',
510 $fname = __METHOD__
, $options = []
512 $options['EXPLAIN'] = true;
513 $res = $this->select( $table, $vars, $conds, $fname, $options );
514 if ( $res === false ) {
517 if ( !$this->numRows( $res ) ) {
522 foreach ( $res as $plan ) {
523 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
529 public function tableExists( $table, $fname = __METHOD__
) {
530 $table = $this->tableName( $table, 'raw' );
531 if ( isset( $this->mSessionTempTables
[$table] ) ) {
532 return true; // already known to exist and won't show in SHOW TABLES anyway
535 // We can't use buildLike() here, because it specifies an escape character
536 // other than the backslash, which is the only one supported by SHOW TABLES
537 $encLike = $this->escapeLikeInternal( $table, '\\' );
539 return $this->query( "SHOW TABLES LIKE '$encLike'", $fname )->numRows() > 0;
543 * @param string $table
544 * @param string $field
545 * @return bool|MySQLField
547 public function fieldInfo( $table, $field ) {
548 $table = $this->tableName( $table );
549 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
553 $n = $this->mysqlNumFields( $res->result
);
554 for ( $i = 0; $i < $n; $i++
) {
555 $meta = $this->mysqlFetchField( $res->result
, $i );
556 if ( $field == $meta->name
) {
557 return new MySQLField( $meta );
565 * Get column information from a result
567 * @param resource $res Raw result
571 abstract protected function mysqlFetchField( $res, $n );
574 * Get information about an index into an object
575 * Returns false if the index does not exist
577 * @param string $table
578 * @param string $index
579 * @param string $fname
580 * @return bool|array|null False or null on failure
582 public function indexInfo( $table, $index, $fname = __METHOD__
) {
583 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
584 # SHOW INDEX should work for 3.x and up:
585 # https://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
586 $table = $this->tableName( $table );
587 $index = $this->indexName( $index );
589 $sql = 'SHOW INDEX FROM ' . $table;
590 $res = $this->query( $sql, $fname );
598 foreach ( $res as $row ) {
599 if ( $row->Key_name
== $index ) {
604 return empty( $result ) ?
false : $result;
611 public function strencode( $s ) {
612 return $this->mysqlRealEscapeString( $s );
619 abstract protected function mysqlRealEscapeString( $s );
621 public function addQuotes( $s ) {
622 if ( is_bool( $s ) ) {
623 // Parent would transform to int, which does not play nice with MySQL type juggling.
624 // When searching for an int in a string column, the strings are cast to int, which
625 // means false would match any string not starting with a number.
626 $s = (string)(int)$s;
628 return parent
::addQuotes( $s );
632 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
637 public function addIdentifierQuotes( $s ) {
638 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
639 // Remove NUL bytes and escape backticks by doubling
640 return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
644 * @param string $name
647 public function isQuotedIdentifier( $name ) {
648 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
651 public function getLag() {
652 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
653 return $this->getLagFromPtHeartbeat();
655 return $this->getLagFromSlaveStatus();
662 protected function getLagDetectionMethod() {
663 return $this->lagDetectionMethod
;
669 protected function getLagFromSlaveStatus() {
670 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
671 $row = $res ?
$res->fetchObject() : false;
672 if ( $row && strval( $row->Seconds_Behind_Master
) !== '' ) {
673 return intval( $row->Seconds_Behind_Master
);
682 protected function getLagFromPtHeartbeat() {
683 $options = $this->lagDetectionOptions
;
685 if ( isset( $options['conds'] ) ) {
686 // Best method for multi-DC setups: use logical channel names
687 $data = $this->getHeartbeatData( $options['conds'] );
689 // Standard method: use master server ID (works with stock pt-heartbeat)
690 $masterInfo = $this->getMasterServerInfo();
691 if ( !$masterInfo ) {
692 $this->queryLogger
->error(
693 "Unable to query master of {db_server} for server ID",
694 $this->getLogContext( [
695 'method' => __METHOD__
699 return false; // could not get master server ID
702 $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
703 $data = $this->getHeartbeatData( $conds );
706 list( $time, $nowUnix ) = $data;
707 if ( $time !== null ) {
708 // @time is in ISO format like "2015-09-25T16:48:10.000510"
709 $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
710 $timeUnix = (int)$dateTime->format( 'U' ) +
$dateTime->format( 'u' ) / 1e6
;
712 return max( $nowUnix - $timeUnix, 0.0 );
715 $this->queryLogger
->error(
716 "Unable to find pt-heartbeat row for {db_server}",
717 $this->getLogContext( [
718 'method' => __METHOD__
725 protected function getMasterServerInfo() {
726 $cache = $this->srvCache
;
727 $key = $cache->makeGlobalKey(
730 // Using one key for all cluster replica DBs is preferable
731 $this->getLBInfo( 'clusterMasterHost' ) ?
: $this->getServer()
734 return $cache->getWithSetCallback(
736 $cache::TTL_INDEFINITE
,
737 function () use ( $cache, $key ) {
738 // Get and leave a lock key in place for a short period
739 if ( !$cache->lock( $key, 0, 10 ) ) {
740 return false; // avoid master connection spike slams
743 $conn = $this->getLazyMasterHandle();
745 return false; // something is misconfigured
748 // Connect to and query the master; catch errors to avoid outages
750 $res = $conn->query( 'SELECT @@server_id AS id', __METHOD__
);
751 $row = $res ?
$res->fetchObject() : false;
752 $id = $row ?
(int)$row->id
: 0;
753 } catch ( DBError
$e ) {
757 // Cache the ID if it was retrieved
758 return $id ?
[ 'serverId' => $id, 'asOf' => time() ] : false;
764 * @param array $conds WHERE clause conditions to find a row
765 * @return array (heartbeat `ts` column value or null, UNIX timestamp) for the newest beat
766 * @see https://www.percona.com/doc/percona-toolkit/2.1/pt-heartbeat.html
768 protected function getHeartbeatData( array $conds ) {
769 // Do not bother starting implicit transactions here
770 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
772 $whereSQL = $this->makeList( $conds, self
::LIST_AND
);
773 // Use ORDER BY for channel based queries since that field might not be UNIQUE.
774 // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
775 // percision field is not supported in MySQL <= 5.5.
777 "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1"
779 $row = $res ?
$res->fetchObject() : false;
781 $this->restoreFlags();
784 return [ $row ?
$row->ts
: null, microtime( true ) ];
787 protected function getApproximateLagStatus() {
788 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
789 // Disable caching since this is fast enough and we don't wan't
790 // to be *too* pessimistic by having both the cache TTL and the
791 // pt-heartbeat interval count as lag in getSessionLagStatus()
792 return parent
::getApproximateLagStatus();
795 $key = $this->srvCache
->makeGlobalKey( 'mysql-lag', $this->getServer() );
796 $approxLag = $this->srvCache
->get( $key );
798 $approxLag = parent
::getApproximateLagStatus();
799 $this->srvCache
->set( $key, $approxLag, 1 );
805 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
806 if ( !( $pos instanceof MySQLMasterPos
) ) {
807 throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
810 if ( $this->getLBInfo( 'is static' ) === true ) {
811 return 0; // this is a copy of a read-only dataset with no master DB
812 } elseif ( $this->lastKnownReplicaPos
&& $this->lastKnownReplicaPos
->hasReached( $pos ) ) {
813 return 0; // already reached this point for sure
816 // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
817 if ( $this->useGTIDs
&& $pos->gtids
) {
818 // Wait on the GTID set (MariaDB only)
819 $gtidArg = $this->addQuotes( implode( ',', $pos->gtids
) );
820 $res = $this->doQuery( "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)" );
822 // Wait on the binlog coordinates
823 $encFile = $this->addQuotes( $pos->file
);
824 $encPos = intval( $pos->pos
);
825 $res = $this->doQuery( "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)" );
828 $row = $res ?
$this->fetchRow( $res ) : false;
830 throw new DBExpectedError( $this,
831 "MASTER_POS_WAIT() or MASTER_GTID_WAIT() failed: {$this->lastError()}" );
834 // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
835 $status = ( $row[0] !== null ) ?
intval( $row[0] ) : null;
836 if ( $status === null ) {
837 // T126436: jobs programmed to wait on master positions might be referencing binlogs
838 // with an old master hostname. Such calls make MASTER_POS_WAIT() return null. Try
839 // to detect this and treat the replica DB as having reached the position; a proper master
840 // switchover already requires that the new master be caught up before the switch.
841 $replicationPos = $this->getReplicaPos();
842 if ( $replicationPos && !$replicationPos->channelsMatch( $pos ) ) {
843 $this->lastKnownReplicaPos
= $replicationPos;
846 } elseif ( $status >= 0 ) {
847 // Remember that this position was reached to save queries next time
848 $this->lastKnownReplicaPos
= $pos;
855 * Get the position of the master from SHOW SLAVE STATUS
857 * @return MySQLMasterPos|bool
859 public function getReplicaPos() {
860 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
861 $row = $this->fetchObject( $res );
864 $pos = isset( $row->Exec_master_log_pos
)
865 ?
$row->Exec_master_log_pos
866 : $row->Exec_Master_Log_Pos
;
867 // Also fetch the last-applied GTID set (MariaDB)
868 if ( $this->useGTIDs
) {
869 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_slave_pos'", __METHOD__
);
870 $gtidRow = $this->fetchObject( $res );
871 $gtidSet = $gtidRow ?
$gtidRow->Value
: '';
876 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos, $gtidSet );
883 * Get the position of the master from SHOW MASTER STATUS
885 * @return MySQLMasterPos|bool
887 public function getMasterPos() {
888 $res = $this->query( 'SHOW MASTER STATUS', __METHOD__
);
889 $row = $this->fetchObject( $res );
892 // Also fetch the last-written GTID set (MariaDB)
893 if ( $this->useGTIDs
) {
894 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_binlog_pos'", __METHOD__
);
895 $gtidRow = $this->fetchObject( $res );
896 $gtidSet = $gtidRow ?
$gtidRow->Value
: '';
901 return new MySQLMasterPos( $row->File
, $row->Position
, $gtidSet );
907 public function serverIsReadOnly() {
908 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'read_only'", __METHOD__
);
909 $row = $this->fetchObject( $res );
911 return $row ?
( strtolower( $row->Value
) === 'on' ) : false;
915 * @param string $index
918 function useIndexClause( $index ) {
919 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
923 * @param string $index
926 function ignoreIndexClause( $index ) {
927 return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
933 function lowPriorityOption() {
934 return 'LOW_PRIORITY';
940 public function getSoftwareLink() {
941 // MariaDB includes its name in its version string; this is how MariaDB's version of
942 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
943 // in libmysql/libmysql.c).
944 $version = $this->getServerVersion();
945 if ( strpos( $version, 'MariaDB' ) !== false ||
strpos( $version, '-maria-' ) !== false ) {
946 return '[{{int:version-db-mariadb-url}} MariaDB]';
949 // Percona Server's version suffix is not very distinctive, and @@version_comment
950 // doesn't give the necessary info for source builds, so assume the server is MySQL.
951 // (Even Percona's version of mysql doesn't try to make the distinction.)
952 return '[{{int:version-db-mysql-url}} MySQL]';
958 public function getServerVersion() {
959 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
960 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
961 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
962 if ( $this->serverVersion
=== null ) {
963 $this->serverVersion
= $this->selectField( '', 'VERSION()', '', __METHOD__
);
965 return $this->serverVersion
;
969 * @param array $options
971 public function setSessionOptions( array $options ) {
972 if ( isset( $options['connTimeout'] ) ) {
973 $timeout = (int)$options['connTimeout'];
974 $this->query( "SET net_read_timeout=$timeout" );
975 $this->query( "SET net_write_timeout=$timeout" );
981 * @param string $newLine
984 public function streamStatementEnd( &$sql, &$newLine ) {
985 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
986 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
987 $this->delimiter
= $m[1];
991 return parent
::streamStatementEnd( $sql, $newLine );
995 * Check to see if a named lock is available. This is non-blocking.
997 * @param string $lockName Name of lock to poll
998 * @param string $method Name of method calling us
1002 public function lockIsFree( $lockName, $method ) {
1003 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1004 $result = $this->query( "SELECT IS_FREE_LOCK($encName) AS lockstatus", $method );
1005 $row = $this->fetchObject( $result );
1007 return ( $row->lockstatus
== 1 );
1011 * @param string $lockName
1012 * @param string $method
1013 * @param int $timeout
1016 public function lock( $lockName, $method, $timeout = 5 ) {
1017 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1018 $result = $this->query( "SELECT GET_LOCK($encName, $timeout) AS lockstatus", $method );
1019 $row = $this->fetchObject( $result );
1021 if ( $row->lockstatus
== 1 ) {
1022 parent
::lock( $lockName, $method, $timeout ); // record
1026 $this->queryLogger
->warning( __METHOD__
. " failed to acquire lock '$lockName'\n" );
1033 * https://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
1034 * @param string $lockName
1035 * @param string $method
1038 public function unlock( $lockName, $method ) {
1039 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1040 $result = $this->query( "SELECT RELEASE_LOCK($encName) as lockstatus", $method );
1041 $row = $this->fetchObject( $result );
1043 if ( $row->lockstatus
== 1 ) {
1044 parent
::unlock( $lockName, $method ); // record
1048 $this->queryLogger
->warning( __METHOD__
. " failed to release lock '$lockName'\n" );
1053 private function makeLockName( $lockName ) {
1054 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1055 // Newer version enforce a 64 char length limit.
1056 return ( strlen( $lockName ) > 64 ) ?
sha1( $lockName ) : $lockName;
1059 public function namedLocksEnqueue() {
1063 public function tableLocksHaveTransactionScope() {
1064 return false; // tied to TCP connection
1067 protected function doLockTables( array $read, array $write, $method ) {
1069 foreach ( $write as $table ) {
1070 $items[] = $this->tableName( $table ) . ' WRITE';
1072 foreach ( $read as $table ) {
1073 $items[] = $this->tableName( $table ) . ' READ';
1076 $sql = "LOCK TABLES " . implode( ',', $items );
1077 $this->query( $sql, $method );
1082 protected function doUnlockTables( $method ) {
1083 $this->query( "UNLOCK TABLES", $method );
1089 * @param bool $value
1091 public function setBigSelects( $value = true ) {
1092 if ( $value === 'default' ) {
1093 if ( $this->mDefaultBigSelects
=== null ) {
1094 # Function hasn't been called before so it must already be set to the default
1097 $value = $this->mDefaultBigSelects
;
1099 } elseif ( $this->mDefaultBigSelects
=== null ) {
1100 $this->mDefaultBigSelects
=
1101 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__
);
1103 $encValue = $value ?
'1' : '0';
1104 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
1108 * DELETE where the condition is a join. MySql uses multi-table deletes.
1109 * @param string $delTable
1110 * @param string $joinTable
1111 * @param string $delVar
1112 * @param string $joinVar
1113 * @param array|string $conds
1114 * @param bool|string $fname
1115 * @throws DBUnexpectedError
1116 * @return bool|ResultWrapper
1118 public function deleteJoin(
1119 $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
1122 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
1125 $delTable = $this->tableName( $delTable );
1126 $joinTable = $this->tableName( $joinTable );
1127 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1129 if ( $conds != '*' ) {
1130 $sql .= ' AND ' . $this->makeList( $conds, self
::LIST_AND
);
1133 return $this->query( $sql, $fname );
1137 * @param string $table
1138 * @param array $rows
1139 * @param array $uniqueIndexes
1141 * @param string $fname
1144 public function upsert( $table, array $rows, array $uniqueIndexes,
1145 array $set, $fname = __METHOD__
1147 if ( !count( $rows ) ) {
1148 return true; // nothing to do
1151 if ( !is_array( reset( $rows ) ) ) {
1155 $table = $this->tableName( $table );
1156 $columns = array_keys( $rows[0] );
1158 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1160 foreach ( $rows as $row ) {
1161 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1163 $sql .= implode( ',', $rowTuples );
1164 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, self
::LIST_SET
);
1166 return (bool)$this->query( $sql, $fname );
1170 * Determines how long the server has been up
1174 public function getServerUptime() {
1175 $vars = $this->getMysqlStatus( 'Uptime' );
1177 return (int)$vars['Uptime'];
1181 * Determines if the last failure was due to a deadlock
1185 public function wasDeadlock() {
1186 return $this->lastErrno() == 1213;
1190 * Determines if the last failure was due to a lock timeout
1194 public function wasLockTimeout() {
1195 return $this->lastErrno() == 1205;
1198 public function wasErrorReissuable() {
1199 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
1203 * Determines if the last failure was due to the database being read-only.
1207 public function wasReadOnlyError() {
1208 return $this->lastErrno() == 1223 ||
1209 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1212 public function wasConnectionError( $errno ) {
1213 return $errno == 2013 ||
$errno == 2006;
1217 * @param string $oldName
1218 * @param string $newName
1219 * @param bool $temporary
1220 * @param string $fname
1223 public function duplicateTableStructure(
1224 $oldName, $newName, $temporary = false, $fname = __METHOD__
1226 $tmp = $temporary ?
'TEMPORARY ' : '';
1227 $newName = $this->addIdentifierQuotes( $newName );
1228 $oldName = $this->addIdentifierQuotes( $oldName );
1229 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1231 return $this->query( $query, $fname );
1235 * List all tables on the database
1237 * @param string $prefix Only show tables with this prefix, e.g. mw_
1238 * @param string $fname Calling function name
1241 public function listTables( $prefix = null, $fname = __METHOD__
) {
1242 $result = $this->query( "SHOW TABLES", $fname );
1246 foreach ( $result as $table ) {
1247 $vars = get_object_vars( $table );
1248 $table = array_pop( $vars );
1250 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1251 $endArray[] = $table;
1259 * @param string $tableName
1260 * @param string $fName
1261 * @return bool|ResultWrapper
1263 public function dropTable( $tableName, $fName = __METHOD__
) {
1264 if ( !$this->tableExists( $tableName, $fName ) ) {
1268 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1272 * Get status information from SHOW STATUS in an associative array
1274 * @param string $which
1277 private function getMysqlStatus( $which = "%" ) {
1278 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1281 foreach ( $res as $row ) {
1282 $status[$row->Variable_name
] = $row->Value
;
1289 * Lists VIEWs in the database
1291 * @param string $prefix Only show VIEWs with this prefix, eg.
1292 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1293 * @param string $fname Name of calling function
1297 public function listViews( $prefix = null, $fname = __METHOD__
) {
1298 // The name of the column containing the name of the VIEW
1299 $propertyName = 'Tables_in_' . $this->mDBname
;
1301 // Query for the VIEWS
1302 $res = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1304 foreach ( $res as $row ) {
1305 array_push( $allViews, $row->$propertyName );
1308 if ( is_null( $prefix ) ||
$prefix === '' ) {
1312 $filteredViews = [];
1313 foreach ( $allViews as $viewName ) {
1314 // Does the name of this VIEW start with the table-prefix?
1315 if ( strpos( $viewName, $prefix ) === 0 ) {
1316 array_push( $filteredViews, $viewName );
1320 return $filteredViews;
1324 * Differentiates between a TABLE and a VIEW.
1326 * @param string $name Name of the TABLE/VIEW to test
1327 * @param string $prefix
1331 public function isView( $name, $prefix = null ) {
1332 return in_array( $name, $this->listViews( $prefix ) );
1336 * Allows for index remapping in queries where this is not consistent across DBMS
1338 * @param string $index
1341 protected function indexName( $index ) {
1343 * When SQLite indexes were introduced in r45764, it was noted that
1344 * SQLite requires index names to be unique within the whole database,
1345 * not just within a schema. As discussed in CR r45819, to avoid the
1346 * need for a schema change on existing installations, the indexes
1347 * were implicitly mapped from the new names to the old names.
1349 * This mapping can be removed if DB patches are introduced to alter
1350 * the relevant tables in existing installations. Note that because
1351 * this index mapping applies to table creation, even new installations
1352 * of MySQL have the old names (except for installations created during
1353 * a period where this mapping was inappropriately removed, see
1357 'ar_usertext_timestamp' => 'usertext_timestamp',
1358 'un_user_id' => 'user_id',
1359 'un_user_ip' => 'user_ip',
1362 if ( isset( $renamed[$index] ) ) {
1363 return $renamed[$index];
1370 class_alias( DatabaseMysqlBase
::class, 'DatabaseMysqlBase' );