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
25 * Database abstraction object for MySQL.
26 * Defines methods independent on used MySQL extension.
32 abstract class DatabaseMysqlBase
extends DatabaseBase
{
33 /** @var MysqlMasterPos */
34 protected $lastKnownSlavePos;
35 /** @var string Method to detect slave lag */
36 protected $lagDetectionMethod;
38 /** @var BagOStuff APC cache */
41 /** @var string|null */
42 private $serverVersion = null;
45 * Additional $params include:
46 * - lagDetectionMethod : set to one of (Seconds_Behind_Master,pt-heartbeat).
47 * pt-heartbeat assumes the table is at heartbeat.heartbeat
48 * and uses UTC timestamps in the heartbeat.ts column.
49 * (https://www.percona.com/doc/percona-toolkit/2.2/pt-heartbeat.html)
50 * @param array $params
52 function __construct( array $params ) {
53 parent
::__construct( $params );
55 $this->lagDetectionMethod
= isset( $params['lagDetectionMethod'] )
56 ?
$params['lagDetectionMethod']
57 : 'Seconds_Behind_Master';
59 $this->srvCache
= ObjectCache
::newAccelerator( 'hash' );
70 * @param string $server
72 * @param string $password
73 * @param string $dbName
74 * @throws Exception|DBConnectionError
77 function open( $server, $user, $password, $dbName ) {
78 global $wgAllDBsAreLocalhost, $wgSQLMode;
80 # Close/unset connection handle
83 # Debugging hack -- fake cluster
84 $realServer = $wgAllDBsAreLocalhost ?
'localhost' : $server;
85 $this->mServer
= $server;
87 $this->mPassword
= $password;
88 $this->mDBname
= $dbName;
90 $this->installErrorHandler();
92 $this->mConn
= $this->mysqlConnect( $realServer );
93 } catch ( Exception
$ex ) {
94 $this->restoreErrorHandler();
97 $error = $this->restoreErrorHandler();
99 # Always log connection errors
100 if ( !$this->mConn
) {
102 $error = $this->lastError();
105 "Error connecting to {db_server}: {error}",
106 $this->getLogContext( array(
107 'method' => __METHOD__
,
111 wfDebug( "DB connection error\n" .
112 "Server: $server, User: $user, Password: " .
113 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
115 $this->reportConnectionError( $error );
118 if ( $dbName != '' ) {
119 MediaWiki\
suppressWarnings();
120 $success = $this->selectDB( $dbName );
121 MediaWiki\restoreWarnings
();
124 "Error selecting database {db_name} on server {db_server}",
125 $this->getLogContext( array(
126 'method' => __METHOD__
,
129 wfDebug( "Error selecting database $dbName on server {$this->mServer} " .
130 "from client host " . wfHostname() . "\n" );
132 $this->reportConnectionError( "Error selecting database $dbName" );
136 // Tell the server what we're communicating with
137 if ( !$this->connectInitCharset() ) {
138 $this->reportConnectionError( "Error setting character set" );
141 // Abstract over any insane MySQL defaults
142 $set = array( 'group_concat_max_len = 262144' );
143 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
144 if ( is_string( $wgSQLMode ) ) {
145 $set[] = 'sql_mode = ' . $this->addQuotes( $wgSQLMode );
147 // Set any custom settings defined by site config
148 // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
149 foreach ( $this->mSessionVars
as $var => $val ) {
150 // Escape strings but not numbers to avoid MySQL complaining
151 if ( !is_int( $val ) && !is_float( $val ) ) {
152 $val = $this->addQuotes( $val );
154 $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
158 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
159 $success = $this->doQuery( 'SET ' . implode( ', ', $set ) );
162 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)',
163 $this->getLogContext( array(
164 'method' => __METHOD__
,
167 $this->reportConnectionError(
168 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)' );
172 $this->mOpened
= true;
178 * Set the character set information right after connection
181 protected function connectInitCharset() {
185 // Tell the server we're communicating with it in UTF-8.
186 // This may engage various charset conversions.
187 return $this->mysqlSetCharset( 'utf8' );
189 return $this->mysqlSetCharset( 'binary' );
194 * Open a connection to a MySQL server
196 * @param string $realServer
197 * @return mixed Raw connection
198 * @throws DBConnectionError
200 abstract protected function mysqlConnect( $realServer );
203 * Set the character set of the MySQL link
205 * @param string $charset
208 abstract protected function mysqlSetCharset( $charset );
211 * @param ResultWrapper|resource $res
212 * @throws DBUnexpectedError
214 function freeResult( $res ) {
215 if ( $res instanceof ResultWrapper
) {
218 MediaWiki\
suppressWarnings();
219 $ok = $this->mysqlFreeResult( $res );
220 MediaWiki\restoreWarnings
();
222 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
229 * @param resource $res Raw result
232 abstract protected function mysqlFreeResult( $res );
235 * @param ResultWrapper|resource $res
236 * @return stdClass|bool
237 * @throws DBUnexpectedError
239 function fetchObject( $res ) {
240 if ( $res instanceof ResultWrapper
) {
243 MediaWiki\
suppressWarnings();
244 $row = $this->mysqlFetchObject( $res );
245 MediaWiki\restoreWarnings
();
247 $errno = $this->lastErrno();
248 // Unfortunately, mysql_fetch_object does not reset the last errno.
249 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
250 // these are the only errors mysql_fetch_object can cause.
251 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
252 if ( $errno == 2000 ||
$errno == 2013 ) {
253 throw new DBUnexpectedError(
255 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
263 * Fetch a result row as an object
265 * @param resource $res Raw result
268 abstract protected function mysqlFetchObject( $res );
271 * @param ResultWrapper|resource $res
273 * @throws DBUnexpectedError
275 function fetchRow( $res ) {
276 if ( $res instanceof ResultWrapper
) {
279 MediaWiki\
suppressWarnings();
280 $row = $this->mysqlFetchArray( $res );
281 MediaWiki\restoreWarnings
();
283 $errno = $this->lastErrno();
284 // Unfortunately, mysql_fetch_array does not reset the last errno.
285 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
286 // these are the only errors mysql_fetch_array can cause.
287 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
288 if ( $errno == 2000 ||
$errno == 2013 ) {
289 throw new DBUnexpectedError(
291 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
299 * Fetch a result row as an associative and numeric array
301 * @param resource $res Raw result
304 abstract protected function mysqlFetchArray( $res );
307 * @throws DBUnexpectedError
308 * @param ResultWrapper|resource $res
311 function numRows( $res ) {
312 if ( $res instanceof ResultWrapper
) {
315 MediaWiki\
suppressWarnings();
316 $n = $this->mysqlNumRows( $res );
317 MediaWiki\restoreWarnings
();
319 // Unfortunately, mysql_num_rows does not reset the last errno.
320 // We are not checking for any errors here, since
321 // these are no errors mysql_num_rows can cause.
322 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
323 // See https://phabricator.wikimedia.org/T44430
328 * Get number of rows in result
330 * @param resource $res Raw result
333 abstract protected function mysqlNumRows( $res );
336 * @param ResultWrapper|resource $res
339 function numFields( $res ) {
340 if ( $res instanceof ResultWrapper
) {
344 return $this->mysqlNumFields( $res );
348 * Get number of fields in result
350 * @param resource $res Raw result
353 abstract protected function mysqlNumFields( $res );
356 * @param ResultWrapper|resource $res
360 function fieldName( $res, $n ) {
361 if ( $res instanceof ResultWrapper
) {
365 return $this->mysqlFieldName( $res, $n );
369 * Get the name of the specified field in a result
371 * @param ResultWrapper|resource $res
375 abstract protected function mysqlFieldName( $res, $n );
378 * mysql_field_type() wrapper
379 * @param ResultWrapper|resource $res
383 public function fieldType( $res, $n ) {
384 if ( $res instanceof ResultWrapper
) {
388 return $this->mysqlFieldType( $res, $n );
392 * Get the type of the specified field in a result
394 * @param ResultWrapper|resource $res
398 abstract protected function mysqlFieldType( $res, $n );
401 * @param ResultWrapper|resource $res
405 function dataSeek( $res, $row ) {
406 if ( $res instanceof ResultWrapper
) {
410 return $this->mysqlDataSeek( $res, $row );
414 * Move internal result pointer
416 * @param ResultWrapper|resource $res
420 abstract protected function mysqlDataSeek( $res, $row );
425 function lastError() {
426 if ( $this->mConn
) {
427 # Even if it's non-zero, it can still be invalid
428 MediaWiki\
suppressWarnings();
429 $error = $this->mysqlError( $this->mConn
);
431 $error = $this->mysqlError();
433 MediaWiki\restoreWarnings
();
435 $error = $this->mysqlError();
438 $error .= ' (' . $this->mServer
. ')';
445 * Returns the text of the error message from previous MySQL operation
447 * @param resource $conn Raw connection
450 abstract protected function mysqlError( $conn = null );
453 * @param string $table
454 * @param array $uniqueIndexes
456 * @param string $fname
457 * @return ResultWrapper
459 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
460 return $this->nativeReplace( $table, $rows, $fname );
464 * Estimate rows in dataset
465 * Returns estimated count, based on EXPLAIN output
466 * Takes same arguments as Database::select()
468 * @param string|array $table
469 * @param string|array $vars
470 * @param string|array $conds
471 * @param string $fname
472 * @param string|array $options
475 public function estimateRowCount( $table, $vars = '*', $conds = '',
476 $fname = __METHOD__
, $options = array()
478 $options['EXPLAIN'] = true;
479 $res = $this->select( $table, $vars, $conds, $fname, $options );
480 if ( $res === false ) {
483 if ( !$this->numRows( $res ) ) {
488 foreach ( $res as $plan ) {
489 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
496 * @param string $table
497 * @param string $field
498 * @return bool|MySQLField
500 function fieldInfo( $table, $field ) {
501 $table = $this->tableName( $table );
502 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
506 $n = $this->mysqlNumFields( $res->result
);
507 for ( $i = 0; $i < $n; $i++
) {
508 $meta = $this->mysqlFetchField( $res->result
, $i );
509 if ( $field == $meta->name
) {
510 return new MySQLField( $meta );
518 * Get column information from a result
520 * @param resource $res Raw result
524 abstract protected function mysqlFetchField( $res, $n );
527 * Get information about an index into an object
528 * Returns false if the index does not exist
530 * @param string $table
531 * @param string $index
532 * @param string $fname
533 * @return bool|array|null False or null on failure
535 function indexInfo( $table, $index, $fname = __METHOD__
) {
536 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
537 # SHOW INDEX should work for 3.x and up:
538 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
539 $table = $this->tableName( $table );
540 $index = $this->indexName( $index );
542 $sql = 'SHOW INDEX FROM ' . $table;
543 $res = $this->query( $sql, $fname );
551 foreach ( $res as $row ) {
552 if ( $row->Key_name
== $index ) {
557 return empty( $result ) ?
false : $result;
564 function strencode( $s ) {
565 $sQuoted = $this->mysqlRealEscapeString( $s );
567 if ( $sQuoted === false ) {
569 $sQuoted = $this->mysqlRealEscapeString( $s );
579 abstract protected function mysqlRealEscapeString( $s );
582 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
587 public function addIdentifierQuotes( $s ) {
588 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
589 // Remove NUL bytes and escape backticks by doubling
590 return '`' . str_replace( array( "\0", '`' ), array( '', '``' ), $s ) . '`';
594 * @param string $name
597 public function isQuotedIdentifier( $name ) {
598 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
605 $ping = $this->mysqlPing();
607 // Connection was good or lost but reconnected...
608 // @note: mysqlnd (php 5.6+) does not support this (PHP bug 52561)
612 // Try a full disconnect/reconnect cycle if ping() failed
613 $this->closeConnection();
614 $this->mOpened
= false;
615 $this->mConn
= false;
616 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
622 * Ping a server connection or reconnect if there is no connection
626 abstract protected function mysqlPing();
631 * This will do a SHOW SLAVE STATUS
636 if ( $this->lagDetectionMethod
=== 'pt-heartbeat' ) {
637 return $this->getLagFromPtHeartbeat();
639 return $this->getLagFromSlaveStatus();
646 protected function getLagFromSlaveStatus() {
647 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
648 $row = $res ?
$res->fetchObject() : false;
649 if ( $row && strval( $row->Seconds_Behind_Master
) !== '' ) {
650 return intval( $row->Seconds_Behind_Master
);
659 protected function getLagFromPtHeartbeat() {
660 $key = wfMemcKey( 'mysql', 'master-server-id', $this->getServer() );
661 $masterId = intval( $this->srvCache
->get( $key ) );
663 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
664 $row = $res ?
$res->fetchObject() : false;
665 if ( $row && strval( $row->Master_Server_Id
) !== '' ) {
666 $masterId = intval( $row->Master_Server_Id
);
667 $this->srvCache
->set( $key, $masterId, 30 );
676 "SELECT TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6)) AS Lag " .
677 "FROM heartbeat.heartbeat WHERE server_id = $masterId"
679 $row = $res ?
$res->fetchObject() : false;
681 return max( floatval( $row->Lag
) / 1e6
, 0.0 );
688 * Wait for the slave to catch up to a given master position.
689 * @todo Return values for this and base class are rubbish
691 * @param DBMasterPos|MySQLMasterPos $pos
692 * @param int $timeout The maximum number of seconds to wait for synchronisation
693 * @return int Zero if the slave was past that position already,
694 * greater than zero if we waited for some period of time, less than
695 * zero if we timed out.
697 function masterPosWait( DBMasterPos
$pos, $timeout ) {
698 if ( $this->lastKnownSlavePos
&& $this->lastKnownSlavePos
->hasReached( $pos ) ) {
699 return '0'; // http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html
702 # Commit any open transactions
703 $this->commit( __METHOD__
, 'flush' );
705 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
706 $encFile = $this->addQuotes( $pos->file
);
707 $encPos = intval( $pos->pos
);
708 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
709 $res = $this->doQuery( $sql );
712 if ( $res && $row = $this->fetchRow( $res ) ) {
713 $status = $row[0]; // can be NULL, -1, or 0+ per the MySQL manual
714 if ( ctype_digit( $status ) ) { // success
715 $this->lastKnownSlavePos
= $pos;
723 * Get the position of the master from SHOW SLAVE STATUS
725 * @return MySQLMasterPos|bool
727 function getSlavePos() {
728 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
729 $row = $this->fetchObject( $res );
732 $pos = isset( $row->Exec_master_log_pos
)
733 ?
$row->Exec_master_log_pos
734 : $row->Exec_Master_Log_Pos
;
736 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
743 * Get the position of the master from SHOW MASTER STATUS
745 * @return MySQLMasterPos|bool
747 function getMasterPos() {
748 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
749 $row = $this->fetchObject( $res );
752 return new MySQLMasterPos( $row->File
, $row->Position
);
759 * @param string $index
762 function useIndexClause( $index ) {
763 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
769 function lowPriorityOption() {
770 return 'LOW_PRIORITY';
776 public function getSoftwareLink() {
777 // MariaDB includes its name in its version string; this is how MariaDB's version of
778 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
779 // in libmysql/libmysql.c).
780 $version = $this->getServerVersion();
781 if ( strpos( $version, 'MariaDB' ) !== false ||
strpos( $version, '-maria-' ) !== false ) {
782 return '[{{int:version-db-mariadb-url}} MariaDB]';
785 // Percona Server's version suffix is not very distinctive, and @@version_comment
786 // doesn't give the necessary info for source builds, so assume the server is MySQL.
787 // (Even Percona's version of mysql doesn't try to make the distinction.)
788 return '[{{int:version-db-mysql-url}} MySQL]';
794 public function getServerVersion() {
795 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
796 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
797 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
798 if ( $this->serverVersion
=== null ) {
799 $this->serverVersion
= $this->selectField( '', 'VERSION()', '', __METHOD__
);
801 return $this->serverVersion
;
805 * @param array $options
807 public function setSessionOptions( array $options ) {
808 if ( isset( $options['connTimeout'] ) ) {
809 $timeout = (int)$options['connTimeout'];
810 $this->query( "SET net_read_timeout=$timeout" );
811 $this->query( "SET net_write_timeout=$timeout" );
817 * @param string $newLine
820 public function streamStatementEnd( &$sql, &$newLine ) {
821 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
822 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
823 $this->delimiter
= $m[1];
827 return parent
::streamStatementEnd( $sql, $newLine );
831 * Check to see if a named lock is available. This is non-blocking.
833 * @param string $lockName Name of lock to poll
834 * @param string $method Name of method calling us
838 public function lockIsFree( $lockName, $method ) {
839 $lockName = $this->addQuotes( $lockName );
840 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
841 $row = $this->fetchObject( $result );
843 return ( $row->lockstatus
== 1 );
847 * @param string $lockName
848 * @param string $method
849 * @param int $timeout
852 public function lock( $lockName, $method, $timeout = 5 ) {
853 $lockName = $this->addQuotes( $lockName );
854 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
855 $row = $this->fetchObject( $result );
857 if ( $row->lockstatus
== 1 ) {
860 wfDebug( __METHOD__
. " failed to acquire lock\n" );
868 * http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
869 * @param string $lockName
870 * @param string $method
873 public function unlock( $lockName, $method ) {
874 $lockName = $this->addQuotes( $lockName );
875 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
876 $row = $this->fetchObject( $result );
878 return ( $row->lockstatus
== 1 );
881 public function namedLocksEnqueue() {
887 * @param array $write
888 * @param string $method
889 * @param bool $lowPriority
892 public function lockTables( $read, $write, $method, $lowPriority = true ) {
895 foreach ( $write as $table ) {
896 $tbl = $this->tableName( $table ) .
897 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
901 foreach ( $read as $table ) {
902 $items[] = $this->tableName( $table ) . ' READ';
904 $sql = "LOCK TABLES " . implode( ',', $items );
905 $this->query( $sql, $method );
911 * @param string $method
914 public function unlockTables( $method ) {
915 $this->query( "UNLOCK TABLES", $method );
921 * Get search engine class. All subclasses of this
922 * need to implement this if they wish to use searching.
926 public function getSearchEngine() {
927 return 'SearchMySQL';
933 public function setBigSelects( $value = true ) {
934 if ( $value === 'default' ) {
935 if ( $this->mDefaultBigSelects
=== null ) {
936 # Function hasn't been called before so it must already be set to the default
939 $value = $this->mDefaultBigSelects
;
941 } elseif ( $this->mDefaultBigSelects
=== null ) {
942 $this->mDefaultBigSelects
=
943 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__
);
945 $encValue = $value ?
'1' : '0';
946 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
950 * DELETE where the condition is a join. MySql uses multi-table deletes.
951 * @param string $delTable
952 * @param string $joinTable
953 * @param string $delVar
954 * @param string $joinVar
955 * @param array|string $conds
956 * @param bool|string $fname
957 * @throws DBUnexpectedError
958 * @return bool|ResultWrapper
960 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
) {
962 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
965 $delTable = $this->tableName( $delTable );
966 $joinTable = $this->tableName( $joinTable );
967 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
969 if ( $conds != '*' ) {
970 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
973 return $this->query( $sql, $fname );
977 * @param string $table
979 * @param array $uniqueIndexes
981 * @param string $fname
984 public function upsert( $table, array $rows, array $uniqueIndexes,
985 array $set, $fname = __METHOD__
987 if ( !count( $rows ) ) {
988 return true; // nothing to do
991 if ( !is_array( reset( $rows ) ) ) {
992 $rows = array( $rows );
995 $table = $this->tableName( $table );
996 $columns = array_keys( $rows[0] );
998 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
999 $rowTuples = array();
1000 foreach ( $rows as $row ) {
1001 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1003 $sql .= implode( ',', $rowTuples );
1004 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, LIST_SET
);
1006 return (bool)$this->query( $sql, $fname );
1010 * Determines how long the server has been up
1014 function getServerUptime() {
1015 $vars = $this->getMysqlStatus( 'Uptime' );
1017 return (int)$vars['Uptime'];
1021 * Determines if the last failure was due to a deadlock
1025 function wasDeadlock() {
1026 return $this->lastErrno() == 1213;
1030 * Determines if the last failure was due to a lock timeout
1034 function wasLockTimeout() {
1035 return $this->lastErrno() == 1205;
1039 * Determines if the last query error was something that should be dealt
1040 * with by pinging the connection and reissuing the query
1044 function wasErrorReissuable() {
1045 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
1049 * Determines if the last failure was due to the database being read-only.
1053 function wasReadOnlyError() {
1054 return $this->lastErrno() == 1223 ||
1055 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1058 function wasConnectionError( $errno ) {
1059 return $errno == 2013 ||
$errno == 2006;
1063 * Get the underlying binding handle, mConn
1065 * Makes sure that mConn is set (disconnects and ping() failure can unset it).
1066 * This catches broken callers than catch and ignore disconnection exceptions.
1067 * Unlike checking isOpen(), this is safe to call inside of open().
1069 * @return resource|object
1070 * @throws DBUnexpectedError
1073 protected function getBindingHandle() {
1074 if ( !$this->mConn
) {
1075 throw new DBUnexpectedError(
1077 'DB connection was already closed or the connection dropped.'
1081 return $this->mConn
;
1085 * @param string $oldName
1086 * @param string $newName
1087 * @param bool $temporary
1088 * @param string $fname
1091 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
1092 $tmp = $temporary ?
'TEMPORARY ' : '';
1093 $newName = $this->addIdentifierQuotes( $newName );
1094 $oldName = $this->addIdentifierQuotes( $oldName );
1095 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1097 return $this->query( $query, $fname );
1101 * List all tables on the database
1103 * @param string $prefix Only show tables with this prefix, e.g. mw_
1104 * @param string $fname Calling function name
1107 function listTables( $prefix = null, $fname = __METHOD__
) {
1108 $result = $this->query( "SHOW TABLES", $fname );
1110 $endArray = array();
1112 foreach ( $result as $table ) {
1113 $vars = get_object_vars( $table );
1114 $table = array_pop( $vars );
1116 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1117 $endArray[] = $table;
1125 * @param string $tableName
1126 * @param string $fName
1127 * @return bool|ResultWrapper
1129 public function dropTable( $tableName, $fName = __METHOD__
) {
1130 if ( !$this->tableExists( $tableName, $fName ) ) {
1134 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1140 protected function getDefaultSchemaVars() {
1141 $vars = parent
::getDefaultSchemaVars();
1142 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
1143 $vars['wgDBTableOptions'] = str_replace(
1146 $vars['wgDBTableOptions']
1153 * Get status information from SHOW STATUS in an associative array
1155 * @param string $which
1158 function getMysqlStatus( $which = "%" ) {
1159 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1162 foreach ( $res as $row ) {
1163 $status[$row->Variable_name
] = $row->Value
;
1170 * Lists VIEWs in the database
1172 * @param string $prefix Only show VIEWs with this prefix, eg.
1173 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1174 * @param string $fname Name of calling function
1178 public function listViews( $prefix = null, $fname = __METHOD__
) {
1180 if ( !isset( $this->allViews
) ) {
1182 // The name of the column containing the name of the VIEW
1183 $propertyName = 'Tables_in_' . $this->mDBname
;
1185 // Query for the VIEWS
1186 $result = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1187 $this->allViews
= array();
1188 while ( ( $row = $this->fetchRow( $result ) ) !== false ) {
1189 array_push( $this->allViews
, $row[$propertyName] );
1193 if ( is_null( $prefix ) ||
$prefix === '' ) {
1194 return $this->allViews
;
1197 $filteredViews = array();
1198 foreach ( $this->allViews
as $viewName ) {
1199 // Does the name of this VIEW start with the table-prefix?
1200 if ( strpos( $viewName, $prefix ) === 0 ) {
1201 array_push( $filteredViews, $viewName );
1205 return $filteredViews;
1209 * Differentiates between a TABLE and a VIEW.
1211 * @param string $name Name of the TABLE/VIEW to test
1212 * @param string $prefix
1216 public function isView( $name, $prefix = null ) {
1217 return in_array( $name, $this->listViews( $prefix ) );
1225 class MySQLField
implements Field
{
1226 private $name, $tablename, $default, $max_length, $nullable,
1227 $is_pk, $is_unique, $is_multiple, $is_key, $type, $binary,
1228 $is_numeric, $is_blob, $is_unsigned, $is_zerofill;
1230 function __construct( $info ) {
1231 $this->name
= $info->name
;
1232 $this->tablename
= $info->table
;
1233 $this->default = $info->def
;
1234 $this->max_length
= $info->max_length
;
1235 $this->nullable
= !$info->not_null
;
1236 $this->is_pk
= $info->primary_key
;
1237 $this->is_unique
= $info->unique_key
;
1238 $this->is_multiple
= $info->multiple_key
;
1239 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
1240 $this->type
= $info->type
;
1241 $this->binary
= isset( $info->binary
) ?
$info->binary
: false;
1242 $this->is_numeric
= isset( $info->numeric ) ?
$info->numeric : false;
1243 $this->is_blob
= isset( $info->blob
) ?
$info->blob
: false;
1244 $this->is_unsigned
= isset( $info->unsigned
) ?
$info->unsigned
: false;
1245 $this->is_zerofill
= isset( $info->zerofill
) ?
$info->zerofill
: false;
1258 function tableName() {
1259 return $this->tablename
;
1272 function isNullable() {
1273 return $this->nullable
;
1276 function defaultValue() {
1277 return $this->default;
1284 return $this->is_key
;
1290 function isMultipleKey() {
1291 return $this->is_multiple
;
1297 function isBinary() {
1298 return $this->binary
;
1304 function isNumeric() {
1305 return $this->is_numeric
;
1312 return $this->is_blob
;
1318 function isUnsigned() {
1319 return $this->is_unsigned
;
1325 function isZerofill() {
1326 return $this->is_zerofill
;
1330 class MySQLMasterPos
implements DBMasterPos
{
1333 /** @var int Position */
1335 /** @var float UNIX timestamp */
1336 public $asOfTime = 0.0;
1338 function __construct( $file, $pos ) {
1339 $this->file
= $file;
1341 $this->asOfTime
= microtime( true );
1344 function __toString() {
1345 // e.g db1034-bin.000976/843431247
1346 return "{$this->file}/{$this->pos}";
1350 * @return array|bool (int, int)
1352 protected function getCoordinates() {
1354 if ( preg_match( '!\.(\d+)/(\d+)$!', (string)$this, $m ) ) {
1355 return array( (int)$m[1], (int)$m[2] );
1361 function hasReached( MySQLMasterPos
$pos ) {
1362 $thisPos = $this->getCoordinates();
1363 $thatPos = $pos->getCoordinates();
1365 return ( $thisPos && $thatPos && $thisPos >= $thatPos );
1368 function asOfTime() {
1369 return $this->asOfTime
;