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 use Wikimedia\Rdbms\DBMasterPos
;
24 use Wikimedia\Rdbms\MySQLMasterPos
;
25 use Wikimedia\Rdbms\MySQLField
;
28 * Database abstraction object for MySQL.
29 * Defines methods independent on used MySQL extension.
35 abstract class DatabaseMysqlBase
extends Database
{
36 /** @var MysqlMasterPos */
37 protected $lastKnownReplicaPos;
38 /** @var string Method to detect replica DB lag */
39 protected $lagDetectionMethod;
40 /** @var array Method to detect replica DB lag */
41 protected $lagDetectionOptions = [];
42 /** @var bool bool Whether to use GTID methods */
43 protected $useGTIDs = false;
44 /** @var string|null */
45 protected $sslKeyPath;
46 /** @var string|null */
47 protected $sslCertPath;
48 /** @var string|null */
50 /** @var string[]|null */
51 protected $sslCiphers;
52 /** @var string sql_mode value to send on connection */
54 /** @var bool Use experimental UTF-8 transmission encoding */
57 /** @var string|null */
58 private $serverVersion = null;
61 * Additional $params include:
62 * - lagDetectionMethod : set to one of (Seconds_Behind_Master,pt-heartbeat).
63 * pt-heartbeat assumes the table is at heartbeat.heartbeat
64 * and uses UTC timestamps in the heartbeat.ts column.
65 * (https://www.percona.com/doc/percona-toolkit/2.2/pt-heartbeat.html)
66 * - lagDetectionOptions : if using pt-heartbeat, this can be set to an array map to change
67 * the default behavior. Normally, the heartbeat row with the server
68 * ID of this server's master will be used. Set the "conds" field to
69 * override the query conditions, e.g. ['shard' => 's1'].
70 * - useGTIDs : use GTID methods like MASTER_GTID_WAIT() when possible.
71 * - sslKeyPath : path to key file [default: null]
72 * - sslCertPath : path to certificate file [default: null]
73 * - sslCAPath : parth to certificate authority PEM files [default: null]
74 * - sslCiphers : array list of allowable ciphers [default: null]
75 * @param array $params
77 function __construct( array $params ) {
78 $this->lagDetectionMethod
= isset( $params['lagDetectionMethod'] )
79 ?
$params['lagDetectionMethod']
80 : 'Seconds_Behind_Master';
81 $this->lagDetectionOptions
= isset( $params['lagDetectionOptions'] )
82 ?
$params['lagDetectionOptions']
84 $this->useGTIDs
= !empty( $params['useGTIDs' ] );
85 foreach ( [ 'KeyPath', 'CertPath', 'CAPath', 'Ciphers' ] as $name ) {
87 if ( isset( $params[$var] ) ) {
88 $this->$var = $params[$var];
91 $this->sqlMode
= isset( $params['sqlMode'] ) ?
$params['sqlMode'] : '';
92 $this->utf8Mode
= !empty( $params['utf8Mode'] );
94 parent
::__construct( $params );
100 public function getType() {
105 * @param string $server
106 * @param string $user
107 * @param string $password
108 * @param string $dbName
109 * @throws Exception|DBConnectionError
112 public function open( $server, $user, $password, $dbName ) {
113 # Close/unset connection handle
116 $this->mServer
= $server;
117 $this->mUser
= $user;
118 $this->mPassword
= $password;
119 $this->mDBname
= $dbName;
121 $this->installErrorHandler();
123 $this->mConn
= $this->mysqlConnect( $this->mServer
);
124 } catch ( Exception
$ex ) {
125 $this->restoreErrorHandler();
128 $error = $this->restoreErrorHandler();
130 # Always log connection errors
131 if ( !$this->mConn
) {
133 $error = $this->lastError();
135 $this->connLogger
->error(
136 "Error connecting to {db_server}: {error}",
137 $this->getLogContext( [
138 'method' => __METHOD__
,
142 $this->connLogger
->debug( "DB connection error\n" .
143 "Server: $server, User: $user, Password: " .
144 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
146 $this->reportConnectionError( $error );
149 if ( $dbName != '' ) {
150 MediaWiki\
suppressWarnings();
151 $success = $this->selectDB( $dbName );
152 MediaWiki\restoreWarnings
();
154 $this->queryLogger
->error(
155 "Error selecting database {db_name} on server {db_server}",
156 $this->getLogContext( [
157 'method' => __METHOD__
,
160 $this->queryLogger
->debug(
161 "Error selecting database $dbName on server {$this->mServer}" );
163 $this->reportConnectionError( "Error selecting database $dbName" );
167 // Tell the server what we're communicating with
168 if ( !$this->connectInitCharset() ) {
169 $this->reportConnectionError( "Error setting character set" );
172 // Abstract over any insane MySQL defaults
173 $set = [ 'group_concat_max_len = 262144' ];
174 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
175 if ( is_string( $this->sqlMode
) ) {
176 $set[] = 'sql_mode = ' . $this->addQuotes( $this->sqlMode
);
178 // Set any custom settings defined by site config
179 // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
180 foreach ( $this->mSessionVars
as $var => $val ) {
181 // Escape strings but not numbers to avoid MySQL complaining
182 if ( !is_int( $val ) && !is_float( $val ) ) {
183 $val = $this->addQuotes( $val );
185 $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
189 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
190 $success = $this->doQuery( 'SET ' . implode( ', ', $set ) );
192 $this->queryLogger
->error(
193 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)',
194 $this->getLogContext( [
195 'method' => __METHOD__
,
198 $this->reportConnectionError(
199 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)' );
203 $this->mOpened
= true;
209 * Set the character set information right after connection
212 protected function connectInitCharset() {
213 if ( $this->utf8Mode
) {
214 // Tell the server we're communicating with it in UTF-8.
215 // This may engage various charset conversions.
216 return $this->mysqlSetCharset( 'utf8' );
218 return $this->mysqlSetCharset( 'binary' );
223 * Open a connection to a MySQL server
225 * @param string $realServer
226 * @return mixed Raw connection
227 * @throws DBConnectionError
229 abstract protected function mysqlConnect( $realServer );
232 * Set the character set of the MySQL link
234 * @param string $charset
237 abstract protected function mysqlSetCharset( $charset );
240 * @param ResultWrapper|resource $res
241 * @throws DBUnexpectedError
243 public function freeResult( $res ) {
244 if ( $res instanceof ResultWrapper
) {
247 MediaWiki\
suppressWarnings();
248 $ok = $this->mysqlFreeResult( $res );
249 MediaWiki\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 ResultWrapper|resource $res
265 * @return stdClass|bool
266 * @throws DBUnexpectedError
268 public function fetchObject( $res ) {
269 if ( $res instanceof ResultWrapper
) {
272 MediaWiki\
suppressWarnings();
273 $row = $this->mysqlFetchObject( $res );
274 MediaWiki\restoreWarnings
();
276 $errno = $this->lastErrno();
277 // Unfortunately, mysql_fetch_object does not reset the last errno.
278 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
279 // these are the only errors mysql_fetch_object can cause.
280 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
281 if ( $errno == 2000 ||
$errno == 2013 ) {
282 throw new DBUnexpectedError(
284 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
292 * Fetch a result row as an object
294 * @param resource $res Raw result
297 abstract protected function mysqlFetchObject( $res );
300 * @param ResultWrapper|resource $res
302 * @throws DBUnexpectedError
304 public function fetchRow( $res ) {
305 if ( $res instanceof ResultWrapper
) {
308 MediaWiki\
suppressWarnings();
309 $row = $this->mysqlFetchArray( $res );
310 MediaWiki\restoreWarnings
();
312 $errno = $this->lastErrno();
313 // Unfortunately, mysql_fetch_array does not reset the last errno.
314 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
315 // these are the only errors mysql_fetch_array can cause.
316 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
317 if ( $errno == 2000 ||
$errno == 2013 ) {
318 throw new DBUnexpectedError(
320 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
328 * Fetch a result row as an associative and numeric array
330 * @param resource $res Raw result
333 abstract protected function mysqlFetchArray( $res );
336 * @throws DBUnexpectedError
337 * @param ResultWrapper|resource $res
340 function numRows( $res ) {
341 if ( $res instanceof ResultWrapper
) {
344 MediaWiki\
suppressWarnings();
345 $n = $this->mysqlNumRows( $res );
346 MediaWiki\restoreWarnings
();
348 // Unfortunately, mysql_num_rows does not reset the last errno.
349 // We are not checking for any errors here, since
350 // these are no errors mysql_num_rows can cause.
351 // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
352 // See https://phabricator.wikimedia.org/T44430
357 * Get number of rows in result
359 * @param resource $res Raw result
362 abstract protected function mysqlNumRows( $res );
365 * @param ResultWrapper|resource $res
368 public function numFields( $res ) {
369 if ( $res instanceof ResultWrapper
) {
373 return $this->mysqlNumFields( $res );
377 * Get number of fields in result
379 * @param resource $res Raw result
382 abstract protected function mysqlNumFields( $res );
385 * @param ResultWrapper|resource $res
389 public function fieldName( $res, $n ) {
390 if ( $res instanceof ResultWrapper
) {
394 return $this->mysqlFieldName( $res, $n );
398 * Get the name of the specified field in a result
400 * @param ResultWrapper|resource $res
404 abstract protected function mysqlFieldName( $res, $n );
407 * mysql_field_type() wrapper
408 * @param ResultWrapper|resource $res
412 public function fieldType( $res, $n ) {
413 if ( $res instanceof ResultWrapper
) {
417 return $this->mysqlFieldType( $res, $n );
421 * Get the type of the specified field in a result
423 * @param ResultWrapper|resource $res
427 abstract protected function mysqlFieldType( $res, $n );
430 * @param ResultWrapper|resource $res
434 public function dataSeek( $res, $row ) {
435 if ( $res instanceof ResultWrapper
) {
439 return $this->mysqlDataSeek( $res, $row );
443 * Move internal result pointer
445 * @param ResultWrapper|resource $res
449 abstract protected function mysqlDataSeek( $res, $row );
454 public function lastError() {
455 if ( $this->mConn
) {
456 # Even if it's non-zero, it can still be invalid
457 MediaWiki\
suppressWarnings();
458 $error = $this->mysqlError( $this->mConn
);
460 $error = $this->mysqlError();
462 MediaWiki\restoreWarnings
();
464 $error = $this->mysqlError();
467 $error .= ' (' . $this->mServer
. ')';
474 * Returns the text of the error message from previous MySQL operation
476 * @param resource $conn Raw connection
479 abstract protected function mysqlError( $conn = null );
482 * @param string $table
483 * @param array $uniqueIndexes
485 * @param string $fname
486 * @return ResultWrapper
488 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
489 return $this->nativeReplace( $table, $rows, $fname );
493 * Estimate rows in dataset
494 * Returns estimated count, based on EXPLAIN output
495 * Takes same arguments as Database::select()
497 * @param string|array $table
498 * @param string|array $vars
499 * @param string|array $conds
500 * @param string $fname
501 * @param string|array $options
504 public function estimateRowCount( $table, $vars = '*', $conds = '',
505 $fname = __METHOD__
, $options = []
507 $options['EXPLAIN'] = true;
508 $res = $this->select( $table, $vars, $conds, $fname, $options );
509 if ( $res === false ) {
512 if ( !$this->numRows( $res ) ) {
517 foreach ( $res as $plan ) {
518 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
524 public function tableExists( $table, $fname = __METHOD__
) {
525 $table = $this->tableName( $table, 'raw' );
526 if ( isset( $this->mSessionTempTables
[$table] ) ) {
527 return true; // already known to exist and won't show in SHOW TABLES anyway
530 $encLike = $this->buildLike( $table );
532 return $this->query( "SHOW TABLES $encLike", $fname )->numRows() > 0;
536 * @param string $table
537 * @param string $field
538 * @return bool|MySQLField
540 public function fieldInfo( $table, $field ) {
541 $table = $this->tableName( $table );
542 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
546 $n = $this->mysqlNumFields( $res->result
);
547 for ( $i = 0; $i < $n; $i++
) {
548 $meta = $this->mysqlFetchField( $res->result
, $i );
549 if ( $field == $meta->name
) {
550 return new MySQLField( $meta );
558 * Get column information from a result
560 * @param resource $res Raw result
564 abstract protected function mysqlFetchField( $res, $n );
567 * Get information about an index into an object
568 * Returns false if the index does not exist
570 * @param string $table
571 * @param string $index
572 * @param string $fname
573 * @return bool|array|null False or null on failure
575 public function indexInfo( $table, $index, $fname = __METHOD__
) {
576 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
577 # SHOW INDEX should work for 3.x and up:
578 # https://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
579 $table = $this->tableName( $table );
580 $index = $this->indexName( $index );
582 $sql = 'SHOW INDEX FROM ' . $table;
583 $res = $this->query( $sql, $fname );
591 foreach ( $res as $row ) {
592 if ( $row->Key_name
== $index ) {
597 return empty( $result ) ?
false : $result;
604 public function strencode( $s ) {
605 return $this->mysqlRealEscapeString( $s );
612 abstract protected function mysqlRealEscapeString( $s );
614 public function addQuotes( $s ) {
615 if ( is_bool( $s ) ) {
616 // Parent would transform to int, which does not play nice with MySQL type juggling.
617 // When searching for an int in a string column, the strings are cast to int, which
618 // means false would match any string not starting with a number.
619 $s = (string)(int)$s;
621 return parent
::addQuotes( $s );
625 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
630 public function addIdentifierQuotes( $s ) {
631 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
632 // Remove NUL bytes and escape backticks by doubling
633 return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
637 * @param string $name
640 public function isQuotedIdentifier( $name ) {
641 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
644 public function getLag() {
645 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
646 return $this->getLagFromPtHeartbeat();
648 return $this->getLagFromSlaveStatus();
655 protected function getLagDetectionMethod() {
656 return $this->lagDetectionMethod
;
662 protected function getLagFromSlaveStatus() {
663 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
664 $row = $res ?
$res->fetchObject() : false;
665 if ( $row && strval( $row->Seconds_Behind_Master
) !== '' ) {
666 return intval( $row->Seconds_Behind_Master
);
675 protected function getLagFromPtHeartbeat() {
676 $options = $this->lagDetectionOptions
;
678 if ( isset( $options['conds'] ) ) {
679 // Best method for multi-DC setups: use logical channel names
680 $data = $this->getHeartbeatData( $options['conds'] );
682 // Standard method: use master server ID (works with stock pt-heartbeat)
683 $masterInfo = $this->getMasterServerInfo();
684 if ( !$masterInfo ) {
685 $this->queryLogger
->error(
686 "Unable to query master of {db_server} for server ID",
687 $this->getLogContext( [
688 'method' => __METHOD__
692 return false; // could not get master server ID
695 $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
696 $data = $this->getHeartbeatData( $conds );
699 list( $time, $nowUnix ) = $data;
700 if ( $time !== null ) {
701 // @time is in ISO format like "2015-09-25T16:48:10.000510"
702 $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
703 $timeUnix = (int)$dateTime->format( 'U' ) +
$dateTime->format( 'u' ) / 1e6
;
705 return max( $nowUnix - $timeUnix, 0.0 );
708 $this->queryLogger
->error(
709 "Unable to find pt-heartbeat row for {db_server}",
710 $this->getLogContext( [
711 'method' => __METHOD__
718 protected function getMasterServerInfo() {
719 $cache = $this->srvCache
;
720 $key = $cache->makeGlobalKey(
723 // Using one key for all cluster replica DBs is preferable
724 $this->getLBInfo( 'clusterMasterHost' ) ?
: $this->getServer()
727 return $cache->getWithSetCallback(
729 $cache::TTL_INDEFINITE
,
730 function () use ( $cache, $key ) {
731 // Get and leave a lock key in place for a short period
732 if ( !$cache->lock( $key, 0, 10 ) ) {
733 return false; // avoid master connection spike slams
736 $conn = $this->getLazyMasterHandle();
738 return false; // something is misconfigured
741 // Connect to and query the master; catch errors to avoid outages
743 $res = $conn->query( 'SELECT @@server_id AS id', __METHOD__
);
744 $row = $res ?
$res->fetchObject() : false;
745 $id = $row ?
(int)$row->id
: 0;
746 } catch ( DBError
$e ) {
750 // Cache the ID if it was retrieved
751 return $id ?
[ 'serverId' => $id, 'asOf' => time() ] : false;
757 * @param array $conds WHERE clause conditions to find a row
758 * @return array (heartbeat `ts` column value or null, UNIX timestamp) for the newest beat
759 * @see https://www.percona.com/doc/percona-toolkit/2.1/pt-heartbeat.html
761 protected function getHeartbeatData( array $conds ) {
762 // Do not bother starting implicit transactions here
763 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
765 $whereSQL = $this->makeList( $conds, self
::LIST_AND
);
766 // Use ORDER BY for channel based queries since that field might not be UNIQUE.
767 // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
768 // percision field is not supported in MySQL <= 5.5.
770 "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1"
772 $row = $res ?
$res->fetchObject() : false;
774 $this->restoreFlags();
777 return [ $row ?
$row->ts
: null, microtime( true ) ];
780 protected function getApproximateLagStatus() {
781 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
782 // Disable caching since this is fast enough and we don't wan't
783 // to be *too* pessimistic by having both the cache TTL and the
784 // pt-heartbeat interval count as lag in getSessionLagStatus()
785 return parent
::getApproximateLagStatus();
788 $key = $this->srvCache
->makeGlobalKey( 'mysql-lag', $this->getServer() );
789 $approxLag = $this->srvCache
->get( $key );
791 $approxLag = parent
::getApproximateLagStatus();
792 $this->srvCache
->set( $key, $approxLag, 1 );
798 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
799 if ( !( $pos instanceof MySQLMasterPos
) ) {
800 throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
803 if ( $this->getLBInfo( 'is static' ) === true ) {
804 return 0; // this is a copy of a read-only dataset with no master DB
805 } elseif ( $this->lastKnownReplicaPos
&& $this->lastKnownReplicaPos
->hasReached( $pos ) ) {
806 return 0; // already reached this point for sure
809 // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
810 if ( $this->useGTIDs
&& $pos->gtids
) {
811 // Wait on the GTID set (MariaDB only)
812 $gtidArg = $this->addQuotes( implode( ',', $pos->gtids
) );
813 $res = $this->doQuery( "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)" );
815 // Wait on the binlog coordinates
816 $encFile = $this->addQuotes( $pos->file
);
817 $encPos = intval( $pos->pos
);
818 $res = $this->doQuery( "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)" );
821 $row = $res ?
$this->fetchRow( $res ) : false;
823 throw new DBExpectedError( $this, "Failed to query MASTER_POS_WAIT()" );
826 // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
827 $status = ( $row[0] !== null ) ?
intval( $row[0] ) : null;
828 if ( $status === null ) {
829 // T126436: jobs programmed to wait on master positions might be referencing binlogs
830 // with an old master hostname. Such calls make MASTER_POS_WAIT() return null. Try
831 // to detect this and treat the replica DB as having reached the position; a proper master
832 // switchover already requires that the new master be caught up before the switch.
833 $replicationPos = $this->getReplicaPos();
834 if ( $replicationPos && !$replicationPos->channelsMatch( $pos ) ) {
835 $this->lastKnownReplicaPos
= $replicationPos;
838 } elseif ( $status >= 0 ) {
839 // Remember that this position was reached to save queries next time
840 $this->lastKnownReplicaPos
= $pos;
847 * Get the position of the master from SHOW SLAVE STATUS
849 * @return MySQLMasterPos|bool
851 public function getReplicaPos() {
852 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
853 $row = $this->fetchObject( $res );
856 $pos = isset( $row->Exec_master_log_pos
)
857 ?
$row->Exec_master_log_pos
858 : $row->Exec_Master_Log_Pos
;
859 // Also fetch the last-applied GTID set (MariaDB)
860 if ( $this->useGTIDs
) {
861 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_slave_pos'", __METHOD__
);
862 $gtidRow = $this->fetchObject( $res );
863 $gtidSet = $gtidRow ?
$gtidRow->Value
: '';
868 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos, $gtidSet );
875 * Get the position of the master from SHOW MASTER STATUS
877 * @return MySQLMasterPos|bool
879 public function getMasterPos() {
880 $res = $this->query( 'SHOW MASTER STATUS', __METHOD__
);
881 $row = $this->fetchObject( $res );
884 // Also fetch the last-written GTID set (MariaDB)
885 if ( $this->useGTIDs
) {
886 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_binlog_pos'", __METHOD__
);
887 $gtidRow = $this->fetchObject( $res );
888 $gtidSet = $gtidRow ?
$gtidRow->Value
: '';
893 return new MySQLMasterPos( $row->File
, $row->Position
, $gtidSet );
899 public function serverIsReadOnly() {
900 $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'read_only'", __METHOD__
);
901 $row = $this->fetchObject( $res );
903 return $row ?
( strtolower( $row->Value
) === 'on' ) : false;
907 * @param string $index
910 function useIndexClause( $index ) {
911 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
915 * @param string $index
918 function ignoreIndexClause( $index ) {
919 return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
925 function lowPriorityOption() {
926 return 'LOW_PRIORITY';
932 public function getSoftwareLink() {
933 // MariaDB includes its name in its version string; this is how MariaDB's version of
934 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
935 // in libmysql/libmysql.c).
936 $version = $this->getServerVersion();
937 if ( strpos( $version, 'MariaDB' ) !== false ||
strpos( $version, '-maria-' ) !== false ) {
938 return '[{{int:version-db-mariadb-url}} MariaDB]';
941 // Percona Server's version suffix is not very distinctive, and @@version_comment
942 // doesn't give the necessary info for source builds, so assume the server is MySQL.
943 // (Even Percona's version of mysql doesn't try to make the distinction.)
944 return '[{{int:version-db-mysql-url}} MySQL]';
950 public function getServerVersion() {
951 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
952 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
953 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
954 if ( $this->serverVersion
=== null ) {
955 $this->serverVersion
= $this->selectField( '', 'VERSION()', '', __METHOD__
);
957 return $this->serverVersion
;
961 * @param array $options
963 public function setSessionOptions( array $options ) {
964 if ( isset( $options['connTimeout'] ) ) {
965 $timeout = (int)$options['connTimeout'];
966 $this->query( "SET net_read_timeout=$timeout" );
967 $this->query( "SET net_write_timeout=$timeout" );
973 * @param string $newLine
976 public function streamStatementEnd( &$sql, &$newLine ) {
977 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
978 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
979 $this->delimiter
= $m[1];
983 return parent
::streamStatementEnd( $sql, $newLine );
987 * Check to see if a named lock is available. This is non-blocking.
989 * @param string $lockName Name of lock to poll
990 * @param string $method Name of method calling us
994 public function lockIsFree( $lockName, $method ) {
995 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
996 $result = $this->query( "SELECT IS_FREE_LOCK($encName) AS lockstatus", $method );
997 $row = $this->fetchObject( $result );
999 return ( $row->lockstatus
== 1 );
1003 * @param string $lockName
1004 * @param string $method
1005 * @param int $timeout
1008 public function lock( $lockName, $method, $timeout = 5 ) {
1009 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1010 $result = $this->query( "SELECT GET_LOCK($encName, $timeout) AS lockstatus", $method );
1011 $row = $this->fetchObject( $result );
1013 if ( $row->lockstatus
== 1 ) {
1014 parent
::lock( $lockName, $method, $timeout ); // record
1018 $this->queryLogger
->warning( __METHOD__
. " failed to acquire lock '$lockName'\n" );
1025 * https://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
1026 * @param string $lockName
1027 * @param string $method
1030 public function unlock( $lockName, $method ) {
1031 $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
1032 $result = $this->query( "SELECT RELEASE_LOCK($encName) as lockstatus", $method );
1033 $row = $this->fetchObject( $result );
1035 if ( $row->lockstatus
== 1 ) {
1036 parent
::unlock( $lockName, $method ); // record
1040 $this->queryLogger
->warning( __METHOD__
. " failed to release lock '$lockName'\n" );
1045 private function makeLockName( $lockName ) {
1046 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1047 // Newer version enforce a 64 char length limit.
1048 return ( strlen( $lockName ) > 64 ) ?
sha1( $lockName ) : $lockName;
1051 public function namedLocksEnqueue() {
1056 * @param array $read
1057 * @param array $write
1058 * @param string $method
1059 * @param bool $lowPriority
1062 public function lockTables( $read, $write, $method, $lowPriority = true ) {
1065 foreach ( $write as $table ) {
1066 $tbl = $this->tableName( $table ) .
1067 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
1071 foreach ( $read as $table ) {
1072 $items[] = $this->tableName( $table ) . ' READ';
1074 $sql = "LOCK TABLES " . implode( ',', $items );
1075 $this->query( $sql, $method );
1081 * @param string $method
1084 public function unlockTables( $method ) {
1085 $this->query( "UNLOCK TABLES", $method );
1091 * @param bool $value
1093 public function setBigSelects( $value = true ) {
1094 if ( $value === 'default' ) {
1095 if ( $this->mDefaultBigSelects
=== null ) {
1096 # Function hasn't been called before so it must already be set to the default
1099 $value = $this->mDefaultBigSelects
;
1101 } elseif ( $this->mDefaultBigSelects
=== null ) {
1102 $this->mDefaultBigSelects
=
1103 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__
);
1105 $encValue = $value ?
'1' : '0';
1106 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
1110 * DELETE where the condition is a join. MySql uses multi-table deletes.
1111 * @param string $delTable
1112 * @param string $joinTable
1113 * @param string $delVar
1114 * @param string $joinVar
1115 * @param array|string $conds
1116 * @param bool|string $fname
1117 * @throws DBUnexpectedError
1118 * @return bool|ResultWrapper
1120 public function deleteJoin(
1121 $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
1124 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
1127 $delTable = $this->tableName( $delTable );
1128 $joinTable = $this->tableName( $joinTable );
1129 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1131 if ( $conds != '*' ) {
1132 $sql .= ' AND ' . $this->makeList( $conds, self
::LIST_AND
);
1135 return $this->query( $sql, $fname );
1139 * @param string $table
1140 * @param array $rows
1141 * @param array $uniqueIndexes
1143 * @param string $fname
1146 public function upsert( $table, array $rows, array $uniqueIndexes,
1147 array $set, $fname = __METHOD__
1149 if ( !count( $rows ) ) {
1150 return true; // nothing to do
1153 if ( !is_array( reset( $rows ) ) ) {
1157 $table = $this->tableName( $table );
1158 $columns = array_keys( $rows[0] );
1160 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1162 foreach ( $rows as $row ) {
1163 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1165 $sql .= implode( ',', $rowTuples );
1166 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, self
::LIST_SET
);
1168 return (bool)$this->query( $sql, $fname );
1172 * Determines how long the server has been up
1176 public function getServerUptime() {
1177 $vars = $this->getMysqlStatus( 'Uptime' );
1179 return (int)$vars['Uptime'];
1183 * Determines if the last failure was due to a deadlock
1187 public function wasDeadlock() {
1188 return $this->lastErrno() == 1213;
1192 * Determines if the last failure was due to a lock timeout
1196 public function wasLockTimeout() {
1197 return $this->lastErrno() == 1205;
1200 public function wasErrorReissuable() {
1201 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
1205 * Determines if the last failure was due to the database being read-only.
1209 public function wasReadOnlyError() {
1210 return $this->lastErrno() == 1223 ||
1211 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1214 public function wasConnectionError( $errno ) {
1215 return $errno == 2013 ||
$errno == 2006;
1219 * @param string $oldName
1220 * @param string $newName
1221 * @param bool $temporary
1222 * @param string $fname
1225 public function duplicateTableStructure(
1226 $oldName, $newName, $temporary = false, $fname = __METHOD__
1228 $tmp = $temporary ?
'TEMPORARY ' : '';
1229 $newName = $this->addIdentifierQuotes( $newName );
1230 $oldName = $this->addIdentifierQuotes( $oldName );
1231 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1233 return $this->query( $query, $fname );
1237 * List all tables on the database
1239 * @param string $prefix Only show tables with this prefix, e.g. mw_
1240 * @param string $fname Calling function name
1243 public function listTables( $prefix = null, $fname = __METHOD__
) {
1244 $result = $this->query( "SHOW TABLES", $fname );
1248 foreach ( $result as $table ) {
1249 $vars = get_object_vars( $table );
1250 $table = array_pop( $vars );
1252 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1253 $endArray[] = $table;
1261 * @param string $tableName
1262 * @param string $fName
1263 * @return bool|ResultWrapper
1265 public function dropTable( $tableName, $fName = __METHOD__
) {
1266 if ( !$this->tableExists( $tableName, $fName ) ) {
1270 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1274 * Get status information from SHOW STATUS in an associative array
1276 * @param string $which
1279 private function getMysqlStatus( $which = "%" ) {
1280 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1283 foreach ( $res as $row ) {
1284 $status[$row->Variable_name
] = $row->Value
;
1291 * Lists VIEWs in the database
1293 * @param string $prefix Only show VIEWs with this prefix, eg.
1294 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1295 * @param string $fname Name of calling function
1299 public function listViews( $prefix = null, $fname = __METHOD__
) {
1300 // The name of the column containing the name of the VIEW
1301 $propertyName = 'Tables_in_' . $this->mDBname
;
1303 // Query for the VIEWS
1304 $res = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1306 foreach ( $res as $row ) {
1307 array_push( $allViews, $row->$propertyName );
1310 if ( is_null( $prefix ) ||
$prefix === '' ) {
1314 $filteredViews = [];
1315 foreach ( $allViews as $viewName ) {
1316 // Does the name of this VIEW start with the table-prefix?
1317 if ( strpos( $viewName, $prefix ) === 0 ) {
1318 array_push( $filteredViews, $viewName );
1322 return $filteredViews;
1326 * Differentiates between a TABLE and a VIEW.
1328 * @param string $name Name of the TABLE/VIEW to test
1329 * @param string $prefix
1333 public function isView( $name, $prefix = null ) {
1334 return in_array( $name, $this->listViews( $prefix ) );