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;
37 protected $mFakeSlaveLag = null;
39 protected $mFakeMaster = false;
41 /** @var string|null */
42 private $serverVersion = null;
52 * @param string $server
54 * @param string $password
55 * @param string $dbName
56 * @throws Exception|DBConnectionError
59 function open( $server, $user, $password, $dbName ) {
60 global $wgAllDBsAreLocalhost, $wgSQLMode;
62 # Close/unset connection handle
65 # Debugging hack -- fake cluster
66 $realServer = $wgAllDBsAreLocalhost ?
'localhost' : $server;
67 $this->mServer
= $server;
69 $this->mPassword
= $password;
70 $this->mDBname
= $dbName;
72 $this->installErrorHandler();
74 $this->mConn
= $this->mysqlConnect( $realServer );
75 } catch ( Exception
$ex ) {
76 $this->restoreErrorHandler();
79 $error = $this->restoreErrorHandler();
81 # Always log connection errors
82 if ( !$this->mConn
) {
84 $error = $this->lastError();
87 "Error connecting to {db_server}: {error}",
88 $this->getLogContext( array(
89 'method' => __METHOD__
,
93 wfDebug( "DB connection error\n" .
94 "Server: $server, User: $user, Password: " .
95 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
97 $this->reportConnectionError( $error );
100 if ( $dbName != '' ) {
101 MediaWiki\
suppressWarnings();
102 $success = $this->selectDB( $dbName );
103 MediaWiki\restoreWarnings
();
106 "Error selecting database {db_name} on server {db_server}",
107 $this->getLogContext( array(
108 'method' => __METHOD__
,
111 wfDebug( "Error selecting database $dbName on server {$this->mServer} " .
112 "from client host " . wfHostname() . "\n" );
114 $this->reportConnectionError( "Error selecting database $dbName" );
118 // Tell the server what we're communicating with
119 if ( !$this->connectInitCharset() ) {
120 $this->reportConnectionError( "Error setting character set" );
123 // Abstract over any insane MySQL defaults
124 $set = array( 'group_concat_max_len = 262144' );
125 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
126 if ( is_string( $wgSQLMode ) ) {
127 $set[] = 'sql_mode = ' . $this->addQuotes( $wgSQLMode );
129 // Set any custom settings defined by site config
130 // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
131 foreach ( $this->mSessionVars
as $var => $val ) {
132 // Escape strings but not numbers to avoid MySQL complaining
133 if ( !is_int( $val ) && !is_float( $val ) ) {
134 $val = $this->addQuotes( $val );
136 $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
140 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
141 $success = $this->doQuery( 'SET ' . implode( ', ', $set ), __METHOD__
);
144 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)',
145 $this->getLogContext( array(
146 'method' => __METHOD__
,
149 $this->reportConnectionError(
150 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)' );
154 $this->mOpened
= true;
160 * Set the character set information right after connection
163 protected function connectInitCharset() {
167 // Tell the server we're communicating with it in UTF-8.
168 // This may engage various charset conversions.
169 return $this->mysqlSetCharset( 'utf8' );
171 return $this->mysqlSetCharset( 'binary' );
176 * Open a connection to a MySQL server
178 * @param string $realServer
179 * @return mixed Raw connection
180 * @throws DBConnectionError
182 abstract protected function mysqlConnect( $realServer );
185 * Set the character set of the MySQL link
187 * @param string $charset
190 abstract protected function mysqlSetCharset( $charset );
193 * @param ResultWrapper|resource $res
194 * @throws DBUnexpectedError
196 function freeResult( $res ) {
197 if ( $res instanceof ResultWrapper
) {
200 MediaWiki\
suppressWarnings();
201 $ok = $this->mysqlFreeResult( $res );
202 MediaWiki\restoreWarnings
();
204 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
211 * @param resource $res Raw result
214 abstract protected function mysqlFreeResult( $res );
217 * @param ResultWrapper|resource $res
218 * @return stdClass|bool
219 * @throws DBUnexpectedError
221 function fetchObject( $res ) {
222 if ( $res instanceof ResultWrapper
) {
225 MediaWiki\
suppressWarnings();
226 $row = $this->mysqlFetchObject( $res );
227 MediaWiki\restoreWarnings
();
229 $errno = $this->lastErrno();
230 // Unfortunately, mysql_fetch_object does not reset the last errno.
231 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
232 // these are the only errors mysql_fetch_object can cause.
233 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
234 if ( $errno == 2000 ||
$errno == 2013 ) {
235 throw new DBUnexpectedError(
237 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
245 * Fetch a result row as an object
247 * @param resource $res Raw result
250 abstract protected function mysqlFetchObject( $res );
253 * @param ResultWrapper|resource $res
255 * @throws DBUnexpectedError
257 function fetchRow( $res ) {
258 if ( $res instanceof ResultWrapper
) {
261 MediaWiki\
suppressWarnings();
262 $row = $this->mysqlFetchArray( $res );
263 MediaWiki\restoreWarnings
();
265 $errno = $this->lastErrno();
266 // Unfortunately, mysql_fetch_array does not reset the last errno.
267 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
268 // these are the only errors mysql_fetch_array can cause.
269 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
270 if ( $errno == 2000 ||
$errno == 2013 ) {
271 throw new DBUnexpectedError(
273 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
281 * Fetch a result row as an associative and numeric array
283 * @param resource $res Raw result
286 abstract protected function mysqlFetchArray( $res );
289 * @throws DBUnexpectedError
290 * @param ResultWrapper|resource $res
293 function numRows( $res ) {
294 if ( $res instanceof ResultWrapper
) {
297 MediaWiki\
suppressWarnings();
298 $n = $this->mysqlNumRows( $res );
299 MediaWiki\restoreWarnings
();
301 // Unfortunately, mysql_num_rows does not reset the last errno.
302 // We are not checking for any errors here, since
303 // these are no errors mysql_num_rows can cause.
304 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
305 // See https://bugzilla.wikimedia.org/42430
310 * Get number of rows in result
312 * @param resource $res Raw result
315 abstract protected function mysqlNumRows( $res );
318 * @param ResultWrapper|resource $res
321 function numFields( $res ) {
322 if ( $res instanceof ResultWrapper
) {
326 return $this->mysqlNumFields( $res );
330 * Get number of fields in result
332 * @param resource $res Raw result
335 abstract protected function mysqlNumFields( $res );
338 * @param ResultWrapper|resource $res
342 function fieldName( $res, $n ) {
343 if ( $res instanceof ResultWrapper
) {
347 return $this->mysqlFieldName( $res, $n );
351 * Get the name of the specified field in a result
353 * @param ResultWrapper|resource $res
357 abstract protected function mysqlFieldName( $res, $n );
360 * mysql_field_type() wrapper
361 * @param ResultWrapper|resource $res
365 public function fieldType( $res, $n ) {
366 if ( $res instanceof ResultWrapper
) {
370 return $this->mysqlFieldType( $res, $n );
374 * Get the type of the specified field in a result
376 * @param ResultWrapper|resource $res
380 abstract protected function mysqlFieldType( $res, $n );
383 * @param ResultWrapper|resource $res
387 function dataSeek( $res, $row ) {
388 if ( $res instanceof ResultWrapper
) {
392 return $this->mysqlDataSeek( $res, $row );
396 * Move internal result pointer
398 * @param ResultWrapper|resource $res
402 abstract protected function mysqlDataSeek( $res, $row );
407 function lastError() {
408 if ( $this->mConn
) {
409 # Even if it's non-zero, it can still be invalid
410 MediaWiki\
suppressWarnings();
411 $error = $this->mysqlError( $this->mConn
);
413 $error = $this->mysqlError();
415 MediaWiki\restoreWarnings
();
417 $error = $this->mysqlError();
420 $error .= ' (' . $this->mServer
. ')';
427 * Returns the text of the error message from previous MySQL operation
429 * @param resource $conn Raw connection
432 abstract protected function mysqlError( $conn = null );
435 * @param string $table
436 * @param array $uniqueIndexes
438 * @param string $fname
439 * @return ResultWrapper
441 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
442 return $this->nativeReplace( $table, $rows, $fname );
446 * Estimate rows in dataset
447 * Returns estimated count, based on EXPLAIN output
448 * Takes same arguments as Database::select()
450 * @param string|array $table
451 * @param string|array $vars
452 * @param string|array $conds
453 * @param string $fname
454 * @param string|array $options
457 public function estimateRowCount( $table, $vars = '*', $conds = '',
458 $fname = __METHOD__
, $options = array()
460 $options['EXPLAIN'] = true;
461 $res = $this->select( $table, $vars, $conds, $fname, $options );
462 if ( $res === false ) {
465 if ( !$this->numRows( $res ) ) {
470 foreach ( $res as $plan ) {
471 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
478 * @param string $table
479 * @param string $field
480 * @return bool|MySQLField
482 function fieldInfo( $table, $field ) {
483 $table = $this->tableName( $table );
484 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
488 $n = $this->mysqlNumFields( $res->result
);
489 for ( $i = 0; $i < $n; $i++
) {
490 $meta = $this->mysqlFetchField( $res->result
, $i );
491 if ( $field == $meta->name
) {
492 return new MySQLField( $meta );
500 * Get column information from a result
502 * @param resource $res Raw result
506 abstract protected function mysqlFetchField( $res, $n );
509 * Get information about an index into an object
510 * Returns false if the index does not exist
512 * @param string $table
513 * @param string $index
514 * @param string $fname
515 * @return bool|array|null False or null on failure
517 function indexInfo( $table, $index, $fname = __METHOD__
) {
518 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
519 # SHOW INDEX should work for 3.x and up:
520 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
521 $table = $this->tableName( $table );
522 $index = $this->indexName( $index );
524 $sql = 'SHOW INDEX FROM ' . $table;
525 $res = $this->query( $sql, $fname );
533 foreach ( $res as $row ) {
534 if ( $row->Key_name
== $index ) {
539 return empty( $result ) ?
false : $result;
546 function strencode( $s ) {
547 $sQuoted = $this->mysqlRealEscapeString( $s );
549 if ( $sQuoted === false ) {
551 $sQuoted = $this->mysqlRealEscapeString( $s );
558 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
563 public function addIdentifierQuotes( $s ) {
564 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
565 // Remove NUL bytes and escape backticks by doubling
566 return '`' . str_replace( array( "\0", '`' ), array( '', '``' ), $s ) . '`';
570 * @param string $name
573 public function isQuotedIdentifier( $name ) {
574 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
581 $ping = $this->mysqlPing();
583 // Connection was good or lost but reconnected...
584 // @note: mysqlnd (php 5.6+) does not support this (PHP bug 52561)
588 // Try a full disconnect/reconnect cycle if ping() failed
589 $this->closeConnection();
590 $this->mOpened
= false;
591 $this->mConn
= false;
592 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
598 * Ping a server connection or reconnect if there is no connection
602 abstract protected function mysqlPing();
605 * Set lag time in seconds for a fake slave
609 public function setFakeSlaveLag( $lag ) {
610 $this->mFakeSlaveLag
= $lag;
614 * Make this connection a fake master
616 * @param bool $enabled
618 public function setFakeMaster( $enabled = true ) {
619 $this->mFakeMaster
= $enabled;
625 * This will do a SHOW SLAVE STATUS
630 if ( !is_null( $this->mFakeSlaveLag
) ) {
631 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
633 return $this->mFakeSlaveLag
;
636 return $this->getLagFromSlaveStatus();
642 function getLagFromSlaveStatus() {
643 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
647 $row = $res->fetchObject();
651 if ( strval( $row->Seconds_Behind_Master
) === '' ) {
654 return intval( $row->Seconds_Behind_Master
);
659 * Wait for the slave to catch up to a given master position.
660 * @todo Return values for this and base class are rubbish
662 * @param DBMasterPos|MySQLMasterPos $pos
663 * @param int $timeout The maximum number of seconds to wait for synchronisation
664 * @return int Zero if the slave was past that position already,
665 * greater than zero if we waited for some period of time, less than
666 * zero if we timed out.
668 function masterPosWait( DBMasterPos
$pos, $timeout ) {
669 if ( $this->lastKnownSlavePos
&& $this->lastKnownSlavePos
->hasReached( $pos ) ) {
670 return '0'; // http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html
673 # Commit any open transactions
674 $this->commit( __METHOD__
, 'flush' );
676 if ( !is_null( $this->mFakeSlaveLag
) ) {
677 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
679 if ( $wait > $timeout * 1e6
) {
680 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
683 } elseif ( $wait > 0 ) {
684 wfDebug( "Fake slave waiting $wait us\n" );
689 wfDebug( "Fake slave up to date ($wait us)\n" );
695 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
696 $encFile = $this->addQuotes( $pos->file
);
697 $encPos = intval( $pos->pos
);
698 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
699 $res = $this->doQuery( $sql );
702 if ( $res && $row = $this->fetchRow( $res ) ) {
703 $status = $row[0]; // can be NULL, -1, or 0+ per the MySQL manual
704 if ( ctype_digit( $status ) ) { // success
705 $this->lastKnownSlavePos
= $pos;
713 * Get the position of the master from SHOW SLAVE STATUS
715 * @return MySQLMasterPos|bool
717 function getSlavePos() {
718 if ( !is_null( $this->mFakeSlaveLag
) ) {
719 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
720 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
725 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
726 $row = $this->fetchObject( $res );
729 $pos = isset( $row->Exec_master_log_pos
)
730 ?
$row->Exec_master_log_pos
731 : $row->Exec_Master_Log_Pos
;
733 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
740 * Get the position of the master from SHOW MASTER STATUS
742 * @return MySQLMasterPos|bool
744 function getMasterPos() {
745 if ( $this->mFakeMaster
) {
746 return new MySQLMasterPos( 'fake', microtime( true ) );
749 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
750 $row = $this->fetchObject( $res );
753 return new MySQLMasterPos( $row->File
, $row->Position
);
760 * @param string $index
763 function useIndexClause( $index ) {
764 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
770 function lowPriorityOption() {
771 return 'LOW_PRIORITY';
777 public function getSoftwareLink() {
778 // MariaDB includes its name in its version string; this is how MariaDB's version of
779 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
780 // in libmysql/libmysql.c).
781 $version = $this->getServerVersion();
782 if ( strpos( $version, 'MariaDB' ) !== false ||
strpos( $version, '-maria-' ) !== false ) {
783 return '[{{int:version-db-mariadb-url}} MariaDB]';
786 // Percona Server's version suffix is not very distinctive, and @@version_comment
787 // doesn't give the necessary info for source builds, so assume the server is MySQL.
788 // (Even Percona's version of mysql doesn't try to make the distinction.)
789 return '[{{int:version-db-mysql-url}} MySQL]';
795 public function getServerVersion() {
796 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
797 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
798 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
799 if ( $this->serverVersion
=== null ) {
800 $this->serverVersion
= $this->selectField( '', 'VERSION()', '', __METHOD__
);
802 return $this->serverVersion
;
806 * @param array $options
808 public function setSessionOptions( array $options ) {
809 if ( isset( $options['connTimeout'] ) ) {
810 $timeout = (int)$options['connTimeout'];
811 $this->query( "SET net_read_timeout=$timeout" );
812 $this->query( "SET net_write_timeout=$timeout" );
818 * @param string $newLine
821 public function streamStatementEnd( &$sql, &$newLine ) {
822 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
823 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
824 $this->delimiter
= $m[1];
828 return parent
::streamStatementEnd( $sql, $newLine );
832 * Check to see if a named lock is available. This is non-blocking.
834 * @param string $lockName Name of lock to poll
835 * @param string $method Name of method calling us
839 public function lockIsFree( $lockName, $method ) {
840 $lockName = $this->addQuotes( $lockName );
841 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
842 $row = $this->fetchObject( $result );
844 return ( $row->lockstatus
== 1 );
848 * @param string $lockName
849 * @param string $method
850 * @param int $timeout
853 public function lock( $lockName, $method, $timeout = 5 ) {
854 $lockName = $this->addQuotes( $lockName );
855 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
856 $row = $this->fetchObject( $result );
858 if ( $row->lockstatus
== 1 ) {
861 wfDebug( __METHOD__
. " failed to acquire lock\n" );
869 * http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
870 * @param string $lockName
871 * @param string $method
874 public function unlock( $lockName, $method ) {
875 $lockName = $this->addQuotes( $lockName );
876 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
877 $row = $this->fetchObject( $result );
879 return ( $row->lockstatus
== 1 );
882 public function namedLocksEnqueue() {
888 * @param array $write
889 * @param string $method
890 * @param bool $lowPriority
893 public function lockTables( $read, $write, $method, $lowPriority = true ) {
896 foreach ( $write as $table ) {
897 $tbl = $this->tableName( $table ) .
898 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
902 foreach ( $read as $table ) {
903 $items[] = $this->tableName( $table ) . ' READ';
905 $sql = "LOCK TABLES " . implode( ',', $items );
906 $this->query( $sql, $method );
912 * @param string $method
915 public function unlockTables( $method ) {
916 $this->query( "UNLOCK TABLES", $method );
922 * Get search engine class. All subclasses of this
923 * need to implement this if they wish to use searching.
927 public function getSearchEngine() {
928 return 'SearchMySQL';
934 public function setBigSelects( $value = true ) {
935 if ( $value === 'default' ) {
936 if ( $this->mDefaultBigSelects
=== null ) {
937 # Function hasn't been called before so it must already be set to the default
940 $value = $this->mDefaultBigSelects
;
942 } elseif ( $this->mDefaultBigSelects
=== null ) {
943 $this->mDefaultBigSelects
= (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 );
1059 * Get the underlying binding handle, mConn
1061 * Makes sure that mConn is set (disconnects and ping() failure can unset it).
1062 * This catches broken callers than catch and ignore disconnection exceptions.
1063 * Unlike checking isOpen(), this is safe to call inside of open().
1065 * @return resource|object
1066 * @throws DBUnexpectedError
1069 protected function getBindingHandle() {
1070 if ( !$this->mConn
) {
1071 throw new DBUnexpectedError(
1073 'DB connection was already closed or the connection dropped.'
1077 return $this->mConn
;
1081 * @param string $oldName
1082 * @param string $newName
1083 * @param bool $temporary
1084 * @param string $fname
1087 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
1088 $tmp = $temporary ?
'TEMPORARY ' : '';
1089 $newName = $this->addIdentifierQuotes( $newName );
1090 $oldName = $this->addIdentifierQuotes( $oldName );
1091 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1093 return $this->query( $query, $fname );
1097 * List all tables on the database
1099 * @param string $prefix Only show tables with this prefix, e.g. mw_
1100 * @param string $fname Calling function name
1103 function listTables( $prefix = null, $fname = __METHOD__
) {
1104 $result = $this->query( "SHOW TABLES", $fname );
1106 $endArray = array();
1108 foreach ( $result as $table ) {
1109 $vars = get_object_vars( $table );
1110 $table = array_pop( $vars );
1112 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1113 $endArray[] = $table;
1121 * @param string $tableName
1122 * @param string $fName
1123 * @return bool|ResultWrapper
1125 public function dropTable( $tableName, $fName = __METHOD__
) {
1126 if ( !$this->tableExists( $tableName, $fName ) ) {
1130 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1136 protected function getDefaultSchemaVars() {
1137 $vars = parent
::getDefaultSchemaVars();
1138 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
1139 $vars['wgDBTableOptions'] = str_replace(
1142 $vars['wgDBTableOptions']
1149 * Get status information from SHOW STATUS in an associative array
1151 * @param string $which
1154 function getMysqlStatus( $which = "%" ) {
1155 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1158 foreach ( $res as $row ) {
1159 $status[$row->Variable_name
] = $row->Value
;
1166 * Lists VIEWs in the database
1168 * @param string $prefix Only show VIEWs with this prefix, eg.
1169 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1170 * @param string $fname Name of calling function
1174 public function listViews( $prefix = null, $fname = __METHOD__
) {
1176 if ( !isset( $this->allViews
) ) {
1178 // The name of the column containing the name of the VIEW
1179 $propertyName = 'Tables_in_' . $this->mDBname
;
1181 // Query for the VIEWS
1182 $result = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1183 $this->allViews
= array();
1184 while ( ( $row = $this->fetchRow( $result ) ) !== false ) {
1185 array_push( $this->allViews
, $row[$propertyName] );
1189 if ( is_null( $prefix ) ||
$prefix === '' ) {
1190 return $this->allViews
;
1193 $filteredViews = array();
1194 foreach ( $this->allViews
as $viewName ) {
1195 // Does the name of this VIEW start with the table-prefix?
1196 if ( strpos( $viewName, $prefix ) === 0 ) {
1197 array_push( $filteredViews, $viewName );
1201 return $filteredViews;
1205 * Differentiates between a TABLE and a VIEW.
1207 * @param string $name Name of the TABLE/VIEW to test
1208 * @param string $prefix
1212 public function isView( $name, $prefix = null ) {
1213 return in_array( $name, $this->listViews( $prefix ) );
1221 class MySQLField
implements Field
{
1222 private $name, $tablename, $default, $max_length, $nullable,
1223 $is_pk, $is_unique, $is_multiple, $is_key, $type, $binary,
1224 $is_numeric, $is_blob, $is_unsigned, $is_zerofill;
1226 function __construct( $info ) {
1227 $this->name
= $info->name
;
1228 $this->tablename
= $info->table
;
1229 $this->default = $info->def
;
1230 $this->max_length
= $info->max_length
;
1231 $this->nullable
= !$info->not_null
;
1232 $this->is_pk
= $info->primary_key
;
1233 $this->is_unique
= $info->unique_key
;
1234 $this->is_multiple
= $info->multiple_key
;
1235 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
1236 $this->type
= $info->type
;
1237 $this->binary
= isset( $info->binary
) ?
$info->binary
: false;
1238 $this->is_numeric
= isset( $info->numeric ) ?
$info->numeric : false;
1239 $this->is_blob
= isset( $info->blob
) ?
$info->blob
: false;
1240 $this->is_unsigned
= isset( $info->unsigned
) ?
$info->unsigned
: false;
1241 $this->is_zerofill
= isset( $info->zerofill
) ?
$info->zerofill
: false;
1254 function tableName() {
1255 return $this->tableName
;
1268 function isNullable() {
1269 return $this->nullable
;
1272 function defaultValue() {
1273 return $this->default;
1280 return $this->is_key
;
1286 function isMultipleKey() {
1287 return $this->is_multiple
;
1293 function isBinary() {
1294 return $this->binary
;
1300 function isNumeric() {
1301 return $this->is_numeric
;
1308 return $this->is_blob
;
1314 function isUnsigned() {
1315 return $this->is_unsigned
;
1321 function isZerofill() {
1322 return $this->is_zerofill
;
1326 class MySQLMasterPos
implements DBMasterPos
{
1329 /** @var int Position */
1331 /** @var float UNIX timestamp */
1332 public $asOfTime = 0.0;
1334 function __construct( $file, $pos ) {
1335 $this->file
= $file;
1337 $this->asOfTime
= microtime( true );
1340 function __toString() {
1341 // e.g db1034-bin.000976/843431247
1342 return "{$this->file}/{$this->pos}";
1346 * @return array|bool (int, int)
1348 protected function getCoordinates() {
1350 if ( preg_match( '!\.(\d+)/(\d+)$!', (string)$this, $m ) ) {
1351 return array( (int)$m[1], (int)$m[2] );
1357 function hasReached( MySQLMasterPos
$pos ) {
1358 $thisPos = $this->getCoordinates();
1359 $thatPos = $pos->getCoordinates();
1361 return ( $thisPos && $thatPos && $thisPos >= $thatPos );
1364 function asOfTime() {
1365 return $this->asOfTime
;