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() {
123 protected function open( $server, $user, $password, $dbName ) {
124 # Close/unset connection handle
127 $this->server
= $server;
129 $this->password
= $password;
130 $this->dbName
= $dbName;
132 $this->installErrorHandler();
134 $this->conn
= $this->mysqlConnect( $this->server
);
135 } catch ( Exception
$ex ) {
136 $this->restoreErrorHandler();
139 $error = $this->restoreErrorHandler();
141 # Always log connection errors
142 if ( !$this->conn
) {
143 $error = $error ?
: $this->lastError();
144 $this->connLogger
->error(
145 "Error connecting to {db_server}: {error}",
146 $this->getLogContext( [
147 'method' => __METHOD__
,
151 $this->connLogger
->debug( "DB connection error\n" .
152 "Server: $server, User: $user, Password: " .
153 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
155 throw new DBConnectionError( $this, $error );
158 if ( strlen( $dbName ) ) {
159 Wikimedia\
suppressWarnings();
160 $success = $this->selectDB( $dbName );
161 Wikimedia\restoreWarnings
();
163 $error = $this->lastError();
164 $this->queryLogger
->error(
165 "Error selecting database {db_name} on server {db_server}: {error}",
166 $this->getLogContext( [
167 'method' => __METHOD__
,
171 throw new DBConnectionError( $this, "Error selecting database $dbName: $error" );
175 // Tell the server what we're communicating with
176 if ( !$this->connectInitCharset() ) {
177 $error = $this->lastError();
178 $this->queryLogger
->error(
179 "Error setting character set: {error}",
180 $this->getLogContext( [
181 'method' => __METHOD__
,
182 'error' => $this->lastError(),
185 throw new DBConnectionError( $this, "Error setting character set: $error" );
188 // Abstract over any insane MySQL defaults
189 $set = [ 'group_concat_max_len = 262144' ];
190 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
191 if ( is_string( $this->sqlMode
) ) {
192 $set[] = 'sql_mode = ' . $this->addQuotes( $this->sqlMode
);
194 // Set any custom settings defined by site config
195 // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
196 foreach ( $this->sessionVars
as $var => $val ) {
197 // Escape strings but not numbers to avoid MySQL complaining
198 if ( !is_int( $val ) && !is_float( $val ) ) {
199 $val = $this->addQuotes( $val );
201 $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
205 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
206 $success = $this->doQuery( 'SET ' . implode( ', ', $set ) );
208 $error = $this->lastError();
209 $this->queryLogger
->error(
210 'Error setting MySQL variables on server {db_server}: {error}',
211 $this->getLogContext( [
212 'method' => __METHOD__
,
216 throw new DBConnectionError( $this, "Error setting MySQL variables: $error" );
220 $this->opened
= true;
226 * Set the character set information right after connection
229 protected function connectInitCharset() {
230 if ( $this->utf8Mode
) {
231 // Tell the server we're communicating with it in UTF-8.
232 // This may engage various charset conversions.
233 return $this->mysqlSetCharset( 'utf8' );
235 return $this->mysqlSetCharset( 'binary' );
240 * Open a connection to a MySQL server
242 * @param string $realServer
243 * @return mixed Raw connection
244 * @throws DBConnectionError
246 abstract protected function mysqlConnect( $realServer );
249 * Set the character set of the MySQL link
251 * @param string $charset
254 abstract protected function mysqlSetCharset( $charset );
257 * @param ResultWrapper|resource $res
258 * @throws DBUnexpectedError
260 public function freeResult( $res ) {
261 if ( $res instanceof ResultWrapper
) {
264 Wikimedia\
suppressWarnings();
265 $ok = $this->mysqlFreeResult( $res );
266 Wikimedia\restoreWarnings
();
268 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
275 * @param resource $res Raw result
278 abstract protected function mysqlFreeResult( $res );
281 * @param ResultWrapper|resource $res
282 * @return stdClass|bool
283 * @throws DBUnexpectedError
285 public function fetchObject( $res ) {
286 if ( $res instanceof ResultWrapper
) {
289 Wikimedia\
suppressWarnings();
290 $row = $this->mysqlFetchObject( $res );
291 Wikimedia\restoreWarnings
();
293 $errno = $this->lastErrno();
294 // Unfortunately, mysql_fetch_object does not reset the last errno.
295 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
296 // these are the only errors mysql_fetch_object can cause.
297 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
298 if ( $errno == 2000 ||
$errno == 2013 ) {
299 throw new DBUnexpectedError(
301 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
309 * Fetch a result row as an object
311 * @param resource $res Raw result
314 abstract protected function mysqlFetchObject( $res );
317 * @param IResultWrapper|resource $res
319 * @throws DBUnexpectedError
321 public function fetchRow( $res ) {
322 if ( $res instanceof ResultWrapper
) {
325 Wikimedia\
suppressWarnings();
326 $row = $this->mysqlFetchArray( $res );
327 Wikimedia\restoreWarnings
();
329 $errno = $this->lastErrno();
330 // Unfortunately, mysql_fetch_array does not reset the last errno.
331 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
332 // these are the only errors mysql_fetch_array can cause.
333 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
334 if ( $errno == 2000 ||
$errno == 2013 ) {
335 throw new DBUnexpectedError(
337 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
345 * Fetch a result row as an associative and numeric array
347 * @param resource $res Raw result
350 abstract protected function mysqlFetchArray( $res );
353 * @throws DBUnexpectedError
354 * @param ResultWrapper|resource $res
357 function numRows( $res ) {
358 if ( $res instanceof ResultWrapper
) {
361 Wikimedia\
suppressWarnings();
362 $n = $res ?
$this->mysqlNumRows( $res ) : 0;
363 Wikimedia\restoreWarnings
();
365 // Unfortunately, mysql_num_rows does not reset the last errno.
366 // We are not checking for any errors here, since
367 // there are no errors mysql_num_rows can cause.
368 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
369 // See https://phabricator.wikimedia.org/T44430
374 * Get number of rows in result
376 * @param resource $res Raw result
379 abstract protected function mysqlNumRows( $res );
382 * @param ResultWrapper|resource $res
385 public function numFields( $res ) {
386 if ( $res instanceof ResultWrapper
) {
390 return $this->mysqlNumFields( $res );
394 * Get number of fields in result
396 * @param resource $res Raw result
399 abstract protected function mysqlNumFields( $res );
402 * @param ResultWrapper|resource $res
406 public function fieldName( $res, $n ) {
407 if ( $res instanceof ResultWrapper
) {
411 return $this->mysqlFieldName( $res, $n );
415 * Get the name of the specified field in a result
417 * @param ResultWrapper|resource $res
421 abstract protected function mysqlFieldName( $res, $n );
424 * mysql_field_type() wrapper
425 * @param ResultWrapper|resource $res
429 public function fieldType( $res, $n ) {
430 if ( $res instanceof ResultWrapper
) {
434 return $this->mysqlFieldType( $res, $n );
438 * Get the type of the specified field in a result
440 * @param ResultWrapper|resource $res
444 abstract protected function mysqlFieldType( $res, $n );
447 * @param ResultWrapper|resource $res
451 public function dataSeek( $res, $row ) {
452 if ( $res instanceof ResultWrapper
) {
456 return $this->mysqlDataSeek( $res, $row );
460 * Move internal result pointer
462 * @param ResultWrapper|resource $res
466 abstract protected function mysqlDataSeek( $res, $row );
471 public function lastError() {
473 # Even if it's non-zero, it can still be invalid
474 Wikimedia\
suppressWarnings();
475 $error = $this->mysqlError( $this->conn
);
477 $error = $this->mysqlError();
479 Wikimedia\restoreWarnings
();
481 $error = $this->mysqlError();
484 $error .= ' (' . $this->server
. ')';
491 * Returns the text of the error message from previous MySQL operation
493 * @param resource|null $conn Raw connection
496 abstract protected function mysqlError( $conn = null );
498 protected function wasQueryTimeout( $error, $errno ) {
499 return $errno == 2062;
503 * @param string $table
504 * @param array $uniqueIndexes
506 * @param string $fname
507 * @return ResultWrapper
509 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
510 return $this->nativeReplace( $table, $rows, $fname );
513 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
514 $row = $this->getReplicationSafetyInfo();
515 // For row-based-replication, the resulting changes will be relayed, not the query
516 if ( $row->binlog_format
=== 'ROW' ) {
519 // LIMIT requires ORDER BY on a unique key or it is non-deterministic
520 if ( isset( $selectOptions['LIMIT'] ) ) {
523 // In MySQL, an INSERT SELECT is only replication safe with row-based
524 // replication or if innodb_autoinc_lock_mode is 0. When those
525 // conditions aren't met, use non-native mode.
526 // While we could try to determine if the insert is safe anyway by
527 // checking if the target table has an auto-increment column that
528 // isn't set in $varMap, that seems unlikely to be worth the extra
531 in_array( 'NO_AUTO_COLUMNS', $insertOptions ) ||
532 (int)$row->innodb_autoinc_lock_mode
=== 0
537 * @return stdClass Process cached row
539 protected function getReplicationSafetyInfo() {
540 if ( $this->replicationInfoRow
=== null ) {
541 $this->replicationInfoRow
= $this->selectRow(
544 'innodb_autoinc_lock_mode' => '@@innodb_autoinc_lock_mode',
545 'binlog_format' => '@@binlog_format',
552 return $this->replicationInfoRow
;
556 * Estimate rows in dataset
557 * Returns estimated count, based on EXPLAIN output
558 * Takes same arguments as Database::select()
560 * @param string|array $table
561 * @param string|array $var
562 * @param string|array $conds
563 * @param string $fname
564 * @param string|array $options
565 * @param array $join_conds
568 public function estimateRowCount( $table, $var = '*', $conds = '',
569 $fname = __METHOD__
, $options = [], $join_conds = []
571 $conds = $this->normalizeConditions( $conds, $fname );
572 $column = $this->extractSingleFieldFromList( $var );
573 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
574 $conds[] = "$column IS NOT NULL";
577 $options['EXPLAIN'] = true;
578 $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
579 if ( $res === false ) {
582 if ( !$this->numRows( $res ) ) {
587 foreach ( $res as $plan ) {
588 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
594 public function tableExists( $table, $fname = __METHOD__
) {
595 // Split database and table into proper variables as Database::tableName() returns
596 // shared tables prefixed with their database, which do not work in SHOW TABLES statements
597 list( $database, , $prefix, $table ) = $this->qualifiedTableComponents( $table );
598 $tableName = "{$prefix}{$table}";
600 if ( isset( $this->sessionTempTables
[$tableName] ) ) {
601 return true; // already known to exist and won't show in SHOW TABLES anyway
604 // We can't use buildLike() here, because it specifies an escape character
605 // other than the backslash, which is the only one supported by SHOW TABLES
606 $encLike = $this->escapeLikeInternal( $tableName, '\\' );
608 // If the database has been specified (such as for shared tables), use "FROM"
609 if ( $database !== '' ) {
610 $encDatabase = $this->addIdentifierQuotes( $database );
611 $query = "SHOW TABLES FROM $encDatabase LIKE '$encLike'";
613 $query = "SHOW TABLES LIKE '$encLike'";
616 return $this->query( $query, $fname )->numRows() > 0;
620 * @param string $table
621 * @param string $field
622 * @return bool|MySQLField
624 public function fieldInfo( $table, $field ) {
625 $table = $this->tableName( $table );
626 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
630 $n = $this->mysqlNumFields( $res->result
);
631 for ( $i = 0; $i < $n; $i++
) {
632 $meta = $this->mysqlFetchField( $res->result
, $i );
633 if ( $field == $meta->name
) {
634 return new MySQLField( $meta );
642 * Get column information from a result
644 * @param resource $res Raw result
648 abstract protected function mysqlFetchField( $res, $n );
651 * Get information about an index into an object
652 * Returns false if the index does not exist
654 * @param string $table
655 * @param string $index
656 * @param string $fname
657 * @return bool|array|null False or null on failure
659 public function indexInfo( $table, $index, $fname = __METHOD__
) {
660 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
661 # SHOW INDEX should work for 3.x and up:
662 # https://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
663 $table = $this->tableName( $table );
664 $index = $this->indexName( $index );
666 $sql = 'SHOW INDEX FROM ' . $table;
667 $res = $this->query( $sql, $fname );
675 foreach ( $res as $row ) {
676 if ( $row->Key_name
== $index ) {
681 return $result ?
: false;
688 public function strencode( $s ) {
689 return $this->mysqlRealEscapeString( $s );
696 abstract protected function mysqlRealEscapeString( $s );
698 public function addQuotes( $s ) {
699 if ( is_bool( $s ) ) {
700 // Parent would transform to int, which does not play nice with MySQL type juggling.
701 // When searching for an int in a string column, the strings are cast to int, which
702 // means false would match any string not starting with a number.
703 $s = (string)(int)$s;
705 return parent
::addQuotes( $s );
709 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
714 public function addIdentifierQuotes( $s ) {
715 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
716 // Remove NUL bytes and escape backticks by doubling
717 return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
721 * @param string $name
724 public function isQuotedIdentifier( $name ) {
725 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
728 public function getLag() {
729 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
730 return $this->getLagFromPtHeartbeat();
732 return $this->getLagFromSlaveStatus();
739 protected function getLagDetectionMethod() {
740 return $this->lagDetectionMethod
;
746 protected function getLagFromSlaveStatus() {
747 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
748 $row = $res ?
$res->fetchObject() : false;
749 // If the server is not replicating, there will be no row
750 if ( $row && strval( $row->Seconds_Behind_Master
) !== '' ) {
751 return intval( $row->Seconds_Behind_Master
);
760 protected function getLagFromPtHeartbeat() {
761 $options = $this->lagDetectionOptions
;
763 $currentTrxInfo = $this->getRecordedTransactionLagStatus();
764 if ( $currentTrxInfo ) {
765 // There is an active transaction and the initial lag was already queried
766 $staleness = microtime( true ) - $currentTrxInfo['since'];
767 if ( $staleness > self
::LAG_STALE_WARN_THRESHOLD
) {
768 // Avoid returning higher and higher lag value due to snapshot age
769 // given that the isolation level will typically be REPEATABLE-READ
770 $this->queryLogger
->warning(
771 "Using cached lag value for {db_server} due to active transaction",
772 $this->getLogContext( [ 'method' => __METHOD__
, 'age' => $staleness ] )
776 return $currentTrxInfo['lag'];
779 if ( isset( $options['conds'] ) ) {
780 // Best method for multi-DC setups: use logical channel names
781 $data = $this->getHeartbeatData( $options['conds'] );
783 // Standard method: use master server ID (works with stock pt-heartbeat)
784 $masterInfo = $this->getMasterServerInfo();
785 if ( !$masterInfo ) {
786 $this->queryLogger
->error(
787 "Unable to query master of {db_server} for server ID",
788 $this->getLogContext( [
789 'method' => __METHOD__
793 return false; // could not get master server ID
796 $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
797 $data = $this->getHeartbeatData( $conds );
800 list( $time, $nowUnix ) = $data;
801 if ( $time !== null ) {
802 // @time is in ISO format like "2015-09-25T16:48:10.000510"
803 $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
804 $timeUnix = (int)$dateTime->format( 'U' ) +
$dateTime->format( 'u' ) / 1e6
;
806 return max( $nowUnix - $timeUnix, 0.0 );
809 $this->queryLogger
->error(
810 "Unable to find pt-heartbeat row for {db_server}",
811 $this->getLogContext( [
812 'method' => __METHOD__
819 protected function getMasterServerInfo() {
820 $cache = $this->srvCache
;
821 $key = $cache->makeGlobalKey(
824 // Using one key for all cluster replica DBs is preferable
825 $this->getLBInfo( 'clusterMasterHost' ) ?
: $this->getServer()
829 return $cache->getWithSetCallback(
831 $cache::TTL_INDEFINITE
,
832 function () use ( $cache, $key, $fname ) {
833 // Get and leave a lock key in place for a short period
834 if ( !$cache->lock( $key, 0, 10 ) ) {
835 return false; // avoid master connection spike slams
838 $conn = $this->getLazyMasterHandle();
840 return false; // something is misconfigured
843 // Connect to and query the master; catch errors to avoid outages
845 $res = $conn->query( 'SELECT @@server_id AS id', $fname );
846 $row = $res ?
$res->fetchObject() : false;
847 $id = $row ?
(int)$row->id
: 0;
848 } catch ( DBError
$e ) {
852 // Cache the ID if it was retrieved
853 return $id ?
[ 'serverId' => $id, 'asOf' => time() ] : false;
859 * @param array $conds WHERE clause conditions to find a row
860 * @return array (heartbeat `ts` column value or null, UNIX timestamp) for the newest beat
861 * @see https://www.percona.com/doc/percona-toolkit/2.1/pt-heartbeat.html
863 protected function getHeartbeatData( array $conds ) {
864 // Query time and trip time are not counted
865 $nowUnix = microtime( true );
866 // Do not bother starting implicit transactions here
867 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
869 $whereSQL = $this->makeList( $conds, self
::LIST_AND
);
870 // Use ORDER BY for channel based queries since that field might not be UNIQUE.
871 // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
872 // percision field is not supported in MySQL <= 5.5.
874 "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1",
877 $row = $res ?
$res->fetchObject() : false;
879 $this->restoreFlags();
882 return [ $row ?
$row->ts
: null, $nowUnix ];
885 protected function getApproximateLagStatus() {
886 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
887 // Disable caching since this is fast enough and we don't wan't
888 // to be *too* pessimistic by having both the cache TTL and the
889 // pt-heartbeat interval count as lag in getSessionLagStatus()
890 return parent
::getApproximateLagStatus();
893 $key = $this->srvCache
->makeGlobalKey( 'mysql-lag', $this->getServer() );
894 $approxLag = $this->srvCache
->get( $key );
896 $approxLag = parent
::getApproximateLagStatus();
897 $this->srvCache
->set( $key, $approxLag, 1 );
903 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
904 if ( !( $pos instanceof MySQLMasterPos
) ) {
905 throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
908 if ( $this->getLBInfo( 'is static' ) === true ) {
909 return 0; // this is a copy of a read-only dataset with no master DB
910 } elseif ( $this->lastKnownReplicaPos
&& $this->lastKnownReplicaPos
->hasReached( $pos ) ) {
911 return 0; // already reached this point for sure
914 // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
915 if ( $pos->getGTIDs() ) {
916 // Ignore GTIDs from domains exclusive to the master DB (presumably inactive)
917 $rpos = $this->getReplicaPos();
918 $gtidsWait = $rpos ? MySQLMasterPos
::getCommonDomainGTIDs( $pos, $rpos ) : [];
920 $this->queryLogger
->error(
921 "No GTIDs with the same domain between master ($pos) and replica ($rpos)",
922 $this->getLogContext( [
923 'method' => __METHOD__
,
927 return -1; // $pos is from the wrong cluster?
929 // Wait on the GTID set (MariaDB only)
930 $gtidArg = $this->addQuotes( implode( ',', $gtidsWait ) );
931 if ( strpos( $gtidArg, ':' ) !== false ) {
932 // MySQL GTIDs, e.g "source_id:transaction_id"
933 $res = $this->doQuery( "SELECT WAIT_FOR_EXECUTED_GTID_SET($gtidArg, $timeout)" );
935 // MariaDB GTIDs, e.g."domain:server:sequence"
936 $res = $this->doQuery( "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)" );
939 // Wait on the binlog coordinates
940 $encFile = $this->addQuotes( $pos->getLogFile() );
941 $encPos = intval( $pos->getLogPosition()[$pos::CORD_EVENT
] );
942 $res = $this->doQuery( "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)" );
945 $row = $res ?
$this->fetchRow( $res ) : false;
947 throw new DBExpectedError( $this, "Replication wait failed: {$this->lastError()}" );
950 // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
951 $status = ( $row[0] !== null ) ?
intval( $row[0] ) : null;
952 if ( $status === null ) {
953 if ( !$pos->getGTIDs() ) {
954 // T126436: jobs programmed to wait on master positions might be referencing
955 // binlogs with an old master hostname; this makes MASTER_POS_WAIT() return null.
956 // Try to detect this case and treat the replica DB as having reached the given
957 // position (any master switchover already requires that the new master be caught
958 // up before the switch).
959 $replicationPos = $this->getReplicaPos();
960 if ( $replicationPos && !$replicationPos->channelsMatch( $pos ) ) {
961 $this->lastKnownReplicaPos
= $replicationPos;
965 } elseif ( $status >= 0 ) {
966 // Remember that this position was reached to save queries next time
967 $this->lastKnownReplicaPos
= $pos;
974 * Get the position of the master from SHOW SLAVE STATUS
976 * @return MySQLMasterPos|bool
978 public function getReplicaPos() {
979 $now = microtime( true ); // as-of-time *before* fetching GTID variables
981 if ( $this->useGTIDs() ) {
982 // Try to use GTIDs, fallbacking to binlog positions if not possible
983 $data = $this->getServerGTIDs( __METHOD__
);
984 // Use gtid_slave_pos for MariaDB and gtid_executed for MySQL
985 foreach ( [ 'gtid_slave_pos', 'gtid_executed' ] as $name ) {
986 if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
987 return new MySQLMasterPos( $data[$name], $now );
992 $data = $this->getServerRoleStatus( 'SLAVE', __METHOD__
);
993 if ( $data && strlen( $data['Relay_Master_Log_File'] ) ) {
994 return new MySQLMasterPos(
995 "{$data['Relay_Master_Log_File']}/{$data['Exec_Master_Log_Pos']}",
1004 * Get the position of the master from SHOW MASTER STATUS
1006 * @return MySQLMasterPos|bool
1008 public function getMasterPos() {
1009 $now = microtime( true ); // as-of-time *before* fetching GTID variables
1012 if ( $this->useGTIDs() ) {
1013 // Try to use GTIDs, fallbacking to binlog positions if not possible
1014 $data = $this->getServerGTIDs( __METHOD__
);
1015 // Use gtid_binlog_pos for MariaDB and gtid_executed for MySQL
1016 foreach ( [ 'gtid_binlog_pos', 'gtid_executed' ] as $name ) {
1017 if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
1018 $pos = new MySQLMasterPos( $data[$name], $now );
1022 // Filter domains that are inactive or not relevant to the session
1024 $pos->setActiveOriginServerId( $this->getServerId() );
1025 $pos->setActiveOriginServerUUID( $this->getServerUUID() );
1026 if ( isset( $data['gtid_domain_id'] ) ) {
1027 $pos->setActiveDomain( $data['gtid_domain_id'] );
1033 $data = $this->getServerRoleStatus( 'MASTER', __METHOD__
);
1034 if ( $data && strlen( $data['File'] ) ) {
1035 $pos = new MySQLMasterPos( "{$data['File']}/{$data['Position']}", $now );
1044 * @throws DBQueryError If the variable doesn't exist for some reason
1046 protected function getServerId() {
1047 $fname = __METHOD__
;
1048 return $this->srvCache
->getWithSetCallback(
1049 $this->srvCache
->makeGlobalKey( 'mysql-server-id', $this->getServer() ),
1050 self
::SERVER_ID_CACHE_TTL
,
1051 function () use ( $fname ) {
1052 $res = $this->query( "SELECT @@server_id AS id", $fname );
1053 return intval( $this->fetchObject( $res )->id
);
1059 * @return string|null
1061 protected function getServerUUID() {
1062 return $this->srvCache
->getWithSetCallback(
1063 $this->srvCache
->makeGlobalKey( 'mysql-server-uuid', $this->getServer() ),
1064 self
::SERVER_ID_CACHE_TTL
,
1066 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'server_uuid'" );
1067 $row = $this->fetchObject( $res );
1069 return $row ?
$row->Value
: null;
1075 * @param string $fname
1078 protected function getServerGTIDs( $fname = __METHOD__
) {
1080 // Get global-only variables like gtid_executed
1081 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_%'", $fname );
1082 foreach ( $res as $row ) {
1083 $map[$row->Variable_name
] = $row->Value
;
1085 // Get session-specific (e.g. gtid_domain_id since that is were writes will log)
1086 $res = $this->query( "SHOW SESSION VARIABLES LIKE 'gtid_%'", $fname );
1087 foreach ( $res as $row ) {
1088 $map[$row->Variable_name
] = $row->Value
;
1095 * @param string $role One of "MASTER"/"SLAVE"
1096 * @param string $fname
1097 * @return string[] Latest available server status row
1099 protected function getServerRoleStatus( $role, $fname = __METHOD__
) {
1100 return $this->query( "SHOW $role STATUS", $fname )->fetchRow() ?
: [];
1103 public function serverIsReadOnly() {
1104 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'read_only'", __METHOD__
);
1105 $row = $this->fetchObject( $res );
1107 return $row ?
( strtolower( $row->Value
) === 'on' ) : false;
1111 * @param string $index
1114 function useIndexClause( $index ) {
1115 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
1119 * @param string $index
1122 function ignoreIndexClause( $index ) {
1123 return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
1129 function lowPriorityOption() {
1130 return 'LOW_PRIORITY';
1136 public function getSoftwareLink() {
1137 // MariaDB includes its name in its version string; this is how MariaDB's version of
1138 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
1139 // in libmysql/libmysql.c).
1140 $version = $this->getServerVersion();
1141 if ( strpos( $version, 'MariaDB' ) !== false ||
strpos( $version, '-maria-' ) !== false ) {
1142 return '[{{int:version-db-mariadb-url}} MariaDB]';
1145 // Percona Server's version suffix is not very distinctive, and @@version_comment
1146 // doesn't give the necessary info for source builds, so assume the server is MySQL.
1147 // (Even Percona's version of mysql doesn't try to make the distinction.)
1148 return '[{{int:version-db-mysql-url}} MySQL]';
1154 public function getServerVersion() {
1155 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
1156 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
1157 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
1158 if ( $this->serverVersion
=== null ) {
1159 $this->serverVersion
= $this->selectField( '', 'VERSION()', '', __METHOD__
);
1161 return $this->serverVersion
;
1165 * @param array $options
1167 public function setSessionOptions( array $options ) {
1168 if ( isset( $options['connTimeout'] ) ) {
1169 $timeout = (int)$options['connTimeout'];
1170 $this->query( "SET net_read_timeout=$timeout" );
1171 $this->query( "SET net_write_timeout=$timeout" );
1176 * @param string &$sql
1177 * @param string &$newLine
1180 public function streamStatementEnd( &$sql, &$newLine ) {
1181 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
1182 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
1183 $this->delimiter
= $m[1];
1187 return parent
::streamStatementEnd( $sql, $newLine );
1191 * Check to see if a named lock is available. This is non-blocking.
1193 * @param string $lockName Name of lock to poll
1194 * @param string $method Name of method calling us
1198 public function lockIsFree( $lockName, $method ) {
1199 if ( !parent
::lockIsFree( $lockName, $method ) ) {
1200 return false; // already held
1203 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1204 $result = $this->query( "SELECT IS_FREE_LOCK($encName) AS lockstatus", $method );
1205 $row = $this->fetchObject( $result );
1207 return ( $row->lockstatus
== 1 );
1211 * @param string $lockName
1212 * @param string $method
1213 * @param int $timeout
1216 public function lock( $lockName, $method, $timeout = 5 ) {
1217 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1218 $result = $this->query( "SELECT GET_LOCK($encName, $timeout) AS lockstatus", $method );
1219 $row = $this->fetchObject( $result );
1221 if ( $row->lockstatus
== 1 ) {
1222 parent
::lock( $lockName, $method, $timeout ); // record
1226 $this->queryLogger
->info( __METHOD__
. " failed to acquire lock '{lockname}'",
1227 [ 'lockname' => $lockName ] );
1234 * https://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
1235 * @param string $lockName
1236 * @param string $method
1239 public function unlock( $lockName, $method ) {
1240 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1241 $result = $this->query( "SELECT RELEASE_LOCK($encName) as lockstatus", $method );
1242 $row = $this->fetchObject( $result );
1244 if ( $row->lockstatus
== 1 ) {
1245 parent
::unlock( $lockName, $method ); // record
1249 $this->queryLogger
->warning( __METHOD__
. " failed to release lock '$lockName'\n" );
1254 private function makeLockName( $lockName ) {
1255 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1256 // Newer version enforce a 64 char length limit.
1257 return ( strlen( $lockName ) > 64 ) ?
sha1( $lockName ) : $lockName;
1260 public function namedLocksEnqueue() {
1264 public function tableLocksHaveTransactionScope() {
1265 return false; // tied to TCP connection
1268 protected function doLockTables( array $read, array $write, $method ) {
1270 foreach ( $write as $table ) {
1271 $items[] = $this->tableName( $table ) . ' WRITE';
1273 foreach ( $read as $table ) {
1274 $items[] = $this->tableName( $table ) . ' READ';
1277 $sql = "LOCK TABLES " . implode( ',', $items );
1278 $this->query( $sql, $method );
1283 protected function doUnlockTables( $method ) {
1284 $this->query( "UNLOCK TABLES", $method );
1290 * @param bool $value
1292 public function setBigSelects( $value = true ) {
1293 if ( $value === 'default' ) {
1294 if ( $this->defaultBigSelects
=== null ) {
1295 # Function hasn't been called before so it must already be set to the default
1298 $value = $this->defaultBigSelects
;
1300 } elseif ( $this->defaultBigSelects
=== null ) {
1301 $this->defaultBigSelects
=
1302 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__
);
1304 $encValue = $value ?
'1' : '0';
1305 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
1309 * DELETE where the condition is a join. MySql uses multi-table deletes.
1310 * @param string $delTable
1311 * @param string $joinTable
1312 * @param string $delVar
1313 * @param string $joinVar
1314 * @param array|string $conds
1315 * @param bool|string $fname
1316 * @throws DBUnexpectedError
1317 * @return bool|ResultWrapper
1319 public function deleteJoin(
1320 $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
1323 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
1326 $delTable = $this->tableName( $delTable );
1327 $joinTable = $this->tableName( $joinTable );
1328 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1330 if ( $conds != '*' ) {
1331 $sql .= ' AND ' . $this->makeList( $conds, self
::LIST_AND
);
1334 return $this->query( $sql, $fname );
1338 * @param string $table
1339 * @param array $rows
1340 * @param array $uniqueIndexes
1342 * @param string $fname
1345 public function upsert( $table, array $rows, array $uniqueIndexes,
1346 array $set, $fname = __METHOD__
1348 if ( !count( $rows ) ) {
1349 return true; // nothing to do
1352 if ( !is_array( reset( $rows ) ) ) {
1356 $table = $this->tableName( $table );
1357 $columns = array_keys( $rows[0] );
1359 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1361 foreach ( $rows as $row ) {
1362 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1364 $sql .= implode( ',', $rowTuples );
1365 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, self
::LIST_SET
);
1367 return (bool)$this->query( $sql, $fname );
1371 * Determines how long the server has been up
1375 public function getServerUptime() {
1376 $vars = $this->getMysqlStatus( 'Uptime' );
1378 return (int)$vars['Uptime'];
1382 * Determines if the last failure was due to a deadlock
1386 public function wasDeadlock() {
1387 return $this->lastErrno() == 1213;
1391 * Determines if the last failure was due to a lock timeout
1395 public function wasLockTimeout() {
1396 return $this->lastErrno() == 1205;
1400 * Determines if the last failure was due to the database being read-only.
1404 public function wasReadOnlyError() {
1405 return $this->lastErrno() == 1223 ||
1406 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1409 public function wasConnectionError( $errno ) {
1410 return $errno == 2013 ||
$errno == 2006;
1413 protected function wasKnownStatementRollbackError() {
1414 $errno = $this->lastErrno();
1416 if ( $errno === 1205 ) { // lock wait timeout
1417 // Note that this is uncached to avoid stale values of SET is used
1418 $row = $this->selectRow(
1420 [ 'innodb_rollback_on_timeout' => '@@innodb_rollback_on_timeout' ],
1424 // https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
1425 // https://dev.mysql.com/doc/refman/5.5/en/innodb-parameters.html
1426 return $row->innodb_rollback_on_timeout ?
false : true;
1429 // See https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1430 return in_array( $errno, [ 1022, 1216, 1217, 1137 ], true );
1434 * @param string $oldName
1435 * @param string $newName
1436 * @param bool $temporary
1437 * @param string $fname
1440 public function duplicateTableStructure(
1441 $oldName, $newName, $temporary = false, $fname = __METHOD__
1443 $tmp = $temporary ?
'TEMPORARY ' : '';
1444 $newName = $this->addIdentifierQuotes( $newName );
1445 $oldName = $this->addIdentifierQuotes( $oldName );
1446 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1448 return $this->query( $query, $fname );
1452 * List all tables on the database
1454 * @param string|null $prefix Only show tables with this prefix, e.g. mw_
1455 * @param string $fname Calling function name
1458 public function listTables( $prefix = null, $fname = __METHOD__
) {
1459 $result = $this->query( "SHOW TABLES", $fname );
1463 foreach ( $result as $table ) {
1464 $vars = get_object_vars( $table );
1465 $table = array_pop( $vars );
1467 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1468 $endArray[] = $table;
1476 * @param string $tableName
1477 * @param string $fName
1478 * @return bool|ResultWrapper
1480 public function dropTable( $tableName, $fName = __METHOD__
) {
1481 if ( !$this->tableExists( $tableName, $fName ) ) {
1485 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1489 * Get status information from SHOW STATUS in an associative array
1491 * @param string $which
1494 private function getMysqlStatus( $which = "%" ) {
1495 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1498 foreach ( $res as $row ) {
1499 $status[$row->Variable_name
] = $row->Value
;
1506 * Lists VIEWs in the database
1508 * @param string|null $prefix Only show VIEWs with this prefix, eg.
1509 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1510 * @param string $fname Name of calling function
1514 public function listViews( $prefix = null, $fname = __METHOD__
) {
1515 // The name of the column containing the name of the VIEW
1516 $propertyName = 'Tables_in_' . $this->dbName
;
1518 // Query for the VIEWS
1519 $res = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1521 foreach ( $res as $row ) {
1522 array_push( $allViews, $row->$propertyName );
1525 if ( is_null( $prefix ) ||
$prefix === '' ) {
1529 $filteredViews = [];
1530 foreach ( $allViews as $viewName ) {
1531 // Does the name of this VIEW start with the table-prefix?
1532 if ( strpos( $viewName, $prefix ) === 0 ) {
1533 array_push( $filteredViews, $viewName );
1537 return $filteredViews;
1541 * Differentiates between a TABLE and a VIEW.
1543 * @param string $name Name of the TABLE/VIEW to test
1544 * @param string|null $prefix
1548 public function isView( $name, $prefix = null ) {
1549 return in_array( $name, $this->listViews( $prefix ) );
1552 protected function isTransactableQuery( $sql ) {
1553 return parent
::isTransactableQuery( $sql ) &&
1554 !preg_match( '/^SELECT\s+(GET|RELEASE|IS_FREE)_LOCK\(/', $sql );
1558 * @param string $field Field or column to cast
1561 public function buildIntegerCast( $field ) {
1562 return 'CAST( ' . $field . ' AS SIGNED )';
1566 * @return bool Whether GTID support is used (mockable for testing)
1568 protected function useGTIDs() {
1569 return $this->useGTIDs
;
1574 * @deprecated since 1.29
1576 class_alias( DatabaseMysqlBase
::class, 'DatabaseMysqlBase' );