wfMsgForContentNoTrans() was removed
[mediawiki.git] / includes / db / DatabaseMysqlBase.php
blob5bcfd66d0ceeb69fe2d0692815b348391cf6a8d3
1 <?php
2 /**
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
20 * @file
21 * @ingroup Database
24 /**
25 * Database abstraction object for MySQL.
26 * Defines methods independent on used MySQL extension.
28 * @ingroup Database
29 * @since 1.22
30 * @see Database
32 abstract class DatabaseMysqlBase extends Database {
33 /** @var MysqlMasterPos */
34 protected $lastKnownSlavePos;
35 /** @var string Method to detect slave lag */
36 protected $lagDetectionMethod;
38 /** @var string|null */
39 private $serverVersion = null;
41 /**
42 * Additional $params include:
43 * - lagDetectionMethod : set to one of (Seconds_Behind_Master,pt-heartbeat).
44 * pt-heartbeat assumes the table is at heartbeat.heartbeat
45 * and uses UTC timestamps in the heartbeat.ts column.
46 * (https://www.percona.com/doc/percona-toolkit/2.2/pt-heartbeat.html)
47 * @param array $params
49 function __construct( array $params ) {
50 parent::__construct( $params );
52 $this->lagDetectionMethod = isset( $params['lagDetectionMethod'] )
53 ? $params['lagDetectionMethod']
54 : 'Seconds_Behind_Master';
57 /**
58 * @return string
60 function getType() {
61 return 'mysql';
64 /**
65 * @param string $server
66 * @param string $user
67 * @param string $password
68 * @param string $dbName
69 * @throws Exception|DBConnectionError
70 * @return bool
72 function open( $server, $user, $password, $dbName ) {
73 global $wgAllDBsAreLocalhost, $wgSQLMode;
75 # Close/unset connection handle
76 $this->close();
78 # Debugging hack -- fake cluster
79 $realServer = $wgAllDBsAreLocalhost ? 'localhost' : $server;
80 $this->mServer = $server;
81 $this->mUser = $user;
82 $this->mPassword = $password;
83 $this->mDBname = $dbName;
85 $this->installErrorHandler();
86 try {
87 $this->mConn = $this->mysqlConnect( $realServer );
88 } catch ( Exception $ex ) {
89 $this->restoreErrorHandler();
90 throw $ex;
92 $error = $this->restoreErrorHandler();
94 # Always log connection errors
95 if ( !$this->mConn ) {
96 if ( !$error ) {
97 $error = $this->lastError();
99 wfLogDBError(
100 "Error connecting to {db_server}: {error}",
101 $this->getLogContext( array(
102 'method' => __METHOD__,
103 'error' => $error,
106 wfDebug( "DB connection error\n" .
107 "Server: $server, User: $user, Password: " .
108 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
110 $this->reportConnectionError( $error );
113 if ( $dbName != '' ) {
114 MediaWiki\suppressWarnings();
115 $success = $this->selectDB( $dbName );
116 MediaWiki\restoreWarnings();
117 if ( !$success ) {
118 wfLogDBError(
119 "Error selecting database {db_name} on server {db_server}",
120 $this->getLogContext( array(
121 'method' => __METHOD__,
124 wfDebug( "Error selecting database $dbName on server {$this->mServer} " .
125 "from client host " . wfHostname() . "\n" );
127 $this->reportConnectionError( "Error selecting database $dbName" );
131 // Tell the server what we're communicating with
132 if ( !$this->connectInitCharset() ) {
133 $this->reportConnectionError( "Error setting character set" );
136 // Abstract over any insane MySQL defaults
137 $set = array( 'group_concat_max_len = 262144' );
138 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
139 if ( is_string( $wgSQLMode ) ) {
140 $set[] = 'sql_mode = ' . $this->addQuotes( $wgSQLMode );
142 // Set any custom settings defined by site config
143 // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
144 foreach ( $this->mSessionVars as $var => $val ) {
145 // Escape strings but not numbers to avoid MySQL complaining
146 if ( !is_int( $val ) && !is_float( $val ) ) {
147 $val = $this->addQuotes( $val );
149 $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
152 if ( $set ) {
153 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
154 $success = $this->doQuery( 'SET ' . implode( ', ', $set ) );
155 if ( !$success ) {
156 wfLogDBError(
157 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)',
158 $this->getLogContext( array(
159 'method' => __METHOD__,
162 $this->reportConnectionError(
163 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)' );
167 $this->mOpened = true;
169 return true;
173 * Set the character set information right after connection
174 * @return bool
176 protected function connectInitCharset() {
177 global $wgDBmysql5;
179 if ( $wgDBmysql5 ) {
180 // Tell the server we're communicating with it in UTF-8.
181 // This may engage various charset conversions.
182 return $this->mysqlSetCharset( 'utf8' );
183 } else {
184 return $this->mysqlSetCharset( 'binary' );
189 * Open a connection to a MySQL server
191 * @param string $realServer
192 * @return mixed Raw connection
193 * @throws DBConnectionError
195 abstract protected function mysqlConnect( $realServer );
198 * Set the character set of the MySQL link
200 * @param string $charset
201 * @return bool
203 abstract protected function mysqlSetCharset( $charset );
206 * @param ResultWrapper|resource $res
207 * @throws DBUnexpectedError
209 function freeResult( $res ) {
210 if ( $res instanceof ResultWrapper ) {
211 $res = $res->result;
213 MediaWiki\suppressWarnings();
214 $ok = $this->mysqlFreeResult( $res );
215 MediaWiki\restoreWarnings();
216 if ( !$ok ) {
217 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
222 * Free result memory
224 * @param resource $res Raw result
225 * @return bool
227 abstract protected function mysqlFreeResult( $res );
230 * @param ResultWrapper|resource $res
231 * @return stdClass|bool
232 * @throws DBUnexpectedError
234 function fetchObject( $res ) {
235 if ( $res instanceof ResultWrapper ) {
236 $res = $res->result;
238 MediaWiki\suppressWarnings();
239 $row = $this->mysqlFetchObject( $res );
240 MediaWiki\restoreWarnings();
242 $errno = $this->lastErrno();
243 // Unfortunately, mysql_fetch_object does not reset the last errno.
244 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
245 // these are the only errors mysql_fetch_object can cause.
246 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
247 if ( $errno == 2000 || $errno == 2013 ) {
248 throw new DBUnexpectedError(
249 $this,
250 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
254 return $row;
258 * Fetch a result row as an object
260 * @param resource $res Raw result
261 * @return stdClass
263 abstract protected function mysqlFetchObject( $res );
266 * @param ResultWrapper|resource $res
267 * @return array|bool
268 * @throws DBUnexpectedError
270 function fetchRow( $res ) {
271 if ( $res instanceof ResultWrapper ) {
272 $res = $res->result;
274 MediaWiki\suppressWarnings();
275 $row = $this->mysqlFetchArray( $res );
276 MediaWiki\restoreWarnings();
278 $errno = $this->lastErrno();
279 // Unfortunately, mysql_fetch_array does not reset the last errno.
280 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
281 // these are the only errors mysql_fetch_array can cause.
282 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
283 if ( $errno == 2000 || $errno == 2013 ) {
284 throw new DBUnexpectedError(
285 $this,
286 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
290 return $row;
294 * Fetch a result row as an associative and numeric array
296 * @param resource $res Raw result
297 * @return array
299 abstract protected function mysqlFetchArray( $res );
302 * @throws DBUnexpectedError
303 * @param ResultWrapper|resource $res
304 * @return int
306 function numRows( $res ) {
307 if ( $res instanceof ResultWrapper ) {
308 $res = $res->result;
310 MediaWiki\suppressWarnings();
311 $n = $this->mysqlNumRows( $res );
312 MediaWiki\restoreWarnings();
314 // Unfortunately, mysql_num_rows does not reset the last errno.
315 // We are not checking for any errors here, since
316 // these are no errors mysql_num_rows can cause.
317 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
318 // See https://phabricator.wikimedia.org/T44430
319 return $n;
323 * Get number of rows in result
325 * @param resource $res Raw result
326 * @return int
328 abstract protected function mysqlNumRows( $res );
331 * @param ResultWrapper|resource $res
332 * @return int
334 function numFields( $res ) {
335 if ( $res instanceof ResultWrapper ) {
336 $res = $res->result;
339 return $this->mysqlNumFields( $res );
343 * Get number of fields in result
345 * @param resource $res Raw result
346 * @return int
348 abstract protected function mysqlNumFields( $res );
351 * @param ResultWrapper|resource $res
352 * @param int $n
353 * @return string
355 function fieldName( $res, $n ) {
356 if ( $res instanceof ResultWrapper ) {
357 $res = $res->result;
360 return $this->mysqlFieldName( $res, $n );
364 * Get the name of the specified field in a result
366 * @param ResultWrapper|resource $res
367 * @param int $n
368 * @return string
370 abstract protected function mysqlFieldName( $res, $n );
373 * mysql_field_type() wrapper
374 * @param ResultWrapper|resource $res
375 * @param int $n
376 * @return string
378 public function fieldType( $res, $n ) {
379 if ( $res instanceof ResultWrapper ) {
380 $res = $res->result;
383 return $this->mysqlFieldType( $res, $n );
387 * Get the type of the specified field in a result
389 * @param ResultWrapper|resource $res
390 * @param int $n
391 * @return string
393 abstract protected function mysqlFieldType( $res, $n );
396 * @param ResultWrapper|resource $res
397 * @param int $row
398 * @return bool
400 function dataSeek( $res, $row ) {
401 if ( $res instanceof ResultWrapper ) {
402 $res = $res->result;
405 return $this->mysqlDataSeek( $res, $row );
409 * Move internal result pointer
411 * @param ResultWrapper|resource $res
412 * @param int $row
413 * @return bool
415 abstract protected function mysqlDataSeek( $res, $row );
418 * @return string
420 function lastError() {
421 if ( $this->mConn ) {
422 # Even if it's non-zero, it can still be invalid
423 MediaWiki\suppressWarnings();
424 $error = $this->mysqlError( $this->mConn );
425 if ( !$error ) {
426 $error = $this->mysqlError();
428 MediaWiki\restoreWarnings();
429 } else {
430 $error = $this->mysqlError();
432 if ( $error ) {
433 $error .= ' (' . $this->mServer . ')';
436 return $error;
440 * Returns the text of the error message from previous MySQL operation
442 * @param resource $conn Raw connection
443 * @return string
445 abstract protected function mysqlError( $conn = null );
448 * @param string $table
449 * @param array $uniqueIndexes
450 * @param array $rows
451 * @param string $fname
452 * @return ResultWrapper
454 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
455 return $this->nativeReplace( $table, $rows, $fname );
459 * Estimate rows in dataset
460 * Returns estimated count, based on EXPLAIN output
461 * Takes same arguments as Database::select()
463 * @param string|array $table
464 * @param string|array $vars
465 * @param string|array $conds
466 * @param string $fname
467 * @param string|array $options
468 * @return bool|int
470 public function estimateRowCount( $table, $vars = '*', $conds = '',
471 $fname = __METHOD__, $options = array()
473 $options['EXPLAIN'] = true;
474 $res = $this->select( $table, $vars, $conds, $fname, $options );
475 if ( $res === false ) {
476 return false;
478 if ( !$this->numRows( $res ) ) {
479 return 0;
482 $rows = 1;
483 foreach ( $res as $plan ) {
484 $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
487 return (int)$rows;
491 * @param string $table
492 * @param string $field
493 * @return bool|MySQLField
495 function fieldInfo( $table, $field ) {
496 $table = $this->tableName( $table );
497 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__, true );
498 if ( !$res ) {
499 return false;
501 $n = $this->mysqlNumFields( $res->result );
502 for ( $i = 0; $i < $n; $i++ ) {
503 $meta = $this->mysqlFetchField( $res->result, $i );
504 if ( $field == $meta->name ) {
505 return new MySQLField( $meta );
509 return false;
513 * Get column information from a result
515 * @param resource $res Raw result
516 * @param int $n
517 * @return stdClass
519 abstract protected function mysqlFetchField( $res, $n );
522 * Get information about an index into an object
523 * Returns false if the index does not exist
525 * @param string $table
526 * @param string $index
527 * @param string $fname
528 * @return bool|array|null False or null on failure
530 function indexInfo( $table, $index, $fname = __METHOD__ ) {
531 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
532 # SHOW INDEX should work for 3.x and up:
533 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
534 $table = $this->tableName( $table );
535 $index = $this->indexName( $index );
537 $sql = 'SHOW INDEX FROM ' . $table;
538 $res = $this->query( $sql, $fname );
540 if ( !$res ) {
541 return null;
544 $result = array();
546 foreach ( $res as $row ) {
547 if ( $row->Key_name == $index ) {
548 $result[] = $row;
552 return empty( $result ) ? false : $result;
556 * @param string $s
557 * @return string
559 function strencode( $s ) {
560 $sQuoted = $this->mysqlRealEscapeString( $s );
562 if ( $sQuoted === false ) {
563 $this->ping();
564 $sQuoted = $this->mysqlRealEscapeString( $s );
567 return $sQuoted;
571 * @param string $s
572 * @return mixed
574 abstract protected function mysqlRealEscapeString( $s );
577 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
579 * @param string $s
580 * @return string
582 public function addIdentifierQuotes( $s ) {
583 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
584 // Remove NUL bytes and escape backticks by doubling
585 return '`' . str_replace( array( "\0", '`' ), array( '', '``' ), $s ) . '`';
589 * @param string $name
590 * @return bool
592 public function isQuotedIdentifier( $name ) {
593 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
597 * @return bool
599 function ping() {
600 $ping = $this->mysqlPing();
601 if ( $ping ) {
602 // Connection was good or lost but reconnected...
603 // @note: mysqlnd (php 5.6+) does not support this (PHP bug 52561)
604 return true;
607 // Try a full disconnect/reconnect cycle if ping() failed
608 $this->closeConnection();
609 $this->mOpened = false;
610 $this->mConn = false;
611 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
613 return true;
617 * Ping a server connection or reconnect if there is no connection
619 * @return bool
621 abstract protected function mysqlPing();
623 function getLag() {
624 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
625 return $this->getLagFromPtHeartbeat();
626 } else {
627 return $this->getLagFromSlaveStatus();
632 * @return string
634 protected function getLagDetectionMethod() {
635 return $this->lagDetectionMethod;
639 * @return bool|int
641 protected function getLagFromSlaveStatus() {
642 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
643 $row = $res ? $res->fetchObject() : false;
644 if ( $row && strval( $row->Seconds_Behind_Master ) !== '' ) {
645 return intval( $row->Seconds_Behind_Master );
648 return false;
652 * @return bool|float
654 protected function getLagFromPtHeartbeat() {
655 $masterInfo = $this->getMasterServerInfo();
656 if ( !$masterInfo ) {
657 return false; // could not get master server ID
660 list( $time, $nowUnix ) = $this->getHeartbeatData( $masterInfo['serverId'] );
661 if ( $time !== null ) {
662 // @time is in ISO format like "2015-09-25T16:48:10.000510"
663 $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
664 $timeUnix = (int)$dateTime->format( 'U' ) + $dateTime->format( 'u' ) / 1e6;
666 return max( $nowUnix - $timeUnix, 0.0 );
669 return false;
672 protected function getMasterServerInfo() {
673 $cache = $this->srvCache;
674 $key = $cache->makeGlobalKey(
675 'mysql',
676 'master-info',
677 // Using one key for all cluster slaves is preferable
678 $this->getLBInfo( 'clusterMasterHost' ) ?: $this->getServer()
681 $that = $this;
682 return $cache->getWithSetCallback(
683 $key,
684 $cache::TTL_INDEFINITE,
685 function () use ( $that, $cache, $key ) {
686 // Get and leave a lock key in place for a short period
687 if ( !$cache->lock( $key, 0, 10 ) ) {
688 return false; // avoid master connection spike slams
691 $conn = $that->getLazyMasterHandle();
692 if ( !$conn ) {
693 return false; // something is misconfigured
696 // Connect to and query the master; catch errors to avoid outages
697 try {
698 $res = $conn->query( 'SELECT @@server_id AS id', __METHOD__ );
699 $row = $res ? $res->fetchObject() : false;
700 $id = $row ? (int)$row->id : 0;
701 } catch ( DBError $e ) {
702 $id = 0;
705 // Cache the ID if it was retrieved
706 return $id ? array( 'serverId' => $id, 'asOf' => time() ) : false;
712 * @param string $masterId Server ID
713 * @return array (heartbeat `ts` column value or null, UNIX timestamp)
714 * @see https://www.percona.com/doc/percona-toolkit/2.1/pt-heartbeat.html
716 protected function getHeartbeatData( $masterId ) {
717 // Get the status row for this master; use the oldest for sanity in case the master
718 // has entries listed under different server IDs (which should really not happen).
719 // Note: this would use "MAX(TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6)))" but the
720 // percision field is not supported in MySQL <= 5.5.
721 $res = $this->query(
722 "SELECT ts FROM heartbeat.heartbeat WHERE server_id=" . intval( $masterId )
724 $row = $res ? $res->fetchObject() : false;
726 return array( $row ? $row->ts : null, microtime( true ) );
729 public function getApproximateLagStatus() {
730 if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
731 // Disable caching since this is fast enough and we don't wan't
732 // to be *too* pessimistic by having both the cache TTL and the
733 // pt-heartbeat interval count as lag in getSessionLagStatus()
734 return parent::getApproximateLagStatus();
737 $key = $this->srvCache->makeGlobalKey( 'mysql-lag', $this->getServer() );
738 $approxLag = $this->srvCache->get( $key );
739 if ( !$approxLag ) {
740 $approxLag = parent::getApproximateLagStatus();
741 $this->srvCache->set( $key, $approxLag, 1 );
744 return $approxLag;
748 * Wait for the slave to catch up to a given master position.
749 * @todo Return values for this and base class are rubbish
751 * @param DBMasterPos|MySQLMasterPos $pos
752 * @param int $timeout The maximum number of seconds to wait for synchronisation
753 * @return int Zero if the slave was past that position already,
754 * greater than zero if we waited for some period of time, less than
755 * zero if we timed out.
757 function masterPosWait( DBMasterPos $pos, $timeout ) {
758 if ( $this->lastKnownSlavePos && $this->lastKnownSlavePos->hasReached( $pos ) ) {
759 return '0'; // http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html
762 # Commit any open transactions
763 $this->commit( __METHOD__, 'flush' );
765 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
766 $encFile = $this->addQuotes( $pos->file );
767 $encPos = intval( $pos->pos );
768 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
769 $res = $this->doQuery( $sql );
771 $status = false;
772 if ( $res ) {
773 $row = $this->fetchRow( $res );
774 if ( $row ) {
775 $status = $row[0]; // can be NULL, -1, or 0+ per the MySQL manual
776 if ( ctype_digit( $status ) ) { // success
777 $this->lastKnownSlavePos = $pos;
782 return $status;
786 * Get the position of the master from SHOW SLAVE STATUS
788 * @return MySQLMasterPos|bool
790 function getSlavePos() {
791 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
792 $row = $this->fetchObject( $res );
794 if ( $row ) {
795 $pos = isset( $row->Exec_master_log_pos )
796 ? $row->Exec_master_log_pos
797 : $row->Exec_Master_Log_Pos;
799 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
800 } else {
801 return false;
806 * Get the position of the master from SHOW MASTER STATUS
808 * @return MySQLMasterPos|bool
810 function getMasterPos() {
811 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
812 $row = $this->fetchObject( $res );
814 if ( $row ) {
815 return new MySQLMasterPos( $row->File, $row->Position );
816 } else {
817 return false;
822 * @param string $index
823 * @return string
825 function useIndexClause( $index ) {
826 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
830 * @return string
832 function lowPriorityOption() {
833 return 'LOW_PRIORITY';
837 * @return string
839 public function getSoftwareLink() {
840 // MariaDB includes its name in its version string; this is how MariaDB's version of
841 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
842 // in libmysql/libmysql.c).
843 $version = $this->getServerVersion();
844 if ( strpos( $version, 'MariaDB' ) !== false || strpos( $version, '-maria-' ) !== false ) {
845 return '[{{int:version-db-mariadb-url}} MariaDB]';
848 // Percona Server's version suffix is not very distinctive, and @@version_comment
849 // doesn't give the necessary info for source builds, so assume the server is MySQL.
850 // (Even Percona's version of mysql doesn't try to make the distinction.)
851 return '[{{int:version-db-mysql-url}} MySQL]';
855 * @return string
857 public function getServerVersion() {
858 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
859 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
860 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
861 if ( $this->serverVersion === null ) {
862 $this->serverVersion = $this->selectField( '', 'VERSION()', '', __METHOD__ );
864 return $this->serverVersion;
868 * @param array $options
870 public function setSessionOptions( array $options ) {
871 if ( isset( $options['connTimeout'] ) ) {
872 $timeout = (int)$options['connTimeout'];
873 $this->query( "SET net_read_timeout=$timeout" );
874 $this->query( "SET net_write_timeout=$timeout" );
879 * @param string $sql
880 * @param string $newLine
881 * @return bool
883 public function streamStatementEnd( &$sql, &$newLine ) {
884 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
885 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
886 $this->delimiter = $m[1];
887 $newLine = '';
890 return parent::streamStatementEnd( $sql, $newLine );
894 * Check to see if a named lock is available. This is non-blocking.
896 * @param string $lockName Name of lock to poll
897 * @param string $method Name of method calling us
898 * @return bool
899 * @since 1.20
901 public function lockIsFree( $lockName, $method ) {
902 $lockName = $this->addQuotes( $this->makeLockName( $lockName ) );
903 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
904 $row = $this->fetchObject( $result );
906 return ( $row->lockstatus == 1 );
910 * @param string $lockName
911 * @param string $method
912 * @param int $timeout
913 * @return bool
915 public function lock( $lockName, $method, $timeout = 5 ) {
916 $lockName = $this->addQuotes( $this->makeLockName( $lockName ) );
917 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
918 $row = $this->fetchObject( $result );
920 if ( $row->lockstatus == 1 ) {
921 return true;
922 } else {
923 wfDebug( __METHOD__ . " failed to acquire lock\n" );
925 return false;
930 * FROM MYSQL DOCS:
931 * http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
932 * @param string $lockName
933 * @param string $method
934 * @return bool
936 public function unlock( $lockName, $method ) {
937 $lockName = $this->addQuotes( $this->makeLockName( $lockName ) );
938 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
939 $row = $this->fetchObject( $result );
941 return ( $row->lockstatus == 1 );
944 private function makeLockName( $lockName ) {
945 // http://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
946 // Newer version enforce a 64 char length limit.
947 return ( strlen( $lockName ) > 64 ) ? sha1( $lockName ) : $lockName;
950 public function namedLocksEnqueue() {
951 return true;
955 * @param array $read
956 * @param array $write
957 * @param string $method
958 * @param bool $lowPriority
959 * @return bool
961 public function lockTables( $read, $write, $method, $lowPriority = true ) {
962 $items = array();
964 foreach ( $write as $table ) {
965 $tbl = $this->tableName( $table ) .
966 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
967 ' WRITE';
968 $items[] = $tbl;
970 foreach ( $read as $table ) {
971 $items[] = $this->tableName( $table ) . ' READ';
973 $sql = "LOCK TABLES " . implode( ',', $items );
974 $this->query( $sql, $method );
976 return true;
980 * @param string $method
981 * @return bool
983 public function unlockTables( $method ) {
984 $this->query( "UNLOCK TABLES", $method );
986 return true;
990 * Get search engine class. All subclasses of this
991 * need to implement this if they wish to use searching.
993 * @return string
995 public function getSearchEngine() {
996 return 'SearchMySQL';
1000 * @param bool $value
1002 public function setBigSelects( $value = true ) {
1003 if ( $value === 'default' ) {
1004 if ( $this->mDefaultBigSelects === null ) {
1005 # Function hasn't been called before so it must already be set to the default
1006 return;
1007 } else {
1008 $value = $this->mDefaultBigSelects;
1010 } elseif ( $this->mDefaultBigSelects === null ) {
1011 $this->mDefaultBigSelects =
1012 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__ );
1014 $encValue = $value ? '1' : '0';
1015 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
1019 * DELETE where the condition is a join. MySql uses multi-table deletes.
1020 * @param string $delTable
1021 * @param string $joinTable
1022 * @param string $delVar
1023 * @param string $joinVar
1024 * @param array|string $conds
1025 * @param bool|string $fname
1026 * @throws DBUnexpectedError
1027 * @return bool|ResultWrapper
1029 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__ ) {
1030 if ( !$conds ) {
1031 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
1034 $delTable = $this->tableName( $delTable );
1035 $joinTable = $this->tableName( $joinTable );
1036 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1038 if ( $conds != '*' ) {
1039 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1042 return $this->query( $sql, $fname );
1046 * @param string $table
1047 * @param array $rows
1048 * @param array $uniqueIndexes
1049 * @param array $set
1050 * @param string $fname
1051 * @return bool
1053 public function upsert( $table, array $rows, array $uniqueIndexes,
1054 array $set, $fname = __METHOD__
1056 if ( !count( $rows ) ) {
1057 return true; // nothing to do
1060 if ( !is_array( reset( $rows ) ) ) {
1061 $rows = array( $rows );
1064 $table = $this->tableName( $table );
1065 $columns = array_keys( $rows[0] );
1067 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1068 $rowTuples = array();
1069 foreach ( $rows as $row ) {
1070 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1072 $sql .= implode( ',', $rowTuples );
1073 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, LIST_SET );
1075 return (bool)$this->query( $sql, $fname );
1079 * Determines how long the server has been up
1081 * @return int
1083 function getServerUptime() {
1084 $vars = $this->getMysqlStatus( 'Uptime' );
1086 return (int)$vars['Uptime'];
1090 * Determines if the last failure was due to a deadlock
1092 * @return bool
1094 function wasDeadlock() {
1095 return $this->lastErrno() == 1213;
1099 * Determines if the last failure was due to a lock timeout
1101 * @return bool
1103 function wasLockTimeout() {
1104 return $this->lastErrno() == 1205;
1108 * Determines if the last query error was something that should be dealt
1109 * with by pinging the connection and reissuing the query
1111 * @return bool
1113 function wasErrorReissuable() {
1114 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
1118 * Determines if the last failure was due to the database being read-only.
1120 * @return bool
1122 function wasReadOnlyError() {
1123 return $this->lastErrno() == 1223 ||
1124 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1127 function wasConnectionError( $errno ) {
1128 return $errno == 2013 || $errno == 2006;
1132 * Get the underlying binding handle, mConn
1134 * Makes sure that mConn is set (disconnects and ping() failure can unset it).
1135 * This catches broken callers than catch and ignore disconnection exceptions.
1136 * Unlike checking isOpen(), this is safe to call inside of open().
1138 * @return resource|object
1139 * @throws DBUnexpectedError
1140 * @since 1.26
1142 protected function getBindingHandle() {
1143 if ( !$this->mConn ) {
1144 throw new DBUnexpectedError(
1145 $this,
1146 'DB connection was already closed or the connection dropped.'
1150 return $this->mConn;
1154 * @param string $oldName
1155 * @param string $newName
1156 * @param bool $temporary
1157 * @param string $fname
1158 * @return bool
1160 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
1161 $tmp = $temporary ? 'TEMPORARY ' : '';
1162 $newName = $this->addIdentifierQuotes( $newName );
1163 $oldName = $this->addIdentifierQuotes( $oldName );
1164 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1166 return $this->query( $query, $fname );
1170 * List all tables on the database
1172 * @param string $prefix Only show tables with this prefix, e.g. mw_
1173 * @param string $fname Calling function name
1174 * @return array
1176 function listTables( $prefix = null, $fname = __METHOD__ ) {
1177 $result = $this->query( "SHOW TABLES", $fname );
1179 $endArray = array();
1181 foreach ( $result as $table ) {
1182 $vars = get_object_vars( $table );
1183 $table = array_pop( $vars );
1185 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1186 $endArray[] = $table;
1190 return $endArray;
1194 * @param string $tableName
1195 * @param string $fName
1196 * @return bool|ResultWrapper
1198 public function dropTable( $tableName, $fName = __METHOD__ ) {
1199 if ( !$this->tableExists( $tableName, $fName ) ) {
1200 return false;
1203 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1207 * @return array
1209 protected function getDefaultSchemaVars() {
1210 $vars = parent::getDefaultSchemaVars();
1211 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
1212 $vars['wgDBTableOptions'] = str_replace(
1213 'CHARSET=mysql4',
1214 'CHARSET=binary',
1215 $vars['wgDBTableOptions']
1218 return $vars;
1222 * Get status information from SHOW STATUS in an associative array
1224 * @param string $which
1225 * @return array
1227 function getMysqlStatus( $which = "%" ) {
1228 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1229 $status = array();
1231 foreach ( $res as $row ) {
1232 $status[$row->Variable_name] = $row->Value;
1235 return $status;
1239 * Lists VIEWs in the database
1241 * @param string $prefix Only show VIEWs with this prefix, eg.
1242 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1243 * @param string $fname Name of calling function
1244 * @return array
1245 * @since 1.22
1247 public function listViews( $prefix = null, $fname = __METHOD__ ) {
1249 if ( !isset( $this->allViews ) ) {
1251 // The name of the column containing the name of the VIEW
1252 $propertyName = 'Tables_in_' . $this->mDBname;
1254 // Query for the VIEWS
1255 $result = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1256 $this->allViews = array();
1257 while ( ( $row = $this->fetchRow( $result ) ) !== false ) {
1258 array_push( $this->allViews, $row[$propertyName] );
1262 if ( is_null( $prefix ) || $prefix === '' ) {
1263 return $this->allViews;
1266 $filteredViews = array();
1267 foreach ( $this->allViews as $viewName ) {
1268 // Does the name of this VIEW start with the table-prefix?
1269 if ( strpos( $viewName, $prefix ) === 0 ) {
1270 array_push( $filteredViews, $viewName );
1274 return $filteredViews;
1278 * Differentiates between a TABLE and a VIEW.
1280 * @param string $name Name of the TABLE/VIEW to test
1281 * @param string $prefix
1282 * @return bool
1283 * @since 1.22
1285 public function isView( $name, $prefix = null ) {
1286 return in_array( $name, $this->listViews( $prefix ) );
1291 * Utility class.
1292 * @ingroup Database
1294 class MySQLField implements Field {
1295 private $name, $tablename, $default, $max_length, $nullable,
1296 $is_pk, $is_unique, $is_multiple, $is_key, $type, $binary,
1297 $is_numeric, $is_blob, $is_unsigned, $is_zerofill;
1299 function __construct( $info ) {
1300 $this->name = $info->name;
1301 $this->tablename = $info->table;
1302 $this->default = $info->def;
1303 $this->max_length = $info->max_length;
1304 $this->nullable = !$info->not_null;
1305 $this->is_pk = $info->primary_key;
1306 $this->is_unique = $info->unique_key;
1307 $this->is_multiple = $info->multiple_key;
1308 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
1309 $this->type = $info->type;
1310 $this->binary = isset( $info->binary ) ? $info->binary : false;
1311 $this->is_numeric = isset( $info->numeric ) ? $info->numeric : false;
1312 $this->is_blob = isset( $info->blob ) ? $info->blob : false;
1313 $this->is_unsigned = isset( $info->unsigned ) ? $info->unsigned : false;
1314 $this->is_zerofill = isset( $info->zerofill ) ? $info->zerofill : false;
1318 * @return string
1320 function name() {
1321 return $this->name;
1325 * @return string
1327 function tableName() {
1328 return $this->tablename;
1332 * @return string
1334 function type() {
1335 return $this->type;
1339 * @return bool
1341 function isNullable() {
1342 return $this->nullable;
1345 function defaultValue() {
1346 return $this->default;
1350 * @return bool
1352 function isKey() {
1353 return $this->is_key;
1357 * @return bool
1359 function isMultipleKey() {
1360 return $this->is_multiple;
1364 * @return bool
1366 function isBinary() {
1367 return $this->binary;
1371 * @return bool
1373 function isNumeric() {
1374 return $this->is_numeric;
1378 * @return bool
1380 function isBlob() {
1381 return $this->is_blob;
1385 * @return bool
1387 function isUnsigned() {
1388 return $this->is_unsigned;
1392 * @return bool
1394 function isZerofill() {
1395 return $this->is_zerofill;
1399 class MySQLMasterPos implements DBMasterPos {
1400 /** @var string */
1401 public $file;
1402 /** @var int Position */
1403 public $pos;
1404 /** @var float UNIX timestamp */
1405 public $asOfTime = 0.0;
1407 function __construct( $file, $pos ) {
1408 $this->file = $file;
1409 $this->pos = $pos;
1410 $this->asOfTime = microtime( true );
1413 function asOfTime() {
1414 return $this->asOfTime;
1417 function hasReached( DBMasterPos $pos ) {
1418 if ( !( $pos instanceof self ) ) {
1419 throw new InvalidArgumentException( "Position not an instance of " . __CLASS__ );
1422 $thisPos = $this->getCoordinates();
1423 $thatPos = $pos->getCoordinates();
1425 return ( $thisPos && $thatPos && $thisPos >= $thatPos );
1428 function __toString() {
1429 // e.g db1034-bin.000976/843431247
1430 return "{$this->file}/{$this->pos}";
1434 * @return array|bool (int, int)
1436 protected function getCoordinates() {
1437 $m = array();
1438 if ( preg_match( '!\.(\d+)/(\d+)$!', (string)$this, $m ) ) {
1439 return array( (int)$m[1], (int)$m[2] );
1442 return false;