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
;
34 * Database abstraction object for MySQL.
35 * Defines methods independent on used MySQL extension.
41 abstract class DatabaseMysqlBase
extends Database
{
42 /** @var MysqlMasterPos */
43 protected $lastKnownReplicaPos;
44 /** @var string Method to detect replica DB lag */
45 protected $lagDetectionMethod;
46 /** @var array Method to detect replica DB lag */
47 protected $lagDetectionOptions = [];
48 /** @var bool bool Whether to use GTID methods */
49 protected $useGTIDs = false;
50 /** @var string|null */
51 protected $sslKeyPath;
52 /** @var string|null */
53 protected $sslCertPath;
54 /** @var string|null */
56 /** @var string|null */
58 /** @var string[]|null */
59 protected $sslCiphers;
60 /** @var string sql_mode value to send on connection */
62 /** @var bool Use experimental UTF-8 transmission encoding */
65 protected $defaultBigSelects = null;
67 /** @var string|null */
68 private $serverVersion = null;
70 private $insertSelectIsSafe = null;
71 /** @var stdClass|null */
72 private $replicationInfoRow = null;
74 // Cache getServerId() for 24 hours
75 const SERVER_ID_CACHE_TTL
= 86400;
77 /** @var float Warn if lag estimates are made for transactions older than this many seconds */
78 const LAG_STALE_WARN_THRESHOLD
= 0.100;
81 * Additional $params include:
82 * - lagDetectionMethod : set to one of (Seconds_Behind_Master,pt-heartbeat).
83 * pt-heartbeat assumes the table is at heartbeat.heartbeat
84 * and uses UTC timestamps in the heartbeat.ts column.
85 * (https://www.percona.com/doc/percona-toolkit/2.2/pt-heartbeat.html)
86 * - lagDetectionOptions : if using pt-heartbeat, this can be set to an array map to change
87 * the default behavior. Normally, the heartbeat row with the server
88 * ID of this server's master will be used. Set the "conds" field to
89 * override the query conditions, e.g. ['shard' => 's1'].
90 * - useGTIDs : use GTID methods like MASTER_GTID_WAIT() when possible.
91 * - insertSelectIsSafe : force that native INSERT SELECT is or is not safe [default: null]
92 * - sslKeyPath : path to key file [default: null]
93 * - sslCertPath : path to certificate file [default: null]
94 * - sslCAFile: path to a single certificate authority PEM file [default: null]
95 * - sslCAPath : parth to certificate authority PEM directory [default: null]
96 * - sslCiphers : array list of allowable ciphers [default: null]
97 * @param array $params
99 public function __construct( array $params ) {
100 $this->lagDetectionMethod
= $params['lagDetectionMethod'] ??
'Seconds_Behind_Master';
101 $this->lagDetectionOptions
= $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
= $params['sqlMode'] ??
null;
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() {
124 protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix ) {
127 if ( $schema !== null ) {
128 throw new DBExpectedError( $this, __CLASS__
. ": cannot use schemas ('$schema')" );
131 $this->server
= $server;
133 $this->password
= $password;
135 $this->installErrorHandler();
137 $this->conn
= $this->mysqlConnect( $this->server
, $dbName );
138 } catch ( Exception
$ex ) {
139 $this->restoreErrorHandler();
142 $error = $this->restoreErrorHandler();
144 # Always log connection errors
145 if ( !$this->conn
) {
146 $error = $error ?
: $this->lastError();
147 $this->connLogger
->error(
148 "Error connecting to {db_server}: {error}",
149 $this->getLogContext( [ 'method' => __METHOD__
, 'error' => $error ] )
151 $this->connLogger
->debug( "DB connection error\n" .
152 "Server: $server, User: $user, Password: " .
153 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
154 throw new DBConnectionError( $this, $error );
158 $this->currentDomain
= new DatabaseDomain(
159 strlen( $dbName ) ?
$dbName : null,
164 // Abstract over any insane MySQL defaults
165 $set = [ 'group_concat_max_len = 262144' ];
166 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
167 if ( is_string( $this->sqlMode
) ) {
168 $set[] = 'sql_mode = ' . $this->addQuotes( $this->sqlMode
);
170 // Set any custom settings defined by site config
171 // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
172 foreach ( $this->connectionVariables
as $var => $val ) {
173 // Escape strings but not numbers to avoid MySQL complaining
174 if ( !is_int( $val ) && !is_float( $val ) ) {
175 $val = $this->addQuotes( $val );
177 $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
182 'SET ' . implode( ', ', $set ),
184 self
::QUERY_IGNORE_DBO_TRX | self
::QUERY_NO_RETRY
187 } catch ( Exception
$e ) {
188 // Connection was not fully initialized and is not safe for use
195 protected function doSelectDomain( DatabaseDomain
$domain ) {
196 if ( $domain->getSchema() !== null ) {
197 throw new DBExpectedError(
199 __CLASS__
. ": domain '{$domain->getId()}' has a schema component"
203 $database = $domain->getDatabase();
204 // A null database means "don't care" so leave it as is and update the table prefix
205 if ( $database === null ) {
206 $this->currentDomain
= new DatabaseDomain(
207 $this->currentDomain
->getDatabase(),
209 $domain->getTablePrefix()
215 if ( $database !== $this->getDBname() ) {
216 $sql = 'USE ' . $this->addIdentifierQuotes( $database );
217 list( $res, $err, $errno ) =
218 $this->executeQuery( $sql, __METHOD__
, self
::QUERY_IGNORE_DBO_TRX
);
220 if ( $res === false ) {
221 $this->reportQueryError( $err, $errno, $sql, __METHOD__
);
222 return false; // unreachable
226 // Update that domain fields on success (no exception thrown)
227 $this->currentDomain
= $domain;
233 * Open a connection to a MySQL server
235 * @param string $realServer
236 * @param string|null $dbName
237 * @return mixed Raw connection
238 * @throws DBConnectionError
240 abstract protected function mysqlConnect( $realServer, $dbName );
243 * @param IResultWrapper|resource $res
244 * @throws DBUnexpectedError
246 public function freeResult( $res ) {
247 Wikimedia\
suppressWarnings();
248 $ok = $this->mysqlFreeResult( ResultWrapper
::unwrap( $res ) );
249 Wikimedia\restoreWarnings
();
251 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
258 * @param resource $res Raw result
261 abstract protected function mysqlFreeResult( $res );
264 * @param IResultWrapper|resource $res
265 * @return stdClass|bool
266 * @throws DBUnexpectedError
268 public function fetchObject( $res ) {
269 Wikimedia\
suppressWarnings();
270 $row = $this->mysqlFetchObject( ResultWrapper
::unwrap( $res ) );
271 Wikimedia\restoreWarnings
();
273 $errno = $this->lastErrno();
274 // Unfortunately, mysql_fetch_object does not reset the last errno.
275 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
276 // these are the only errors mysql_fetch_object can cause.
277 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
278 if ( $errno == 2000 ||
$errno == 2013 ) {
279 throw new DBUnexpectedError(
281 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
289 * Fetch a result row as an object
291 * @param resource $res Raw result
294 abstract protected function mysqlFetchObject( $res );
297 * @param IResultWrapper|resource $res
299 * @throws DBUnexpectedError
301 public function fetchRow( $res ) {
302 Wikimedia\
suppressWarnings();
303 $row = $this->mysqlFetchArray( ResultWrapper
::unwrap( $res ) );
304 Wikimedia\restoreWarnings
();
306 $errno = $this->lastErrno();
307 // Unfortunately, mysql_fetch_array does not reset the last errno.
308 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
309 // these are the only errors mysql_fetch_array can cause.
310 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
311 if ( $errno == 2000 ||
$errno == 2013 ) {
312 throw new DBUnexpectedError(
314 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
322 * Fetch a result row as an associative and numeric array
324 * @param resource $res Raw result
325 * @return array|false
327 abstract protected function mysqlFetchArray( $res );
330 * @throws DBUnexpectedError
331 * @param IResultWrapper|resource $res
334 function numRows( $res ) {
335 if ( is_bool( $res ) ) {
338 Wikimedia\
suppressWarnings();
339 $n = $this->mysqlNumRows( ResultWrapper
::unwrap( $res ) );
340 Wikimedia\restoreWarnings
();
343 // Unfortunately, mysql_num_rows does not reset the last errno.
344 // We are not checking for any errors here, since
345 // there are no errors mysql_num_rows can cause.
346 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
347 // See https://phabricator.wikimedia.org/T44430
352 * Get number of rows in result
354 * @param resource $res Raw result
357 abstract protected function mysqlNumRows( $res );
360 * @param IResultWrapper|resource $res
363 public function numFields( $res ) {
364 return $this->mysqlNumFields( ResultWrapper
::unwrap( $res ) );
368 * Get number of fields in result
370 * @param resource $res Raw result
373 abstract protected function mysqlNumFields( $res );
376 * @param IResultWrapper|resource $res
380 public function fieldName( $res, $n ) {
381 return $this->mysqlFieldName( ResultWrapper
::unwrap( $res ), $n );
385 * Get the name of the specified field in a result
387 * @param IResultWrapper|resource $res
391 abstract protected function mysqlFieldName( $res, $n );
394 * mysql_field_type() wrapper
395 * @param IResultWrapper|resource $res
399 public function fieldType( $res, $n ) {
400 return $this->mysqlFieldType( ResultWrapper
::unwrap( $res ), $n );
404 * Get the type of the specified field in a result
406 * @param IResultWrapper|resource $res
410 abstract protected function mysqlFieldType( $res, $n );
413 * @param IResultWrapper|resource $res
417 public function dataSeek( $res, $row ) {
418 return $this->mysqlDataSeek( ResultWrapper
::unwrap( $res ), $row );
422 * Move internal result pointer
424 * @param IResultWrapper|resource $res
428 abstract protected function mysqlDataSeek( $res, $row );
433 public function lastError() {
435 # Even if it's non-zero, it can still be invalid
436 Wikimedia\
suppressWarnings();
437 $error = $this->mysqlError( $this->conn
);
439 $error = $this->mysqlError();
441 Wikimedia\restoreWarnings
();
443 $error = $this->mysqlError();
446 $error .= ' (' . $this->server
. ')';
453 * Returns the text of the error message from previous MySQL operation
455 * @param resource|null $conn Raw connection
458 abstract protected function mysqlError( $conn = null );
460 protected function wasQueryTimeout( $error, $errno ) {
461 // https://dev.mysql.com/doc/refman/8.0/en/client-error-reference.html
462 // https://phabricator.wikimedia.org/T170638
463 return in_array( $errno, [ 2062, 3024 ] );
466 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
467 $this->nativeReplace( $table, $rows, $fname );
470 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
471 $row = $this->getReplicationSafetyInfo();
472 // For row-based-replication, the resulting changes will be relayed, not the query
473 if ( $row->binlog_format
=== 'ROW' ) {
476 // LIMIT requires ORDER BY on a unique key or it is non-deterministic
477 if ( isset( $selectOptions['LIMIT'] ) ) {
480 // In MySQL, an INSERT SELECT is only replication safe with row-based
481 // replication or if innodb_autoinc_lock_mode is 0. When those
482 // conditions aren't met, use non-native mode.
483 // While we could try to determine if the insert is safe anyway by
484 // checking if the target table has an auto-increment column that
485 // isn't set in $varMap, that seems unlikely to be worth the extra
488 in_array( 'NO_AUTO_COLUMNS', $insertOptions ) ||
489 (int)$row->innodb_autoinc_lock_mode
=== 0
494 * @return stdClass Process cached row
496 protected function getReplicationSafetyInfo() {
497 if ( $this->replicationInfoRow
=== null ) {
498 $this->replicationInfoRow
= $this->selectRow(
501 'innodb_autoinc_lock_mode' => '@@innodb_autoinc_lock_mode',
502 'binlog_format' => '@@binlog_format',
509 return $this->replicationInfoRow
;
513 * Estimate rows in dataset
514 * Returns estimated count, based on EXPLAIN output
515 * Takes same arguments as Database::select()
517 * @param string|array $table
518 * @param string|array $var
519 * @param string|array $conds
520 * @param string $fname
521 * @param string|array $options
522 * @param array $join_conds
525 public function estimateRowCount( $table, $var = '*', $conds = '',
526 $fname = __METHOD__
, $options = [], $join_conds = []
528 $conds = $this->normalizeConditions( $conds, $fname );
529 $column = $this->extractSingleFieldFromList( $var );
530 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
531 $conds[] = "$column IS NOT NULL";
534 $options['EXPLAIN'] = true;
535 $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
536 if ( $res === false ) {
539 if ( !$this->numRows( $res ) ) {
544 foreach ( $res as $plan ) {
545 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
551 public function tableExists( $table, $fname = __METHOD__
) {
552 // Split database and table into proper variables as Database::tableName() returns
553 // shared tables prefixed with their database, which do not work in SHOW TABLES statements
554 list( $database, , $prefix, $table ) = $this->qualifiedTableComponents( $table );
555 $tableName = "{$prefix}{$table}";
557 if ( isset( $this->sessionTempTables
[$tableName] ) ) {
558 return true; // already known to exist and won't show in SHOW TABLES anyway
561 // We can't use buildLike() here, because it specifies an escape character
562 // other than the backslash, which is the only one supported by SHOW TABLES
563 $encLike = $this->escapeLikeInternal( $tableName, '\\' );
565 // If the database has been specified (such as for shared tables), use "FROM"
566 if ( $database !== '' ) {
567 $encDatabase = $this->addIdentifierQuotes( $database );
568 $query = "SHOW TABLES FROM $encDatabase LIKE '$encLike'";
570 $query = "SHOW TABLES LIKE '$encLike'";
573 return $this->query( $query, $fname )->numRows() > 0;
577 * @param string $table
578 * @param string $field
579 * @return bool|MySQLField
581 public function fieldInfo( $table, $field ) {
582 $table = $this->tableName( $table );
583 $flags = self
::QUERY_SILENCE_ERRORS
;
584 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, $flags );
588 $n = $this->mysqlNumFields( ResultWrapper
::unwrap( $res ) );
589 for ( $i = 0; $i < $n; $i++
) {
590 $meta = $this->mysqlFetchField( ResultWrapper
::unwrap( $res ), $i );
591 if ( $field == $meta->name
) {
592 return new MySQLField( $meta );
600 * Get column information from a result
602 * @param resource $res Raw result
606 abstract protected function mysqlFetchField( $res, $n );
609 * Get information about an index into an object
610 * Returns false if the index does not exist
612 * @param string $table
613 * @param string $index
614 * @param string $fname
615 * @return bool|array|null False or null on failure
617 public function indexInfo( $table, $index, $fname = __METHOD__
) {
618 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
619 # SHOW INDEX should work for 3.x and up:
620 # https://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
621 $table = $this->tableName( $table );
622 $index = $this->indexName( $index );
624 $sql = 'SHOW INDEX FROM ' . $table;
625 $res = $this->query( $sql, $fname );
633 foreach ( $res as $row ) {
634 if ( $row->Key_name
== $index ) {
639 return $result ?
: false;
646 public function strencode( $s ) {
647 return $this->mysqlRealEscapeString( $s );
654 abstract protected function mysqlRealEscapeString( $s );
656 public function addQuotes( $s ) {
657 if ( is_bool( $s ) ) {
658 // Parent would transform to int, which does not play nice with MySQL type juggling.
659 // When searching for an int in a string column, the strings are cast to int, which
660 // means false would match any string not starting with a number.
661 $s = (string)(int)$s;
663 return parent
::addQuotes( $s );
667 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
672 public function addIdentifierQuotes( $s ) {
673 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
674 // Remove NUL bytes and escape backticks by doubling
675 return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
679 * @param string $name
682 public function isQuotedIdentifier( $name ) {
683 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
686 protected function doGetLag() {
687 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
688 return $this->getLagFromPtHeartbeat();
690 return $this->getLagFromSlaveStatus();
697 protected function getLagDetectionMethod() {
698 return $this->lagDetectionMethod
;
704 protected function getLagFromSlaveStatus() {
705 $flags = self
::QUERY_SILENCE_ERRORS | self
::QUERY_IGNORE_DBO_TRX
;
706 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
, $flags );
707 $row = $res ?
$res->fetchObject() : false;
708 // If the server is not replicating, there will be no row
709 if ( $row && strval( $row->Seconds_Behind_Master
) !== '' ) {
710 return intval( $row->Seconds_Behind_Master
);
719 protected function getLagFromPtHeartbeat() {
720 $options = $this->lagDetectionOptions
;
722 $currentTrxInfo = $this->getRecordedTransactionLagStatus();
723 if ( $currentTrxInfo ) {
724 // There is an active transaction and the initial lag was already queried
725 $staleness = microtime( true ) - $currentTrxInfo['since'];
726 if ( $staleness > self
::LAG_STALE_WARN_THRESHOLD
) {
727 // Avoid returning higher and higher lag value due to snapshot age
728 // given that the isolation level will typically be REPEATABLE-READ
729 $this->queryLogger
->warning(
730 "Using cached lag value for {db_server} due to active transaction",
731 $this->getLogContext( [
732 'method' => __METHOD__
,
734 'trace' => ( new RuntimeException() )->getTraceAsString()
739 return $currentTrxInfo['lag'];
742 if ( isset( $options['conds'] ) ) {
743 // Best method for multi-DC setups: use logical channel names
744 $data = $this->getHeartbeatData( $options['conds'] );
746 // Standard method: use master server ID (works with stock pt-heartbeat)
747 $masterInfo = $this->getMasterServerInfo();
748 if ( !$masterInfo ) {
749 $this->queryLogger
->error(
750 "Unable to query master of {db_server} for server ID",
751 $this->getLogContext( [
752 'method' => __METHOD__
756 return false; // could not get master server ID
759 $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
760 $data = $this->getHeartbeatData( $conds );
763 list( $time, $nowUnix ) = $data;
764 if ( $time !== null ) {
765 // @time is in ISO format like "2015-09-25T16:48:10.000510"
766 $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
767 $timeUnix = (int)$dateTime->format( 'U' ) +
$dateTime->format( 'u' ) / 1e6
;
769 return max( $nowUnix - $timeUnix, 0.0 );
772 $this->queryLogger
->error(
773 "Unable to find pt-heartbeat row for {db_server}",
774 $this->getLogContext( [
775 'method' => __METHOD__
782 protected function getMasterServerInfo() {
783 $cache = $this->srvCache
;
784 $key = $cache->makeGlobalKey(
787 // Using one key for all cluster replica DBs is preferable
788 $this->getLBInfo( 'clusterMasterHost' ) ?
: $this->getServer()
792 return $cache->getWithSetCallback(
794 $cache::TTL_INDEFINITE
,
795 function () use ( $cache, $key, $fname ) {
796 // Get and leave a lock key in place for a short period
797 if ( !$cache->lock( $key, 0, 10 ) ) {
798 return false; // avoid master connection spike slams
801 $conn = $this->getLazyMasterHandle();
803 return false; // something is misconfigured
806 // Connect to and query the master; catch errors to avoid outages
808 $flags = self
::QUERY_SILENCE_ERRORS | self
::QUERY_IGNORE_DBO_TRX
;
809 $res = $conn->query( 'SELECT @@server_id AS id', $fname, $flags );
810 $row = $res ?
$res->fetchObject() : false;
811 $id = $row ?
(int)$row->id
: 0;
812 } catch ( DBError
$e ) {
816 // Cache the ID if it was retrieved
817 return $id ?
[ 'serverId' => $id, 'asOf' => time() ] : false;
823 * @param array $conds WHERE clause conditions to find a row
824 * @return array (heartbeat `ts` column value or null, UNIX timestamp) for the newest beat
825 * @see https://www.percona.com/doc/percona-toolkit/2.1/pt-heartbeat.html
827 protected function getHeartbeatData( array $conds ) {
828 // Query time and trip time are not counted
829 $nowUnix = microtime( true );
830 // Do not bother starting implicit transactions here
831 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
833 $whereSQL = $this->makeList( $conds, self
::LIST_AND
);
834 // Use ORDER BY for channel based queries since that field might not be UNIQUE.
835 // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
836 // percision field is not supported in MySQL <= 5.5.
838 "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1",
840 self
::QUERY_SILENCE_ERRORS | self
::QUERY_IGNORE_DBO_TRX
842 $row = $res ?
$res->fetchObject() : false;
844 $this->restoreFlags();
847 return [ $row ?
$row->ts
: null, $nowUnix ];
850 protected function getApproximateLagStatus() {
851 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
852 // Disable caching since this is fast enough and we don't wan't
853 // to be *too* pessimistic by having both the cache TTL and the
854 // pt-heartbeat interval count as lag in getSessionLagStatus()
855 return parent
::getApproximateLagStatus();
858 $key = $this->srvCache
->makeGlobalKey( 'mysql-lag', $this->getServer() );
859 $approxLag = $this->srvCache
->get( $key );
861 $approxLag = parent
::getApproximateLagStatus();
862 $this->srvCache
->set( $key, $approxLag, 1 );
868 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
869 if ( !( $pos instanceof MySQLMasterPos
) ) {
870 throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
873 if ( $this->getLBInfo( 'is static' ) === true ) {
874 return 0; // this is a copy of a read-only dataset with no master DB
875 } elseif ( $this->lastKnownReplicaPos
&& $this->lastKnownReplicaPos
->hasReached( $pos ) ) {
876 return 0; // already reached this point for sure
879 // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
880 if ( $pos->getGTIDs() ) {
881 // Ignore GTIDs from domains exclusive to the master DB (presumably inactive)
882 $rpos = $this->getReplicaPos();
883 $gtidsWait = $rpos ? MySQLMasterPos
::getCommonDomainGTIDs( $pos, $rpos ) : [];
885 $this->queryLogger
->error(
886 "No GTIDs with the same domain between master ($pos) and replica ($rpos)",
887 $this->getLogContext( [
888 'method' => __METHOD__
,
892 return -1; // $pos is from the wrong cluster?
894 // Wait on the GTID set (MariaDB only)
895 $gtidArg = $this->addQuotes( implode( ',', $gtidsWait ) );
896 if ( strpos( $gtidArg, ':' ) !== false ) {
897 // MySQL GTIDs, e.g "source_id:transaction_id"
898 $sql = "SELECT WAIT_FOR_EXECUTED_GTID_SET($gtidArg, $timeout)";
900 // MariaDB GTIDs, e.g."domain:server:sequence"
901 $sql = "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)";
904 // Wait on the binlog coordinates
905 $encFile = $this->addQuotes( $pos->getLogFile() );
906 $encPos = intval( $pos->getLogPosition()[$pos::CORD_EVENT
] );
907 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
910 list( $res, $err ) = $this->executeQuery( $sql, __METHOD__
, self
::QUERY_IGNORE_DBO_TRX
);
911 $row = $res ?
$this->fetchRow( $res ) : false;
913 throw new DBExpectedError( $this, "Replication wait failed: {$err}" );
916 // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
917 $status = ( $row[0] !== null ) ?
intval( $row[0] ) : null;
918 if ( $status === null ) {
919 if ( !$pos->getGTIDs() ) {
920 // T126436: jobs programmed to wait on master positions might be referencing
921 // binlogs with an old master hostname; this makes MASTER_POS_WAIT() return null.
922 // Try to detect this case and treat the replica DB as having reached the given
923 // position (any master switchover already requires that the new master be caught
924 // up before the switch).
925 $replicationPos = $this->getReplicaPos();
926 if ( $replicationPos && !$replicationPos->channelsMatch( $pos ) ) {
927 $this->lastKnownReplicaPos
= $replicationPos;
931 } elseif ( $status >= 0 ) {
932 // Remember that this position was reached to save queries next time
933 $this->lastKnownReplicaPos
= $pos;
940 * Get the position of the master from SHOW SLAVE STATUS
942 * @return MySQLMasterPos|bool
944 public function getReplicaPos() {
945 $now = microtime( true ); // as-of-time *before* fetching GTID variables
947 if ( $this->useGTIDs() ) {
948 // Try to use GTIDs, fallbacking to binlog positions if not possible
949 $data = $this->getServerGTIDs( __METHOD__
);
950 // Use gtid_slave_pos for MariaDB and gtid_executed for MySQL
951 foreach ( [ 'gtid_slave_pos', 'gtid_executed' ] as $name ) {
952 if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
953 return new MySQLMasterPos( $data[$name], $now );
958 $data = $this->getServerRoleStatus( 'SLAVE', __METHOD__
);
959 if ( $data && strlen( $data['Relay_Master_Log_File'] ) ) {
960 return new MySQLMasterPos(
961 "{$data['Relay_Master_Log_File']}/{$data['Exec_Master_Log_Pos']}",
970 * Get the position of the master from SHOW MASTER STATUS
972 * @return MySQLMasterPos|bool
974 public function getMasterPos() {
975 $now = microtime( true ); // as-of-time *before* fetching GTID variables
978 if ( $this->useGTIDs() ) {
979 // Try to use GTIDs, fallbacking to binlog positions if not possible
980 $data = $this->getServerGTIDs( __METHOD__
);
981 // Use gtid_binlog_pos for MariaDB and gtid_executed for MySQL
982 foreach ( [ 'gtid_binlog_pos', 'gtid_executed' ] as $name ) {
983 if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
984 $pos = new MySQLMasterPos( $data[$name], $now );
988 // Filter domains that are inactive or not relevant to the session
990 $pos->setActiveOriginServerId( $this->getServerId() );
991 $pos->setActiveOriginServerUUID( $this->getServerUUID() );
992 if ( isset( $data['gtid_domain_id'] ) ) {
993 $pos->setActiveDomain( $data['gtid_domain_id'] );
999 $data = $this->getServerRoleStatus( 'MASTER', __METHOD__
);
1000 if ( $data && strlen( $data['File'] ) ) {
1001 $pos = new MySQLMasterPos( "{$data['File']}/{$data['Position']}", $now );
1010 * @throws DBQueryError If the variable doesn't exist for some reason
1012 protected function getServerId() {
1013 $fname = __METHOD__
;
1014 return $this->srvCache
->getWithSetCallback(
1015 $this->srvCache
->makeGlobalKey( 'mysql-server-id', $this->getServer() ),
1016 self
::SERVER_ID_CACHE_TTL
,
1017 function () use ( $fname ) {
1018 $flags = self
::QUERY_IGNORE_DBO_TRX
;
1019 $res = $this->query( "SELECT @@server_id AS id", $fname, $flags );
1021 return intval( $this->fetchObject( $res )->id
);
1027 * @return string|null
1029 protected function getServerUUID() {
1030 $fname = __METHOD__
;
1031 return $this->srvCache
->getWithSetCallback(
1032 $this->srvCache
->makeGlobalKey( 'mysql-server-uuid', $this->getServer() ),
1033 self
::SERVER_ID_CACHE_TTL
,
1034 function () use ( $fname ) {
1035 $flags = self
::QUERY_IGNORE_DBO_TRX
;
1036 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'server_uuid'", $fname, $flags );
1037 $row = $this->fetchObject( $res );
1039 return $row ?
$row->Value
: null;
1045 * @param string $fname
1048 protected function getServerGTIDs( $fname = __METHOD__
) {
1051 $flags = self
::QUERY_IGNORE_DBO_TRX
;
1052 // Get global-only variables like gtid_executed
1053 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_%'", $fname, $flags );
1054 foreach ( $res as $row ) {
1055 $map[$row->Variable_name
] = $row->Value
;
1057 // Get session-specific (e.g. gtid_domain_id since that is were writes will log)
1058 $res = $this->query( "SHOW SESSION VARIABLES LIKE 'gtid_%'", $fname, $flags );
1059 foreach ( $res as $row ) {
1060 $map[$row->Variable_name
] = $row->Value
;
1067 * @param string $role One of "MASTER"/"SLAVE"
1068 * @param string $fname
1069 * @return string[] Latest available server status row
1071 protected function getServerRoleStatus( $role, $fname = __METHOD__
) {
1072 $flags = self
::QUERY_IGNORE_DBO_TRX
;
1074 return $this->query( "SHOW $role STATUS", $fname, $flags )->fetchRow() ?
: [];
1077 public function serverIsReadOnly() {
1078 $flags = self
::QUERY_IGNORE_DBO_TRX
;
1079 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'read_only'", __METHOD__
, $flags );
1080 $row = $this->fetchObject( $res );
1082 return $row ?
( strtolower( $row->Value
) === 'on' ) : false;
1086 * @param string $index
1089 function useIndexClause( $index ) {
1090 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
1094 * @param string $index
1097 function ignoreIndexClause( $index ) {
1098 return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
1104 function lowPriorityOption() {
1105 return 'LOW_PRIORITY';
1111 public function getSoftwareLink() {
1112 // MariaDB includes its name in its version string; this is how MariaDB's version of
1113 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
1114 // in libmysql/libmysql.c).
1115 $version = $this->getServerVersion();
1116 if ( strpos( $version, 'MariaDB' ) !== false ||
strpos( $version, '-maria-' ) !== false ) {
1117 return '[{{int:version-db-mariadb-url}} MariaDB]';
1120 // Percona Server's version suffix is not very distinctive, and @@version_comment
1121 // doesn't give the necessary info for source builds, so assume the server is MySQL.
1122 // (Even Percona's version of mysql doesn't try to make the distinction.)
1123 return '[{{int:version-db-mysql-url}} MySQL]';
1129 public function getServerVersion() {
1130 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
1131 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
1132 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
1133 if ( $this->serverVersion
=== null ) {
1134 $this->serverVersion
= $this->selectField( '', 'VERSION()', '', __METHOD__
);
1136 return $this->serverVersion
;
1140 * @param array $options
1142 public function setSessionOptions( array $options ) {
1143 if ( isset( $options['connTimeout'] ) ) {
1144 $flags = self
::QUERY_IGNORE_DBO_TRX
;
1145 $timeout = (int)$options['connTimeout'];
1146 $this->query( "SET net_read_timeout=$timeout", __METHOD__
, $flags );
1147 $this->query( "SET net_write_timeout=$timeout", __METHOD__
, $flags );
1152 * @param string &$sql
1153 * @param string &$newLine
1156 public function streamStatementEnd( &$sql, &$newLine ) {
1157 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
1158 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
1159 $this->delimiter
= $m[1];
1163 return parent
::streamStatementEnd( $sql, $newLine );
1167 * Check to see if a named lock is available. This is non-blocking.
1169 * @param string $lockName Name of lock to poll
1170 * @param string $method Name of method calling us
1174 public function lockIsFree( $lockName, $method ) {
1175 if ( !parent
::lockIsFree( $lockName, $method ) ) {
1176 return false; // already held
1179 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1181 $flags = self
::QUERY_IGNORE_DBO_TRX
;
1182 $res = $this->query( "SELECT IS_FREE_LOCK($encName) AS lockstatus", $method, $flags );
1183 $row = $this->fetchObject( $res );
1185 return ( $row->lockstatus
== 1 );
1189 * @param string $lockName
1190 * @param string $method
1191 * @param int $timeout
1194 public function lock( $lockName, $method, $timeout = 5 ) {
1195 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1197 $flags = self
::QUERY_IGNORE_DBO_TRX
;
1198 $res = $this->query( "SELECT GET_LOCK($encName, $timeout) AS lockstatus", $method, $flags );
1199 $row = $this->fetchObject( $res );
1201 if ( $row->lockstatus
== 1 ) {
1202 parent
::lock( $lockName, $method, $timeout ); // record
1206 $this->queryLogger
->info( __METHOD__
. " failed to acquire lock '{lockname}'",
1207 [ 'lockname' => $lockName ] );
1214 * https://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
1215 * @param string $lockName
1216 * @param string $method
1219 public function unlock( $lockName, $method ) {
1220 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1222 $flags = self
::QUERY_IGNORE_DBO_TRX
;
1223 $res = $this->query( "SELECT RELEASE_LOCK($encName) as lockstatus", $method, $flags );
1224 $row = $this->fetchObject( $res );
1226 if ( $row->lockstatus
== 1 ) {
1227 parent
::unlock( $lockName, $method ); // record
1231 $this->queryLogger
->warning( __METHOD__
. " failed to release lock '$lockName'\n" );
1236 private function makeLockName( $lockName ) {
1237 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1238 // Newer version enforce a 64 char length limit.
1239 return ( strlen( $lockName ) > 64 ) ?
sha1( $lockName ) : $lockName;
1242 public function namedLocksEnqueue() {
1246 public function tableLocksHaveTransactionScope() {
1247 return false; // tied to TCP connection
1250 protected function doLockTables( array $read, array $write, $method ) {
1252 foreach ( $write as $table ) {
1253 $items[] = $this->tableName( $table ) . ' WRITE';
1255 foreach ( $read as $table ) {
1256 $items[] = $this->tableName( $table ) . ' READ';
1259 $sql = "LOCK TABLES " . implode( ',', $items );
1260 $this->query( $sql, $method, self
::QUERY_IGNORE_DBO_TRX
);
1265 protected function doUnlockTables( $method ) {
1266 $this->query( "UNLOCK TABLES", $method, self
::QUERY_IGNORE_DBO_TRX
);
1272 * @param bool $value
1274 public function setBigSelects( $value = true ) {
1275 if ( $value === 'default' ) {
1276 if ( $this->defaultBigSelects
=== null ) {
1277 # Function hasn't been called before so it must already be set to the default
1280 $value = $this->defaultBigSelects
;
1282 } elseif ( $this->defaultBigSelects
=== null ) {
1283 $this->defaultBigSelects
=
1284 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__
);
1286 $encValue = $value ?
'1' : '0';
1287 $this->query( "SET sql_big_selects=$encValue", __METHOD__
, self
::QUERY_IGNORE_DBO_TRX
);
1291 * DELETE where the condition is a join. MySql uses multi-table deletes.
1292 * @param string $delTable
1293 * @param string $joinTable
1294 * @param string $delVar
1295 * @param string $joinVar
1296 * @param array|string $conds
1297 * @param bool|string $fname
1298 * @throws DBUnexpectedError
1300 public function deleteJoin(
1301 $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
1304 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
1307 $delTable = $this->tableName( $delTable );
1308 $joinTable = $this->tableName( $joinTable );
1309 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1311 if ( $conds != '*' ) {
1312 $sql .= ' AND ' . $this->makeList( $conds, self
::LIST_AND
);
1315 $this->query( $sql, $fname );
1318 public function upsert(
1319 $table, array $rows, $uniqueIndexes, array $set, $fname = __METHOD__
1321 if ( $rows === [] ) {
1322 return true; // nothing to do
1325 if ( !is_array( reset( $rows ) ) ) {
1329 $table = $this->tableName( $table );
1330 $columns = array_keys( $rows[0] );
1332 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1334 foreach ( $rows as $row ) {
1335 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1337 $sql .= implode( ',', $rowTuples );
1338 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, self
::LIST_SET
);
1340 $this->query( $sql, $fname );
1346 * Determines how long the server has been up
1350 public function getServerUptime() {
1351 $vars = $this->getMysqlStatus( 'Uptime' );
1353 return (int)$vars['Uptime'];
1357 * Determines if the last failure was due to a deadlock
1361 public function wasDeadlock() {
1362 return $this->lastErrno() == 1213;
1366 * Determines if the last failure was due to a lock timeout
1370 public function wasLockTimeout() {
1371 return $this->lastErrno() == 1205;
1375 * Determines if the last failure was due to the database being read-only.
1379 public function wasReadOnlyError() {
1380 return $this->lastErrno() == 1223 ||
1381 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1384 public function wasConnectionError( $errno ) {
1385 return $errno == 2013 ||
$errno == 2006;
1388 protected function wasKnownStatementRollbackError() {
1389 $errno = $this->lastErrno();
1391 if ( $errno === 1205 ) { // lock wait timeout
1392 // Note that this is uncached to avoid stale values of SET is used
1393 $row = $this->selectRow(
1395 [ 'innodb_rollback_on_timeout' => '@@innodb_rollback_on_timeout' ],
1399 // https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
1400 // https://dev.mysql.com/doc/refman/5.5/en/innodb-parameters.html
1401 return $row->innodb_rollback_on_timeout ?
false : true;
1404 // See https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1405 return in_array( $errno, [ 1022, 1062, 1216, 1217, 1137, 1146, 1051, 1054 ], true );
1409 * @param string $oldName
1410 * @param string $newName
1411 * @param bool $temporary
1412 * @param string $fname
1415 public function duplicateTableStructure(
1416 $oldName, $newName, $temporary = false, $fname = __METHOD__
1418 $tmp = $temporary ?
'TEMPORARY ' : '';
1419 $newName = $this->addIdentifierQuotes( $newName );
1420 $oldName = $this->addIdentifierQuotes( $oldName );
1421 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1423 return $this->query( $query, $fname, $this::QUERY_PSEUDO_PERMANENT
);
1427 * List all tables on the database
1429 * @param string|null $prefix Only show tables with this prefix, e.g. mw_
1430 * @param string $fname Calling function name
1433 public function listTables( $prefix = null, $fname = __METHOD__
) {
1434 $result = $this->query( "SHOW TABLES", $fname );
1438 foreach ( $result as $table ) {
1439 $vars = get_object_vars( $table );
1440 $table = array_pop( $vars );
1442 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1443 $endArray[] = $table;
1451 * @param string $tableName
1452 * @param string $fName
1453 * @return bool|IResultWrapper
1455 public function dropTable( $tableName, $fName = __METHOD__
) {
1456 if ( !$this->tableExists( $tableName, $fName ) ) {
1460 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1464 * Get status information from SHOW STATUS in an associative array
1466 * @param string $which
1469 private function getMysqlStatus( $which = "%" ) {
1470 $flags = self
::QUERY_IGNORE_DBO_TRX
;
1471 $res = $this->query( "SHOW STATUS LIKE '{$which}'", __METHOD__
, $flags );
1474 foreach ( $res as $row ) {
1475 $status[$row->Variable_name
] = $row->Value
;
1482 * Lists VIEWs in the database
1484 * @param string|null $prefix Only show VIEWs with this prefix, eg.
1485 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1486 * @param string $fname Name of calling function
1490 public function listViews( $prefix = null, $fname = __METHOD__
) {
1491 // The name of the column containing the name of the VIEW
1492 $propertyName = 'Tables_in_' . $this->getDBname();
1494 // Query for the VIEWS
1495 $res = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1497 foreach ( $res as $row ) {
1498 array_push( $allViews, $row->$propertyName );
1501 if ( is_null( $prefix ) ||
$prefix === '' ) {
1505 $filteredViews = [];
1506 foreach ( $allViews as $viewName ) {
1507 // Does the name of this VIEW start with the table-prefix?
1508 if ( strpos( $viewName, $prefix ) === 0 ) {
1509 array_push( $filteredViews, $viewName );
1513 return $filteredViews;
1517 * Differentiates between a TABLE and a VIEW.
1519 * @param string $name Name of the TABLE/VIEW to test
1520 * @param string|null $prefix
1524 public function isView( $name, $prefix = null ) {
1525 return in_array( $name, $this->listViews( $prefix ) );
1528 protected function isTransactableQuery( $sql ) {
1529 return parent
::isTransactableQuery( $sql ) &&
1530 !preg_match( '/^SELECT\s+(GET|RELEASE|IS_FREE)_LOCK\(/', $sql );
1533 public function buildStringCast( $field ) {
1534 return "CAST( $field AS BINARY )";
1538 * @param string $field Field or column to cast
1541 public function buildIntegerCast( $field ) {
1542 return 'CAST( ' . $field . ' AS SIGNED )';
1546 * @return bool Whether GTID support is used (mockable for testing)
1548 protected function useGTIDs() {
1549 return $this->useGTIDs
;
1554 * @deprecated since 1.29
1556 class_alias( DatabaseMysqlBase
::class, 'DatabaseMysqlBase' );