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;
76 /** @var float Warn if lag estimates are made for transactions older than this many seconds */
77 const LAG_STALE_WARN_THRESHOLD
= 0.100;
80 * Additional $params include:
81 * - lagDetectionMethod : set to one of (Seconds_Behind_Master,pt-heartbeat).
82 * pt-heartbeat assumes the table is at heartbeat.heartbeat
83 * and uses UTC timestamps in the heartbeat.ts column.
84 * (https://www.percona.com/doc/percona-toolkit/2.2/pt-heartbeat.html)
85 * - lagDetectionOptions : if using pt-heartbeat, this can be set to an array map to change
86 * the default behavior. Normally, the heartbeat row with the server
87 * ID of this server's master will be used. Set the "conds" field to
88 * override the query conditions, e.g. ['shard' => 's1'].
89 * - useGTIDs : use GTID methods like MASTER_GTID_WAIT() when possible.
90 * - insertSelectIsSafe : force that native INSERT SELECT is or is not safe [default: null]
91 * - sslKeyPath : path to key file [default: null]
92 * - sslCertPath : path to certificate file [default: null]
93 * - sslCAFile: path to a single certificate authority PEM file [default: null]
94 * - sslCAPath : parth to certificate authority PEM directory [default: null]
95 * - sslCiphers : array list of allowable ciphers [default: null]
96 * @param array $params
98 function __construct( array $params ) {
99 $this->lagDetectionMethod
= $params['lagDetectionMethod'] ??
'Seconds_Behind_Master';
100 $this->lagDetectionOptions
= $params['lagDetectionOptions'] ??
[];
101 $this->useGTIDs
= !empty( $params['useGTIDs' ] );
102 foreach ( [ 'KeyPath', 'CertPath', 'CAFile', 'CAPath', 'Ciphers' ] as $name ) {
104 if ( isset( $params[$var] ) ) {
105 $this->$var = $params[$var];
108 $this->sqlMode
= $params['sqlMode'] ??
'';
109 $this->utf8Mode
= !empty( $params['utf8Mode'] );
110 $this->insertSelectIsSafe
= isset( $params['insertSelectIsSafe'] )
111 ?
(bool)$params['insertSelectIsSafe'] : null;
113 parent
::__construct( $params );
119 public function getType() {
124 * @param string $server
125 * @param string $user
126 * @param string $password
127 * @param string $dbName
128 * @throws Exception|DBConnectionError
131 public function open( $server, $user, $password, $dbName ) {
132 # Close/unset connection handle
135 $this->server
= $server;
137 $this->password
= $password;
138 $this->dbName
= $dbName;
140 $this->installErrorHandler();
142 $this->conn
= $this->mysqlConnect( $this->server
);
143 } catch ( Exception
$ex ) {
144 $this->restoreErrorHandler();
147 $error = $this->restoreErrorHandler();
149 # Always log connection errors
150 if ( !$this->conn
) {
151 $error = $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 throw new DBConnectionError( $this, $error );
166 if ( strlen( $dbName ) ) {
167 Wikimedia\
suppressWarnings();
168 $success = $this->selectDB( $dbName );
169 Wikimedia\restoreWarnings
();
171 $error = $this->lastError();
172 $this->queryLogger
->error(
173 "Error selecting database {db_name} on server {db_server}: {error}",
174 $this->getLogContext( [
175 'method' => __METHOD__
,
179 throw new DBConnectionError( $this, "Error selecting database $dbName: $error" );
183 // Tell the server what we're communicating with
184 if ( !$this->connectInitCharset() ) {
185 $error = $this->lastError();
186 $this->queryLogger
->error(
187 "Error setting character set: {error}",
188 $this->getLogContext( [
189 'method' => __METHOD__
,
190 'error' => $this->lastError(),
193 throw new DBConnectionError( $this, "Error setting character set: $error" );
196 // Abstract over any insane MySQL defaults
197 $set = [ 'group_concat_max_len = 262144' ];
198 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
199 if ( is_string( $this->sqlMode
) ) {
200 $set[] = 'sql_mode = ' . $this->addQuotes( $this->sqlMode
);
202 // Set any custom settings defined by site config
203 // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
204 foreach ( $this->sessionVars
as $var => $val ) {
205 // Escape strings but not numbers to avoid MySQL complaining
206 if ( !is_int( $val ) && !is_float( $val ) ) {
207 $val = $this->addQuotes( $val );
209 $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
213 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
214 $success = $this->doQuery( 'SET ' . implode( ', ', $set ) );
216 $error = $this->lastError();
217 $this->queryLogger
->error(
218 'Error setting MySQL variables on server {db_server}: {error}',
219 $this->getLogContext( [
220 'method' => __METHOD__
,
224 throw new DBConnectionError( $this, "Error setting MySQL variables: $error" );
228 $this->opened
= true;
234 * Set the character set information right after connection
237 protected function connectInitCharset() {
238 if ( $this->utf8Mode
) {
239 // Tell the server we're communicating with it in UTF-8.
240 // This may engage various charset conversions.
241 return $this->mysqlSetCharset( 'utf8' );
243 return $this->mysqlSetCharset( 'binary' );
248 * Open a connection to a MySQL server
250 * @param string $realServer
251 * @return mixed Raw connection
252 * @throws DBConnectionError
254 abstract protected function mysqlConnect( $realServer );
257 * Set the character set of the MySQL link
259 * @param string $charset
262 abstract protected function mysqlSetCharset( $charset );
265 * @param ResultWrapper|resource $res
266 * @throws DBUnexpectedError
268 public function freeResult( $res ) {
269 if ( $res instanceof ResultWrapper
) {
272 Wikimedia\
suppressWarnings();
273 $ok = $this->mysqlFreeResult( $res );
274 Wikimedia\restoreWarnings
();
276 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
283 * @param resource $res Raw result
286 abstract protected function mysqlFreeResult( $res );
289 * @param ResultWrapper|resource $res
290 * @return stdClass|bool
291 * @throws DBUnexpectedError
293 public function fetchObject( $res ) {
294 if ( $res instanceof ResultWrapper
) {
297 Wikimedia\
suppressWarnings();
298 $row = $this->mysqlFetchObject( $res );
299 Wikimedia\restoreWarnings
();
301 $errno = $this->lastErrno();
302 // Unfortunately, mysql_fetch_object does not reset the last errno.
303 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
304 // these are the only errors mysql_fetch_object can cause.
305 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
306 if ( $errno == 2000 ||
$errno == 2013 ) {
307 throw new DBUnexpectedError(
309 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
317 * Fetch a result row as an object
319 * @param resource $res Raw result
322 abstract protected function mysqlFetchObject( $res );
325 * @param IResultWrapper|resource $res
327 * @throws DBUnexpectedError
329 public function fetchRow( $res ) {
330 if ( $res instanceof ResultWrapper
) {
333 Wikimedia\
suppressWarnings();
334 $row = $this->mysqlFetchArray( $res );
335 Wikimedia\restoreWarnings
();
337 $errno = $this->lastErrno();
338 // Unfortunately, mysql_fetch_array does not reset the last errno.
339 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
340 // these are the only errors mysql_fetch_array can cause.
341 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
342 if ( $errno == 2000 ||
$errno == 2013 ) {
343 throw new DBUnexpectedError(
345 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
353 * Fetch a result row as an associative and numeric array
355 * @param resource $res Raw result
358 abstract protected function mysqlFetchArray( $res );
361 * @throws DBUnexpectedError
362 * @param ResultWrapper|resource $res
365 function numRows( $res ) {
366 if ( $res instanceof ResultWrapper
) {
369 Wikimedia\
suppressWarnings();
370 $n = $this->mysqlNumRows( $res );
371 Wikimedia\restoreWarnings
();
373 // Unfortunately, mysql_num_rows does not reset the last errno.
374 // We are not checking for any errors here, since
375 // there are no errors mysql_num_rows can cause.
376 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
377 // See https://phabricator.wikimedia.org/T44430
382 * Get number of rows in result
384 * @param resource $res Raw result
387 abstract protected function mysqlNumRows( $res );
390 * @param ResultWrapper|resource $res
393 public function numFields( $res ) {
394 if ( $res instanceof ResultWrapper
) {
398 return $this->mysqlNumFields( $res );
402 * Get number of fields in result
404 * @param resource $res Raw result
407 abstract protected function mysqlNumFields( $res );
410 * @param ResultWrapper|resource $res
414 public function fieldName( $res, $n ) {
415 if ( $res instanceof ResultWrapper
) {
419 return $this->mysqlFieldName( $res, $n );
423 * Get the name of the specified field in a result
425 * @param ResultWrapper|resource $res
429 abstract protected function mysqlFieldName( $res, $n );
432 * mysql_field_type() wrapper
433 * @param ResultWrapper|resource $res
437 public function fieldType( $res, $n ) {
438 if ( $res instanceof ResultWrapper
) {
442 return $this->mysqlFieldType( $res, $n );
446 * Get the type of the specified field in a result
448 * @param ResultWrapper|resource $res
452 abstract protected function mysqlFieldType( $res, $n );
455 * @param ResultWrapper|resource $res
459 public function dataSeek( $res, $row ) {
460 if ( $res instanceof ResultWrapper
) {
464 return $this->mysqlDataSeek( $res, $row );
468 * Move internal result pointer
470 * @param ResultWrapper|resource $res
474 abstract protected function mysqlDataSeek( $res, $row );
479 public function lastError() {
481 # Even if it's non-zero, it can still be invalid
482 Wikimedia\
suppressWarnings();
483 $error = $this->mysqlError( $this->conn
);
485 $error = $this->mysqlError();
487 Wikimedia\restoreWarnings
();
489 $error = $this->mysqlError();
492 $error .= ' (' . $this->server
. ')';
499 * Returns the text of the error message from previous MySQL operation
501 * @param resource|null $conn Raw connection
504 abstract protected function mysqlError( $conn = null );
506 protected function wasQueryTimeout( $error, $errno ) {
507 return $errno == 2062;
511 * @param string $table
512 * @param array $uniqueIndexes
514 * @param string $fname
515 * @return ResultWrapper
517 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
518 return $this->nativeReplace( $table, $rows, $fname );
521 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
522 $row = $this->getReplicationSafetyInfo();
523 // For row-based-replication, the resulting changes will be relayed, not the query
524 if ( $row->binlog_format
=== 'ROW' ) {
527 // LIMIT requires ORDER BY on a unique key or it is non-deterministic
528 if ( isset( $selectOptions['LIMIT'] ) ) {
531 // In MySQL, an INSERT SELECT is only replication safe with row-based
532 // replication or if innodb_autoinc_lock_mode is 0. When those
533 // conditions aren't met, use non-native mode.
534 // While we could try to determine if the insert is safe anyway by
535 // checking if the target table has an auto-increment column that
536 // isn't set in $varMap, that seems unlikely to be worth the extra
539 in_array( 'NO_AUTO_COLUMNS', $insertOptions ) ||
540 (int)$row->innodb_autoinc_lock_mode
=== 0
545 * @return stdClass Process cached row
547 protected function getReplicationSafetyInfo() {
548 if ( $this->replicationInfoRow
=== null ) {
549 $this->replicationInfoRow
= $this->selectRow(
552 'innodb_autoinc_lock_mode' => '@@innodb_autoinc_lock_mode',
553 'binlog_format' => '@@binlog_format',
560 return $this->replicationInfoRow
;
564 * Estimate rows in dataset
565 * Returns estimated count, based on EXPLAIN output
566 * Takes same arguments as Database::select()
568 * @param string|array $table
569 * @param string|array $var
570 * @param string|array $conds
571 * @param string $fname
572 * @param string|array $options
573 * @param array $join_conds
576 public function estimateRowCount( $table, $var = '*', $conds = '',
577 $fname = __METHOD__
, $options = [], $join_conds = []
579 $conds = $this->normalizeConditions( $conds, $fname );
580 $column = $this->extractSingleFieldFromList( $var );
581 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
582 $conds[] = "$column IS NOT NULL";
585 $options['EXPLAIN'] = true;
586 $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
587 if ( $res === false ) {
590 if ( !$this->numRows( $res ) ) {
595 foreach ( $res as $plan ) {
596 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
602 public function tableExists( $table, $fname = __METHOD__
) {
603 // Split database and table into proper variables as Database::tableName() returns
604 // shared tables prefixed with their database, which do not work in SHOW TABLES statements
605 list( $database, , $prefix, $table ) = $this->qualifiedTableComponents( $table );
606 $tableName = "{$prefix}{$table}";
608 if ( isset( $this->sessionTempTables
[$tableName] ) ) {
609 return true; // already known to exist and won't show in SHOW TABLES anyway
612 // We can't use buildLike() here, because it specifies an escape character
613 // other than the backslash, which is the only one supported by SHOW TABLES
614 $encLike = $this->escapeLikeInternal( $tableName, '\\' );
616 // If the database has been specified (such as for shared tables), use "FROM"
617 if ( $database !== '' ) {
618 $encDatabase = $this->addIdentifierQuotes( $database );
619 $query = "SHOW TABLES FROM $encDatabase LIKE '$encLike'";
621 $query = "SHOW TABLES LIKE '$encLike'";
624 return $this->query( $query, $fname )->numRows() > 0;
628 * @param string $table
629 * @param string $field
630 * @return bool|MySQLField
632 public function fieldInfo( $table, $field ) {
633 $table = $this->tableName( $table );
634 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
638 $n = $this->mysqlNumFields( $res->result
);
639 for ( $i = 0; $i < $n; $i++
) {
640 $meta = $this->mysqlFetchField( $res->result
, $i );
641 if ( $field == $meta->name
) {
642 return new MySQLField( $meta );
650 * Get column information from a result
652 * @param resource $res Raw result
656 abstract protected function mysqlFetchField( $res, $n );
659 * Get information about an index into an object
660 * Returns false if the index does not exist
662 * @param string $table
663 * @param string $index
664 * @param string $fname
665 * @return bool|array|null False or null on failure
667 public function indexInfo( $table, $index, $fname = __METHOD__
) {
668 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
669 # SHOW INDEX should work for 3.x and up:
670 # https://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
671 $table = $this->tableName( $table );
672 $index = $this->indexName( $index );
674 $sql = 'SHOW INDEX FROM ' . $table;
675 $res = $this->query( $sql, $fname );
683 foreach ( $res as $row ) {
684 if ( $row->Key_name
== $index ) {
689 return $result ?
: false;
696 public function strencode( $s ) {
697 return $this->mysqlRealEscapeString( $s );
704 abstract protected function mysqlRealEscapeString( $s );
706 public function addQuotes( $s ) {
707 if ( is_bool( $s ) ) {
708 // Parent would transform to int, which does not play nice with MySQL type juggling.
709 // When searching for an int in a string column, the strings are cast to int, which
710 // means false would match any string not starting with a number.
711 $s = (string)(int)$s;
713 return parent
::addQuotes( $s );
717 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
722 public function addIdentifierQuotes( $s ) {
723 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
724 // Remove NUL bytes and escape backticks by doubling
725 return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
729 * @param string $name
732 public function isQuotedIdentifier( $name ) {
733 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
736 public function getLag() {
737 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
738 return $this->getLagFromPtHeartbeat();
740 return $this->getLagFromSlaveStatus();
747 protected function getLagDetectionMethod() {
748 return $this->lagDetectionMethod
;
754 protected function getLagFromSlaveStatus() {
755 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
756 $row = $res ?
$res->fetchObject() : false;
757 // If the server is not replicating, there will be no row
758 if ( $row && strval( $row->Seconds_Behind_Master
) !== '' ) {
759 return intval( $row->Seconds_Behind_Master
);
768 protected function getLagFromPtHeartbeat() {
769 $options = $this->lagDetectionOptions
;
771 $currentTrxInfo = $this->getRecordedTransactionLagStatus();
772 if ( $currentTrxInfo ) {
773 // There is an active transaction and the initial lag was already queried
774 $staleness = microtime( true ) - $currentTrxInfo['since'];
775 if ( $staleness > self
::LAG_STALE_WARN_THRESHOLD
) {
776 // Avoid returning higher and higher lag value due to snapshot age
777 // given that the isolation level will typically be REPEATABLE-READ
778 $this->queryLogger
->warning(
779 "Using cached lag value for {db_server} due to active transaction",
780 $this->getLogContext( [ 'method' => __METHOD__
, 'age' => $staleness ] )
784 return $currentTrxInfo['lag'];
787 if ( isset( $options['conds'] ) ) {
788 // Best method for multi-DC setups: use logical channel names
789 $data = $this->getHeartbeatData( $options['conds'] );
791 // Standard method: use master server ID (works with stock pt-heartbeat)
792 $masterInfo = $this->getMasterServerInfo();
793 if ( !$masterInfo ) {
794 $this->queryLogger
->error(
795 "Unable to query master of {db_server} for server ID",
796 $this->getLogContext( [
797 'method' => __METHOD__
801 return false; // could not get master server ID
804 $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
805 $data = $this->getHeartbeatData( $conds );
808 list( $time, $nowUnix ) = $data;
809 if ( $time !== null ) {
810 // @time is in ISO format like "2015-09-25T16:48:10.000510"
811 $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
812 $timeUnix = (int)$dateTime->format( 'U' ) +
$dateTime->format( 'u' ) / 1e6
;
814 return max( $nowUnix - $timeUnix, 0.0 );
817 $this->queryLogger
->error(
818 "Unable to find pt-heartbeat row for {db_server}",
819 $this->getLogContext( [
820 'method' => __METHOD__
827 protected function getMasterServerInfo() {
828 $cache = $this->srvCache
;
829 $key = $cache->makeGlobalKey(
832 // Using one key for all cluster replica DBs is preferable
833 $this->getLBInfo( 'clusterMasterHost' ) ?
: $this->getServer()
836 return $cache->getWithSetCallback(
838 $cache::TTL_INDEFINITE
,
839 function () use ( $cache, $key ) {
840 // Get and leave a lock key in place for a short period
841 if ( !$cache->lock( $key, 0, 10 ) ) {
842 return false; // avoid master connection spike slams
845 $conn = $this->getLazyMasterHandle();
847 return false; // something is misconfigured
850 // Connect to and query the master; catch errors to avoid outages
852 $res = $conn->query( 'SELECT @@server_id AS id', __METHOD__
);
853 $row = $res ?
$res->fetchObject() : false;
854 $id = $row ?
(int)$row->id
: 0;
855 } catch ( DBError
$e ) {
859 // Cache the ID if it was retrieved
860 return $id ?
[ 'serverId' => $id, 'asOf' => time() ] : false;
866 * @param array $conds WHERE clause conditions to find a row
867 * @return array (heartbeat `ts` column value or null, UNIX timestamp) for the newest beat
868 * @see https://www.percona.com/doc/percona-toolkit/2.1/pt-heartbeat.html
870 protected function getHeartbeatData( array $conds ) {
871 // Query time and trip time are not counted
872 $nowUnix = microtime( true );
873 // Do not bother starting implicit transactions here
874 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
876 $whereSQL = $this->makeList( $conds, self
::LIST_AND
);
877 // Use ORDER BY for channel based queries since that field might not be UNIQUE.
878 // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
879 // percision field is not supported in MySQL <= 5.5.
881 "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1",
884 $row = $res ?
$res->fetchObject() : false;
886 $this->restoreFlags();
889 return [ $row ?
$row->ts
: null, $nowUnix ];
892 protected function getApproximateLagStatus() {
893 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
894 // Disable caching since this is fast enough and we don't wan't
895 // to be *too* pessimistic by having both the cache TTL and the
896 // pt-heartbeat interval count as lag in getSessionLagStatus()
897 return parent
::getApproximateLagStatus();
900 $key = $this->srvCache
->makeGlobalKey( 'mysql-lag', $this->getServer() );
901 $approxLag = $this->srvCache
->get( $key );
903 $approxLag = parent
::getApproximateLagStatus();
904 $this->srvCache
->set( $key, $approxLag, 1 );
910 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
911 if ( !( $pos instanceof MySQLMasterPos
) ) {
912 throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
915 if ( $this->getLBInfo( 'is static' ) === true ) {
916 return 0; // this is a copy of a read-only dataset with no master DB
917 } elseif ( $this->lastKnownReplicaPos
&& $this->lastKnownReplicaPos
->hasReached( $pos ) ) {
918 return 0; // already reached this point for sure
921 // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
922 if ( $pos->getGTIDs() ) {
923 // Ignore GTIDs from domains exclusive to the master DB (presumably inactive)
924 $rpos = $this->getReplicaPos();
925 $gtidsWait = $rpos ? MySQLMasterPos
::getCommonDomainGTIDs( $pos, $rpos ) : [];
927 $this->queryLogger
->error(
928 "No GTIDs with the same domain between master ($pos) and replica ($rpos)",
929 $this->getLogContext( [
930 'method' => __METHOD__
,
934 return -1; // $pos is from the wrong cluster?
936 // Wait on the GTID set (MariaDB only)
937 $gtidArg = $this->addQuotes( implode( ',', $gtidsWait ) );
938 if ( strpos( $gtidArg, ':' ) !== false ) {
939 // MySQL GTIDs, e.g "source_id:transaction_id"
940 $res = $this->doQuery( "SELECT WAIT_FOR_EXECUTED_GTID_SET($gtidArg, $timeout)" );
942 // MariaDB GTIDs, e.g."domain:server:sequence"
943 $res = $this->doQuery( "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)" );
946 // Wait on the binlog coordinates
947 $encFile = $this->addQuotes( $pos->getLogFile() );
948 $encPos = intval( $pos->getLogPosition()[$pos::CORD_EVENT
] );
949 $res = $this->doQuery( "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)" );
952 $row = $res ?
$this->fetchRow( $res ) : false;
954 throw new DBExpectedError( $this, "Replication wait failed: {$this->lastError()}" );
957 // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
958 $status = ( $row[0] !== null ) ?
intval( $row[0] ) : null;
959 if ( $status === null ) {
960 if ( !$pos->getGTIDs() ) {
961 // T126436: jobs programmed to wait on master positions might be referencing
962 // binlogs with an old master hostname; this makes MASTER_POS_WAIT() return null.
963 // Try to detect this case and treat the replica DB as having reached the given
964 // position (any master switchover already requires that the new master be caught
965 // up before the switch).
966 $replicationPos = $this->getReplicaPos();
967 if ( $replicationPos && !$replicationPos->channelsMatch( $pos ) ) {
968 $this->lastKnownReplicaPos
= $replicationPos;
972 } elseif ( $status >= 0 ) {
973 // Remember that this position was reached to save queries next time
974 $this->lastKnownReplicaPos
= $pos;
981 * Get the position of the master from SHOW SLAVE STATUS
983 * @return MySQLMasterPos|bool
985 public function getReplicaPos() {
986 $now = microtime( true ); // as-of-time *before* fetching GTID variables
988 if ( $this->useGTIDs() ) {
989 // Try to use GTIDs, fallbacking to binlog positions if not possible
990 $data = $this->getServerGTIDs( __METHOD__
);
991 // Use gtid_slave_pos for MariaDB and gtid_executed for MySQL
992 foreach ( [ 'gtid_slave_pos', 'gtid_executed' ] as $name ) {
993 if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
994 return new MySQLMasterPos( $data[$name], $now );
999 $data = $this->getServerRoleStatus( 'SLAVE', __METHOD__
);
1000 if ( $data && strlen( $data['Relay_Master_Log_File'] ) ) {
1001 return new MySQLMasterPos(
1002 "{$data['Relay_Master_Log_File']}/{$data['Exec_Master_Log_Pos']}",
1011 * Get the position of the master from SHOW MASTER STATUS
1013 * @return MySQLMasterPos|bool
1015 public function getMasterPos() {
1016 $now = microtime( true ); // as-of-time *before* fetching GTID variables
1019 if ( $this->useGTIDs() ) {
1020 // Try to use GTIDs, fallbacking to binlog positions if not possible
1021 $data = $this->getServerGTIDs( __METHOD__
);
1022 // Use gtid_binlog_pos for MariaDB and gtid_executed for MySQL
1023 foreach ( [ 'gtid_binlog_pos', 'gtid_executed' ] as $name ) {
1024 if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
1025 $pos = new MySQLMasterPos( $data[$name], $now );
1029 // Filter domains that are inactive or not relevant to the session
1031 $pos->setActiveOriginServerId( $this->getServerId() );
1032 $pos->setActiveOriginServerUUID( $this->getServerUUID() );
1033 if ( isset( $data['gtid_domain_id'] ) ) {
1034 $pos->setActiveDomain( $data['gtid_domain_id'] );
1040 $data = $this->getServerRoleStatus( 'MASTER', __METHOD__
);
1041 if ( $data && strlen( $data['File'] ) ) {
1042 $pos = new MySQLMasterPos( "{$data['File']}/{$data['Position']}", $now );
1051 * @throws DBQueryError If the variable doesn't exist for some reason
1053 protected function getServerId() {
1054 return $this->srvCache
->getWithSetCallback(
1055 $this->srvCache
->makeGlobalKey( 'mysql-server-id', $this->getServer() ),
1056 self
::SERVER_ID_CACHE_TTL
,
1058 $res = $this->query( "SELECT @@server_id AS id", __METHOD__
);
1059 return intval( $this->fetchObject( $res )->id
);
1065 * @return string|null
1067 protected function getServerUUID() {
1068 return $this->srvCache
->getWithSetCallback(
1069 $this->srvCache
->makeGlobalKey( 'mysql-server-uuid', $this->getServer() ),
1070 self
::SERVER_ID_CACHE_TTL
,
1072 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'server_uuid'" );
1073 $row = $this->fetchObject( $res );
1075 return $row ?
$row->Value
: null;
1081 * @param string $fname
1084 protected function getServerGTIDs( $fname = __METHOD__
) {
1086 // Get global-only variables like gtid_executed
1087 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_%'", $fname );
1088 foreach ( $res as $row ) {
1089 $map[$row->Variable_name
] = $row->Value
;
1091 // Get session-specific (e.g. gtid_domain_id since that is were writes will log)
1092 $res = $this->query( "SHOW SESSION VARIABLES LIKE 'gtid_%'", $fname );
1093 foreach ( $res as $row ) {
1094 $map[$row->Variable_name
] = $row->Value
;
1101 * @param string $role One of "MASTER"/"SLAVE"
1102 * @param string $fname
1103 * @return string[] Latest available server status row
1105 protected function getServerRoleStatus( $role, $fname = __METHOD__
) {
1106 return $this->query( "SHOW $role STATUS", $fname )->fetchRow() ?
: [];
1109 public function serverIsReadOnly() {
1110 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'read_only'", __METHOD__
);
1111 $row = $this->fetchObject( $res );
1113 return $row ?
( strtolower( $row->Value
) === 'on' ) : false;
1117 * @param string $index
1120 function useIndexClause( $index ) {
1121 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
1125 * @param string $index
1128 function ignoreIndexClause( $index ) {
1129 return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
1135 function lowPriorityOption() {
1136 return 'LOW_PRIORITY';
1142 public function getSoftwareLink() {
1143 // MariaDB includes its name in its version string; this is how MariaDB's version of
1144 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
1145 // in libmysql/libmysql.c).
1146 $version = $this->getServerVersion();
1147 if ( strpos( $version, 'MariaDB' ) !== false ||
strpos( $version, '-maria-' ) !== false ) {
1148 return '[{{int:version-db-mariadb-url}} MariaDB]';
1151 // Percona Server's version suffix is not very distinctive, and @@version_comment
1152 // doesn't give the necessary info for source builds, so assume the server is MySQL.
1153 // (Even Percona's version of mysql doesn't try to make the distinction.)
1154 return '[{{int:version-db-mysql-url}} MySQL]';
1160 public function getServerVersion() {
1161 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
1162 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
1163 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
1164 if ( $this->serverVersion
=== null ) {
1165 $this->serverVersion
= $this->selectField( '', 'VERSION()', '', __METHOD__
);
1167 return $this->serverVersion
;
1171 * @param array $options
1173 public function setSessionOptions( array $options ) {
1174 if ( isset( $options['connTimeout'] ) ) {
1175 $timeout = (int)$options['connTimeout'];
1176 $this->query( "SET net_read_timeout=$timeout" );
1177 $this->query( "SET net_write_timeout=$timeout" );
1182 * @param string &$sql
1183 * @param string &$newLine
1186 public function streamStatementEnd( &$sql, &$newLine ) {
1187 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
1188 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
1189 $this->delimiter
= $m[1];
1193 return parent
::streamStatementEnd( $sql, $newLine );
1197 * Check to see if a named lock is available. This is non-blocking.
1199 * @param string $lockName Name of lock to poll
1200 * @param string $method Name of method calling us
1204 public function lockIsFree( $lockName, $method ) {
1205 if ( !parent
::lockIsFree( $lockName, $method ) ) {
1206 return false; // already held
1209 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1210 $result = $this->query( "SELECT IS_FREE_LOCK($encName) AS lockstatus", $method );
1211 $row = $this->fetchObject( $result );
1213 return ( $row->lockstatus
== 1 );
1217 * @param string $lockName
1218 * @param string $method
1219 * @param int $timeout
1222 public function lock( $lockName, $method, $timeout = 5 ) {
1223 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1224 $result = $this->query( "SELECT GET_LOCK($encName, $timeout) AS lockstatus", $method );
1225 $row = $this->fetchObject( $result );
1227 if ( $row->lockstatus
== 1 ) {
1228 parent
::lock( $lockName, $method, $timeout ); // record
1232 $this->queryLogger
->info( __METHOD__
. " failed to acquire lock '{lockname}'",
1233 [ 'lockname' => $lockName ] );
1240 * https://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
1241 * @param string $lockName
1242 * @param string $method
1245 public function unlock( $lockName, $method ) {
1246 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1247 $result = $this->query( "SELECT RELEASE_LOCK($encName) as lockstatus", $method );
1248 $row = $this->fetchObject( $result );
1250 if ( $row->lockstatus
== 1 ) {
1251 parent
::unlock( $lockName, $method ); // record
1255 $this->queryLogger
->warning( __METHOD__
. " failed to release lock '$lockName'\n" );
1260 private function makeLockName( $lockName ) {
1261 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1262 // Newer version enforce a 64 char length limit.
1263 return ( strlen( $lockName ) > 64 ) ?
sha1( $lockName ) : $lockName;
1266 public function namedLocksEnqueue() {
1270 public function tableLocksHaveTransactionScope() {
1271 return false; // tied to TCP connection
1274 protected function doLockTables( array $read, array $write, $method ) {
1276 foreach ( $write as $table ) {
1277 $items[] = $this->tableName( $table ) . ' WRITE';
1279 foreach ( $read as $table ) {
1280 $items[] = $this->tableName( $table ) . ' READ';
1283 $sql = "LOCK TABLES " . implode( ',', $items );
1284 $this->query( $sql, $method );
1289 protected function doUnlockTables( $method ) {
1290 $this->query( "UNLOCK TABLES", $method );
1296 * @param bool $value
1298 public function setBigSelects( $value = true ) {
1299 if ( $value === 'default' ) {
1300 if ( $this->defaultBigSelects
=== null ) {
1301 # Function hasn't been called before so it must already be set to the default
1304 $value = $this->defaultBigSelects
;
1306 } elseif ( $this->defaultBigSelects
=== null ) {
1307 $this->defaultBigSelects
=
1308 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__
);
1310 $encValue = $value ?
'1' : '0';
1311 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
1315 * DELETE where the condition is a join. MySql uses multi-table deletes.
1316 * @param string $delTable
1317 * @param string $joinTable
1318 * @param string $delVar
1319 * @param string $joinVar
1320 * @param array|string $conds
1321 * @param bool|string $fname
1322 * @throws DBUnexpectedError
1323 * @return bool|ResultWrapper
1325 public function deleteJoin(
1326 $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
1329 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
1332 $delTable = $this->tableName( $delTable );
1333 $joinTable = $this->tableName( $joinTable );
1334 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1336 if ( $conds != '*' ) {
1337 $sql .= ' AND ' . $this->makeList( $conds, self
::LIST_AND
);
1340 return $this->query( $sql, $fname );
1344 * @param string $table
1345 * @param array $rows
1346 * @param array $uniqueIndexes
1348 * @param string $fname
1351 public function upsert( $table, array $rows, array $uniqueIndexes,
1352 array $set, $fname = __METHOD__
1354 if ( !count( $rows ) ) {
1355 return true; // nothing to do
1358 if ( !is_array( reset( $rows ) ) ) {
1362 $table = $this->tableName( $table );
1363 $columns = array_keys( $rows[0] );
1365 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1367 foreach ( $rows as $row ) {
1368 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1370 $sql .= implode( ',', $rowTuples );
1371 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, self
::LIST_SET
);
1373 return (bool)$this->query( $sql, $fname );
1377 * Determines how long the server has been up
1381 public function getServerUptime() {
1382 $vars = $this->getMysqlStatus( 'Uptime' );
1384 return (int)$vars['Uptime'];
1388 * Determines if the last failure was due to a deadlock
1392 public function wasDeadlock() {
1393 return $this->lastErrno() == 1213;
1397 * Determines if the last failure was due to a lock timeout
1401 public function wasLockTimeout() {
1402 return $this->lastErrno() == 1205;
1406 * Determines if the last failure was due to the database being read-only.
1410 public function wasReadOnlyError() {
1411 return $this->lastErrno() == 1223 ||
1412 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1415 public function wasConnectionError( $errno ) {
1416 return $errno == 2013 ||
$errno == 2006;
1419 protected function wasKnownStatementRollbackError() {
1420 $errno = $this->lastErrno();
1422 if ( $errno === 1205 ) { // lock wait timeout
1423 // Note that this is uncached to avoid stale values of SET is used
1424 $row = $this->selectRow(
1426 [ 'innodb_rollback_on_timeout' => '@@innodb_rollback_on_timeout' ],
1430 // https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
1431 // https://dev.mysql.com/doc/refman/5.5/en/innodb-parameters.html
1432 return $row->innodb_rollback_on_timeout ?
false : true;
1435 // See https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1436 return in_array( $errno, [ 1022, 1216, 1217, 1137 ], true );
1440 * @param string $oldName
1441 * @param string $newName
1442 * @param bool $temporary
1443 * @param string $fname
1446 public function duplicateTableStructure(
1447 $oldName, $newName, $temporary = false, $fname = __METHOD__
1449 $tmp = $temporary ?
'TEMPORARY ' : '';
1450 $newName = $this->addIdentifierQuotes( $newName );
1451 $oldName = $this->addIdentifierQuotes( $oldName );
1452 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1454 return $this->query( $query, $fname );
1458 * List all tables on the database
1460 * @param string|null $prefix Only show tables with this prefix, e.g. mw_
1461 * @param string $fname Calling function name
1464 public function listTables( $prefix = null, $fname = __METHOD__
) {
1465 $result = $this->query( "SHOW TABLES", $fname );
1469 foreach ( $result as $table ) {
1470 $vars = get_object_vars( $table );
1471 $table = array_pop( $vars );
1473 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1474 $endArray[] = $table;
1482 * @param string $tableName
1483 * @param string $fName
1484 * @return bool|ResultWrapper
1486 public function dropTable( $tableName, $fName = __METHOD__
) {
1487 if ( !$this->tableExists( $tableName, $fName ) ) {
1491 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1495 * Get status information from SHOW STATUS in an associative array
1497 * @param string $which
1500 private function getMysqlStatus( $which = "%" ) {
1501 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1504 foreach ( $res as $row ) {
1505 $status[$row->Variable_name
] = $row->Value
;
1512 * Lists VIEWs in the database
1514 * @param string|null $prefix Only show VIEWs with this prefix, eg.
1515 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1516 * @param string $fname Name of calling function
1520 public function listViews( $prefix = null, $fname = __METHOD__
) {
1521 // The name of the column containing the name of the VIEW
1522 $propertyName = 'Tables_in_' . $this->dbName
;
1524 // Query for the VIEWS
1525 $res = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1527 foreach ( $res as $row ) {
1528 array_push( $allViews, $row->$propertyName );
1531 if ( is_null( $prefix ) ||
$prefix === '' ) {
1535 $filteredViews = [];
1536 foreach ( $allViews as $viewName ) {
1537 // Does the name of this VIEW start with the table-prefix?
1538 if ( strpos( $viewName, $prefix ) === 0 ) {
1539 array_push( $filteredViews, $viewName );
1543 return $filteredViews;
1547 * Differentiates between a TABLE and a VIEW.
1549 * @param string $name Name of the TABLE/VIEW to test
1550 * @param string|null $prefix
1554 public function isView( $name, $prefix = null ) {
1555 return in_array( $name, $this->listViews( $prefix ) );
1558 protected function isTransactableQuery( $sql ) {
1559 return parent
::isTransactableQuery( $sql ) &&
1560 !preg_match( '/^SELECT\s+(GET|RELEASE|IS_FREE)_LOCK\(/', $sql );
1564 * @param string $field Field or column to cast
1567 public function buildIntegerCast( $field ) {
1568 return 'CAST( ' . $field . ' AS SIGNED )';
1572 * @return bool Whether GTID support is used (mockable for testing)
1574 protected function useGTIDs() {
1575 return $this->useGTIDs
;
1580 * @deprecated since 1.29
1582 class_alias( DatabaseMysqlBase
::class, 'DatabaseMysqlBase' );