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 */
57 /** @var string[]|null */
58 protected $sslCiphers;
59 /** @var string sql_mode value to send on connection */
61 /** @var bool Use experimental UTF-8 transmission encoding */
64 protected $defaultBigSelects = null;
66 /** @var string|null */
67 private $serverVersion = null;
69 private $insertSelectIsSafe = null;
70 /** @var stdClass|null */
71 private $replicationInfoRow = null;
74 * Additional $params include:
75 * - lagDetectionMethod : set to one of (Seconds_Behind_Master,pt-heartbeat).
76 * pt-heartbeat assumes the table is at heartbeat.heartbeat
77 * and uses UTC timestamps in the heartbeat.ts column.
78 * (https://www.percona.com/doc/percona-toolkit/2.2/pt-heartbeat.html)
79 * - lagDetectionOptions : if using pt-heartbeat, this can be set to an array map to change
80 * the default behavior. Normally, the heartbeat row with the server
81 * ID of this server's master will be used. Set the "conds" field to
82 * override the query conditions, e.g. ['shard' => 's1'].
83 * - useGTIDs : use GTID methods like MASTER_GTID_WAIT() when possible.
84 * - insertSelectIsSafe : force that native INSERT SELECT is or is not safe [default: null]
85 * - sslKeyPath : path to key file [default: null]
86 * - sslCertPath : path to certificate file [default: null]
87 * - sslCAFile: path to a single certificate authority PEM file [default: null]
88 * - sslCAPath : parth to certificate authority PEM directory [default: null]
89 * - sslCiphers : array list of allowable ciphers [default: null]
90 * @param array $params
92 function __construct( array $params ) {
93 $this->lagDetectionMethod
= isset( $params['lagDetectionMethod'] )
94 ?
$params['lagDetectionMethod']
95 : 'Seconds_Behind_Master';
96 $this->lagDetectionOptions
= isset( $params['lagDetectionOptions'] )
97 ?
$params['lagDetectionOptions']
99 $this->useGTIDs
= !empty( $params['useGTIDs' ] );
100 foreach ( [ 'KeyPath', 'CertPath', 'CAFile', 'CAPath', 'Ciphers' ] as $name ) {
102 if ( isset( $params[$var] ) ) {
103 $this->$var = $params[$var];
106 $this->sqlMode
= isset( $params['sqlMode'] ) ?
$params['sqlMode'] : '';
107 $this->utf8Mode
= !empty( $params['utf8Mode'] );
108 $this->insertSelectIsSafe
= isset( $params['insertSelectIsSafe'] )
109 ?
(bool)$params['insertSelectIsSafe'] : null;
111 parent
::__construct( $params );
117 public function getType() {
122 * @param string $server
123 * @param string $user
124 * @param string $password
125 * @param string $dbName
126 * @throws Exception|DBConnectionError
129 public function open( $server, $user, $password, $dbName ) {
130 # Close/unset connection handle
133 $this->server
= $server;
135 $this->password
= $password;
136 $this->dbName
= $dbName;
138 $this->installErrorHandler();
140 $this->conn
= $this->mysqlConnect( $this->server
);
141 } catch ( Exception
$ex ) {
142 $this->restoreErrorHandler();
145 $error = $this->restoreErrorHandler();
147 # Always log connection errors
148 if ( !$this->conn
) {
150 $error = $this->lastError();
152 $this->connLogger
->error(
153 "Error connecting to {db_server}: {error}",
154 $this->getLogContext( [
155 'method' => __METHOD__
,
159 $this->connLogger
->debug( "DB connection error\n" .
160 "Server: $server, User: $user, Password: " .
161 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
163 $this->reportConnectionError( $error );
166 if ( strlen( $dbName ) ) {
167 Wikimedia\
suppressWarnings();
168 $success = $this->selectDB( $dbName );
169 Wikimedia\restoreWarnings
();
171 $this->queryLogger
->error(
172 "Error selecting database {db_name} on server {db_server}",
173 $this->getLogContext( [
174 'method' => __METHOD__
,
177 $this->queryLogger
->debug(
178 "Error selecting database $dbName on server {$this->server}" );
180 $this->reportConnectionError( "Error selecting database $dbName" );
184 // Tell the server what we're communicating with
185 if ( !$this->connectInitCharset() ) {
186 $this->reportConnectionError( "Error setting character set" );
189 // Abstract over any insane MySQL defaults
190 $set = [ 'group_concat_max_len = 262144' ];
191 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
192 if ( is_string( $this->sqlMode
) ) {
193 $set[] = 'sql_mode = ' . $this->addQuotes( $this->sqlMode
);
195 // Set any custom settings defined by site config
196 // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
197 foreach ( $this->sessionVars
as $var => $val ) {
198 // Escape strings but not numbers to avoid MySQL complaining
199 if ( !is_int( $val ) && !is_float( $val ) ) {
200 $val = $this->addQuotes( $val );
202 $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
206 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
207 $success = $this->doQuery( 'SET ' . implode( ', ', $set ) );
209 $this->queryLogger
->error(
210 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)',
211 $this->getLogContext( [
212 'method' => __METHOD__
,
215 $this->reportConnectionError(
216 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)' );
220 $this->opened
= true;
226 * Set the character set information right after connection
229 protected function connectInitCharset() {
230 if ( $this->utf8Mode
) {
231 // Tell the server we're communicating with it in UTF-8.
232 // This may engage various charset conversions.
233 return $this->mysqlSetCharset( 'utf8' );
235 return $this->mysqlSetCharset( 'binary' );
240 * Open a connection to a MySQL server
242 * @param string $realServer
243 * @return mixed Raw connection
244 * @throws DBConnectionError
246 abstract protected function mysqlConnect( $realServer );
249 * Set the character set of the MySQL link
251 * @param string $charset
254 abstract protected function mysqlSetCharset( $charset );
257 * @param ResultWrapper|resource $res
258 * @throws DBUnexpectedError
260 public function freeResult( $res ) {
261 if ( $res instanceof ResultWrapper
) {
264 Wikimedia\
suppressWarnings();
265 $ok = $this->mysqlFreeResult( $res );
266 Wikimedia\restoreWarnings
();
268 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
275 * @param resource $res Raw result
278 abstract protected function mysqlFreeResult( $res );
281 * @param ResultWrapper|resource $res
282 * @return stdClass|bool
283 * @throws DBUnexpectedError
285 public function fetchObject( $res ) {
286 if ( $res instanceof ResultWrapper
) {
289 Wikimedia\
suppressWarnings();
290 $row = $this->mysqlFetchObject( $res );
291 Wikimedia\restoreWarnings
();
293 $errno = $this->lastErrno();
294 // Unfortunately, mysql_fetch_object does not reset the last errno.
295 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
296 // these are the only errors mysql_fetch_object can cause.
297 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
298 if ( $errno == 2000 ||
$errno == 2013 ) {
299 throw new DBUnexpectedError(
301 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
309 * Fetch a result row as an object
311 * @param resource $res Raw result
314 abstract protected function mysqlFetchObject( $res );
317 * @param ResultWrapper|resource $res
319 * @throws DBUnexpectedError
321 public function fetchRow( $res ) {
322 if ( $res instanceof ResultWrapper
) {
325 Wikimedia\
suppressWarnings();
326 $row = $this->mysqlFetchArray( $res );
327 Wikimedia\restoreWarnings
();
329 $errno = $this->lastErrno();
330 // Unfortunately, mysql_fetch_array does not reset the last errno.
331 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
332 // these are the only errors mysql_fetch_array can cause.
333 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
334 if ( $errno == 2000 ||
$errno == 2013 ) {
335 throw new DBUnexpectedError(
337 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
345 * Fetch a result row as an associative and numeric array
347 * @param resource $res Raw result
350 abstract protected function mysqlFetchArray( $res );
353 * @throws DBUnexpectedError
354 * @param ResultWrapper|resource $res
357 function numRows( $res ) {
358 if ( $res instanceof ResultWrapper
) {
361 Wikimedia\
suppressWarnings();
362 $n = $this->mysqlNumRows( $res );
363 Wikimedia\restoreWarnings
();
365 // Unfortunately, mysql_num_rows does not reset the last errno.
366 // We are not checking for any errors here, since
367 // these are no errors mysql_num_rows can cause.
368 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
369 // See https://phabricator.wikimedia.org/T44430
374 * Get number of rows in result
376 * @param resource $res Raw result
379 abstract protected function mysqlNumRows( $res );
382 * @param ResultWrapper|resource $res
385 public function numFields( $res ) {
386 if ( $res instanceof ResultWrapper
) {
390 return $this->mysqlNumFields( $res );
394 * Get number of fields in result
396 * @param resource $res Raw result
399 abstract protected function mysqlNumFields( $res );
402 * @param ResultWrapper|resource $res
406 public function fieldName( $res, $n ) {
407 if ( $res instanceof ResultWrapper
) {
411 return $this->mysqlFieldName( $res, $n );
415 * Get the name of the specified field in a result
417 * @param ResultWrapper|resource $res
421 abstract protected function mysqlFieldName( $res, $n );
424 * mysql_field_type() wrapper
425 * @param ResultWrapper|resource $res
429 public function fieldType( $res, $n ) {
430 if ( $res instanceof ResultWrapper
) {
434 return $this->mysqlFieldType( $res, $n );
438 * Get the type of the specified field in a result
440 * @param ResultWrapper|resource $res
444 abstract protected function mysqlFieldType( $res, $n );
447 * @param ResultWrapper|resource $res
451 public function dataSeek( $res, $row ) {
452 if ( $res instanceof ResultWrapper
) {
456 return $this->mysqlDataSeek( $res, $row );
460 * Move internal result pointer
462 * @param ResultWrapper|resource $res
466 abstract protected function mysqlDataSeek( $res, $row );
471 public function lastError() {
473 # Even if it's non-zero, it can still be invalid
474 Wikimedia\
suppressWarnings();
475 $error = $this->mysqlError( $this->conn
);
477 $error = $this->mysqlError();
479 Wikimedia\restoreWarnings
();
481 $error = $this->mysqlError();
484 $error .= ' (' . $this->server
. ')';
491 * Returns the text of the error message from previous MySQL operation
493 * @param resource $conn Raw connection
496 abstract protected function mysqlError( $conn = null );
498 protected function wasQueryTimeout( $error, $errno ) {
499 return $errno == 2062;
503 * @param string $table
504 * @param array $uniqueIndexes
506 * @param string $fname
507 * @return ResultWrapper
509 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
510 return $this->nativeReplace( $table, $rows, $fname );
513 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
514 $row = $this->getReplicationSafetyInfo();
515 // For row-based-replication, the resulting changes will be relayed, not the query
516 if ( $row->binlog_format
=== 'ROW' ) {
519 // LIMIT requires ORDER BY on a unique key or it is non-deterministic
520 if ( isset( $selectOptions['LIMIT'] ) ) {
523 // In MySQL, an INSERT SELECT is only replication safe with row-based
524 // replication or if innodb_autoinc_lock_mode is 0. When those
525 // conditions aren't met, use non-native mode.
526 // While we could try to determine if the insert is safe anyway by
527 // checking if the target table has an auto-increment column that
528 // isn't set in $varMap, that seems unlikely to be worth the extra
530 return ( (int)$row->innodb_autoinc_lock_mode
=== 0 );
534 * @return stdClass Process cached row
536 private function getReplicationSafetyInfo() {
537 if ( $this->replicationInfoRow
=== null ) {
538 $this->replicationInfoRow
= $this->selectRow(
541 'innodb_autoinc_lock_mode' => '@@innodb_autoinc_lock_mode',
542 'binlog_format' => '@@binlog_format',
549 return $this->replicationInfoRow
;
553 * Estimate rows in dataset
554 * Returns estimated count, based on EXPLAIN output
555 * Takes same arguments as Database::select()
557 * @param string|array $table
558 * @param string|array $vars
559 * @param string|array $conds
560 * @param string $fname
561 * @param string|array $options
564 public function estimateRowCount( $table, $vars = '*', $conds = '',
565 $fname = __METHOD__
, $options = []
567 $options['EXPLAIN'] = true;
568 $res = $this->select( $table, $vars, $conds, $fname, $options );
569 if ( $res === false ) {
572 if ( !$this->numRows( $res ) ) {
577 foreach ( $res as $plan ) {
578 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
584 public function tableExists( $table, $fname = __METHOD__
) {
585 // Split database and table into proper variables as Database::tableName() returns
586 // shared tables prefixed with their database, which do not work in SHOW TABLES statements
587 list( $database, , $prefix, $table ) = $this->qualifiedTableComponents( $table );
588 $tableName = "{$prefix}{$table}";
590 if ( isset( $this->sessionTempTables
[$tableName] ) ) {
591 return true; // already known to exist and won't show in SHOW TABLES anyway
594 // We can't use buildLike() here, because it specifies an escape character
595 // other than the backslash, which is the only one supported by SHOW TABLES
596 $encLike = $this->escapeLikeInternal( $tableName, '\\' );
598 // If the database has been specified (such as for shared tables), use "FROM"
599 if ( $database !== '' ) {
600 $encDatabase = $this->addIdentifierQuotes( $database );
601 $query = "SHOW TABLES FROM $encDatabase LIKE '$encLike'";
603 $query = "SHOW TABLES LIKE '$encLike'";
606 return $this->query( $query, $fname )->numRows() > 0;
610 * @param string $table
611 * @param string $field
612 * @return bool|MySQLField
614 public function fieldInfo( $table, $field ) {
615 $table = $this->tableName( $table );
616 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
620 $n = $this->mysqlNumFields( $res->result
);
621 for ( $i = 0; $i < $n; $i++
) {
622 $meta = $this->mysqlFetchField( $res->result
, $i );
623 if ( $field == $meta->name
) {
624 return new MySQLField( $meta );
632 * Get column information from a result
634 * @param resource $res Raw result
638 abstract protected function mysqlFetchField( $res, $n );
641 * Get information about an index into an object
642 * Returns false if the index does not exist
644 * @param string $table
645 * @param string $index
646 * @param string $fname
647 * @return bool|array|null False or null on failure
649 public function indexInfo( $table, $index, $fname = __METHOD__
) {
650 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
651 # SHOW INDEX should work for 3.x and up:
652 # https://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
653 $table = $this->tableName( $table );
654 $index = $this->indexName( $index );
656 $sql = 'SHOW INDEX FROM ' . $table;
657 $res = $this->query( $sql, $fname );
665 foreach ( $res as $row ) {
666 if ( $row->Key_name
== $index ) {
671 return empty( $result ) ?
false : $result;
678 public function strencode( $s ) {
679 return $this->mysqlRealEscapeString( $s );
686 abstract protected function mysqlRealEscapeString( $s );
688 public function addQuotes( $s ) {
689 if ( is_bool( $s ) ) {
690 // Parent would transform to int, which does not play nice with MySQL type juggling.
691 // When searching for an int in a string column, the strings are cast to int, which
692 // means false would match any string not starting with a number.
693 $s = (string)(int)$s;
695 return parent
::addQuotes( $s );
699 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
704 public function addIdentifierQuotes( $s ) {
705 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
706 // Remove NUL bytes and escape backticks by doubling
707 return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
711 * @param string $name
714 public function isQuotedIdentifier( $name ) {
715 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
718 public function getLag() {
719 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
720 return $this->getLagFromPtHeartbeat();
722 return $this->getLagFromSlaveStatus();
729 protected function getLagDetectionMethod() {
730 return $this->lagDetectionMethod
;
736 protected function getLagFromSlaveStatus() {
737 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
738 $row = $res ?
$res->fetchObject() : false;
739 if ( $row && strval( $row->Seconds_Behind_Master
) !== '' ) {
740 return intval( $row->Seconds_Behind_Master
);
749 protected function getLagFromPtHeartbeat() {
750 $options = $this->lagDetectionOptions
;
752 if ( isset( $options['conds'] ) ) {
753 // Best method for multi-DC setups: use logical channel names
754 $data = $this->getHeartbeatData( $options['conds'] );
756 // Standard method: use master server ID (works with stock pt-heartbeat)
757 $masterInfo = $this->getMasterServerInfo();
758 if ( !$masterInfo ) {
759 $this->queryLogger
->error(
760 "Unable to query master of {db_server} for server ID",
761 $this->getLogContext( [
762 'method' => __METHOD__
766 return false; // could not get master server ID
769 $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
770 $data = $this->getHeartbeatData( $conds );
773 list( $time, $nowUnix ) = $data;
774 if ( $time !== null ) {
775 // @time is in ISO format like "2015-09-25T16:48:10.000510"
776 $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
777 $timeUnix = (int)$dateTime->format( 'U' ) +
$dateTime->format( 'u' ) / 1e6
;
779 return max( $nowUnix - $timeUnix, 0.0 );
782 $this->queryLogger
->error(
783 "Unable to find pt-heartbeat row for {db_server}",
784 $this->getLogContext( [
785 'method' => __METHOD__
792 protected function getMasterServerInfo() {
793 $cache = $this->srvCache
;
794 $key = $cache->makeGlobalKey(
797 // Using one key for all cluster replica DBs is preferable
798 $this->getLBInfo( 'clusterMasterHost' ) ?
: $this->getServer()
801 return $cache->getWithSetCallback(
803 $cache::TTL_INDEFINITE
,
804 function () use ( $cache, $key ) {
805 // Get and leave a lock key in place for a short period
806 if ( !$cache->lock( $key, 0, 10 ) ) {
807 return false; // avoid master connection spike slams
810 $conn = $this->getLazyMasterHandle();
812 return false; // something is misconfigured
815 // Connect to and query the master; catch errors to avoid outages
817 $res = $conn->query( 'SELECT @@server_id AS id', __METHOD__
);
818 $row = $res ?
$res->fetchObject() : false;
819 $id = $row ?
(int)$row->id
: 0;
820 } catch ( DBError
$e ) {
824 // Cache the ID if it was retrieved
825 return $id ?
[ 'serverId' => $id, 'asOf' => time() ] : false;
831 * @param array $conds WHERE clause conditions to find a row
832 * @return array (heartbeat `ts` column value or null, UNIX timestamp) for the newest beat
833 * @see https://www.percona.com/doc/percona-toolkit/2.1/pt-heartbeat.html
835 protected function getHeartbeatData( array $conds ) {
836 // Query time and trip time are not counted
837 $nowUnix = microtime( true );
838 // Do not bother starting implicit transactions here
839 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
841 $whereSQL = $this->makeList( $conds, self
::LIST_AND
);
842 // Use ORDER BY for channel based queries since that field might not be UNIQUE.
843 // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
844 // percision field is not supported in MySQL <= 5.5.
846 "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1"
848 $row = $res ?
$res->fetchObject() : false;
850 $this->restoreFlags();
853 return [ $row ?
$row->ts
: null, $nowUnix ];
856 protected function getApproximateLagStatus() {
857 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
858 // Disable caching since this is fast enough and we don't wan't
859 // to be *too* pessimistic by having both the cache TTL and the
860 // pt-heartbeat interval count as lag in getSessionLagStatus()
861 return parent
::getApproximateLagStatus();
864 $key = $this->srvCache
->makeGlobalKey( 'mysql-lag', $this->getServer() );
865 $approxLag = $this->srvCache
->get( $key );
867 $approxLag = parent
::getApproximateLagStatus();
868 $this->srvCache
->set( $key, $approxLag, 1 );
874 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
875 if ( !( $pos instanceof MySQLMasterPos
) ) {
876 throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
879 if ( $this->getLBInfo( 'is static' ) === true ) {
880 return 0; // this is a copy of a read-only dataset with no master DB
881 } elseif ( $this->lastKnownReplicaPos
&& $this->lastKnownReplicaPos
->hasReached( $pos ) ) {
882 return 0; // already reached this point for sure
885 // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
886 if ( $pos->getGTIDs() ) {
887 // Ignore GTIDs from domains exclusive to the master DB (presumably inactive)
888 $rpos = $this->getReplicaPos();
889 $gtidsWait = $rpos ? MySQLMasterPos
::getCommonDomainGTIDs( $pos, $rpos ) : [];
891 return -1; // $pos is from the wrong cluster?
893 // Wait on the GTID set (MariaDB only)
894 $gtidArg = $this->addQuotes( implode( ',', $gtidsWait ) );
895 $res = $this->doQuery( "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)" );
897 // Wait on the binlog coordinates
898 $encFile = $this->addQuotes( $pos->getLogFile() );
899 $encPos = intval( $pos->pos
[1] );
900 $res = $this->doQuery( "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)" );
903 $row = $res ?
$this->fetchRow( $res ) : false;
905 throw new DBExpectedError( $this,
906 "MASTER_POS_WAIT() or MASTER_GTID_WAIT() failed: {$this->lastError()}" );
909 // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
910 $status = ( $row[0] !== null ) ?
intval( $row[0] ) : null;
911 if ( $status === null ) {
912 if ( !$pos->getGTIDs() ) {
913 // T126436: jobs programmed to wait on master positions might be referencing
914 // binlogs with an old master hostname; this makes MASTER_POS_WAIT() return null.
915 // Try to detect this case and treat the replica DB as having reached the given
916 // position (any master switchover already requires that the new master be caught
917 // up before the switch).
918 $replicationPos = $this->getReplicaPos();
919 if ( $replicationPos && !$replicationPos->channelsMatch( $pos ) ) {
920 $this->lastKnownReplicaPos
= $replicationPos;
924 } elseif ( $status >= 0 ) {
925 // Remember that this position was reached to save queries next time
926 $this->lastKnownReplicaPos
= $pos;
933 * Get the position of the master from SHOW SLAVE STATUS
935 * @return MySQLMasterPos|bool
937 public function getReplicaPos() {
938 $now = microtime( true );
940 if ( $this->useGTIDs
) {
941 $res = $this->query( "SELECT @@global.gtid_slave_pos AS Value", __METHOD__
);
942 $gtidRow = $this->fetchObject( $res );
943 if ( $gtidRow && strlen( $gtidRow->Value
) ) {
944 return new MySQLMasterPos( $gtidRow->Value
, $now );
948 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
949 $row = $this->fetchObject( $res );
950 if ( $row && strlen( $row->Relay_Master_Log_File
) ) {
951 return new MySQLMasterPos(
952 "{$row->Relay_Master_Log_File}/{$row->Exec_Master_Log_Pos}",
961 * Get the position of the master from SHOW MASTER STATUS
963 * @return MySQLMasterPos|bool
965 public function getMasterPos() {
966 $now = microtime( true );
968 if ( $this->useGTIDs
) {
969 $res = $this->query( "SELECT @@global.gtid_binlog_pos AS Value", __METHOD__
);
970 $gtidRow = $this->fetchObject( $res );
971 if ( $gtidRow && strlen( $gtidRow->Value
) ) {
972 return new MySQLMasterPos( $gtidRow->Value
, $now );
976 $res = $this->query( 'SHOW MASTER STATUS', __METHOD__
);
977 $row = $this->fetchObject( $res );
978 if ( $row && strlen( $row->File
) ) {
979 return new MySQLMasterPos( "{$row->File}/{$row->Position}", $now );
985 public function serverIsReadOnly() {
986 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'read_only'", __METHOD__
);
987 $row = $this->fetchObject( $res );
989 return $row ?
( strtolower( $row->Value
) === 'on' ) : false;
993 * @param string $index
996 function useIndexClause( $index ) {
997 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
1001 * @param string $index
1004 function ignoreIndexClause( $index ) {
1005 return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
1011 function lowPriorityOption() {
1012 return 'LOW_PRIORITY';
1018 public function getSoftwareLink() {
1019 // MariaDB includes its name in its version string; this is how MariaDB's version of
1020 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
1021 // in libmysql/libmysql.c).
1022 $version = $this->getServerVersion();
1023 if ( strpos( $version, 'MariaDB' ) !== false ||
strpos( $version, '-maria-' ) !== false ) {
1024 return '[{{int:version-db-mariadb-url}} MariaDB]';
1027 // Percona Server's version suffix is not very distinctive, and @@version_comment
1028 // doesn't give the necessary info for source builds, so assume the server is MySQL.
1029 // (Even Percona's version of mysql doesn't try to make the distinction.)
1030 return '[{{int:version-db-mysql-url}} MySQL]';
1036 public function getServerVersion() {
1037 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
1038 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
1039 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
1040 if ( $this->serverVersion
=== null ) {
1041 $this->serverVersion
= $this->selectField( '', 'VERSION()', '', __METHOD__
);
1043 return $this->serverVersion
;
1047 * @param array $options
1049 public function setSessionOptions( array $options ) {
1050 if ( isset( $options['connTimeout'] ) ) {
1051 $timeout = (int)$options['connTimeout'];
1052 $this->query( "SET net_read_timeout=$timeout" );
1053 $this->query( "SET net_write_timeout=$timeout" );
1058 * @param string &$sql
1059 * @param string &$newLine
1062 public function streamStatementEnd( &$sql, &$newLine ) {
1063 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
1064 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
1065 $this->delimiter
= $m[1];
1069 return parent
::streamStatementEnd( $sql, $newLine );
1073 * Check to see if a named lock is available. This is non-blocking.
1075 * @param string $lockName Name of lock to poll
1076 * @param string $method Name of method calling us
1080 public function lockIsFree( $lockName, $method ) {
1081 if ( !parent
::lockIsFree( $lockName, $method ) ) {
1082 return false; // already held
1085 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1086 $result = $this->query( "SELECT IS_FREE_LOCK($encName) AS lockstatus", $method );
1087 $row = $this->fetchObject( $result );
1089 return ( $row->lockstatus
== 1 );
1093 * @param string $lockName
1094 * @param string $method
1095 * @param int $timeout
1098 public function lock( $lockName, $method, $timeout = 5 ) {
1099 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1100 $result = $this->query( "SELECT GET_LOCK($encName, $timeout) AS lockstatus", $method );
1101 $row = $this->fetchObject( $result );
1103 if ( $row->lockstatus
== 1 ) {
1104 parent
::lock( $lockName, $method, $timeout ); // record
1108 $this->queryLogger
->info( __METHOD__
. " failed to acquire lock '{lockname}'",
1109 [ 'lockname' => $lockName ] );
1116 * https://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
1117 * @param string $lockName
1118 * @param string $method
1121 public function unlock( $lockName, $method ) {
1122 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1123 $result = $this->query( "SELECT RELEASE_LOCK($encName) as lockstatus", $method );
1124 $row = $this->fetchObject( $result );
1126 if ( $row->lockstatus
== 1 ) {
1127 parent
::unlock( $lockName, $method ); // record
1131 $this->queryLogger
->warning( __METHOD__
. " failed to release lock '$lockName'\n" );
1136 private function makeLockName( $lockName ) {
1137 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1138 // Newer version enforce a 64 char length limit.
1139 return ( strlen( $lockName ) > 64 ) ?
sha1( $lockName ) : $lockName;
1142 public function namedLocksEnqueue() {
1146 public function tableLocksHaveTransactionScope() {
1147 return false; // tied to TCP connection
1150 protected function doLockTables( array $read, array $write, $method ) {
1152 foreach ( $write as $table ) {
1153 $items[] = $this->tableName( $table ) . ' WRITE';
1155 foreach ( $read as $table ) {
1156 $items[] = $this->tableName( $table ) . ' READ';
1159 $sql = "LOCK TABLES " . implode( ',', $items );
1160 $this->query( $sql, $method );
1165 protected function doUnlockTables( $method ) {
1166 $this->query( "UNLOCK TABLES", $method );
1172 * @param bool $value
1174 public function setBigSelects( $value = true ) {
1175 if ( $value === 'default' ) {
1176 if ( $this->defaultBigSelects
=== null ) {
1177 # Function hasn't been called before so it must already be set to the default
1180 $value = $this->defaultBigSelects
;
1182 } elseif ( $this->defaultBigSelects
=== null ) {
1183 $this->defaultBigSelects
=
1184 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__
);
1186 $encValue = $value ?
'1' : '0';
1187 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
1191 * DELETE where the condition is a join. MySql uses multi-table deletes.
1192 * @param string $delTable
1193 * @param string $joinTable
1194 * @param string $delVar
1195 * @param string $joinVar
1196 * @param array|string $conds
1197 * @param bool|string $fname
1198 * @throws DBUnexpectedError
1199 * @return bool|ResultWrapper
1201 public function deleteJoin(
1202 $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
1205 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
1208 $delTable = $this->tableName( $delTable );
1209 $joinTable = $this->tableName( $joinTable );
1210 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1212 if ( $conds != '*' ) {
1213 $sql .= ' AND ' . $this->makeList( $conds, self
::LIST_AND
);
1216 return $this->query( $sql, $fname );
1220 * @param string $table
1221 * @param array $rows
1222 * @param array $uniqueIndexes
1224 * @param string $fname
1227 public function upsert( $table, array $rows, array $uniqueIndexes,
1228 array $set, $fname = __METHOD__
1230 if ( !count( $rows ) ) {
1231 return true; // nothing to do
1234 if ( !is_array( reset( $rows ) ) ) {
1238 $table = $this->tableName( $table );
1239 $columns = array_keys( $rows[0] );
1241 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1243 foreach ( $rows as $row ) {
1244 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1246 $sql .= implode( ',', $rowTuples );
1247 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, self
::LIST_SET
);
1249 return (bool)$this->query( $sql, $fname );
1253 * Determines how long the server has been up
1257 public function getServerUptime() {
1258 $vars = $this->getMysqlStatus( 'Uptime' );
1260 return (int)$vars['Uptime'];
1264 * Determines if the last failure was due to a deadlock
1268 public function wasDeadlock() {
1269 return $this->lastErrno() == 1213;
1273 * Determines if the last failure was due to a lock timeout
1277 public function wasLockTimeout() {
1278 return $this->lastErrno() == 1205;
1281 public function wasErrorReissuable() {
1282 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
1286 * Determines if the last failure was due to the database being read-only.
1290 public function wasReadOnlyError() {
1291 return $this->lastErrno() == 1223 ||
1292 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1295 public function wasConnectionError( $errno ) {
1296 return $errno == 2013 ||
$errno == 2006;
1300 * @param string $oldName
1301 * @param string $newName
1302 * @param bool $temporary
1303 * @param string $fname
1306 public function duplicateTableStructure(
1307 $oldName, $newName, $temporary = false, $fname = __METHOD__
1309 $tmp = $temporary ?
'TEMPORARY ' : '';
1310 $newName = $this->addIdentifierQuotes( $newName );
1311 $oldName = $this->addIdentifierQuotes( $oldName );
1312 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1314 return $this->query( $query, $fname );
1318 * List all tables on the database
1320 * @param string $prefix Only show tables with this prefix, e.g. mw_
1321 * @param string $fname Calling function name
1324 public function listTables( $prefix = null, $fname = __METHOD__
) {
1325 $result = $this->query( "SHOW TABLES", $fname );
1329 foreach ( $result as $table ) {
1330 $vars = get_object_vars( $table );
1331 $table = array_pop( $vars );
1333 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1334 $endArray[] = $table;
1342 * @param string $tableName
1343 * @param string $fName
1344 * @return bool|ResultWrapper
1346 public function dropTable( $tableName, $fName = __METHOD__
) {
1347 if ( !$this->tableExists( $tableName, $fName ) ) {
1351 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1355 * Get status information from SHOW STATUS in an associative array
1357 * @param string $which
1360 private function getMysqlStatus( $which = "%" ) {
1361 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1364 foreach ( $res as $row ) {
1365 $status[$row->Variable_name
] = $row->Value
;
1372 * Lists VIEWs in the database
1374 * @param string $prefix Only show VIEWs with this prefix, eg.
1375 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1376 * @param string $fname Name of calling function
1380 public function listViews( $prefix = null, $fname = __METHOD__
) {
1381 // The name of the column containing the name of the VIEW
1382 $propertyName = 'Tables_in_' . $this->dbName
;
1384 // Query for the VIEWS
1385 $res = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1387 foreach ( $res as $row ) {
1388 array_push( $allViews, $row->$propertyName );
1391 if ( is_null( $prefix ) ||
$prefix === '' ) {
1395 $filteredViews = [];
1396 foreach ( $allViews as $viewName ) {
1397 // Does the name of this VIEW start with the table-prefix?
1398 if ( strpos( $viewName, $prefix ) === 0 ) {
1399 array_push( $filteredViews, $viewName );
1403 return $filteredViews;
1407 * Differentiates between a TABLE and a VIEW.
1409 * @param string $name Name of the TABLE/VIEW to test
1410 * @param string $prefix
1414 public function isView( $name, $prefix = null ) {
1415 return in_array( $name, $this->listViews( $prefix ) );
1419 * Allows for index remapping in queries where this is not consistent across DBMS
1421 * @param string $index
1424 protected function indexName( $index ) {
1426 * When SQLite indexes were introduced in r45764, it was noted that
1427 * SQLite requires index names to be unique within the whole database,
1428 * not just within a schema. As discussed in CR r45819, to avoid the
1429 * need for a schema change on existing installations, the indexes
1430 * were implicitly mapped from the new names to the old names.
1432 * This mapping can be removed if DB patches are introduced to alter
1433 * the relevant tables in existing installations. Note that because
1434 * this index mapping applies to table creation, even new installations
1435 * of MySQL have the old names (except for installations created during
1436 * a period where this mapping was inappropriately removed, see
1440 'ar_usertext_timestamp' => 'usertext_timestamp',
1441 'un_user_id' => 'user_id',
1442 'un_user_ip' => 'user_ip',
1445 if ( isset( $renamed[$index] ) ) {
1446 return $renamed[$index];
1452 protected function isTransactableQuery( $sql ) {
1453 return parent
::isTransactableQuery( $sql ) &&
1454 !preg_match( '/^SELECT\s+(GET|RELEASE|IS_FREE)_LOCK\(/', $sql );
1458 class_alias( DatabaseMysqlBase
::class, 'DatabaseMysqlBase' );