3 * This is the MySQL database abstraction layer.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 namespace Wikimedia\Rdbms
;
28 use InvalidArgumentException
;
33 * Database abstraction object for MySQL.
34 * Defines methods independent on used MySQL extension.
40 abstract class DatabaseMysqlBase
extends Database
{
41 /** @var MysqlMasterPos */
42 protected $lastKnownReplicaPos;
43 /** @var string Method to detect replica DB lag */
44 protected $lagDetectionMethod;
45 /** @var array Method to detect replica DB lag */
46 protected $lagDetectionOptions = [];
47 /** @var bool bool Whether to use GTID methods */
48 protected $useGTIDs = false;
49 /** @var string|null */
50 protected $sslKeyPath;
51 /** @var string|null */
52 protected $sslCertPath;
53 /** @var string|null */
55 /** @var string|null */
57 /** @var string[]|null */
58 protected $sslCiphers;
59 /** @var string sql_mode value to send on connection */
61 /** @var bool Use experimental UTF-8 transmission encoding */
64 protected $defaultBigSelects = null;
66 /** @var string|null */
67 private $serverVersion = null;
69 private $insertSelectIsSafe = null;
70 /** @var stdClass|null */
71 private $replicationInfoRow = null;
73 // Cache getServerId() for 24 hours
74 const SERVER_ID_CACHE_TTL
= 86400;
77 * Additional $params include:
78 * - lagDetectionMethod : set to one of (Seconds_Behind_Master,pt-heartbeat).
79 * pt-heartbeat assumes the table is at heartbeat.heartbeat
80 * and uses UTC timestamps in the heartbeat.ts column.
81 * (https://www.percona.com/doc/percona-toolkit/2.2/pt-heartbeat.html)
82 * - lagDetectionOptions : if using pt-heartbeat, this can be set to an array map to change
83 * the default behavior. Normally, the heartbeat row with the server
84 * ID of this server's master will be used. Set the "conds" field to
85 * override the query conditions, e.g. ['shard' => 's1'].
86 * - useGTIDs : use GTID methods like MASTER_GTID_WAIT() when possible.
87 * - insertSelectIsSafe : force that native INSERT SELECT is or is not safe [default: null]
88 * - sslKeyPath : path to key file [default: null]
89 * - sslCertPath : path to certificate file [default: null]
90 * - sslCAFile: path to a single certificate authority PEM file [default: null]
91 * - sslCAPath : parth to certificate authority PEM directory [default: null]
92 * - sslCiphers : array list of allowable ciphers [default: null]
93 * @param array $params
95 function __construct( array $params ) {
96 $this->lagDetectionMethod
= isset( $params['lagDetectionMethod'] )
97 ?
$params['lagDetectionMethod']
98 : 'Seconds_Behind_Master';
99 $this->lagDetectionOptions
= isset( $params['lagDetectionOptions'] )
100 ?
$params['lagDetectionOptions']
102 $this->useGTIDs
= !empty( $params['useGTIDs' ] );
103 foreach ( [ 'KeyPath', 'CertPath', 'CAFile', 'CAPath', 'Ciphers' ] as $name ) {
105 if ( isset( $params[$var] ) ) {
106 $this->$var = $params[$var];
109 $this->sqlMode
= isset( $params['sqlMode'] ) ?
$params['sqlMode'] : '';
110 $this->utf8Mode
= !empty( $params['utf8Mode'] );
111 $this->insertSelectIsSafe
= isset( $params['insertSelectIsSafe'] )
112 ?
(bool)$params['insertSelectIsSafe'] : null;
114 parent
::__construct( $params );
120 public function getType() {
125 * @param string $server
126 * @param string $user
127 * @param string $password
128 * @param string $dbName
129 * @throws Exception|DBConnectionError
132 public function open( $server, $user, $password, $dbName ) {
133 # Close/unset connection handle
136 $this->server
= $server;
138 $this->password
= $password;
139 $this->dbName
= $dbName;
141 $this->installErrorHandler();
143 $this->conn
= $this->mysqlConnect( $this->server
);
144 } catch ( Exception
$ex ) {
145 $this->restoreErrorHandler();
148 $error = $this->restoreErrorHandler();
150 # Always log connection errors
151 if ( !$this->conn
) {
153 $error = $this->lastError();
155 $this->connLogger
->error(
156 "Error connecting to {db_server}: {error}",
157 $this->getLogContext( [
158 'method' => __METHOD__
,
162 $this->connLogger
->debug( "DB connection error\n" .
163 "Server: $server, User: $user, Password: " .
164 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
166 $this->reportConnectionError( $error );
169 if ( strlen( $dbName ) ) {
170 Wikimedia\
suppressWarnings();
171 $success = $this->selectDB( $dbName );
172 Wikimedia\restoreWarnings
();
174 $this->queryLogger
->error(
175 "Error selecting database {db_name} on server {db_server}",
176 $this->getLogContext( [
177 'method' => __METHOD__
,
180 $this->queryLogger
->debug(
181 "Error selecting database $dbName on server {$this->server}" );
183 $this->reportConnectionError( "Error selecting database $dbName" );
187 // Tell the server what we're communicating with
188 if ( !$this->connectInitCharset() ) {
189 $this->reportConnectionError( "Error setting character set" );
192 // Abstract over any insane MySQL defaults
193 $set = [ 'group_concat_max_len = 262144' ];
194 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
195 if ( is_string( $this->sqlMode
) ) {
196 $set[] = 'sql_mode = ' . $this->addQuotes( $this->sqlMode
);
198 // Set any custom settings defined by site config
199 // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
200 foreach ( $this->sessionVars
as $var => $val ) {
201 // Escape strings but not numbers to avoid MySQL complaining
202 if ( !is_int( $val ) && !is_float( $val ) ) {
203 $val = $this->addQuotes( $val );
205 $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
209 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
210 $success = $this->doQuery( 'SET ' . implode( ', ', $set ) );
212 $this->queryLogger
->error(
213 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)',
214 $this->getLogContext( [
215 'method' => __METHOD__
,
218 $this->reportConnectionError(
219 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)' );
223 $this->opened
= true;
229 * Set the character set information right after connection
232 protected function connectInitCharset() {
233 if ( $this->utf8Mode
) {
234 // Tell the server we're communicating with it in UTF-8.
235 // This may engage various charset conversions.
236 return $this->mysqlSetCharset( 'utf8' );
238 return $this->mysqlSetCharset( 'binary' );
243 * Open a connection to a MySQL server
245 * @param string $realServer
246 * @return mixed Raw connection
247 * @throws DBConnectionError
249 abstract protected function mysqlConnect( $realServer );
252 * Set the character set of the MySQL link
254 * @param string $charset
257 abstract protected function mysqlSetCharset( $charset );
260 * @param ResultWrapper|resource $res
261 * @throws DBUnexpectedError
263 public function freeResult( $res ) {
264 if ( $res instanceof ResultWrapper
) {
267 Wikimedia\
suppressWarnings();
268 $ok = $this->mysqlFreeResult( $res );
269 Wikimedia\restoreWarnings
();
271 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
278 * @param resource $res Raw result
281 abstract protected function mysqlFreeResult( $res );
284 * @param ResultWrapper|resource $res
285 * @return stdClass|bool
286 * @throws DBUnexpectedError
288 public function fetchObject( $res ) {
289 if ( $res instanceof ResultWrapper
) {
292 Wikimedia\
suppressWarnings();
293 $row = $this->mysqlFetchObject( $res );
294 Wikimedia\restoreWarnings
();
296 $errno = $this->lastErrno();
297 // Unfortunately, mysql_fetch_object does not reset the last errno.
298 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
299 // these are the only errors mysql_fetch_object can cause.
300 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
301 if ( $errno == 2000 ||
$errno == 2013 ) {
302 throw new DBUnexpectedError(
304 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
312 * Fetch a result row as an object
314 * @param resource $res Raw result
317 abstract protected function mysqlFetchObject( $res );
320 * @param ResultWrapper|resource $res
322 * @throws DBUnexpectedError
324 public function fetchRow( $res ) {
325 if ( $res instanceof ResultWrapper
) {
328 Wikimedia\
suppressWarnings();
329 $row = $this->mysqlFetchArray( $res );
330 Wikimedia\restoreWarnings
();
332 $errno = $this->lastErrno();
333 // Unfortunately, mysql_fetch_array does not reset the last errno.
334 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
335 // these are the only errors mysql_fetch_array can cause.
336 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
337 if ( $errno == 2000 ||
$errno == 2013 ) {
338 throw new DBUnexpectedError(
340 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
348 * Fetch a result row as an associative and numeric array
350 * @param resource $res Raw result
353 abstract protected function mysqlFetchArray( $res );
356 * @throws DBUnexpectedError
357 * @param ResultWrapper|resource $res
360 function numRows( $res ) {
361 if ( $res instanceof ResultWrapper
) {
364 Wikimedia\
suppressWarnings();
365 $n = $this->mysqlNumRows( $res );
366 Wikimedia\restoreWarnings
();
368 // Unfortunately, mysql_num_rows does not reset the last errno.
369 // We are not checking for any errors here, since
370 // these are no errors mysql_num_rows can cause.
371 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
372 // See https://phabricator.wikimedia.org/T44430
377 * Get number of rows in result
379 * @param resource $res Raw result
382 abstract protected function mysqlNumRows( $res );
385 * @param ResultWrapper|resource $res
388 public function numFields( $res ) {
389 if ( $res instanceof ResultWrapper
) {
393 return $this->mysqlNumFields( $res );
397 * Get number of fields in result
399 * @param resource $res Raw result
402 abstract protected function mysqlNumFields( $res );
405 * @param ResultWrapper|resource $res
409 public function fieldName( $res, $n ) {
410 if ( $res instanceof ResultWrapper
) {
414 return $this->mysqlFieldName( $res, $n );
418 * Get the name of the specified field in a result
420 * @param ResultWrapper|resource $res
424 abstract protected function mysqlFieldName( $res, $n );
427 * mysql_field_type() wrapper
428 * @param ResultWrapper|resource $res
432 public function fieldType( $res, $n ) {
433 if ( $res instanceof ResultWrapper
) {
437 return $this->mysqlFieldType( $res, $n );
441 * Get the type of the specified field in a result
443 * @param ResultWrapper|resource $res
447 abstract protected function mysqlFieldType( $res, $n );
450 * @param ResultWrapper|resource $res
454 public function dataSeek( $res, $row ) {
455 if ( $res instanceof ResultWrapper
) {
459 return $this->mysqlDataSeek( $res, $row );
463 * Move internal result pointer
465 * @param ResultWrapper|resource $res
469 abstract protected function mysqlDataSeek( $res, $row );
474 public function lastError() {
476 # Even if it's non-zero, it can still be invalid
477 Wikimedia\
suppressWarnings();
478 $error = $this->mysqlError( $this->conn
);
480 $error = $this->mysqlError();
482 Wikimedia\restoreWarnings
();
484 $error = $this->mysqlError();
487 $error .= ' (' . $this->server
. ')';
494 * Returns the text of the error message from previous MySQL operation
496 * @param resource $conn Raw connection
499 abstract protected function mysqlError( $conn = null );
501 protected function wasQueryTimeout( $error, $errno ) {
502 return $errno == 2062;
506 * @param string $table
507 * @param array $uniqueIndexes
509 * @param string $fname
510 * @return ResultWrapper
512 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
513 return $this->nativeReplace( $table, $rows, $fname );
516 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
517 $row = $this->getReplicationSafetyInfo();
518 // For row-based-replication, the resulting changes will be relayed, not the query
519 if ( $row->binlog_format
=== 'ROW' ) {
522 // LIMIT requires ORDER BY on a unique key or it is non-deterministic
523 if ( isset( $selectOptions['LIMIT'] ) ) {
526 // In MySQL, an INSERT SELECT is only replication safe with row-based
527 // replication or if innodb_autoinc_lock_mode is 0. When those
528 // conditions aren't met, use non-native mode.
529 // While we could try to determine if the insert is safe anyway by
530 // checking if the target table has an auto-increment column that
531 // isn't set in $varMap, that seems unlikely to be worth the extra
534 in_array( 'NO_AUTO_COLUMNS', $insertOptions ) ||
535 (int)$row->innodb_autoinc_lock_mode
=== 0
540 * @return stdClass Process cached row
542 protected function getReplicationSafetyInfo() {
543 if ( $this->replicationInfoRow
=== null ) {
544 $this->replicationInfoRow
= $this->selectRow(
547 'innodb_autoinc_lock_mode' => '@@innodb_autoinc_lock_mode',
548 'binlog_format' => '@@binlog_format',
555 return $this->replicationInfoRow
;
559 * Estimate rows in dataset
560 * Returns estimated count, based on EXPLAIN output
561 * Takes same arguments as Database::select()
563 * @param string|array $table
564 * @param string|array $var
565 * @param string|array $conds
566 * @param string $fname
567 * @param string|array $options
568 * @param array $join_conds
571 public function estimateRowCount( $table, $var = '*', $conds = '',
572 $fname = __METHOD__
, $options = [], $join_conds = []
574 $conds = $this->normalizeConditions( $conds, $fname );
575 $column = $this->extractSingleFieldFromList( $var );
576 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
577 $conds[] = "$column IS NOT NULL";
580 $options['EXPLAIN'] = true;
581 $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
582 if ( $res === false ) {
585 if ( !$this->numRows( $res ) ) {
590 foreach ( $res as $plan ) {
591 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
597 public function tableExists( $table, $fname = __METHOD__
) {
598 // Split database and table into proper variables as Database::tableName() returns
599 // shared tables prefixed with their database, which do not work in SHOW TABLES statements
600 list( $database, , $prefix, $table ) = $this->qualifiedTableComponents( $table );
601 $tableName = "{$prefix}{$table}";
603 if ( isset( $this->sessionTempTables
[$tableName] ) ) {
604 return true; // already known to exist and won't show in SHOW TABLES anyway
607 // We can't use buildLike() here, because it specifies an escape character
608 // other than the backslash, which is the only one supported by SHOW TABLES
609 $encLike = $this->escapeLikeInternal( $tableName, '\\' );
611 // If the database has been specified (such as for shared tables), use "FROM"
612 if ( $database !== '' ) {
613 $encDatabase = $this->addIdentifierQuotes( $database );
614 $query = "SHOW TABLES FROM $encDatabase LIKE '$encLike'";
616 $query = "SHOW TABLES LIKE '$encLike'";
619 return $this->query( $query, $fname )->numRows() > 0;
623 * @param string $table
624 * @param string $field
625 * @return bool|MySQLField
627 public function fieldInfo( $table, $field ) {
628 $table = $this->tableName( $table );
629 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
633 $n = $this->mysqlNumFields( $res->result
);
634 for ( $i = 0; $i < $n; $i++
) {
635 $meta = $this->mysqlFetchField( $res->result
, $i );
636 if ( $field == $meta->name
) {
637 return new MySQLField( $meta );
645 * Get column information from a result
647 * @param resource $res Raw result
651 abstract protected function mysqlFetchField( $res, $n );
654 * Get information about an index into an object
655 * Returns false if the index does not exist
657 * @param string $table
658 * @param string $index
659 * @param string $fname
660 * @return bool|array|null False or null on failure
662 public function indexInfo( $table, $index, $fname = __METHOD__
) {
663 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
664 # SHOW INDEX should work for 3.x and up:
665 # https://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
666 $table = $this->tableName( $table );
667 $index = $this->indexName( $index );
669 $sql = 'SHOW INDEX FROM ' . $table;
670 $res = $this->query( $sql, $fname );
678 foreach ( $res as $row ) {
679 if ( $row->Key_name
== $index ) {
684 return $result ?
: false;
691 public function strencode( $s ) {
692 return $this->mysqlRealEscapeString( $s );
699 abstract protected function mysqlRealEscapeString( $s );
701 public function addQuotes( $s ) {
702 if ( is_bool( $s ) ) {
703 // Parent would transform to int, which does not play nice with MySQL type juggling.
704 // When searching for an int in a string column, the strings are cast to int, which
705 // means false would match any string not starting with a number.
706 $s = (string)(int)$s;
708 return parent
::addQuotes( $s );
712 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
717 public function addIdentifierQuotes( $s ) {
718 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
719 // Remove NUL bytes and escape backticks by doubling
720 return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
724 * @param string $name
727 public function isQuotedIdentifier( $name ) {
728 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
731 public function getLag() {
732 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
733 return $this->getLagFromPtHeartbeat();
735 return $this->getLagFromSlaveStatus();
742 protected function getLagDetectionMethod() {
743 return $this->lagDetectionMethod
;
749 protected function getLagFromSlaveStatus() {
750 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
751 $row = $res ?
$res->fetchObject() : false;
752 if ( $row && strval( $row->Seconds_Behind_Master
) !== '' ) {
753 return intval( $row->Seconds_Behind_Master
);
762 protected function getLagFromPtHeartbeat() {
763 $options = $this->lagDetectionOptions
;
765 if ( isset( $options['conds'] ) ) {
766 // Best method for multi-DC setups: use logical channel names
767 $data = $this->getHeartbeatData( $options['conds'] );
769 // Standard method: use master server ID (works with stock pt-heartbeat)
770 $masterInfo = $this->getMasterServerInfo();
771 if ( !$masterInfo ) {
772 $this->queryLogger
->error(
773 "Unable to query master of {db_server} for server ID",
774 $this->getLogContext( [
775 'method' => __METHOD__
779 return false; // could not get master server ID
782 $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
783 $data = $this->getHeartbeatData( $conds );
786 list( $time, $nowUnix ) = $data;
787 if ( $time !== null ) {
788 // @time is in ISO format like "2015-09-25T16:48:10.000510"
789 $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
790 $timeUnix = (int)$dateTime->format( 'U' ) +
$dateTime->format( 'u' ) / 1e6
;
792 return max( $nowUnix - $timeUnix, 0.0 );
795 $this->queryLogger
->error(
796 "Unable to find pt-heartbeat row for {db_server}",
797 $this->getLogContext( [
798 'method' => __METHOD__
805 protected function getMasterServerInfo() {
806 $cache = $this->srvCache
;
807 $key = $cache->makeGlobalKey(
810 // Using one key for all cluster replica DBs is preferable
811 $this->getLBInfo( 'clusterMasterHost' ) ?
: $this->getServer()
814 return $cache->getWithSetCallback(
816 $cache::TTL_INDEFINITE
,
817 function () use ( $cache, $key ) {
818 // Get and leave a lock key in place for a short period
819 if ( !$cache->lock( $key, 0, 10 ) ) {
820 return false; // avoid master connection spike slams
823 $conn = $this->getLazyMasterHandle();
825 return false; // something is misconfigured
828 // Connect to and query the master; catch errors to avoid outages
830 $res = $conn->query( 'SELECT @@server_id AS id', __METHOD__
);
831 $row = $res ?
$res->fetchObject() : false;
832 $id = $row ?
(int)$row->id
: 0;
833 } catch ( DBError
$e ) {
837 // Cache the ID if it was retrieved
838 return $id ?
[ 'serverId' => $id, 'asOf' => time() ] : false;
844 * @param array $conds WHERE clause conditions to find a row
845 * @return array (heartbeat `ts` column value or null, UNIX timestamp) for the newest beat
846 * @see https://www.percona.com/doc/percona-toolkit/2.1/pt-heartbeat.html
848 protected function getHeartbeatData( array $conds ) {
849 // Query time and trip time are not counted
850 $nowUnix = microtime( true );
851 // Do not bother starting implicit transactions here
852 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
854 $whereSQL = $this->makeList( $conds, self
::LIST_AND
);
855 // Use ORDER BY for channel based queries since that field might not be UNIQUE.
856 // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
857 // percision field is not supported in MySQL <= 5.5.
859 "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1"
861 $row = $res ?
$res->fetchObject() : false;
863 $this->restoreFlags();
866 return [ $row ?
$row->ts
: null, $nowUnix ];
869 protected function getApproximateLagStatus() {
870 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
871 // Disable caching since this is fast enough and we don't wan't
872 // to be *too* pessimistic by having both the cache TTL and the
873 // pt-heartbeat interval count as lag in getSessionLagStatus()
874 return parent
::getApproximateLagStatus();
877 $key = $this->srvCache
->makeGlobalKey( 'mysql-lag', $this->getServer() );
878 $approxLag = $this->srvCache
->get( $key );
880 $approxLag = parent
::getApproximateLagStatus();
881 $this->srvCache
->set( $key, $approxLag, 1 );
887 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
888 if ( !( $pos instanceof MySQLMasterPos
) ) {
889 throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
892 if ( $this->getLBInfo( 'is static' ) === true ) {
893 return 0; // this is a copy of a read-only dataset with no master DB
894 } elseif ( $this->lastKnownReplicaPos
&& $this->lastKnownReplicaPos
->hasReached( $pos ) ) {
895 return 0; // already reached this point for sure
898 // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
899 if ( $pos->getGTIDs() ) {
900 // Ignore GTIDs from domains exclusive to the master DB (presumably inactive)
901 $rpos = $this->getReplicaPos();
902 $gtidsWait = $rpos ? MySQLMasterPos
::getCommonDomainGTIDs( $pos, $rpos ) : [];
904 return -1; // $pos is from the wrong cluster?
906 // Wait on the GTID set (MariaDB only)
907 $gtidArg = $this->addQuotes( implode( ',', $gtidsWait ) );
908 if ( strpos( $gtidArg, ':' ) !== false ) {
909 // MySQL GTIDs, e.g "source_id:transaction_id"
910 $res = $this->doQuery( "SELECT WAIT_FOR_EXECUTED_GTID_SET($gtidArg, $timeout)" );
912 // MariaDB GTIDs, e.g."domain:server:sequence"
913 $res = $this->doQuery( "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)" );
916 // Wait on the binlog coordinates
917 $encFile = $this->addQuotes( $pos->getLogFile() );
918 $encPos = intval( $pos->getLogPosition()[$pos::CORD_EVENT
] );
919 $res = $this->doQuery( "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)" );
922 $row = $res ?
$this->fetchRow( $res ) : false;
924 throw new DBExpectedError( $this, "Replication wait failed: {$this->lastError()}" );
927 // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
928 $status = ( $row[0] !== null ) ?
intval( $row[0] ) : null;
929 if ( $status === null ) {
930 if ( !$pos->getGTIDs() ) {
931 // T126436: jobs programmed to wait on master positions might be referencing
932 // binlogs with an old master hostname; this makes MASTER_POS_WAIT() return null.
933 // Try to detect this case and treat the replica DB as having reached the given
934 // position (any master switchover already requires that the new master be caught
935 // up before the switch).
936 $replicationPos = $this->getReplicaPos();
937 if ( $replicationPos && !$replicationPos->channelsMatch( $pos ) ) {
938 $this->lastKnownReplicaPos
= $replicationPos;
942 } elseif ( $status >= 0 ) {
943 // Remember that this position was reached to save queries next time
944 $this->lastKnownReplicaPos
= $pos;
951 * Get the position of the master from SHOW SLAVE STATUS
953 * @return MySQLMasterPos|bool
955 public function getReplicaPos() {
956 $now = microtime( true ); // as-of-time *before* fetching GTID variables
958 if ( $this->useGTIDs() ) {
959 // Try to use GTIDs, fallbacking to binlog positions if not possible
960 $data = $this->getServerGTIDs( __METHOD__
);
961 // Use gtid_current_pos for MariaDB and gtid_executed for MySQL
962 foreach ( [ 'gtid_current_pos', 'gtid_executed' ] as $name ) {
963 if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
964 return new MySQLMasterPos( $data[$name], $now );
969 $data = $this->getServerRoleStatus( 'SLAVE', __METHOD__
);
970 if ( $data && strlen( $data['Relay_Master_Log_File'] ) ) {
971 return new MySQLMasterPos(
972 "{$data['Relay_Master_Log_File']}/{$data['Exec_Master_Log_Pos']}",
981 * Get the position of the master from SHOW MASTER STATUS
983 * @return MySQLMasterPos|bool
985 public function getMasterPos() {
986 $now = microtime( true ); // as-of-time *before* fetching GTID variables
989 if ( $this->useGTIDs() ) {
990 // Try to use GTIDs, fallbacking to binlog positions if not possible
991 $data = $this->getServerGTIDs( __METHOD__
);
992 // Use gtid_current_pos for MariaDB and gtid_executed for MySQL
993 foreach ( [ 'gtid_current_pos', 'gtid_executed' ] as $name ) {
994 if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
995 $pos = new MySQLMasterPos( $data[$name], $now );
999 // Filter domains that are inactive or not relevant to the session
1001 $pos->setActiveOriginServerId( $this->getServerId() );
1002 $pos->setActiveOriginServerUUID( $this->getServerUUID() );
1003 if ( isset( $data['gtid_domain_id'] ) ) {
1004 $pos->setActiveDomain( $data['gtid_domain_id'] );
1010 $data = $this->getServerRoleStatus( 'MASTER', __METHOD__
);
1011 if ( $data && strlen( $data['File'] ) ) {
1012 $pos = new MySQLMasterPos( "{$data['File']}/{$data['Position']}", $now );
1021 * @throws DBQueryError If the variable doesn't exist for some reason
1023 protected function getServerId() {
1024 return $this->srvCache
->getWithSetCallback(
1025 $this->srvCache
->makeGlobalKey( 'mysql-server-id', $this->getServer() ),
1026 self
::SERVER_ID_CACHE_TTL
,
1028 $res = $this->query( "SELECT @@server_id AS id", __METHOD__
);
1029 return intval( $this->fetchObject( $res )->id
);
1035 * @return string|null
1037 protected function getServerUUID() {
1038 return $this->srvCache
->getWithSetCallback(
1039 $this->srvCache
->makeGlobalKey( 'mysql-server-uuid', $this->getServer() ),
1040 self
::SERVER_ID_CACHE_TTL
,
1042 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'server_uuid'" );
1043 $row = $this->fetchObject( $res );
1045 return $row ?
$row->Value
: null;
1051 * @param string $fname
1054 protected function getServerGTIDs( $fname = __METHOD__
) {
1056 // Get global-only variables like gtid_executed
1057 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_%'", $fname );
1058 foreach ( $res as $row ) {
1059 $map[$row->Variable_name
] = $row->Value
;
1061 // Get session-specific (e.g. gtid_domain_id since that is were writes will log)
1062 $res = $this->query( "SHOW SESSION VARIABLES LIKE 'gtid_%'", $fname );
1063 foreach ( $res as $row ) {
1064 $map[$row->Variable_name
] = $row->Value
;
1071 * @param string $role One of "MASTER"/"SLAVE"
1072 * @param string $fname
1073 * @return string[] Latest available server status row
1075 protected function getServerRoleStatus( $role, $fname = __METHOD__
) {
1076 return $this->query( "SHOW $role STATUS", $fname )->fetchRow() ?
: [];
1079 public function serverIsReadOnly() {
1080 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'read_only'", __METHOD__
);
1081 $row = $this->fetchObject( $res );
1083 return $row ?
( strtolower( $row->Value
) === 'on' ) : false;
1087 * @param string $index
1090 function useIndexClause( $index ) {
1091 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
1095 * @param string $index
1098 function ignoreIndexClause( $index ) {
1099 return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
1105 function lowPriorityOption() {
1106 return 'LOW_PRIORITY';
1112 public function getSoftwareLink() {
1113 // MariaDB includes its name in its version string; this is how MariaDB's version of
1114 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
1115 // in libmysql/libmysql.c).
1116 $version = $this->getServerVersion();
1117 if ( strpos( $version, 'MariaDB' ) !== false ||
strpos( $version, '-maria-' ) !== false ) {
1118 return '[{{int:version-db-mariadb-url}} MariaDB]';
1121 // Percona Server's version suffix is not very distinctive, and @@version_comment
1122 // doesn't give the necessary info for source builds, so assume the server is MySQL.
1123 // (Even Percona's version of mysql doesn't try to make the distinction.)
1124 return '[{{int:version-db-mysql-url}} MySQL]';
1130 public function getServerVersion() {
1131 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
1132 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
1133 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
1134 if ( $this->serverVersion
=== null ) {
1135 $this->serverVersion
= $this->selectField( '', 'VERSION()', '', __METHOD__
);
1137 return $this->serverVersion
;
1141 * @param array $options
1143 public function setSessionOptions( array $options ) {
1144 if ( isset( $options['connTimeout'] ) ) {
1145 $timeout = (int)$options['connTimeout'];
1146 $this->query( "SET net_read_timeout=$timeout" );
1147 $this->query( "SET net_write_timeout=$timeout" );
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 ) );
1180 $result = $this->query( "SELECT IS_FREE_LOCK($encName) AS lockstatus", $method );
1181 $row = $this->fetchObject( $result );
1183 return ( $row->lockstatus
== 1 );
1187 * @param string $lockName
1188 * @param string $method
1189 * @param int $timeout
1192 public function lock( $lockName, $method, $timeout = 5 ) {
1193 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1194 $result = $this->query( "SELECT GET_LOCK($encName, $timeout) AS lockstatus", $method );
1195 $row = $this->fetchObject( $result );
1197 if ( $row->lockstatus
== 1 ) {
1198 parent
::lock( $lockName, $method, $timeout ); // record
1202 $this->queryLogger
->info( __METHOD__
. " failed to acquire lock '{lockname}'",
1203 [ 'lockname' => $lockName ] );
1210 * https://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
1211 * @param string $lockName
1212 * @param string $method
1215 public function unlock( $lockName, $method ) {
1216 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1217 $result = $this->query( "SELECT RELEASE_LOCK($encName) as lockstatus", $method );
1218 $row = $this->fetchObject( $result );
1220 if ( $row->lockstatus
== 1 ) {
1221 parent
::unlock( $lockName, $method ); // record
1225 $this->queryLogger
->warning( __METHOD__
. " failed to release lock '$lockName'\n" );
1230 private function makeLockName( $lockName ) {
1231 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1232 // Newer version enforce a 64 char length limit.
1233 return ( strlen( $lockName ) > 64 ) ?
sha1( $lockName ) : $lockName;
1236 public function namedLocksEnqueue() {
1240 public function tableLocksHaveTransactionScope() {
1241 return false; // tied to TCP connection
1244 protected function doLockTables( array $read, array $write, $method ) {
1246 foreach ( $write as $table ) {
1247 $items[] = $this->tableName( $table ) . ' WRITE';
1249 foreach ( $read as $table ) {
1250 $items[] = $this->tableName( $table ) . ' READ';
1253 $sql = "LOCK TABLES " . implode( ',', $items );
1254 $this->query( $sql, $method );
1259 protected function doUnlockTables( $method ) {
1260 $this->query( "UNLOCK TABLES", $method );
1266 * @param bool $value
1268 public function setBigSelects( $value = true ) {
1269 if ( $value === 'default' ) {
1270 if ( $this->defaultBigSelects
=== null ) {
1271 # Function hasn't been called before so it must already be set to the default
1274 $value = $this->defaultBigSelects
;
1276 } elseif ( $this->defaultBigSelects
=== null ) {
1277 $this->defaultBigSelects
=
1278 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__
);
1280 $encValue = $value ?
'1' : '0';
1281 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
1285 * DELETE where the condition is a join. MySql uses multi-table deletes.
1286 * @param string $delTable
1287 * @param string $joinTable
1288 * @param string $delVar
1289 * @param string $joinVar
1290 * @param array|string $conds
1291 * @param bool|string $fname
1292 * @throws DBUnexpectedError
1293 * @return bool|ResultWrapper
1295 public function deleteJoin(
1296 $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
1299 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
1302 $delTable = $this->tableName( $delTable );
1303 $joinTable = $this->tableName( $joinTable );
1304 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1306 if ( $conds != '*' ) {
1307 $sql .= ' AND ' . $this->makeList( $conds, self
::LIST_AND
);
1310 return $this->query( $sql, $fname );
1314 * @param string $table
1315 * @param array $rows
1316 * @param array $uniqueIndexes
1318 * @param string $fname
1321 public function upsert( $table, array $rows, array $uniqueIndexes,
1322 array $set, $fname = __METHOD__
1324 if ( !count( $rows ) ) {
1325 return true; // nothing to do
1328 if ( !is_array( reset( $rows ) ) ) {
1332 $table = $this->tableName( $table );
1333 $columns = array_keys( $rows[0] );
1335 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1337 foreach ( $rows as $row ) {
1338 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1340 $sql .= implode( ',', $rowTuples );
1341 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, self
::LIST_SET
);
1343 return (bool)$this->query( $sql, $fname );
1347 * Determines how long the server has been up
1351 public function getServerUptime() {
1352 $vars = $this->getMysqlStatus( 'Uptime' );
1354 return (int)$vars['Uptime'];
1358 * Determines if the last failure was due to a deadlock
1362 public function wasDeadlock() {
1363 return $this->lastErrno() == 1213;
1367 * Determines if the last failure was due to a lock timeout
1371 public function wasLockTimeout() {
1372 return $this->lastErrno() == 1205;
1376 * Determines if the last failure was due to the database being read-only.
1380 public function wasReadOnlyError() {
1381 return $this->lastErrno() == 1223 ||
1382 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1385 public function wasConnectionError( $errno ) {
1386 return $errno == 2013 ||
$errno == 2006;
1390 * @param string $oldName
1391 * @param string $newName
1392 * @param bool $temporary
1393 * @param string $fname
1396 public function duplicateTableStructure(
1397 $oldName, $newName, $temporary = false, $fname = __METHOD__
1399 $tmp = $temporary ?
'TEMPORARY ' : '';
1400 $newName = $this->addIdentifierQuotes( $newName );
1401 $oldName = $this->addIdentifierQuotes( $oldName );
1402 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1404 return $this->query( $query, $fname );
1408 * List all tables on the database
1410 * @param string $prefix Only show tables with this prefix, e.g. mw_
1411 * @param string $fname Calling function name
1414 public function listTables( $prefix = null, $fname = __METHOD__
) {
1415 $result = $this->query( "SHOW TABLES", $fname );
1419 foreach ( $result as $table ) {
1420 $vars = get_object_vars( $table );
1421 $table = array_pop( $vars );
1423 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1424 $endArray[] = $table;
1432 * @param string $tableName
1433 * @param string $fName
1434 * @return bool|ResultWrapper
1436 public function dropTable( $tableName, $fName = __METHOD__
) {
1437 if ( !$this->tableExists( $tableName, $fName ) ) {
1441 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1445 * Get status information from SHOW STATUS in an associative array
1447 * @param string $which
1450 private function getMysqlStatus( $which = "%" ) {
1451 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1454 foreach ( $res as $row ) {
1455 $status[$row->Variable_name
] = $row->Value
;
1462 * Lists VIEWs in the database
1464 * @param string $prefix Only show VIEWs with this prefix, eg.
1465 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1466 * @param string $fname Name of calling function
1470 public function listViews( $prefix = null, $fname = __METHOD__
) {
1471 // The name of the column containing the name of the VIEW
1472 $propertyName = 'Tables_in_' . $this->dbName
;
1474 // Query for the VIEWS
1475 $res = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1477 foreach ( $res as $row ) {
1478 array_push( $allViews, $row->$propertyName );
1481 if ( is_null( $prefix ) ||
$prefix === '' ) {
1485 $filteredViews = [];
1486 foreach ( $allViews as $viewName ) {
1487 // Does the name of this VIEW start with the table-prefix?
1488 if ( strpos( $viewName, $prefix ) === 0 ) {
1489 array_push( $filteredViews, $viewName );
1493 return $filteredViews;
1497 * Differentiates between a TABLE and a VIEW.
1499 * @param string $name Name of the TABLE/VIEW to test
1500 * @param string $prefix
1504 public function isView( $name, $prefix = null ) {
1505 return in_array( $name, $this->listViews( $prefix ) );
1508 protected function isTransactableQuery( $sql ) {
1509 return parent
::isTransactableQuery( $sql ) &&
1510 !preg_match( '/^SELECT\s+(GET|RELEASE|IS_FREE)_LOCK\(/', $sql );
1514 * @param string $field Field or column to cast
1517 public function buildIntegerCast( $field ) {
1518 return 'CAST( ' . $field . ' AS SIGNED )';
1522 * @return bool Whether GTID support is used (mockable for testing)
1524 protected function useGTIDs() {
1525 return $this->useGTIDs
;
1529 class_alias( DatabaseMysqlBase
::class, 'DatabaseMysqlBase' );