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;
73 // Cache getServerId() for 24 hours
74 const SERVER_ID_CACHE_TTL
= 86400;
77 * Additional $params include:
78 * - lagDetectionMethod : set to one of (Seconds_Behind_Master,pt-heartbeat).
79 * pt-heartbeat assumes the table is at heartbeat.heartbeat
80 * and uses UTC timestamps in the heartbeat.ts column.
81 * (https://www.percona.com/doc/percona-toolkit/2.2/pt-heartbeat.html)
82 * - lagDetectionOptions : if using pt-heartbeat, this can be set to an array map to change
83 * the default behavior. Normally, the heartbeat row with the server
84 * ID of this server's master will be used. Set the "conds" field to
85 * override the query conditions, e.g. ['shard' => 's1'].
86 * - useGTIDs : use GTID methods like MASTER_GTID_WAIT() when possible.
87 * - insertSelectIsSafe : force that native INSERT SELECT is or is not safe [default: null]
88 * - sslKeyPath : path to key file [default: null]
89 * - sslCertPath : path to certificate file [default: null]
90 * - sslCAFile: path to a single certificate authority PEM file [default: null]
91 * - sslCAPath : parth to certificate authority PEM directory [default: null]
92 * - sslCiphers : array list of allowable ciphers [default: null]
93 * @param array $params
95 function __construct( array $params ) {
96 $this->lagDetectionMethod
= isset( $params['lagDetectionMethod'] )
97 ?
$params['lagDetectionMethod']
98 : 'Seconds_Behind_Master';
99 $this->lagDetectionOptions
= isset( $params['lagDetectionOptions'] )
100 ?
$params['lagDetectionOptions']
102 $this->useGTIDs
= !empty( $params['useGTIDs' ] );
103 foreach ( [ 'KeyPath', 'CertPath', 'CAFile', 'CAPath', 'Ciphers' ] as $name ) {
105 if ( isset( $params[$var] ) ) {
106 $this->$var = $params[$var];
109 $this->sqlMode
= isset( $params['sqlMode'] ) ?
$params['sqlMode'] : '';
110 $this->utf8Mode
= !empty( $params['utf8Mode'] );
111 $this->insertSelectIsSafe
= isset( $params['insertSelectIsSafe'] )
112 ?
(bool)$params['insertSelectIsSafe'] : null;
114 parent
::__construct( $params );
120 public function getType() {
125 * @param string $server
126 * @param string $user
127 * @param string $password
128 * @param string $dbName
129 * @throws Exception|DBConnectionError
132 public function open( $server, $user, $password, $dbName ) {
133 # Close/unset connection handle
136 $this->server
= $server;
138 $this->password
= $password;
139 $this->dbName
= $dbName;
141 $this->installErrorHandler();
143 $this->conn
= $this->mysqlConnect( $this->server
);
144 } catch ( Exception
$ex ) {
145 $this->restoreErrorHandler();
148 $error = $this->restoreErrorHandler();
150 # Always log connection errors
151 if ( !$this->conn
) {
153 $error = $this->lastError();
155 $this->connLogger
->error(
156 "Error connecting to {db_server}: {error}",
157 $this->getLogContext( [
158 'method' => __METHOD__
,
162 $this->connLogger
->debug( "DB connection error\n" .
163 "Server: $server, User: $user, Password: " .
164 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
166 $this->reportConnectionError( $error );
169 if ( strlen( $dbName ) ) {
170 Wikimedia\
suppressWarnings();
171 $success = $this->selectDB( $dbName );
172 Wikimedia\restoreWarnings
();
174 $this->queryLogger
->error(
175 "Error selecting database {db_name} on server {db_server}",
176 $this->getLogContext( [
177 'method' => __METHOD__
,
180 $this->queryLogger
->debug(
181 "Error selecting database $dbName on server {$this->server}" );
183 $this->reportConnectionError( "Error selecting database $dbName" );
187 // Tell the server what we're communicating with
188 if ( !$this->connectInitCharset() ) {
189 $this->reportConnectionError( "Error setting character set" );
192 // Abstract over any insane MySQL defaults
193 $set = [ 'group_concat_max_len = 262144' ];
194 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
195 if ( is_string( $this->sqlMode
) ) {
196 $set[] = 'sql_mode = ' . $this->addQuotes( $this->sqlMode
);
198 // Set any custom settings defined by site config
199 // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
200 foreach ( $this->sessionVars
as $var => $val ) {
201 // Escape strings but not numbers to avoid MySQL complaining
202 if ( !is_int( $val ) && !is_float( $val ) ) {
203 $val = $this->addQuotes( $val );
205 $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
209 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
210 $success = $this->doQuery( 'SET ' . implode( ', ', $set ) );
212 $this->queryLogger
->error(
213 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)',
214 $this->getLogContext( [
215 'method' => __METHOD__
,
218 $this->reportConnectionError(
219 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)' );
223 $this->opened
= true;
229 * Set the character set information right after connection
232 protected function connectInitCharset() {
233 if ( $this->utf8Mode
) {
234 // Tell the server we're communicating with it in UTF-8.
235 // This may engage various charset conversions.
236 return $this->mysqlSetCharset( 'utf8' );
238 return $this->mysqlSetCharset( 'binary' );
243 * Open a connection to a MySQL server
245 * @param string $realServer
246 * @return mixed Raw connection
247 * @throws DBConnectionError
249 abstract protected function mysqlConnect( $realServer );
252 * Set the character set of the MySQL link
254 * @param string $charset
257 abstract protected function mysqlSetCharset( $charset );
260 * @param ResultWrapper|resource $res
261 * @throws DBUnexpectedError
263 public function freeResult( $res ) {
264 if ( $res instanceof ResultWrapper
) {
267 Wikimedia\
suppressWarnings();
268 $ok = $this->mysqlFreeResult( $res );
269 Wikimedia\restoreWarnings
();
271 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
278 * @param resource $res Raw result
281 abstract protected function mysqlFreeResult( $res );
284 * @param ResultWrapper|resource $res
285 * @return stdClass|bool
286 * @throws DBUnexpectedError
288 public function fetchObject( $res ) {
289 if ( $res instanceof ResultWrapper
) {
292 Wikimedia\
suppressWarnings();
293 $row = $this->mysqlFetchObject( $res );
294 Wikimedia\restoreWarnings
();
296 $errno = $this->lastErrno();
297 // Unfortunately, mysql_fetch_object does not reset the last errno.
298 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
299 // these are the only errors mysql_fetch_object can cause.
300 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
301 if ( $errno == 2000 ||
$errno == 2013 ) {
302 throw new DBUnexpectedError(
304 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
312 * Fetch a result row as an object
314 * @param resource $res Raw result
317 abstract protected function mysqlFetchObject( $res );
320 * @param ResultWrapper|resource $res
322 * @throws DBUnexpectedError
324 public function fetchRow( $res ) {
325 if ( $res instanceof ResultWrapper
) {
328 Wikimedia\
suppressWarnings();
329 $row = $this->mysqlFetchArray( $res );
330 Wikimedia\restoreWarnings
();
332 $errno = $this->lastErrno();
333 // Unfortunately, mysql_fetch_array does not reset the last errno.
334 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
335 // these are the only errors mysql_fetch_array can cause.
336 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
337 if ( $errno == 2000 ||
$errno == 2013 ) {
338 throw new DBUnexpectedError(
340 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
348 * Fetch a result row as an associative and numeric array
350 * @param resource $res Raw result
353 abstract protected function mysqlFetchArray( $res );
356 * @throws DBUnexpectedError
357 * @param ResultWrapper|resource $res
360 function numRows( $res ) {
361 if ( $res instanceof ResultWrapper
) {
364 Wikimedia\
suppressWarnings();
365 $n = $this->mysqlNumRows( $res );
366 Wikimedia\restoreWarnings
();
368 // Unfortunately, mysql_num_rows does not reset the last errno.
369 // We are not checking for any errors here, since
370 // these are no errors mysql_num_rows can cause.
371 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
372 // See https://phabricator.wikimedia.org/T44430
377 * Get number of rows in result
379 * @param resource $res Raw result
382 abstract protected function mysqlNumRows( $res );
385 * @param ResultWrapper|resource $res
388 public function numFields( $res ) {
389 if ( $res instanceof ResultWrapper
) {
393 return $this->mysqlNumFields( $res );
397 * Get number of fields in result
399 * @param resource $res Raw result
402 abstract protected function mysqlNumFields( $res );
405 * @param ResultWrapper|resource $res
409 public function fieldName( $res, $n ) {
410 if ( $res instanceof ResultWrapper
) {
414 return $this->mysqlFieldName( $res, $n );
418 * Get the name of the specified field in a result
420 * @param ResultWrapper|resource $res
424 abstract protected function mysqlFieldName( $res, $n );
427 * mysql_field_type() wrapper
428 * @param ResultWrapper|resource $res
432 public function fieldType( $res, $n ) {
433 if ( $res instanceof ResultWrapper
) {
437 return $this->mysqlFieldType( $res, $n );
441 * Get the type of the specified field in a result
443 * @param ResultWrapper|resource $res
447 abstract protected function mysqlFieldType( $res, $n );
450 * @param ResultWrapper|resource $res
454 public function dataSeek( $res, $row ) {
455 if ( $res instanceof ResultWrapper
) {
459 return $this->mysqlDataSeek( $res, $row );
463 * Move internal result pointer
465 * @param ResultWrapper|resource $res
469 abstract protected function mysqlDataSeek( $res, $row );
474 public function lastError() {
476 # Even if it's non-zero, it can still be invalid
477 Wikimedia\
suppressWarnings();
478 $error = $this->mysqlError( $this->conn
);
480 $error = $this->mysqlError();
482 Wikimedia\restoreWarnings
();
484 $error = $this->mysqlError();
487 $error .= ' (' . $this->server
. ')';
494 * Returns the text of the error message from previous MySQL operation
496 * @param resource $conn Raw connection
499 abstract protected function mysqlError( $conn = null );
501 protected function wasQueryTimeout( $error, $errno ) {
502 return $errno == 2062;
506 * @param string $table
507 * @param array $uniqueIndexes
509 * @param string $fname
510 * @return ResultWrapper
512 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
513 return $this->nativeReplace( $table, $rows, $fname );
516 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
517 $row = $this->getReplicationSafetyInfo();
518 // For row-based-replication, the resulting changes will be relayed, not the query
519 if ( $row->binlog_format
=== 'ROW' ) {
522 // LIMIT requires ORDER BY on a unique key or it is non-deterministic
523 if ( isset( $selectOptions['LIMIT'] ) ) {
526 // In MySQL, an INSERT SELECT is only replication safe with row-based
527 // replication or if innodb_autoinc_lock_mode is 0. When those
528 // conditions aren't met, use non-native mode.
529 // While we could try to determine if the insert is safe anyway by
530 // checking if the target table has an auto-increment column that
531 // isn't set in $varMap, that seems unlikely to be worth the extra
534 in_array( 'NO_AUTO_COLUMNS', $insertOptions ) ||
535 (int)$row->innodb_autoinc_lock_mode
=== 0
540 * @return stdClass Process cached row
542 protected function getReplicationSafetyInfo() {
543 if ( $this->replicationInfoRow
=== null ) {
544 $this->replicationInfoRow
= $this->selectRow(
547 'innodb_autoinc_lock_mode' => '@@innodb_autoinc_lock_mode',
548 'binlog_format' => '@@binlog_format',
555 return $this->replicationInfoRow
;
559 * Estimate rows in dataset
560 * Returns estimated count, based on EXPLAIN output
561 * Takes same arguments as Database::select()
563 * @param string|array $table
564 * @param string|array $var
565 * @param string|array $conds
566 * @param string $fname
567 * @param string|array $options
568 * @param array $join_conds
571 public function estimateRowCount( $table, $var = '*', $conds = '',
572 $fname = __METHOD__
, $options = [], $join_conds = []
574 $conds = $this->normalizeConditions( $conds, $fname );
575 $column = $this->extractSingleFieldFromList( $var );
576 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
577 $conds[] = "$column IS NOT NULL";
580 $options['EXPLAIN'] = true;
581 $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
582 if ( $res === false ) {
585 if ( !$this->numRows( $res ) ) {
590 foreach ( $res as $plan ) {
591 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
597 public function tableExists( $table, $fname = __METHOD__
) {
598 // Split database and table into proper variables as Database::tableName() returns
599 // shared tables prefixed with their database, which do not work in SHOW TABLES statements
600 list( $database, , $prefix, $table ) = $this->qualifiedTableComponents( $table );
601 $tableName = "{$prefix}{$table}";
603 if ( isset( $this->sessionTempTables
[$tableName] ) ) {
604 return true; // already known to exist and won't show in SHOW TABLES anyway
607 // We can't use buildLike() here, because it specifies an escape character
608 // other than the backslash, which is the only one supported by SHOW TABLES
609 $encLike = $this->escapeLikeInternal( $tableName, '\\' );
611 // If the database has been specified (such as for shared tables), use "FROM"
612 if ( $database !== '' ) {
613 $encDatabase = $this->addIdentifierQuotes( $database );
614 $query = "SHOW TABLES FROM $encDatabase LIKE '$encLike'";
616 $query = "SHOW TABLES LIKE '$encLike'";
619 return $this->query( $query, $fname )->numRows() > 0;
623 * @param string $table
624 * @param string $field
625 * @return bool|MySQLField
627 public function fieldInfo( $table, $field ) {
628 $table = $this->tableName( $table );
629 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
633 $n = $this->mysqlNumFields( $res->result
);
634 for ( $i = 0; $i < $n; $i++
) {
635 $meta = $this->mysqlFetchField( $res->result
, $i );
636 if ( $field == $meta->name
) {
637 return new MySQLField( $meta );
645 * Get column information from a result
647 * @param resource $res Raw result
651 abstract protected function mysqlFetchField( $res, $n );
654 * Get information about an index into an object
655 * Returns false if the index does not exist
657 * @param string $table
658 * @param string $index
659 * @param string $fname
660 * @return bool|array|null False or null on failure
662 public function indexInfo( $table, $index, $fname = __METHOD__
) {
663 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
664 # SHOW INDEX should work for 3.x and up:
665 # https://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
666 $table = $this->tableName( $table );
667 $index = $this->indexName( $index );
669 $sql = 'SHOW INDEX FROM ' . $table;
670 $res = $this->query( $sql, $fname );
678 foreach ( $res as $row ) {
679 if ( $row->Key_name
== $index ) {
684 return $result ?
: false;
691 public function strencode( $s ) {
692 return $this->mysqlRealEscapeString( $s );
699 abstract protected function mysqlRealEscapeString( $s );
701 public function addQuotes( $s ) {
702 if ( is_bool( $s ) ) {
703 // Parent would transform to int, which does not play nice with MySQL type juggling.
704 // When searching for an int in a string column, the strings are cast to int, which
705 // means false would match any string not starting with a number.
706 $s = (string)(int)$s;
708 return parent
::addQuotes( $s );
712 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
717 public function addIdentifierQuotes( $s ) {
718 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
719 // Remove NUL bytes and escape backticks by doubling
720 return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
724 * @param string $name
727 public function isQuotedIdentifier( $name ) {
728 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
731 public function getLag() {
732 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
733 return $this->getLagFromPtHeartbeat();
735 return $this->getLagFromSlaveStatus();
742 protected function getLagDetectionMethod() {
743 return $this->lagDetectionMethod
;
749 protected function getLagFromSlaveStatus() {
750 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
751 $row = $res ?
$res->fetchObject() : false;
752 // If the server is not replicating, there will be no row
753 if ( $row && strval( $row->Seconds_Behind_Master
) !== '' ) {
754 return intval( $row->Seconds_Behind_Master
);
763 protected function getLagFromPtHeartbeat() {
764 $options = $this->lagDetectionOptions
;
766 if ( isset( $options['conds'] ) ) {
767 // Best method for multi-DC setups: use logical channel names
768 $data = $this->getHeartbeatData( $options['conds'] );
770 // Standard method: use master server ID (works with stock pt-heartbeat)
771 $masterInfo = $this->getMasterServerInfo();
772 if ( !$masterInfo ) {
773 $this->queryLogger
->error(
774 "Unable to query master of {db_server} for server ID",
775 $this->getLogContext( [
776 'method' => __METHOD__
780 return false; // could not get master server ID
783 $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
784 $data = $this->getHeartbeatData( $conds );
787 list( $time, $nowUnix ) = $data;
788 if ( $time !== null ) {
789 // @time is in ISO format like "2015-09-25T16:48:10.000510"
790 $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
791 $timeUnix = (int)$dateTime->format( 'U' ) +
$dateTime->format( 'u' ) / 1e6
;
793 return max( $nowUnix - $timeUnix, 0.0 );
796 $this->queryLogger
->error(
797 "Unable to find pt-heartbeat row for {db_server}",
798 $this->getLogContext( [
799 'method' => __METHOD__
806 protected function getMasterServerInfo() {
807 $cache = $this->srvCache
;
808 $key = $cache->makeGlobalKey(
811 // Using one key for all cluster replica DBs is preferable
812 $this->getLBInfo( 'clusterMasterHost' ) ?
: $this->getServer()
815 return $cache->getWithSetCallback(
817 $cache::TTL_INDEFINITE
,
818 function () use ( $cache, $key ) {
819 // Get and leave a lock key in place for a short period
820 if ( !$cache->lock( $key, 0, 10 ) ) {
821 return false; // avoid master connection spike slams
824 $conn = $this->getLazyMasterHandle();
826 return false; // something is misconfigured
829 // Connect to and query the master; catch errors to avoid outages
831 $res = $conn->query( 'SELECT @@server_id AS id', __METHOD__
);
832 $row = $res ?
$res->fetchObject() : false;
833 $id = $row ?
(int)$row->id
: 0;
834 } catch ( DBError
$e ) {
838 // Cache the ID if it was retrieved
839 return $id ?
[ 'serverId' => $id, 'asOf' => time() ] : false;
845 * @param array $conds WHERE clause conditions to find a row
846 * @return array (heartbeat `ts` column value or null, UNIX timestamp) for the newest beat
847 * @see https://www.percona.com/doc/percona-toolkit/2.1/pt-heartbeat.html
849 protected function getHeartbeatData( array $conds ) {
850 // Query time and trip time are not counted
851 $nowUnix = microtime( true );
852 // Do not bother starting implicit transactions here
853 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
855 $whereSQL = $this->makeList( $conds, self
::LIST_AND
);
856 // Use ORDER BY for channel based queries since that field might not be UNIQUE.
857 // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
858 // percision field is not supported in MySQL <= 5.5.
860 "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1",
863 $row = $res ?
$res->fetchObject() : false;
865 $this->restoreFlags();
868 return [ $row ?
$row->ts
: null, $nowUnix ];
871 protected function getApproximateLagStatus() {
872 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
873 // Disable caching since this is fast enough and we don't wan't
874 // to be *too* pessimistic by having both the cache TTL and the
875 // pt-heartbeat interval count as lag in getSessionLagStatus()
876 return parent
::getApproximateLagStatus();
879 $key = $this->srvCache
->makeGlobalKey( 'mysql-lag', $this->getServer() );
880 $approxLag = $this->srvCache
->get( $key );
882 $approxLag = parent
::getApproximateLagStatus();
883 $this->srvCache
->set( $key, $approxLag, 1 );
889 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
890 if ( !( $pos instanceof MySQLMasterPos
) ) {
891 throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
894 if ( $this->getLBInfo( 'is static' ) === true ) {
895 return 0; // this is a copy of a read-only dataset with no master DB
896 } elseif ( $this->lastKnownReplicaPos
&& $this->lastKnownReplicaPos
->hasReached( $pos ) ) {
897 return 0; // already reached this point for sure
900 // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
901 if ( $pos->getGTIDs() ) {
902 // Ignore GTIDs from domains exclusive to the master DB (presumably inactive)
903 $rpos = $this->getReplicaPos();
904 $gtidsWait = $rpos ? MySQLMasterPos
::getCommonDomainGTIDs( $pos, $rpos ) : [];
906 $this->queryLogger
->error(
907 "No GTIDs with the same domain between master ($pos) and replica ($rpos)",
908 $this->getLogContext( [
909 'method' => __METHOD__
,
913 return -1; // $pos is from the wrong cluster?
915 // Wait on the GTID set (MariaDB only)
916 $gtidArg = $this->addQuotes( implode( ',', $gtidsWait ) );
917 if ( strpos( $gtidArg, ':' ) !== false ) {
918 // MySQL GTIDs, e.g "source_id:transaction_id"
919 $res = $this->doQuery( "SELECT WAIT_FOR_EXECUTED_GTID_SET($gtidArg, $timeout)" );
921 // MariaDB GTIDs, e.g."domain:server:sequence"
922 $res = $this->doQuery( "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)" );
925 // Wait on the binlog coordinates
926 $encFile = $this->addQuotes( $pos->getLogFile() );
927 $encPos = intval( $pos->getLogPosition()[$pos::CORD_EVENT
] );
928 $res = $this->doQuery( "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)" );
931 $row = $res ?
$this->fetchRow( $res ) : false;
933 throw new DBExpectedError( $this, "Replication wait failed: {$this->lastError()}" );
936 // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
937 $status = ( $row[0] !== null ) ?
intval( $row[0] ) : null;
938 if ( $status === null ) {
939 if ( !$pos->getGTIDs() ) {
940 // T126436: jobs programmed to wait on master positions might be referencing
941 // binlogs with an old master hostname; this makes MASTER_POS_WAIT() return null.
942 // Try to detect this case and treat the replica DB as having reached the given
943 // position (any master switchover already requires that the new master be caught
944 // up before the switch).
945 $replicationPos = $this->getReplicaPos();
946 if ( $replicationPos && !$replicationPos->channelsMatch( $pos ) ) {
947 $this->lastKnownReplicaPos
= $replicationPos;
951 } elseif ( $status >= 0 ) {
952 // Remember that this position was reached to save queries next time
953 $this->lastKnownReplicaPos
= $pos;
960 * Get the position of the master from SHOW SLAVE STATUS
962 * @return MySQLMasterPos|bool
964 public function getReplicaPos() {
965 $now = microtime( true ); // as-of-time *before* fetching GTID variables
967 if ( $this->useGTIDs() ) {
968 // Try to use GTIDs, fallbacking to binlog positions if not possible
969 $data = $this->getServerGTIDs( __METHOD__
);
970 // Use gtid_current_pos for MariaDB and gtid_executed for MySQL
971 foreach ( [ 'gtid_current_pos', 'gtid_executed' ] as $name ) {
972 if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
973 return new MySQLMasterPos( $data[$name], $now );
978 $data = $this->getServerRoleStatus( 'SLAVE', __METHOD__
);
979 if ( $data && strlen( $data['Relay_Master_Log_File'] ) ) {
980 return new MySQLMasterPos(
981 "{$data['Relay_Master_Log_File']}/{$data['Exec_Master_Log_Pos']}",
990 * Get the position of the master from SHOW MASTER STATUS
992 * @return MySQLMasterPos|bool
994 public function getMasterPos() {
995 $now = microtime( true ); // as-of-time *before* fetching GTID variables
998 if ( $this->useGTIDs() ) {
999 // Try to use GTIDs, fallbacking to binlog positions if not possible
1000 $data = $this->getServerGTIDs( __METHOD__
);
1001 // Use gtid_current_pos for MariaDB and gtid_executed for MySQL
1002 foreach ( [ 'gtid_current_pos', 'gtid_executed' ] as $name ) {
1003 if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
1004 $pos = new MySQLMasterPos( $data[$name], $now );
1008 // Filter domains that are inactive or not relevant to the session
1010 $pos->setActiveOriginServerId( $this->getServerId() );
1011 $pos->setActiveOriginServerUUID( $this->getServerUUID() );
1012 if ( isset( $data['gtid_domain_id'] ) ) {
1013 $pos->setActiveDomain( $data['gtid_domain_id'] );
1019 $data = $this->getServerRoleStatus( 'MASTER', __METHOD__
);
1020 if ( $data && strlen( $data['File'] ) ) {
1021 $pos = new MySQLMasterPos( "{$data['File']}/{$data['Position']}", $now );
1030 * @throws DBQueryError If the variable doesn't exist for some reason
1032 protected function getServerId() {
1033 return $this->srvCache
->getWithSetCallback(
1034 $this->srvCache
->makeGlobalKey( 'mysql-server-id', $this->getServer() ),
1035 self
::SERVER_ID_CACHE_TTL
,
1037 $res = $this->query( "SELECT @@server_id AS id", __METHOD__
);
1038 return intval( $this->fetchObject( $res )->id
);
1044 * @return string|null
1046 protected function getServerUUID() {
1047 return $this->srvCache
->getWithSetCallback(
1048 $this->srvCache
->makeGlobalKey( 'mysql-server-uuid', $this->getServer() ),
1049 self
::SERVER_ID_CACHE_TTL
,
1051 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'server_uuid'" );
1052 $row = $this->fetchObject( $res );
1054 return $row ?
$row->Value
: null;
1060 * @param string $fname
1063 protected function getServerGTIDs( $fname = __METHOD__
) {
1065 // Get global-only variables like gtid_executed
1066 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_%'", $fname );
1067 foreach ( $res as $row ) {
1068 $map[$row->Variable_name
] = $row->Value
;
1070 // Get session-specific (e.g. gtid_domain_id since that is were writes will log)
1071 $res = $this->query( "SHOW SESSION VARIABLES LIKE 'gtid_%'", $fname );
1072 foreach ( $res as $row ) {
1073 $map[$row->Variable_name
] = $row->Value
;
1080 * @param string $role One of "MASTER"/"SLAVE"
1081 * @param string $fname
1082 * @return string[] Latest available server status row
1084 protected function getServerRoleStatus( $role, $fname = __METHOD__
) {
1085 return $this->query( "SHOW $role STATUS", $fname )->fetchRow() ?
: [];
1088 public function serverIsReadOnly() {
1089 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'read_only'", __METHOD__
);
1090 $row = $this->fetchObject( $res );
1092 return $row ?
( strtolower( $row->Value
) === 'on' ) : false;
1096 * @param string $index
1099 function useIndexClause( $index ) {
1100 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
1104 * @param string $index
1107 function ignoreIndexClause( $index ) {
1108 return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
1114 function lowPriorityOption() {
1115 return 'LOW_PRIORITY';
1121 public function getSoftwareLink() {
1122 // MariaDB includes its name in its version string; this is how MariaDB's version of
1123 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
1124 // in libmysql/libmysql.c).
1125 $version = $this->getServerVersion();
1126 if ( strpos( $version, 'MariaDB' ) !== false ||
strpos( $version, '-maria-' ) !== false ) {
1127 return '[{{int:version-db-mariadb-url}} MariaDB]';
1130 // Percona Server's version suffix is not very distinctive, and @@version_comment
1131 // doesn't give the necessary info for source builds, so assume the server is MySQL.
1132 // (Even Percona's version of mysql doesn't try to make the distinction.)
1133 return '[{{int:version-db-mysql-url}} MySQL]';
1139 public function getServerVersion() {
1140 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
1141 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
1142 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
1143 if ( $this->serverVersion
=== null ) {
1144 $this->serverVersion
= $this->selectField( '', 'VERSION()', '', __METHOD__
);
1146 return $this->serverVersion
;
1150 * @param array $options
1152 public function setSessionOptions( array $options ) {
1153 if ( isset( $options['connTimeout'] ) ) {
1154 $timeout = (int)$options['connTimeout'];
1155 $this->query( "SET net_read_timeout=$timeout" );
1156 $this->query( "SET net_write_timeout=$timeout" );
1161 * @param string &$sql
1162 * @param string &$newLine
1165 public function streamStatementEnd( &$sql, &$newLine ) {
1166 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
1167 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
1168 $this->delimiter
= $m[1];
1172 return parent
::streamStatementEnd( $sql, $newLine );
1176 * Check to see if a named lock is available. This is non-blocking.
1178 * @param string $lockName Name of lock to poll
1179 * @param string $method Name of method calling us
1183 public function lockIsFree( $lockName, $method ) {
1184 if ( !parent
::lockIsFree( $lockName, $method ) ) {
1185 return false; // already held
1188 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1189 $result = $this->query( "SELECT IS_FREE_LOCK($encName) AS lockstatus", $method );
1190 $row = $this->fetchObject( $result );
1192 return ( $row->lockstatus
== 1 );
1196 * @param string $lockName
1197 * @param string $method
1198 * @param int $timeout
1201 public function lock( $lockName, $method, $timeout = 5 ) {
1202 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1203 $result = $this->query( "SELECT GET_LOCK($encName, $timeout) AS lockstatus", $method );
1204 $row = $this->fetchObject( $result );
1206 if ( $row->lockstatus
== 1 ) {
1207 parent
::lock( $lockName, $method, $timeout ); // record
1211 $this->queryLogger
->info( __METHOD__
. " failed to acquire lock '{lockname}'",
1212 [ 'lockname' => $lockName ] );
1219 * https://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
1220 * @param string $lockName
1221 * @param string $method
1224 public function unlock( $lockName, $method ) {
1225 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1226 $result = $this->query( "SELECT RELEASE_LOCK($encName) as lockstatus", $method );
1227 $row = $this->fetchObject( $result );
1229 if ( $row->lockstatus
== 1 ) {
1230 parent
::unlock( $lockName, $method ); // record
1234 $this->queryLogger
->warning( __METHOD__
. " failed to release lock '$lockName'\n" );
1239 private function makeLockName( $lockName ) {
1240 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1241 // Newer version enforce a 64 char length limit.
1242 return ( strlen( $lockName ) > 64 ) ?
sha1( $lockName ) : $lockName;
1245 public function namedLocksEnqueue() {
1249 public function tableLocksHaveTransactionScope() {
1250 return false; // tied to TCP connection
1253 protected function doLockTables( array $read, array $write, $method ) {
1255 foreach ( $write as $table ) {
1256 $items[] = $this->tableName( $table ) . ' WRITE';
1258 foreach ( $read as $table ) {
1259 $items[] = $this->tableName( $table ) . ' READ';
1262 $sql = "LOCK TABLES " . implode( ',', $items );
1263 $this->query( $sql, $method );
1268 protected function doUnlockTables( $method ) {
1269 $this->query( "UNLOCK TABLES", $method );
1275 * @param bool $value
1277 public function setBigSelects( $value = true ) {
1278 if ( $value === 'default' ) {
1279 if ( $this->defaultBigSelects
=== null ) {
1280 # Function hasn't been called before so it must already be set to the default
1283 $value = $this->defaultBigSelects
;
1285 } elseif ( $this->defaultBigSelects
=== null ) {
1286 $this->defaultBigSelects
=
1287 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__
);
1289 $encValue = $value ?
'1' : '0';
1290 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
1294 * DELETE where the condition is a join. MySql uses multi-table deletes.
1295 * @param string $delTable
1296 * @param string $joinTable
1297 * @param string $delVar
1298 * @param string $joinVar
1299 * @param array|string $conds
1300 * @param bool|string $fname
1301 * @throws DBUnexpectedError
1302 * @return bool|ResultWrapper
1304 public function deleteJoin(
1305 $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
1308 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
1311 $delTable = $this->tableName( $delTable );
1312 $joinTable = $this->tableName( $joinTable );
1313 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1315 if ( $conds != '*' ) {
1316 $sql .= ' AND ' . $this->makeList( $conds, self
::LIST_AND
);
1319 return $this->query( $sql, $fname );
1323 * @param string $table
1324 * @param array $rows
1325 * @param array $uniqueIndexes
1327 * @param string $fname
1330 public function upsert( $table, array $rows, array $uniqueIndexes,
1331 array $set, $fname = __METHOD__
1333 if ( !count( $rows ) ) {
1334 return true; // nothing to do
1337 if ( !is_array( reset( $rows ) ) ) {
1341 $table = $this->tableName( $table );
1342 $columns = array_keys( $rows[0] );
1344 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1346 foreach ( $rows as $row ) {
1347 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1349 $sql .= implode( ',', $rowTuples );
1350 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, self
::LIST_SET
);
1352 return (bool)$this->query( $sql, $fname );
1356 * Determines how long the server has been up
1360 public function getServerUptime() {
1361 $vars = $this->getMysqlStatus( 'Uptime' );
1363 return (int)$vars['Uptime'];
1367 * Determines if the last failure was due to a deadlock
1371 public function wasDeadlock() {
1372 return $this->lastErrno() == 1213;
1376 * Determines if the last failure was due to a lock timeout
1380 public function wasLockTimeout() {
1381 return $this->lastErrno() == 1205;
1385 * Determines if the last failure was due to the database being read-only.
1389 public function wasReadOnlyError() {
1390 return $this->lastErrno() == 1223 ||
1391 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1394 public function wasConnectionError( $errno ) {
1395 return $errno == 2013 ||
$errno == 2006;
1399 * @param string $oldName
1400 * @param string $newName
1401 * @param bool $temporary
1402 * @param string $fname
1405 public function duplicateTableStructure(
1406 $oldName, $newName, $temporary = false, $fname = __METHOD__
1408 $tmp = $temporary ?
'TEMPORARY ' : '';
1409 $newName = $this->addIdentifierQuotes( $newName );
1410 $oldName = $this->addIdentifierQuotes( $oldName );
1411 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1413 return $this->query( $query, $fname );
1417 * List all tables on the database
1419 * @param string $prefix Only show tables with this prefix, e.g. mw_
1420 * @param string $fname Calling function name
1423 public function listTables( $prefix = null, $fname = __METHOD__
) {
1424 $result = $this->query( "SHOW TABLES", $fname );
1428 foreach ( $result as $table ) {
1429 $vars = get_object_vars( $table );
1430 $table = array_pop( $vars );
1432 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1433 $endArray[] = $table;
1441 * @param string $tableName
1442 * @param string $fName
1443 * @return bool|ResultWrapper
1445 public function dropTable( $tableName, $fName = __METHOD__
) {
1446 if ( !$this->tableExists( $tableName, $fName ) ) {
1450 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1454 * Get status information from SHOW STATUS in an associative array
1456 * @param string $which
1459 private function getMysqlStatus( $which = "%" ) {
1460 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1463 foreach ( $res as $row ) {
1464 $status[$row->Variable_name
] = $row->Value
;
1471 * Lists VIEWs in the database
1473 * @param string $prefix Only show VIEWs with this prefix, eg.
1474 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1475 * @param string $fname Name of calling function
1479 public function listViews( $prefix = null, $fname = __METHOD__
) {
1480 // The name of the column containing the name of the VIEW
1481 $propertyName = 'Tables_in_' . $this->dbName
;
1483 // Query for the VIEWS
1484 $res = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1486 foreach ( $res as $row ) {
1487 array_push( $allViews, $row->$propertyName );
1490 if ( is_null( $prefix ) ||
$prefix === '' ) {
1494 $filteredViews = [];
1495 foreach ( $allViews as $viewName ) {
1496 // Does the name of this VIEW start with the table-prefix?
1497 if ( strpos( $viewName, $prefix ) === 0 ) {
1498 array_push( $filteredViews, $viewName );
1502 return $filteredViews;
1506 * Differentiates between a TABLE and a VIEW.
1508 * @param string $name Name of the TABLE/VIEW to test
1509 * @param string $prefix
1513 public function isView( $name, $prefix = null ) {
1514 return in_array( $name, $this->listViews( $prefix ) );
1517 protected function isTransactableQuery( $sql ) {
1518 return parent
::isTransactableQuery( $sql ) &&
1519 !preg_match( '/^SELECT\s+(GET|RELEASE|IS_FREE)_LOCK\(/', $sql );
1523 * @param string $field Field or column to cast
1526 public function buildIntegerCast( $field ) {
1527 return 'CAST( ' . $field . ' AS SIGNED )';
1531 * @return bool Whether GTID support is used (mockable for testing)
1533 protected function useGTIDs() {
1534 return $this->useGTIDs
;
1538 class_alias( DatabaseMysqlBase
::class, 'DatabaseMysqlBase' );