Merge "Whitelist the <wbr> element."
[mediawiki.git] / includes / db / DatabaseMysqlBase.php
blobcae133b9aa1738b5ae3d62755ac712ba2355a746
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 DatabaseBase {
33 /** @var MysqlMasterPos */
34 protected $lastKnownSlavePos;
36 /**
37 * @return string
39 function getType() {
40 return 'mysql';
43 /**
44 * @param $server string
45 * @param $user string
46 * @param $password string
47 * @param $dbName string
48 * @return bool
49 * @throws DBConnectionError
51 function open( $server, $user, $password, $dbName ) {
52 global $wgAllDBsAreLocalhost, $wgDBmysql5, $wgSQLMode;
53 wfProfileIn( __METHOD__ );
55 # Debugging hack -- fake cluster
56 if ( $wgAllDBsAreLocalhost ) {
57 $realServer = 'localhost';
58 } else {
59 $realServer = $server;
61 $this->close();
62 $this->mServer = $server;
63 $this->mUser = $user;
64 $this->mPassword = $password;
65 $this->mDBname = $dbName;
67 wfProfileIn( "dbconnect-$server" );
69 # The kernel's default SYN retransmission period is far too slow for us,
70 # so we use a short timeout plus a manual retry. Retrying means that a small
71 # but finite rate of SYN packet loss won't cause user-visible errors.
72 $this->mConn = false;
73 $this->installErrorHandler();
74 try {
75 $this->mConn = $this->mysqlConnect( $realServer );
76 } catch (Exception $ex) {
77 wfProfileOut( "dbconnect-$server" );
78 wfProfileOut( __METHOD__ );
79 throw $ex;
81 $error = $this->restoreErrorHandler();
83 wfProfileOut( "dbconnect-$server" );
85 # Always log connection errors
86 if ( !$this->mConn ) {
87 if ( !$error ) {
88 $error = $this->lastError();
90 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
91 wfDebug( "DB connection error\n" .
92 "Server: $server, User: $user, Password: " .
93 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
95 wfProfileOut( __METHOD__ );
96 return $this->reportConnectionError( $error );
99 if ( $dbName != '' ) {
100 wfSuppressWarnings();
101 $success = $this->selectDB( $dbName );
102 wfRestoreWarnings();
103 if ( !$success ) {
104 wfLogDBError( "Error selecting database $dbName on server {$this->mServer}\n" );
105 wfDebug( "Error selecting database $dbName on server {$this->mServer} " .
106 "from client host " . wfHostname() . "\n" );
108 wfProfileOut( __METHOD__ );
109 return $this->reportConnectionError( "Error selecting database $dbName" );
113 // Tell the server we're communicating with it in UTF-8.
114 // This may engage various charset conversions.
115 if ( $wgDBmysql5 ) {
116 $this->query( 'SET NAMES utf8', __METHOD__ );
117 } else {
118 $this->query( 'SET NAMES binary', __METHOD__ );
120 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
121 if ( is_string( $wgSQLMode ) ) {
122 $mode = $this->addQuotes( $wgSQLMode );
123 $this->query( "SET sql_mode = $mode", __METHOD__ );
126 $this->mOpened = true;
127 wfProfileOut( __METHOD__ );
128 return true;
132 * Open a connection to a MySQL server
134 * @param $realServer string
135 * @return mixed Raw connection
136 * @throws DBConnectionError
138 abstract protected function mysqlConnect( $realServer );
141 * @param $res ResultWrapper
142 * @throws DBUnexpectedError
144 function freeResult( $res ) {
145 if ( $res instanceof ResultWrapper ) {
146 $res = $res->result;
148 wfSuppressWarnings();
149 $ok = $this->mysqlFreeResult( $res );
150 wfRestoreWarnings();
151 if ( !$ok ) {
152 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
157 * Free result memory
159 * @param $res Raw result
160 * @return bool
162 abstract protected function mysqlFreeResult( $res );
165 * @param $res ResultWrapper
166 * @return object|bool
167 * @throws DBUnexpectedError
169 function fetchObject( $res ) {
170 if ( $res instanceof ResultWrapper ) {
171 $res = $res->result;
173 wfSuppressWarnings();
174 $row = $this->mysqlFetchObject( $res );
175 wfRestoreWarnings();
177 $errno = $this->lastErrno();
178 // Unfortunately, mysql_fetch_object does not reset the last errno.
179 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
180 // these are the only errors mysql_fetch_object can cause.
181 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
182 if ( $errno == 2000 || $errno == 2013 ) {
183 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
185 return $row;
189 * Fetch a result row as an object
191 * @param $res Raw result
192 * @return stdClass
194 abstract protected function mysqlFetchObject( $res );
197 * @param $res ResultWrapper
198 * @return array|bool
199 * @throws DBUnexpectedError
201 function fetchRow( $res ) {
202 if ( $res instanceof ResultWrapper ) {
203 $res = $res->result;
205 wfSuppressWarnings();
206 $row = $this->mysqlFetchArray( $res );
207 wfRestoreWarnings();
209 $errno = $this->lastErrno();
210 // Unfortunately, mysql_fetch_array does not reset the last errno.
211 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
212 // these are the only errors mysql_fetch_array can cause.
213 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
214 if ( $errno == 2000 || $errno == 2013 ) {
215 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
217 return $row;
221 * Fetch a result row as an associative and numeric array
223 * @param $res Raw result
224 * @return array
226 abstract protected function mysqlFetchArray( $res );
229 * @throws DBUnexpectedError
230 * @param $res ResultWrapper
231 * @return int
233 function numRows( $res ) {
234 if ( $res instanceof ResultWrapper ) {
235 $res = $res->result;
237 wfSuppressWarnings();
238 $n = $this->mysqlNumRows( $res );
239 wfRestoreWarnings();
240 // Unfortunately, mysql_num_rows does not reset the last errno.
241 // We are not checking for any errors here, since
242 // these are no errors mysql_num_rows can cause.
243 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
244 // See https://bugzilla.wikimedia.org/42430
245 return $n;
249 * Get number of rows in result
251 * @param $res Raw result
252 * @return int
254 abstract protected function mysqlNumRows( $res );
257 * @param $res ResultWrapper
258 * @return int
260 function numFields( $res ) {
261 if ( $res instanceof ResultWrapper ) {
262 $res = $res->result;
264 return $this->mysqlNumFields( $res );
268 * Get number of fields in result
270 * @param $res Raw result
271 * @return int
273 abstract protected function mysqlNumFields( $res );
276 * @param $res ResultWrapper
277 * @param $n string
278 * @return string
280 function fieldName( $res, $n ) {
281 if ( $res instanceof ResultWrapper ) {
282 $res = $res->result;
284 return $this->mysqlFieldName( $res, $n );
288 * Get the name of the specified field in a result
290 * @param $res Raw result
291 * @param $n int
292 * @return string
294 abstract protected function mysqlFieldName( $res, $n );
297 * @param $res ResultWrapper
298 * @param $row
299 * @return bool
301 function dataSeek( $res, $row ) {
302 if ( $res instanceof ResultWrapper ) {
303 $res = $res->result;
305 return $this->mysqlDataSeek( $res, $row );
309 * Move internal result pointer
311 * @param $res Raw result
312 * @param $row int
313 * @return bool
315 abstract protected function mysqlDataSeek( $res, $row );
318 * @return string
320 function lastError() {
321 if ( $this->mConn ) {
322 # Even if it's non-zero, it can still be invalid
323 wfSuppressWarnings();
324 $error = $this->mysqlError( $this->mConn );
325 if ( !$error ) {
326 $error = $this->mysqlError();
328 wfRestoreWarnings();
329 } else {
330 $error = $this->mysqlError();
332 if ( $error ) {
333 $error .= ' (' . $this->mServer . ')';
335 return $error;
339 * Returns the text of the error message from previous MySQL operation
341 * @param $conn Raw connection
342 * @return string
344 abstract protected function mysqlError( $conn = null );
347 * @param $table string
348 * @param $uniqueIndexes
349 * @param $rows array
350 * @param $fname string
351 * @return ResultWrapper
353 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
354 return $this->nativeReplace( $table, $rows, $fname );
358 * Estimate rows in dataset
359 * Returns estimated count, based on EXPLAIN output
360 * Takes same arguments as Database::select()
362 * @param $table string|array
363 * @param $vars string|array
364 * @param $conds string|array
365 * @param $fname string
366 * @param $options string|array
367 * @return int
369 public function estimateRowCount( $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = array() ) {
370 $options['EXPLAIN'] = true;
371 $res = $this->select( $table, $vars, $conds, $fname, $options );
372 if ( $res === false ) {
373 return false;
375 if ( !$this->numRows( $res ) ) {
376 return 0;
379 $rows = 1;
380 foreach ( $res as $plan ) {
381 $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
383 return $rows;
387 * @param $table string
388 * @param $field string
389 * @return bool|MySQLField
391 function fieldInfo( $table, $field ) {
392 $table = $this->tableName( $table );
393 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__, true );
394 if ( !$res ) {
395 return false;
397 $n = $this->mysqlNumFields( $res->result );
398 for ( $i = 0; $i < $n; $i++ ) {
399 $meta = $this->mysqlFetchField( $res->result, $i );
400 if ( $field == $meta->name ) {
401 return new MySQLField( $meta );
404 return false;
408 * Get column information from a result
410 * @param $res Raw result
411 * @param $n int
412 * @return stdClass
414 abstract protected function mysqlFetchField( $res, $n );
417 * Get information about an index into an object
418 * Returns false if the index does not exist
420 * @param $table string
421 * @param $index string
422 * @param $fname string
423 * @return bool|array|null False or null on failure
425 function indexInfo( $table, $index, $fname = __METHOD__ ) {
426 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
427 # SHOW INDEX should work for 3.x and up:
428 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
429 $table = $this->tableName( $table );
430 $index = $this->indexName( $index );
432 $sql = 'SHOW INDEX FROM ' . $table;
433 $res = $this->query( $sql, $fname );
435 if ( !$res ) {
436 return null;
439 $result = array();
441 foreach ( $res as $row ) {
442 if ( $row->Key_name == $index ) {
443 $result[] = $row;
446 return empty( $result ) ? false : $result;
450 * @param $s string
452 * @return string
454 function strencode( $s ) {
455 $sQuoted = $this->mysqlRealEscapeString( $s );
457 if ( $sQuoted === false ) {
458 $this->ping();
459 $sQuoted = $this->mysqlRealEscapeString( $s );
461 return $sQuoted;
465 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
467 * @param $s string
469 * @return string
471 public function addIdentifierQuotes( $s ) {
472 return "`" . $this->strencode( $s ) . "`";
476 * @param $name string
477 * @return bool
479 public function isQuotedIdentifier( $name ) {
480 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
484 * @return bool
486 function ping() {
487 $ping = $this->mysqlPing();
488 if ( $ping ) {
489 return true;
492 $this->closeConnection();
493 $this->mOpened = false;
494 $this->mConn = false;
495 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
496 return true;
500 * Ping a server connection or reconnect if there is no connection
502 * @return bool
504 abstract protected function mysqlPing();
507 * Returns slave lag.
509 * This will do a SHOW SLAVE STATUS
511 * @return int
513 function getLag() {
514 if ( !is_null( $this->mFakeSlaveLag ) ) {
515 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
516 return $this->mFakeSlaveLag;
519 return $this->getLagFromSlaveStatus();
523 * @return bool|int
525 function getLagFromSlaveStatus() {
526 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
527 if ( !$res ) {
528 return false;
530 $row = $res->fetchObject();
531 if ( !$row ) {
532 return false;
534 if ( strval( $row->Seconds_Behind_Master ) === '' ) {
535 return false;
536 } else {
537 return intval( $row->Seconds_Behind_Master );
542 * @deprecated in 1.19, use getLagFromSlaveStatus
544 * @return bool|int
546 function getLagFromProcesslist() {
547 wfDeprecated( __METHOD__, '1.19' );
548 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__ );
549 if ( !$res ) {
550 return false;
552 # Find slave SQL thread
553 foreach ( $res as $row ) {
554 /* This should work for most situations - when default db
555 * for thread is not specified, it had no events executed,
556 * and therefore it doesn't know yet how lagged it is.
558 * Relay log I/O thread does not select databases.
560 if ( $row->User == 'system user' &&
561 $row->State != 'Waiting for master to send event' &&
562 $row->State != 'Connecting to master' &&
563 $row->State != 'Queueing master event to the relay log' &&
564 $row->State != 'Waiting for master update' &&
565 $row->State != 'Requesting binlog dump' &&
566 $row->State != 'Waiting to reconnect after a failed master event read' &&
567 $row->State != 'Reconnecting after a failed master event read' &&
568 $row->State != 'Registering slave on master'
570 # This is it, return the time (except -ve)
571 if ( $row->Time > 0x7fffffff ) {
572 return false;
573 } else {
574 return $row->Time;
578 return false;
582 * Wait for the slave to catch up to a given master position.
583 * @TODO: return values for this and base class are rubbish
585 * @param $pos DBMasterPos object
586 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
587 * @return bool|string
589 function masterPosWait( DBMasterPos $pos, $timeout ) {
590 if ( $this->lastKnownSlavePos && $this->lastKnownSlavePos->hasReached( $pos ) ) {
591 return '0'; // http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html
594 wfProfileIn( __METHOD__ );
595 # Commit any open transactions
596 $this->commit( __METHOD__, 'flush' );
598 if ( !is_null( $this->mFakeSlaveLag ) ) {
599 $status = parent::masterPosWait( $pos, $timeout );
600 wfProfileOut( __METHOD__ );
601 return $status;
604 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
605 $encFile = $this->addQuotes( $pos->file );
606 $encPos = intval( $pos->pos );
607 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
608 $res = $this->doQuery( $sql );
610 $status = false;
611 if ( $res && $row = $this->fetchRow( $res ) ) {
612 $status = $row[0]; // can be NULL, -1, or 0+ per the MySQL manual
613 if ( ctype_digit( $status ) ) { // success
614 $this->lastKnownSlavePos = $pos;
618 wfProfileOut( __METHOD__ );
619 return $status;
623 * Get the position of the master from SHOW SLAVE STATUS
625 * @return MySQLMasterPos|bool
627 function getSlavePos() {
628 if ( !is_null( $this->mFakeSlaveLag ) ) {
629 return parent::getSlavePos();
632 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
633 $row = $this->fetchObject( $res );
635 if ( $row ) {
636 $pos = isset( $row->Exec_master_log_pos ) ? $row->Exec_master_log_pos : $row->Exec_Master_Log_Pos;
637 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
638 } else {
639 return false;
644 * Get the position of the master from SHOW MASTER STATUS
646 * @return MySQLMasterPos|bool
648 function getMasterPos() {
649 if ( $this->mFakeMaster ) {
650 return parent::getMasterPos();
653 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
654 $row = $this->fetchObject( $res );
656 if ( $row ) {
657 return new MySQLMasterPos( $row->File, $row->Position );
658 } else {
659 return false;
664 * @param $index
665 * @return string
667 function useIndexClause( $index ) {
668 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
672 * @return string
674 function lowPriorityOption() {
675 return 'LOW_PRIORITY';
679 * @return string
681 public function getSoftwareLink() {
682 return '[http://www.mysql.com/ MySQL]';
686 * @param $options array
688 public function setSessionOptions( array $options ) {
689 if ( isset( $options['connTimeout'] ) ) {
690 $timeout = (int)$options['connTimeout'];
691 $this->query( "SET net_read_timeout=$timeout" );
692 $this->query( "SET net_write_timeout=$timeout" );
696 public function streamStatementEnd( &$sql, &$newLine ) {
697 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
698 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
699 $this->delimiter = $m[1];
700 $newLine = '';
702 return parent::streamStatementEnd( $sql, $newLine );
706 * Check to see if a named lock is available. This is non-blocking.
708 * @param string $lockName name of lock to poll
709 * @param string $method name of method calling us
710 * @return Boolean
711 * @since 1.20
713 public function lockIsFree( $lockName, $method ) {
714 $lockName = $this->addQuotes( $lockName );
715 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
716 $row = $this->fetchObject( $result );
717 return ( $row->lockstatus == 1 );
721 * @param $lockName string
722 * @param $method string
723 * @param $timeout int
724 * @return bool
726 public function lock( $lockName, $method, $timeout = 5 ) {
727 $lockName = $this->addQuotes( $lockName );
728 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
729 $row = $this->fetchObject( $result );
731 if ( $row->lockstatus == 1 ) {
732 return true;
733 } else {
734 wfDebug( __METHOD__ . " failed to acquire lock\n" );
735 return false;
740 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
741 * @param $lockName string
742 * @param $method string
743 * @return bool
745 public function unlock( $lockName, $method ) {
746 $lockName = $this->addQuotes( $lockName );
747 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
748 $row = $this->fetchObject( $result );
749 return ( $row->lockstatus == 1 );
753 * @param $read array
754 * @param $write array
755 * @param $method string
756 * @param $lowPriority bool
757 * @return bool
759 public function lockTables( $read, $write, $method, $lowPriority = true ) {
760 $items = array();
762 foreach ( $write as $table ) {
763 $tbl = $this->tableName( $table ) .
764 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
765 ' WRITE';
766 $items[] = $tbl;
768 foreach ( $read as $table ) {
769 $items[] = $this->tableName( $table ) . ' READ';
771 $sql = "LOCK TABLES " . implode( ',', $items );
772 $this->query( $sql, $method );
773 return true;
777 * @param $method string
778 * @return bool
780 public function unlockTables( $method ) {
781 $this->query( "UNLOCK TABLES", $method );
782 return true;
786 * Get search engine class. All subclasses of this
787 * need to implement this if they wish to use searching.
789 * @return String
791 public function getSearchEngine() {
792 return 'SearchMySQL';
796 * @param bool $value
797 * @return mixed
799 public function setBigSelects( $value = true ) {
800 if ( $value === 'default' ) {
801 if ( $this->mDefaultBigSelects === null ) {
802 # Function hasn't been called before so it must already be set to the default
803 return;
804 } else {
805 $value = $this->mDefaultBigSelects;
807 } elseif ( $this->mDefaultBigSelects === null ) {
808 $this->mDefaultBigSelects = (bool)$this->selectField( false, '@@sql_big_selects' );
810 $encValue = $value ? '1' : '0';
811 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
815 * DELETE where the condition is a join. MySql uses multi-table deletes.
816 * @param $delTable string
817 * @param $joinTable string
818 * @param $delVar string
819 * @param $joinVar string
820 * @param $conds array|string
821 * @param bool|string $fname bool
822 * @throws DBUnexpectedError
823 * @return bool|ResultWrapper
825 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__ ) {
826 if ( !$conds ) {
827 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
830 $delTable = $this->tableName( $delTable );
831 $joinTable = $this->tableName( $joinTable );
832 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
834 if ( $conds != '*' ) {
835 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
838 return $this->query( $sql, $fname );
842 * @param string $table
843 * @param array $rows
844 * @param array $uniqueIndexes
845 * @param array $set
846 * @param string $fname
847 * @param array $options
848 * @return bool
850 public function upsert(
851 $table, array $rows, array $uniqueIndexes, array $set, $fname = __METHOD__
853 if ( !count( $rows ) ) {
854 return true; // nothing to do
856 $rows = is_array( reset( $rows ) ) ? $rows : array( $rows );
858 $table = $this->tableName( $table );
859 $columns = array_keys( $rows[0] );
861 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
862 $rowTuples = array();
863 foreach ( $rows as $row ) {
864 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
866 $sql .= implode( ',', $rowTuples );
867 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, LIST_SET );
869 return (bool)$this->query( $sql, $fname );
873 * Determines how long the server has been up
875 * @return int
877 function getServerUptime() {
878 $vars = $this->getMysqlStatus( 'Uptime' );
879 return (int)$vars['Uptime'];
883 * Determines if the last failure was due to a deadlock
885 * @return bool
887 function wasDeadlock() {
888 return $this->lastErrno() == 1213;
892 * Determines if the last failure was due to a lock timeout
894 * @return bool
896 function wasLockTimeout() {
897 return $this->lastErrno() == 1205;
901 * Determines if the last query error was something that should be dealt
902 * with by pinging the connection and reissuing the query
904 * @return bool
906 function wasErrorReissuable() {
907 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
911 * Determines if the last failure was due to the database being read-only.
913 * @return bool
915 function wasReadOnlyError() {
916 return $this->lastErrno() == 1223 ||
917 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
921 * @param $oldName
922 * @param $newName
923 * @param $temporary bool
924 * @param $fname string
926 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
927 $tmp = $temporary ? 'TEMPORARY ' : '';
928 $newName = $this->addIdentifierQuotes( $newName );
929 $oldName = $this->addIdentifierQuotes( $oldName );
930 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
931 $this->query( $query, $fname );
935 * List all tables on the database
937 * @param string $prefix Only show tables with this prefix, e.g. mw_
938 * @param string $fname calling function name
939 * @return array
941 function listTables( $prefix = null, $fname = __METHOD__ ) {
942 $result = $this->query( "SHOW TABLES", $fname );
944 $endArray = array();
946 foreach ( $result as $table ) {
947 $vars = get_object_vars( $table );
948 $table = array_pop( $vars );
950 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
951 $endArray[] = $table;
955 return $endArray;
959 * @param $tableName
960 * @param $fName string
961 * @return bool|ResultWrapper
963 public function dropTable( $tableName, $fName = __METHOD__ ) {
964 if ( !$this->tableExists( $tableName, $fName ) ) {
965 return false;
967 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
971 * @return array
973 protected function getDefaultSchemaVars() {
974 $vars = parent::getDefaultSchemaVars();
975 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
976 $vars['wgDBTableOptions'] = str_replace( 'CHARSET=mysql4', 'CHARSET=binary', $vars['wgDBTableOptions'] );
977 return $vars;
981 * Get status information from SHOW STATUS in an associative array
983 * @param $which string
984 * @return array
986 function getMysqlStatus( $which = "%" ) {
987 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
988 $status = array();
990 foreach ( $res as $row ) {
991 $status[$row->Variable_name] = $row->Value;
994 return $status;
1002 * Utility class.
1003 * @ingroup Database
1005 class MySQLField implements Field {
1006 private $name, $tablename, $default, $max_length, $nullable,
1007 $is_pk, $is_unique, $is_multiple, $is_key, $type;
1009 function __construct( $info ) {
1010 $this->name = $info->name;
1011 $this->tablename = $info->table;
1012 $this->default = $info->def;
1013 $this->max_length = $info->max_length;
1014 $this->nullable = !$info->not_null;
1015 $this->is_pk = $info->primary_key;
1016 $this->is_unique = $info->unique_key;
1017 $this->is_multiple = $info->multiple_key;
1018 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
1019 $this->type = $info->type;
1023 * @return string
1025 function name() {
1026 return $this->name;
1030 * @return string
1032 function tableName() {
1033 return $this->tableName;
1037 * @return string
1039 function type() {
1040 return $this->type;
1044 * @return bool
1046 function isNullable() {
1047 return $this->nullable;
1050 function defaultValue() {
1051 return $this->default;
1055 * @return bool
1057 function isKey() {
1058 return $this->is_key;
1062 * @return bool
1064 function isMultipleKey() {
1065 return $this->is_multiple;
1069 class MySQLMasterPos implements DBMasterPos {
1070 var $file, $pos;
1072 function __construct( $file, $pos ) {
1073 $this->file = $file;
1074 $this->pos = $pos;
1077 function __toString() {
1078 // e.g db1034-bin.000976/843431247
1079 return "{$this->file}/{$this->pos}";
1083 * @return array|false (int, int)
1085 protected function getCoordinates() {
1086 $m = array();
1087 if ( preg_match( '!\.(\d+)/(\d+)$!', (string)$this, $m ) ) {
1088 return array( (int)$m[1], (int)$m[2] );
1090 return false;
1093 function hasReached( MySQLMasterPos $pos ) {
1094 $thisPos = $this->getCoordinates();
1095 $thatPos = $pos->getCoordinates();
1096 return ( $thisPos && $thatPos && $thisPos >= $thatPos );