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 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;
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';
65 * @param string $server
67 * @param string $password
68 * @param string $dbName
69 * @throws Exception|DBConnectionError
72 function open( $server, $user, $password, $dbName ) {
73 global $wgAllDBsAreLocalhost, $wgSQLMode;
75 # Close/unset connection handle
78 # Debugging hack -- fake cluster
79 $realServer = $wgAllDBsAreLocalhost ?
'localhost' : $server;
80 $this->mServer
= $server;
82 $this->mPassword
= $password;
83 $this->mDBname
= $dbName;
85 $this->installErrorHandler();
87 $this->mConn
= $this->mysqlConnect( $realServer );
88 } catch ( Exception
$ex ) {
89 $this->restoreErrorHandler();
92 $error = $this->restoreErrorHandler();
94 # Always log connection errors
95 if ( !$this->mConn
) {
97 $error = $this->lastError();
100 "Error connecting to {db_server}: {error}",
101 $this->getLogContext( array(
102 'method' => __METHOD__
,
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
();
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;
153 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
154 $success = $this->doQuery( 'SET ' . implode( ', ', $set ) );
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;
173 * Set the character set information right after connection
176 protected function connectInitCharset() {
180 // Tell the server we're communicating with it in UTF-8.
181 // This may engage various charset conversions.
182 return $this->mysqlSetCharset( 'utf8' );
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
203 abstract protected function mysqlSetCharset( $charset );
206 * @param ResultWrapper|resource $res
207 * @throws DBUnexpectedError
209 function freeResult( $res ) {
210 if ( $res instanceof ResultWrapper
) {
213 MediaWiki\
suppressWarnings();
214 $ok = $this->mysqlFreeResult( $res );
215 MediaWiki\restoreWarnings
();
217 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
224 * @param resource $res Raw result
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
) {
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(
250 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
258 * Fetch a result row as an object
260 * @param resource $res Raw result
263 abstract protected function mysqlFetchObject( $res );
266 * @param ResultWrapper|resource $res
268 * @throws DBUnexpectedError
270 function fetchRow( $res ) {
271 if ( $res instanceof ResultWrapper
) {
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(
286 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
294 * Fetch a result row as an associative and numeric array
296 * @param resource $res Raw result
299 abstract protected function mysqlFetchArray( $res );
302 * @throws DBUnexpectedError
303 * @param ResultWrapper|resource $res
306 function numRows( $res ) {
307 if ( $res instanceof ResultWrapper
) {
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
323 * Get number of rows in result
325 * @param resource $res Raw result
328 abstract protected function mysqlNumRows( $res );
331 * @param ResultWrapper|resource $res
334 function numFields( $res ) {
335 if ( $res instanceof ResultWrapper
) {
339 return $this->mysqlNumFields( $res );
343 * Get number of fields in result
345 * @param resource $res Raw result
348 abstract protected function mysqlNumFields( $res );
351 * @param ResultWrapper|resource $res
355 function fieldName( $res, $n ) {
356 if ( $res instanceof ResultWrapper
) {
360 return $this->mysqlFieldName( $res, $n );
364 * Get the name of the specified field in a result
366 * @param ResultWrapper|resource $res
370 abstract protected function mysqlFieldName( $res, $n );
373 * mysql_field_type() wrapper
374 * @param ResultWrapper|resource $res
378 public function fieldType( $res, $n ) {
379 if ( $res instanceof ResultWrapper
) {
383 return $this->mysqlFieldType( $res, $n );
387 * Get the type of the specified field in a result
389 * @param ResultWrapper|resource $res
393 abstract protected function mysqlFieldType( $res, $n );
396 * @param ResultWrapper|resource $res
400 function dataSeek( $res, $row ) {
401 if ( $res instanceof ResultWrapper
) {
405 return $this->mysqlDataSeek( $res, $row );
409 * Move internal result pointer
411 * @param ResultWrapper|resource $res
415 abstract protected function mysqlDataSeek( $res, $row );
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
);
426 $error = $this->mysqlError();
428 MediaWiki\restoreWarnings
();
430 $error = $this->mysqlError();
433 $error .= ' (' . $this->mServer
. ')';
440 * Returns the text of the error message from previous MySQL operation
442 * @param resource $conn Raw connection
445 abstract protected function mysqlError( $conn = null );
448 * @param string $table
449 * @param array $uniqueIndexes
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
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 ) {
478 if ( !$this->numRows( $res ) ) {
483 foreach ( $res as $plan ) {
484 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
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 );
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 );
513 * Get column information from a result
515 * @param resource $res Raw result
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 );
546 foreach ( $res as $row ) {
547 if ( $row->Key_name
== $index ) {
552 return empty( $result ) ?
false : $result;
559 function strencode( $s ) {
560 $sQuoted = $this->mysqlRealEscapeString( $s );
562 if ( $sQuoted === false ) {
564 $sQuoted = $this->mysqlRealEscapeString( $s );
574 abstract protected function mysqlRealEscapeString( $s );
577 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
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
592 public function isQuotedIdentifier( $name ) {
593 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
600 $ping = $this->mysqlPing();
602 // Connection was good or lost but reconnected...
603 // @note: mysqlnd (php 5.6+) does not support this (PHP bug 52561)
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
);
617 * Ping a server connection or reconnect if there is no connection
621 abstract protected function mysqlPing();
624 if ( $this->lagDetectionMethod
=== 'pt-heartbeat' ) {
625 return $this->getLagFromPtHeartbeat();
627 return $this->getLagFromSlaveStatus();
634 protected function getLagFromSlaveStatus() {
635 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
636 $row = $res ?
$res->fetchObject() : false;
637 if ( $row && strval( $row->Seconds_Behind_Master
) !== '' ) {
638 return intval( $row->Seconds_Behind_Master
);
647 protected function getLagFromPtHeartbeat() {
648 $key = wfMemcKey( 'mysql', 'master-server-id', $this->getServer() );
649 $masterId = intval( $this->srvCache
->get( $key ) );
651 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
652 $row = $res ?
$res->fetchObject() : false;
653 if ( $row && strval( $row->Master_Server_Id
) !== '' ) {
654 $masterId = intval( $row->Master_Server_Id
);
655 $this->srvCache
->set( $key, $masterId, 30 );
664 "SELECT TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6)) AS Lag " .
665 "FROM heartbeat.heartbeat WHERE server_id = $masterId"
667 $row = $res ?
$res->fetchObject() : false;
669 return max( floatval( $row->Lag
) / 1e6
, 0.0 );
675 public function getApproximateLagStatus() {
676 if ( $this->lagDetectionMethod
=== 'pt-heartbeat' ) {
677 // Disable caching since this is fast enough and we don't wan't
678 // to be *too* pessimistic by having both the cache TTL and the
679 // pt-heartbeat interval count as lag in getSessionLagStatus()
680 return parent
::getApproximateLagStatus();
683 $key = $this->srvCache
->makeGlobalKey( 'mysql-lag', $this->getServer() );
684 $approxLag = $this->srvCache
->get( $key );
686 $approxLag = parent
::getApproximateLagStatus();
687 $this->srvCache
->set( $key, $approxLag, 1 );
694 * Wait for the slave to catch up to a given master position.
695 * @todo Return values for this and base class are rubbish
697 * @param DBMasterPos|MySQLMasterPos $pos
698 * @param int $timeout The maximum number of seconds to wait for synchronisation
699 * @return int Zero if the slave was past that position already,
700 * greater than zero if we waited for some period of time, less than
701 * zero if we timed out.
703 function masterPosWait( DBMasterPos
$pos, $timeout ) {
704 if ( $this->lastKnownSlavePos
&& $this->lastKnownSlavePos
->hasReached( $pos ) ) {
705 return '0'; // http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html
708 # Commit any open transactions
709 $this->commit( __METHOD__
, 'flush' );
711 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
712 $encFile = $this->addQuotes( $pos->file
);
713 $encPos = intval( $pos->pos
);
714 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
715 $res = $this->doQuery( $sql );
719 $row = $this->fetchRow( $res );
721 $status = $row[0]; // can be NULL, -1, or 0+ per the MySQL manual
722 if ( ctype_digit( $status ) ) { // success
723 $this->lastKnownSlavePos
= $pos;
732 * Get the position of the master from SHOW SLAVE STATUS
734 * @return MySQLMasterPos|bool
736 function getSlavePos() {
737 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
738 $row = $this->fetchObject( $res );
741 $pos = isset( $row->Exec_master_log_pos
)
742 ?
$row->Exec_master_log_pos
743 : $row->Exec_Master_Log_Pos
;
745 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
752 * Get the position of the master from SHOW MASTER STATUS
754 * @return MySQLMasterPos|bool
756 function getMasterPos() {
757 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
758 $row = $this->fetchObject( $res );
761 return new MySQLMasterPos( $row->File
, $row->Position
);
768 * @param string $index
771 function useIndexClause( $index ) {
772 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
778 function lowPriorityOption() {
779 return 'LOW_PRIORITY';
785 public function getSoftwareLink() {
786 // MariaDB includes its name in its version string; this is how MariaDB's version of
787 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
788 // in libmysql/libmysql.c).
789 $version = $this->getServerVersion();
790 if ( strpos( $version, 'MariaDB' ) !== false ||
strpos( $version, '-maria-' ) !== false ) {
791 return '[{{int:version-db-mariadb-url}} MariaDB]';
794 // Percona Server's version suffix is not very distinctive, and @@version_comment
795 // doesn't give the necessary info for source builds, so assume the server is MySQL.
796 // (Even Percona's version of mysql doesn't try to make the distinction.)
797 return '[{{int:version-db-mysql-url}} MySQL]';
803 public function getServerVersion() {
804 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
805 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
806 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
807 if ( $this->serverVersion
=== null ) {
808 $this->serverVersion
= $this->selectField( '', 'VERSION()', '', __METHOD__
);
810 return $this->serverVersion
;
814 * @param array $options
816 public function setSessionOptions( array $options ) {
817 if ( isset( $options['connTimeout'] ) ) {
818 $timeout = (int)$options['connTimeout'];
819 $this->query( "SET net_read_timeout=$timeout" );
820 $this->query( "SET net_write_timeout=$timeout" );
826 * @param string $newLine
829 public function streamStatementEnd( &$sql, &$newLine ) {
830 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
831 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
832 $this->delimiter
= $m[1];
836 return parent
::streamStatementEnd( $sql, $newLine );
840 * Check to see if a named lock is available. This is non-blocking.
842 * @param string $lockName Name of lock to poll
843 * @param string $method Name of method calling us
847 public function lockIsFree( $lockName, $method ) {
848 $lockName = $this->addQuotes( $lockName );
849 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
850 $row = $this->fetchObject( $result );
852 return ( $row->lockstatus
== 1 );
856 * @param string $lockName
857 * @param string $method
858 * @param int $timeout
861 public function lock( $lockName, $method, $timeout = 5 ) {
862 $lockName = $this->addQuotes( $lockName );
863 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
864 $row = $this->fetchObject( $result );
866 if ( $row->lockstatus
== 1 ) {
869 wfDebug( __METHOD__
. " failed to acquire lock\n" );
877 * http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
878 * @param string $lockName
879 * @param string $method
882 public function unlock( $lockName, $method ) {
883 $lockName = $this->addQuotes( $lockName );
884 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
885 $row = $this->fetchObject( $result );
887 return ( $row->lockstatus
== 1 );
890 public function namedLocksEnqueue() {
896 * @param array $write
897 * @param string $method
898 * @param bool $lowPriority
901 public function lockTables( $read, $write, $method, $lowPriority = true ) {
904 foreach ( $write as $table ) {
905 $tbl = $this->tableName( $table ) .
906 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
910 foreach ( $read as $table ) {
911 $items[] = $this->tableName( $table ) . ' READ';
913 $sql = "LOCK TABLES " . implode( ',', $items );
914 $this->query( $sql, $method );
920 * @param string $method
923 public function unlockTables( $method ) {
924 $this->query( "UNLOCK TABLES", $method );
930 * Get search engine class. All subclasses of this
931 * need to implement this if they wish to use searching.
935 public function getSearchEngine() {
936 return 'SearchMySQL';
942 public function setBigSelects( $value = true ) {
943 if ( $value === 'default' ) {
944 if ( $this->mDefaultBigSelects
=== null ) {
945 # Function hasn't been called before so it must already be set to the default
948 $value = $this->mDefaultBigSelects
;
950 } elseif ( $this->mDefaultBigSelects
=== null ) {
951 $this->mDefaultBigSelects
=
952 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__
);
954 $encValue = $value ?
'1' : '0';
955 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
959 * DELETE where the condition is a join. MySql uses multi-table deletes.
960 * @param string $delTable
961 * @param string $joinTable
962 * @param string $delVar
963 * @param string $joinVar
964 * @param array|string $conds
965 * @param bool|string $fname
966 * @throws DBUnexpectedError
967 * @return bool|ResultWrapper
969 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
) {
971 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
974 $delTable = $this->tableName( $delTable );
975 $joinTable = $this->tableName( $joinTable );
976 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
978 if ( $conds != '*' ) {
979 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
982 return $this->query( $sql, $fname );
986 * @param string $table
988 * @param array $uniqueIndexes
990 * @param string $fname
993 public function upsert( $table, array $rows, array $uniqueIndexes,
994 array $set, $fname = __METHOD__
996 if ( !count( $rows ) ) {
997 return true; // nothing to do
1000 if ( !is_array( reset( $rows ) ) ) {
1001 $rows = array( $rows );
1004 $table = $this->tableName( $table );
1005 $columns = array_keys( $rows[0] );
1007 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1008 $rowTuples = array();
1009 foreach ( $rows as $row ) {
1010 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1012 $sql .= implode( ',', $rowTuples );
1013 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, LIST_SET
);
1015 return (bool)$this->query( $sql, $fname );
1019 * Determines how long the server has been up
1023 function getServerUptime() {
1024 $vars = $this->getMysqlStatus( 'Uptime' );
1026 return (int)$vars['Uptime'];
1030 * Determines if the last failure was due to a deadlock
1034 function wasDeadlock() {
1035 return $this->lastErrno() == 1213;
1039 * Determines if the last failure was due to a lock timeout
1043 function wasLockTimeout() {
1044 return $this->lastErrno() == 1205;
1048 * Determines if the last query error was something that should be dealt
1049 * with by pinging the connection and reissuing the query
1053 function wasErrorReissuable() {
1054 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
1058 * Determines if the last failure was due to the database being read-only.
1062 function wasReadOnlyError() {
1063 return $this->lastErrno() == 1223 ||
1064 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1067 function wasConnectionError( $errno ) {
1068 return $errno == 2013 ||
$errno == 2006;
1072 * Get the underlying binding handle, mConn
1074 * Makes sure that mConn is set (disconnects and ping() failure can unset it).
1075 * This catches broken callers than catch and ignore disconnection exceptions.
1076 * Unlike checking isOpen(), this is safe to call inside of open().
1078 * @return resource|object
1079 * @throws DBUnexpectedError
1082 protected function getBindingHandle() {
1083 if ( !$this->mConn
) {
1084 throw new DBUnexpectedError(
1086 'DB connection was already closed or the connection dropped.'
1090 return $this->mConn
;
1094 * @param string $oldName
1095 * @param string $newName
1096 * @param bool $temporary
1097 * @param string $fname
1100 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
1101 $tmp = $temporary ?
'TEMPORARY ' : '';
1102 $newName = $this->addIdentifierQuotes( $newName );
1103 $oldName = $this->addIdentifierQuotes( $oldName );
1104 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1106 return $this->query( $query, $fname );
1110 * List all tables on the database
1112 * @param string $prefix Only show tables with this prefix, e.g. mw_
1113 * @param string $fname Calling function name
1116 function listTables( $prefix = null, $fname = __METHOD__
) {
1117 $result = $this->query( "SHOW TABLES", $fname );
1119 $endArray = array();
1121 foreach ( $result as $table ) {
1122 $vars = get_object_vars( $table );
1123 $table = array_pop( $vars );
1125 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1126 $endArray[] = $table;
1134 * @param string $tableName
1135 * @param string $fName
1136 * @return bool|ResultWrapper
1138 public function dropTable( $tableName, $fName = __METHOD__
) {
1139 if ( !$this->tableExists( $tableName, $fName ) ) {
1143 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1149 protected function getDefaultSchemaVars() {
1150 $vars = parent
::getDefaultSchemaVars();
1151 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
1152 $vars['wgDBTableOptions'] = str_replace(
1155 $vars['wgDBTableOptions']
1162 * Get status information from SHOW STATUS in an associative array
1164 * @param string $which
1167 function getMysqlStatus( $which = "%" ) {
1168 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1171 foreach ( $res as $row ) {
1172 $status[$row->Variable_name
] = $row->Value
;
1179 * Lists VIEWs in the database
1181 * @param string $prefix Only show VIEWs with this prefix, eg.
1182 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1183 * @param string $fname Name of calling function
1187 public function listViews( $prefix = null, $fname = __METHOD__
) {
1189 if ( !isset( $this->allViews
) ) {
1191 // The name of the column containing the name of the VIEW
1192 $propertyName = 'Tables_in_' . $this->mDBname
;
1194 // Query for the VIEWS
1195 $result = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1196 $this->allViews
= array();
1197 while ( ( $row = $this->fetchRow( $result ) ) !== false ) {
1198 array_push( $this->allViews
, $row[$propertyName] );
1202 if ( is_null( $prefix ) ||
$prefix === '' ) {
1203 return $this->allViews
;
1206 $filteredViews = array();
1207 foreach ( $this->allViews
as $viewName ) {
1208 // Does the name of this VIEW start with the table-prefix?
1209 if ( strpos( $viewName, $prefix ) === 0 ) {
1210 array_push( $filteredViews, $viewName );
1214 return $filteredViews;
1218 * Differentiates between a TABLE and a VIEW.
1220 * @param string $name Name of the TABLE/VIEW to test
1221 * @param string $prefix
1225 public function isView( $name, $prefix = null ) {
1226 return in_array( $name, $this->listViews( $prefix ) );
1234 class MySQLField
implements Field
{
1235 private $name, $tablename, $default, $max_length, $nullable,
1236 $is_pk, $is_unique, $is_multiple, $is_key, $type, $binary,
1237 $is_numeric, $is_blob, $is_unsigned, $is_zerofill;
1239 function __construct( $info ) {
1240 $this->name
= $info->name
;
1241 $this->tablename
= $info->table
;
1242 $this->default = $info->def
;
1243 $this->max_length
= $info->max_length
;
1244 $this->nullable
= !$info->not_null
;
1245 $this->is_pk
= $info->primary_key
;
1246 $this->is_unique
= $info->unique_key
;
1247 $this->is_multiple
= $info->multiple_key
;
1248 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
1249 $this->type
= $info->type
;
1250 $this->binary
= isset( $info->binary
) ?
$info->binary
: false;
1251 $this->is_numeric
= isset( $info->numeric ) ?
$info->numeric : false;
1252 $this->is_blob
= isset( $info->blob
) ?
$info->blob
: false;
1253 $this->is_unsigned
= isset( $info->unsigned
) ?
$info->unsigned
: false;
1254 $this->is_zerofill
= isset( $info->zerofill
) ?
$info->zerofill
: false;
1267 function tableName() {
1268 return $this->tablename
;
1281 function isNullable() {
1282 return $this->nullable
;
1285 function defaultValue() {
1286 return $this->default;
1293 return $this->is_key
;
1299 function isMultipleKey() {
1300 return $this->is_multiple
;
1306 function isBinary() {
1307 return $this->binary
;
1313 function isNumeric() {
1314 return $this->is_numeric
;
1321 return $this->is_blob
;
1327 function isUnsigned() {
1328 return $this->is_unsigned
;
1334 function isZerofill() {
1335 return $this->is_zerofill
;
1339 class MySQLMasterPos
implements DBMasterPos
{
1342 /** @var int Position */
1344 /** @var float UNIX timestamp */
1345 public $asOfTime = 0.0;
1347 function __construct( $file, $pos ) {
1348 $this->file
= $file;
1350 $this->asOfTime
= microtime( true );
1353 function asOfTime() {
1354 return $this->asOfTime
;
1357 function hasReached( DBMasterPos
$pos ) {
1358 if ( !( $pos instanceof self
) ) {
1359 throw new InvalidArgumentException( "Position not an instance of " . __CLASS__
);
1362 $thisPos = $this->getCoordinates();
1363 $thatPos = $pos->getCoordinates();
1365 return ( $thisPos && $thatPos && $thisPos >= $thatPos );
1368 function __toString() {
1369 // e.g db1034-bin.000976/843431247
1370 return "{$this->file}/{$this->pos}";
1374 * @return array|bool (int, int)
1376 protected function getCoordinates() {
1378 if ( preg_match( '!\.(\d+)/(\d+)$!', (string)$this, $m ) ) {
1379 return array( (int)$m[1], (int)$m[2] );