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;
72 * Additional $params include:
73 * - lagDetectionMethod : set to one of (Seconds_Behind_Master,pt-heartbeat).
74 * pt-heartbeat assumes the table is at heartbeat.heartbeat
75 * and uses UTC timestamps in the heartbeat.ts column.
76 * (https://www.percona.com/doc/percona-toolkit/2.2/pt-heartbeat.html)
77 * - lagDetectionOptions : if using pt-heartbeat, this can be set to an array map to change
78 * the default behavior. Normally, the heartbeat row with the server
79 * ID of this server's master will be used. Set the "conds" field to
80 * override the query conditions, e.g. ['shard' => 's1'].
81 * - useGTIDs : use GTID methods like MASTER_GTID_WAIT() when possible.
82 * - insertSelectIsSafe : force that native INSERT SELECT is or is not safe [default: null]
83 * - sslKeyPath : path to key file [default: null]
84 * - sslCertPath : path to certificate file [default: null]
85 * - sslCAFile: path to a single certificate authority PEM file [default: null]
86 * - sslCAPath : parth to certificate authority PEM directory [default: null]
87 * - sslCiphers : array list of allowable ciphers [default: null]
88 * @param array $params
90 function __construct( array $params ) {
91 $this->lagDetectionMethod
= isset( $params['lagDetectionMethod'] )
92 ?
$params['lagDetectionMethod']
93 : 'Seconds_Behind_Master';
94 $this->lagDetectionOptions
= isset( $params['lagDetectionOptions'] )
95 ?
$params['lagDetectionOptions']
97 $this->useGTIDs
= !empty( $params['useGTIDs' ] );
98 foreach ( [ 'KeyPath', 'CertPath', 'CAFile', 'CAPath', 'Ciphers' ] as $name ) {
100 if ( isset( $params[$var] ) ) {
101 $this->$var = $params[$var];
104 $this->sqlMode
= isset( $params['sqlMode'] ) ?
$params['sqlMode'] : '';
105 $this->utf8Mode
= !empty( $params['utf8Mode'] );
106 $this->insertSelectIsSafe
= isset( $params['insertSelectIsSafe'] )
107 ?
(bool)$params['insertSelectIsSafe'] : null;
109 parent
::__construct( $params );
115 public function getType() {
120 * @param string $server
121 * @param string $user
122 * @param string $password
123 * @param string $dbName
124 * @throws Exception|DBConnectionError
127 public function open( $server, $user, $password, $dbName ) {
128 # Close/unset connection handle
131 $this->server
= $server;
133 $this->password
= $password;
134 $this->dbName
= $dbName;
136 $this->installErrorHandler();
138 $this->conn
= $this->mysqlConnect( $this->server
);
139 } catch ( Exception
$ex ) {
140 $this->restoreErrorHandler();
143 $error = $this->restoreErrorHandler();
145 # Always log connection errors
146 if ( !$this->conn
) {
148 $error = $this->lastError();
150 $this->connLogger
->error(
151 "Error connecting to {db_server}: {error}",
152 $this->getLogContext( [
153 'method' => __METHOD__
,
157 $this->connLogger
->debug( "DB connection error\n" .
158 "Server: $server, User: $user, Password: " .
159 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
161 $this->reportConnectionError( $error );
164 if ( strlen( $dbName ) ) {
165 Wikimedia\
suppressWarnings();
166 $success = $this->selectDB( $dbName );
167 Wikimedia\restoreWarnings
();
169 $this->queryLogger
->error(
170 "Error selecting database {db_name} on server {db_server}",
171 $this->getLogContext( [
172 'method' => __METHOD__
,
175 $this->queryLogger
->debug(
176 "Error selecting database $dbName on server {$this->server}" );
178 $this->reportConnectionError( "Error selecting database $dbName" );
182 // Tell the server what we're communicating with
183 if ( !$this->connectInitCharset() ) {
184 $this->reportConnectionError( "Error setting character set" );
187 // Abstract over any insane MySQL defaults
188 $set = [ 'group_concat_max_len = 262144' ];
189 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
190 if ( is_string( $this->sqlMode
) ) {
191 $set[] = 'sql_mode = ' . $this->addQuotes( $this->sqlMode
);
193 // Set any custom settings defined by site config
194 // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
195 foreach ( $this->sessionVars
as $var => $val ) {
196 // Escape strings but not numbers to avoid MySQL complaining
197 if ( !is_int( $val ) && !is_float( $val ) ) {
198 $val = $this->addQuotes( $val );
200 $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
204 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
205 $success = $this->doQuery( 'SET ' . implode( ', ', $set ) );
207 $this->queryLogger
->error(
208 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)',
209 $this->getLogContext( [
210 'method' => __METHOD__
,
213 $this->reportConnectionError(
214 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)' );
218 $this->opened
= true;
224 * Set the character set information right after connection
227 protected function connectInitCharset() {
228 if ( $this->utf8Mode
) {
229 // Tell the server we're communicating with it in UTF-8.
230 // This may engage various charset conversions.
231 return $this->mysqlSetCharset( 'utf8' );
233 return $this->mysqlSetCharset( 'binary' );
238 * Open a connection to a MySQL server
240 * @param string $realServer
241 * @return mixed Raw connection
242 * @throws DBConnectionError
244 abstract protected function mysqlConnect( $realServer );
247 * Set the character set of the MySQL link
249 * @param string $charset
252 abstract protected function mysqlSetCharset( $charset );
255 * @param ResultWrapper|resource $res
256 * @throws DBUnexpectedError
258 public function freeResult( $res ) {
259 if ( $res instanceof ResultWrapper
) {
262 Wikimedia\
suppressWarnings();
263 $ok = $this->mysqlFreeResult( $res );
264 Wikimedia\restoreWarnings
();
266 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
273 * @param resource $res Raw result
276 abstract protected function mysqlFreeResult( $res );
279 * @param ResultWrapper|resource $res
280 * @return stdClass|bool
281 * @throws DBUnexpectedError
283 public function fetchObject( $res ) {
284 if ( $res instanceof ResultWrapper
) {
287 Wikimedia\
suppressWarnings();
288 $row = $this->mysqlFetchObject( $res );
289 Wikimedia\restoreWarnings
();
291 $errno = $this->lastErrno();
292 // Unfortunately, mysql_fetch_object does not reset the last errno.
293 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
294 // these are the only errors mysql_fetch_object can cause.
295 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
296 if ( $errno == 2000 ||
$errno == 2013 ) {
297 throw new DBUnexpectedError(
299 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
307 * Fetch a result row as an object
309 * @param resource $res Raw result
312 abstract protected function mysqlFetchObject( $res );
315 * @param ResultWrapper|resource $res
317 * @throws DBUnexpectedError
319 public function fetchRow( $res ) {
320 if ( $res instanceof ResultWrapper
) {
323 Wikimedia\
suppressWarnings();
324 $row = $this->mysqlFetchArray( $res );
325 Wikimedia\restoreWarnings
();
327 $errno = $this->lastErrno();
328 // Unfortunately, mysql_fetch_array does not reset the last errno.
329 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
330 // these are the only errors mysql_fetch_array can cause.
331 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
332 if ( $errno == 2000 ||
$errno == 2013 ) {
333 throw new DBUnexpectedError(
335 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
343 * Fetch a result row as an associative and numeric array
345 * @param resource $res Raw result
348 abstract protected function mysqlFetchArray( $res );
351 * @throws DBUnexpectedError
352 * @param ResultWrapper|resource $res
355 function numRows( $res ) {
356 if ( $res instanceof ResultWrapper
) {
359 Wikimedia\
suppressWarnings();
360 $n = $this->mysqlNumRows( $res );
361 Wikimedia\restoreWarnings
();
363 // Unfortunately, mysql_num_rows does not reset the last errno.
364 // We are not checking for any errors here, since
365 // these are no errors mysql_num_rows can cause.
366 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
367 // See https://phabricator.wikimedia.org/T44430
372 * Get number of rows in result
374 * @param resource $res Raw result
377 abstract protected function mysqlNumRows( $res );
380 * @param ResultWrapper|resource $res
383 public function numFields( $res ) {
384 if ( $res instanceof ResultWrapper
) {
388 return $this->mysqlNumFields( $res );
392 * Get number of fields in result
394 * @param resource $res Raw result
397 abstract protected function mysqlNumFields( $res );
400 * @param ResultWrapper|resource $res
404 public function fieldName( $res, $n ) {
405 if ( $res instanceof ResultWrapper
) {
409 return $this->mysqlFieldName( $res, $n );
413 * Get the name of the specified field in a result
415 * @param ResultWrapper|resource $res
419 abstract protected function mysqlFieldName( $res, $n );
422 * mysql_field_type() wrapper
423 * @param ResultWrapper|resource $res
427 public function fieldType( $res, $n ) {
428 if ( $res instanceof ResultWrapper
) {
432 return $this->mysqlFieldType( $res, $n );
436 * Get the type of the specified field in a result
438 * @param ResultWrapper|resource $res
442 abstract protected function mysqlFieldType( $res, $n );
445 * @param ResultWrapper|resource $res
449 public function dataSeek( $res, $row ) {
450 if ( $res instanceof ResultWrapper
) {
454 return $this->mysqlDataSeek( $res, $row );
458 * Move internal result pointer
460 * @param ResultWrapper|resource $res
464 abstract protected function mysqlDataSeek( $res, $row );
469 public function lastError() {
471 # Even if it's non-zero, it can still be invalid
472 Wikimedia\
suppressWarnings();
473 $error = $this->mysqlError( $this->conn
);
475 $error = $this->mysqlError();
477 Wikimedia\restoreWarnings
();
479 $error = $this->mysqlError();
482 $error .= ' (' . $this->server
. ')';
489 * Returns the text of the error message from previous MySQL operation
491 * @param resource $conn Raw connection
494 abstract protected function mysqlError( $conn = null );
496 protected function wasQueryTimeout( $error, $errno ) {
497 return $errno == 2062;
501 * @param string $table
502 * @param array $uniqueIndexes
504 * @param string $fname
505 * @return ResultWrapper
507 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
508 return $this->nativeReplace( $table, $rows, $fname );
511 protected function nativeInsertSelect(
512 $destTable, $srcTable, $varMap, $conds,
513 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
515 $isSafe = in_array( 'NO_AUTO_COLUMNS', $insertOptions, true );
516 if ( !$isSafe && $this->insertSelectIsSafe
=== null ) {
517 // In MySQL, an INSERT SELECT is only replication safe with row-based
518 // replication or if innodb_autoinc_lock_mode is 0. When those
519 // conditions aren't met, use non-native mode.
520 // While we could try to determine if the insert is safe anyway by
521 // checking if the target table has an auto-increment column that
522 // isn't set in $varMap, that seems unlikely to be worth the extra
524 $row = $this->selectRow(
527 'innodb_autoinc_lock_mode' => '@@innodb_autoinc_lock_mode',
528 'binlog_format' => '@@binlog_format',
533 $this->insertSelectIsSafe
= $row->binlog_format
=== 'ROW' ||
534 (int)$row->innodb_autoinc_lock_mode
=== 0;
537 if ( !$isSafe && !$this->insertSelectIsSafe
) {
538 return $this->nonNativeInsertSelect(
549 return parent
::nativeInsertSelect(
563 * Estimate rows in dataset
564 * Returns estimated count, based on EXPLAIN output
565 * Takes same arguments as Database::select()
567 * @param string|array $table
568 * @param string|array $vars
569 * @param string|array $conds
570 * @param string $fname
571 * @param string|array $options
574 public function estimateRowCount( $table, $vars = '*', $conds = '',
575 $fname = __METHOD__
, $options = []
577 $options['EXPLAIN'] = true;
578 $res = $this->select( $table, $vars, $conds, $fname, $options );
579 if ( $res === false ) {
582 if ( !$this->numRows( $res ) ) {
587 foreach ( $res as $plan ) {
588 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
594 public function tableExists( $table, $fname = __METHOD__
) {
595 // Split database and table into proper variables as Database::tableName() returns
596 // shared tables prefixed with their database, which do not work in SHOW TABLES statements
597 list( $database, , $prefix, $table ) = $this->qualifiedTableComponents( $table );
598 $tableName = "{$prefix}{$table}";
600 if ( isset( $this->sessionTempTables
[$tableName] ) ) {
601 return true; // already known to exist and won't show in SHOW TABLES anyway
604 // We can't use buildLike() here, because it specifies an escape character
605 // other than the backslash, which is the only one supported by SHOW TABLES
606 $encLike = $this->escapeLikeInternal( $tableName, '\\' );
608 // If the database has been specified (such as for shared tables), use "FROM"
609 if ( $database !== '' ) {
610 $encDatabase = $this->addIdentifierQuotes( $database );
611 $query = "SHOW TABLES FROM $encDatabase LIKE '$encLike'";
613 $query = "SHOW TABLES LIKE '$encLike'";
616 return $this->query( $query, $fname )->numRows() > 0;
620 * @param string $table
621 * @param string $field
622 * @return bool|MySQLField
624 public function fieldInfo( $table, $field ) {
625 $table = $this->tableName( $table );
626 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
630 $n = $this->mysqlNumFields( $res->result
);
631 for ( $i = 0; $i < $n; $i++
) {
632 $meta = $this->mysqlFetchField( $res->result
, $i );
633 if ( $field == $meta->name
) {
634 return new MySQLField( $meta );
642 * Get column information from a result
644 * @param resource $res Raw result
648 abstract protected function mysqlFetchField( $res, $n );
651 * Get information about an index into an object
652 * Returns false if the index does not exist
654 * @param string $table
655 * @param string $index
656 * @param string $fname
657 * @return bool|array|null False or null on failure
659 public function indexInfo( $table, $index, $fname = __METHOD__
) {
660 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
661 # SHOW INDEX should work for 3.x and up:
662 # https://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
663 $table = $this->tableName( $table );
664 $index = $this->indexName( $index );
666 $sql = 'SHOW INDEX FROM ' . $table;
667 $res = $this->query( $sql, $fname );
675 foreach ( $res as $row ) {
676 if ( $row->Key_name
== $index ) {
681 return empty( $result ) ?
false : $result;
688 public function strencode( $s ) {
689 return $this->mysqlRealEscapeString( $s );
696 abstract protected function mysqlRealEscapeString( $s );
698 public function addQuotes( $s ) {
699 if ( is_bool( $s ) ) {
700 // Parent would transform to int, which does not play nice with MySQL type juggling.
701 // When searching for an int in a string column, the strings are cast to int, which
702 // means false would match any string not starting with a number.
703 $s = (string)(int)$s;
705 return parent
::addQuotes( $s );
709 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
714 public function addIdentifierQuotes( $s ) {
715 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
716 // Remove NUL bytes and escape backticks by doubling
717 return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
721 * @param string $name
724 public function isQuotedIdentifier( $name ) {
725 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
728 public function getLag() {
729 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
730 return $this->getLagFromPtHeartbeat();
732 return $this->getLagFromSlaveStatus();
739 protected function getLagDetectionMethod() {
740 return $this->lagDetectionMethod
;
746 protected function getLagFromSlaveStatus() {
747 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
748 $row = $res ?
$res->fetchObject() : false;
749 if ( $row && strval( $row->Seconds_Behind_Master
) !== '' ) {
750 return intval( $row->Seconds_Behind_Master
);
759 protected function getLagFromPtHeartbeat() {
760 $options = $this->lagDetectionOptions
;
762 if ( isset( $options['conds'] ) ) {
763 // Best method for multi-DC setups: use logical channel names
764 $data = $this->getHeartbeatData( $options['conds'] );
766 // Standard method: use master server ID (works with stock pt-heartbeat)
767 $masterInfo = $this->getMasterServerInfo();
768 if ( !$masterInfo ) {
769 $this->queryLogger
->error(
770 "Unable to query master of {db_server} for server ID",
771 $this->getLogContext( [
772 'method' => __METHOD__
776 return false; // could not get master server ID
779 $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
780 $data = $this->getHeartbeatData( $conds );
783 list( $time, $nowUnix ) = $data;
784 if ( $time !== null ) {
785 // @time is in ISO format like "2015-09-25T16:48:10.000510"
786 $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
787 $timeUnix = (int)$dateTime->format( 'U' ) +
$dateTime->format( 'u' ) / 1e6
;
789 return max( $nowUnix - $timeUnix, 0.0 );
792 $this->queryLogger
->error(
793 "Unable to find pt-heartbeat row for {db_server}",
794 $this->getLogContext( [
795 'method' => __METHOD__
802 protected function getMasterServerInfo() {
803 $cache = $this->srvCache
;
804 $key = $cache->makeGlobalKey(
807 // Using one key for all cluster replica DBs is preferable
808 $this->getLBInfo( 'clusterMasterHost' ) ?
: $this->getServer()
811 return $cache->getWithSetCallback(
813 $cache::TTL_INDEFINITE
,
814 function () use ( $cache, $key ) {
815 // Get and leave a lock key in place for a short period
816 if ( !$cache->lock( $key, 0, 10 ) ) {
817 return false; // avoid master connection spike slams
820 $conn = $this->getLazyMasterHandle();
822 return false; // something is misconfigured
825 // Connect to and query the master; catch errors to avoid outages
827 $res = $conn->query( 'SELECT @@server_id AS id', __METHOD__
);
828 $row = $res ?
$res->fetchObject() : false;
829 $id = $row ?
(int)$row->id
: 0;
830 } catch ( DBError
$e ) {
834 // Cache the ID if it was retrieved
835 return $id ?
[ 'serverId' => $id, 'asOf' => time() ] : false;
841 * @param array $conds WHERE clause conditions to find a row
842 * @return array (heartbeat `ts` column value or null, UNIX timestamp) for the newest beat
843 * @see https://www.percona.com/doc/percona-toolkit/2.1/pt-heartbeat.html
845 protected function getHeartbeatData( array $conds ) {
846 // Query time and trip time are not counted
847 $nowUnix = microtime( true );
848 // Do not bother starting implicit transactions here
849 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
851 $whereSQL = $this->makeList( $conds, self
::LIST_AND
);
852 // Use ORDER BY for channel based queries since that field might not be UNIQUE.
853 // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
854 // percision field is not supported in MySQL <= 5.5.
856 "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1"
858 $row = $res ?
$res->fetchObject() : false;
860 $this->restoreFlags();
863 return [ $row ?
$row->ts
: null, $nowUnix ];
866 protected function getApproximateLagStatus() {
867 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
868 // Disable caching since this is fast enough and we don't wan't
869 // to be *too* pessimistic by having both the cache TTL and the
870 // pt-heartbeat interval count as lag in getSessionLagStatus()
871 return parent
::getApproximateLagStatus();
874 $key = $this->srvCache
->makeGlobalKey( 'mysql-lag', $this->getServer() );
875 $approxLag = $this->srvCache
->get( $key );
877 $approxLag = parent
::getApproximateLagStatus();
878 $this->srvCache
->set( $key, $approxLag, 1 );
884 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
885 if ( !( $pos instanceof MySQLMasterPos
) ) {
886 throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
889 if ( $this->getLBInfo( 'is static' ) === true ) {
890 return 0; // this is a copy of a read-only dataset with no master DB
891 } elseif ( $this->lastKnownReplicaPos
&& $this->lastKnownReplicaPos
->hasReached( $pos ) ) {
892 return 0; // already reached this point for sure
895 // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
896 if ( $pos->getGTIDs() ) {
897 // Ignore GTIDs from domains exclusive to the master DB (presumably inactive)
898 $rpos = $this->getReplicaPos();
899 $gtidsWait = $rpos ? MySQLMasterPos
::getCommonDomainGTIDs( $pos, $rpos ) : [];
901 return -1; // $pos is from the wrong cluster?
903 // Wait on the GTID set (MariaDB only)
904 $gtidArg = $this->addQuotes( implode( ',', $gtidsWait ) );
905 $res = $this->doQuery( "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)" );
907 // Wait on the binlog coordinates
908 $encFile = $this->addQuotes( $pos->getLogFile() );
909 $encPos = intval( $pos->pos
[1] );
910 $res = $this->doQuery( "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)" );
913 $row = $res ?
$this->fetchRow( $res ) : false;
915 throw new DBExpectedError( $this,
916 "MASTER_POS_WAIT() or MASTER_GTID_WAIT() failed: {$this->lastError()}" );
919 // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
920 $status = ( $row[0] !== null ) ?
intval( $row[0] ) : null;
921 if ( $status === null ) {
922 if ( !$pos->getGTIDs() ) {
923 // T126436: jobs programmed to wait on master positions might be referencing
924 // binlogs with an old master hostname; this makes MASTER_POS_WAIT() return null.
925 // Try to detect this case and treat the replica DB as having reached the given
926 // position (any master switchover already requires that the new master be caught
927 // up before the switch).
928 $replicationPos = $this->getReplicaPos();
929 if ( $replicationPos && !$replicationPos->channelsMatch( $pos ) ) {
930 $this->lastKnownReplicaPos
= $replicationPos;
934 } elseif ( $status >= 0 ) {
935 // Remember that this position was reached to save queries next time
936 $this->lastKnownReplicaPos
= $pos;
943 * Get the position of the master from SHOW SLAVE STATUS
945 * @return MySQLMasterPos|bool
947 public function getReplicaPos() {
948 $now = microtime( true );
950 if ( $this->useGTIDs
) {
951 $res = $this->query( "SELECT @@global.gtid_slave_pos AS Value", __METHOD__
);
952 $gtidRow = $this->fetchObject( $res );
953 if ( $gtidRow && strlen( $gtidRow->Value
) ) {
954 return new MySQLMasterPos( $gtidRow->Value
, $now );
958 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
959 $row = $this->fetchObject( $res );
960 if ( $row && strlen( $row->Relay_Master_Log_File
) ) {
961 return new MySQLMasterPos(
962 "{$row->Relay_Master_Log_File}/{$row->Exec_Master_Log_Pos}",
971 * Get the position of the master from SHOW MASTER STATUS
973 * @return MySQLMasterPos|bool
975 public function getMasterPos() {
976 $now = microtime( true );
978 if ( $this->useGTIDs
) {
979 $res = $this->query( "SELECT @@global.gtid_binlog_pos AS Value", __METHOD__
);
980 $gtidRow = $this->fetchObject( $res );
981 if ( $gtidRow && strlen( $gtidRow->Value
) ) {
982 return new MySQLMasterPos( $gtidRow->Value
, $now );
986 $res = $this->query( 'SHOW MASTER STATUS', __METHOD__
);
987 $row = $this->fetchObject( $res );
988 if ( $row && strlen( $row->File
) ) {
989 return new MySQLMasterPos( "{$row->File}/{$row->Position}", $now );
995 public function serverIsReadOnly() {
996 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'read_only'", __METHOD__
);
997 $row = $this->fetchObject( $res );
999 return $row ?
( strtolower( $row->Value
) === 'on' ) : false;
1003 * @param string $index
1006 function useIndexClause( $index ) {
1007 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
1011 * @param string $index
1014 function ignoreIndexClause( $index ) {
1015 return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
1021 function lowPriorityOption() {
1022 return 'LOW_PRIORITY';
1028 public function getSoftwareLink() {
1029 // MariaDB includes its name in its version string; this is how MariaDB's version of
1030 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
1031 // in libmysql/libmysql.c).
1032 $version = $this->getServerVersion();
1033 if ( strpos( $version, 'MariaDB' ) !== false ||
strpos( $version, '-maria-' ) !== false ) {
1034 return '[{{int:version-db-mariadb-url}} MariaDB]';
1037 // Percona Server's version suffix is not very distinctive, and @@version_comment
1038 // doesn't give the necessary info for source builds, so assume the server is MySQL.
1039 // (Even Percona's version of mysql doesn't try to make the distinction.)
1040 return '[{{int:version-db-mysql-url}} MySQL]';
1046 public function getServerVersion() {
1047 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
1048 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
1049 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
1050 if ( $this->serverVersion
=== null ) {
1051 $this->serverVersion
= $this->selectField( '', 'VERSION()', '', __METHOD__
);
1053 return $this->serverVersion
;
1057 * @param array $options
1059 public function setSessionOptions( array $options ) {
1060 if ( isset( $options['connTimeout'] ) ) {
1061 $timeout = (int)$options['connTimeout'];
1062 $this->query( "SET net_read_timeout=$timeout" );
1063 $this->query( "SET net_write_timeout=$timeout" );
1068 * @param string &$sql
1069 * @param string &$newLine
1072 public function streamStatementEnd( &$sql, &$newLine ) {
1073 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
1074 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
1075 $this->delimiter
= $m[1];
1079 return parent
::streamStatementEnd( $sql, $newLine );
1083 * Check to see if a named lock is available. This is non-blocking.
1085 * @param string $lockName Name of lock to poll
1086 * @param string $method Name of method calling us
1090 public function lockIsFree( $lockName, $method ) {
1091 if ( !parent
::lockIsFree( $lockName, $method ) ) {
1092 return false; // already held
1095 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1096 $result = $this->query( "SELECT IS_FREE_LOCK($encName) AS lockstatus", $method );
1097 $row = $this->fetchObject( $result );
1099 return ( $row->lockstatus
== 1 );
1103 * @param string $lockName
1104 * @param string $method
1105 * @param int $timeout
1108 public function lock( $lockName, $method, $timeout = 5 ) {
1109 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1110 $result = $this->query( "SELECT GET_LOCK($encName, $timeout) AS lockstatus", $method );
1111 $row = $this->fetchObject( $result );
1113 if ( $row->lockstatus
== 1 ) {
1114 parent
::lock( $lockName, $method, $timeout ); // record
1118 $this->queryLogger
->info( __METHOD__
. " failed to acquire lock '{lockname}'",
1119 [ 'lockname' => $lockName ] );
1126 * https://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
1127 * @param string $lockName
1128 * @param string $method
1131 public function unlock( $lockName, $method ) {
1132 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1133 $result = $this->query( "SELECT RELEASE_LOCK($encName) as lockstatus", $method );
1134 $row = $this->fetchObject( $result );
1136 if ( $row->lockstatus
== 1 ) {
1137 parent
::unlock( $lockName, $method ); // record
1141 $this->queryLogger
->warning( __METHOD__
. " failed to release lock '$lockName'\n" );
1146 private function makeLockName( $lockName ) {
1147 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1148 // Newer version enforce a 64 char length limit.
1149 return ( strlen( $lockName ) > 64 ) ?
sha1( $lockName ) : $lockName;
1152 public function namedLocksEnqueue() {
1156 public function tableLocksHaveTransactionScope() {
1157 return false; // tied to TCP connection
1160 protected function doLockTables( array $read, array $write, $method ) {
1162 foreach ( $write as $table ) {
1163 $items[] = $this->tableName( $table ) . ' WRITE';
1165 foreach ( $read as $table ) {
1166 $items[] = $this->tableName( $table ) . ' READ';
1169 $sql = "LOCK TABLES " . implode( ',', $items );
1170 $this->query( $sql, $method );
1175 protected function doUnlockTables( $method ) {
1176 $this->query( "UNLOCK TABLES", $method );
1182 * @param bool $value
1184 public function setBigSelects( $value = true ) {
1185 if ( $value === 'default' ) {
1186 if ( $this->defaultBigSelects
=== null ) {
1187 # Function hasn't been called before so it must already be set to the default
1190 $value = $this->defaultBigSelects
;
1192 } elseif ( $this->defaultBigSelects
=== null ) {
1193 $this->defaultBigSelects
=
1194 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__
);
1196 $encValue = $value ?
'1' : '0';
1197 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
1201 * DELETE where the condition is a join. MySql uses multi-table deletes.
1202 * @param string $delTable
1203 * @param string $joinTable
1204 * @param string $delVar
1205 * @param string $joinVar
1206 * @param array|string $conds
1207 * @param bool|string $fname
1208 * @throws DBUnexpectedError
1209 * @return bool|ResultWrapper
1211 public function deleteJoin(
1212 $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
1215 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
1218 $delTable = $this->tableName( $delTable );
1219 $joinTable = $this->tableName( $joinTable );
1220 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1222 if ( $conds != '*' ) {
1223 $sql .= ' AND ' . $this->makeList( $conds, self
::LIST_AND
);
1226 return $this->query( $sql, $fname );
1230 * @param string $table
1231 * @param array $rows
1232 * @param array $uniqueIndexes
1234 * @param string $fname
1237 public function upsert( $table, array $rows, array $uniqueIndexes,
1238 array $set, $fname = __METHOD__
1240 if ( !count( $rows ) ) {
1241 return true; // nothing to do
1244 if ( !is_array( reset( $rows ) ) ) {
1248 $table = $this->tableName( $table );
1249 $columns = array_keys( $rows[0] );
1251 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1253 foreach ( $rows as $row ) {
1254 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1256 $sql .= implode( ',', $rowTuples );
1257 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, self
::LIST_SET
);
1259 return (bool)$this->query( $sql, $fname );
1263 * Determines how long the server has been up
1267 public function getServerUptime() {
1268 $vars = $this->getMysqlStatus( 'Uptime' );
1270 return (int)$vars['Uptime'];
1274 * Determines if the last failure was due to a deadlock
1278 public function wasDeadlock() {
1279 return $this->lastErrno() == 1213;
1283 * Determines if the last failure was due to a lock timeout
1287 public function wasLockTimeout() {
1288 return $this->lastErrno() == 1205;
1291 public function wasErrorReissuable() {
1292 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
1296 * Determines if the last failure was due to the database being read-only.
1300 public function wasReadOnlyError() {
1301 return $this->lastErrno() == 1223 ||
1302 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1305 public function wasConnectionError( $errno ) {
1306 return $errno == 2013 ||
$errno == 2006;
1310 * @param string $oldName
1311 * @param string $newName
1312 * @param bool $temporary
1313 * @param string $fname
1316 public function duplicateTableStructure(
1317 $oldName, $newName, $temporary = false, $fname = __METHOD__
1319 $tmp = $temporary ?
'TEMPORARY ' : '';
1320 $newName = $this->addIdentifierQuotes( $newName );
1321 $oldName = $this->addIdentifierQuotes( $oldName );
1322 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1324 return $this->query( $query, $fname );
1328 * List all tables on the database
1330 * @param string $prefix Only show tables with this prefix, e.g. mw_
1331 * @param string $fname Calling function name
1334 public function listTables( $prefix = null, $fname = __METHOD__
) {
1335 $result = $this->query( "SHOW TABLES", $fname );
1339 foreach ( $result as $table ) {
1340 $vars = get_object_vars( $table );
1341 $table = array_pop( $vars );
1343 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1344 $endArray[] = $table;
1352 * @param string $tableName
1353 * @param string $fName
1354 * @return bool|ResultWrapper
1356 public function dropTable( $tableName, $fName = __METHOD__
) {
1357 if ( !$this->tableExists( $tableName, $fName ) ) {
1361 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1365 * Get status information from SHOW STATUS in an associative array
1367 * @param string $which
1370 private function getMysqlStatus( $which = "%" ) {
1371 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1374 foreach ( $res as $row ) {
1375 $status[$row->Variable_name
] = $row->Value
;
1382 * Lists VIEWs in the database
1384 * @param string $prefix Only show VIEWs with this prefix, eg.
1385 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1386 * @param string $fname Name of calling function
1390 public function listViews( $prefix = null, $fname = __METHOD__
) {
1391 // The name of the column containing the name of the VIEW
1392 $propertyName = 'Tables_in_' . $this->dbName
;
1394 // Query for the VIEWS
1395 $res = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1397 foreach ( $res as $row ) {
1398 array_push( $allViews, $row->$propertyName );
1401 if ( is_null( $prefix ) ||
$prefix === '' ) {
1405 $filteredViews = [];
1406 foreach ( $allViews as $viewName ) {
1407 // Does the name of this VIEW start with the table-prefix?
1408 if ( strpos( $viewName, $prefix ) === 0 ) {
1409 array_push( $filteredViews, $viewName );
1413 return $filteredViews;
1417 * Differentiates between a TABLE and a VIEW.
1419 * @param string $name Name of the TABLE/VIEW to test
1420 * @param string $prefix
1424 public function isView( $name, $prefix = null ) {
1425 return in_array( $name, $this->listViews( $prefix ) );
1429 * Allows for index remapping in queries where this is not consistent across DBMS
1431 * @param string $index
1434 protected function indexName( $index ) {
1436 * When SQLite indexes were introduced in r45764, it was noted that
1437 * SQLite requires index names to be unique within the whole database,
1438 * not just within a schema. As discussed in CR r45819, to avoid the
1439 * need for a schema change on existing installations, the indexes
1440 * were implicitly mapped from the new names to the old names.
1442 * This mapping can be removed if DB patches are introduced to alter
1443 * the relevant tables in existing installations. Note that because
1444 * this index mapping applies to table creation, even new installations
1445 * of MySQL have the old names (except for installations created during
1446 * a period where this mapping was inappropriately removed, see
1450 'ar_usertext_timestamp' => 'usertext_timestamp',
1451 'un_user_id' => 'user_id',
1452 'un_user_ip' => 'user_ip',
1455 if ( isset( $renamed[$index] ) ) {
1456 return $renamed[$index];
1462 protected function isTransactableQuery( $sql ) {
1463 return parent
::isTransactableQuery( $sql ) &&
1464 !preg_match( '/^SELECT\s+(GET|RELEASE|IS_FREE)_LOCK\(/', $sql );
1468 class_alias( DatabaseMysqlBase
::class, 'DatabaseMysqlBase' );