Allow setting of connection timeouts for HTTP requests using cURL
[mediawiki.git] / includes / db / DatabaseMysql.php
blob3eb8c44e90c15b16db3d7ba21dad078ec23eb766
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 * Inherit all methods and properties of Database::Database()
28 * @ingroup Database
29 * @see Database
31 class DatabaseMysql extends DatabaseBase {
33 /**
34 * @return string
36 function getType() {
37 return 'mysql';
40 /**
41 * @param $sql string
42 * @return resource
44 protected function doQuery( $sql ) {
45 if ( $this->bufferResults() ) {
46 $ret = mysql_query( $sql, $this->mConn );
47 } else {
48 $ret = mysql_unbuffered_query( $sql, $this->mConn );
50 return $ret;
53 /**
54 * @param $server string
55 * @param $user string
56 * @param $password string
57 * @param $dbName string
58 * @return bool
59 * @throws DBConnectionError
61 function open( $server, $user, $password, $dbName ) {
62 global $wgAllDBsAreLocalhost, $wgDBmysql5, $wgSQLMode;
63 wfProfileIn( __METHOD__ );
65 # Load mysql.so if we don't have it
66 wfDl( 'mysql' );
68 # Fail now
69 # Otherwise we get a suppressed fatal error, which is very hard to track down
70 if ( !function_exists( 'mysql_connect' ) ) {
71 wfProfileOut( __METHOD__ );
72 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
75 # Debugging hack -- fake cluster
76 if ( $wgAllDBsAreLocalhost ) {
77 $realServer = 'localhost';
78 } else {
79 $realServer = $server;
81 $this->close();
82 $this->mServer = $server;
83 $this->mUser = $user;
84 $this->mPassword = $password;
85 $this->mDBname = $dbName;
87 $connFlags = 0;
88 if ( $this->mFlags & DBO_SSL ) {
89 $connFlags |= MYSQL_CLIENT_SSL;
91 if ( $this->mFlags & DBO_COMPRESS ) {
92 $connFlags |= MYSQL_CLIENT_COMPRESS;
95 wfProfileIn( "dbconnect-$server" );
97 # The kernel's default SYN retransmission period is far too slow for us,
98 # so we use a short timeout plus a manual retry. Retrying means that a small
99 # but finite rate of SYN packet loss won't cause user-visible errors.
100 $this->mConn = false;
101 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
102 $numAttempts = 2;
103 } else {
104 $numAttempts = 1;
106 $this->installErrorHandler();
107 for ( $i = 0; $i < $numAttempts && !$this->mConn; $i++ ) {
108 if ( $i > 1 ) {
109 usleep( 1000 );
111 if ( $this->mFlags & DBO_PERSISTENT ) {
112 $this->mConn = mysql_pconnect( $realServer, $user, $password, $connFlags );
113 } else {
114 # Create a new connection...
115 $this->mConn = mysql_connect( $realServer, $user, $password, true, $connFlags );
117 #if ( $this->mConn === false ) {
118 #$iplus = $i + 1;
119 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
122 $error = $this->restoreErrorHandler();
124 wfProfileOut( "dbconnect-$server" );
126 # Always log connection errors
127 if ( !$this->mConn ) {
128 if ( !$error ) {
129 $error = $this->lastError();
131 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
132 wfDebug( "DB connection error\n" .
133 "Server: $server, User: $user, Password: " .
134 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
136 wfProfileOut( __METHOD__ );
137 return $this->reportConnectionError( $error );
140 if ( $dbName != '' ) {
141 wfSuppressWarnings();
142 $success = mysql_select_db( $dbName, $this->mConn );
143 wfRestoreWarnings();
144 if ( !$success ) {
145 wfLogDBError( "Error selecting database $dbName on server {$this->mServer}\n" );
146 wfDebug( "Error selecting database $dbName on server {$this->mServer} " .
147 "from client host " . wfHostname() . "\n" );
149 wfProfileOut( __METHOD__ );
150 return $this->reportConnectionError( "Error selecting database $dbName" );
154 // Tell the server we're communicating with it in UTF-8.
155 // This may engage various charset conversions.
156 if ( $wgDBmysql5 ) {
157 $this->query( 'SET NAMES utf8', __METHOD__ );
158 } else {
159 $this->query( 'SET NAMES binary', __METHOD__ );
161 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
162 if ( is_string( $wgSQLMode ) ) {
163 $mode = $this->addQuotes( $wgSQLMode );
164 $this->query( "SET sql_mode = $mode", __METHOD__ );
167 $this->mOpened = true;
168 wfProfileOut( __METHOD__ );
169 return true;
173 * @return bool
175 protected function closeConnection() {
176 return mysql_close( $this->mConn );
180 * @param $res ResultWrapper
181 * @throws DBUnexpectedError
183 function freeResult( $res ) {
184 if ( $res instanceof ResultWrapper ) {
185 $res = $res->result;
187 wfSuppressWarnings();
188 $ok = mysql_free_result( $res );
189 wfRestoreWarnings();
190 if ( !$ok ) {
191 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
196 * @param $res ResultWrapper
197 * @return object|bool
198 * @throws DBUnexpectedError
200 function fetchObject( $res ) {
201 if ( $res instanceof ResultWrapper ) {
202 $res = $res->result;
204 wfSuppressWarnings();
205 $row = mysql_fetch_object( $res );
206 wfRestoreWarnings();
208 $errno = $this->lastErrno();
209 // Unfortunately, mysql_fetch_object does not reset the last errno.
210 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
211 // these are the only errors mysql_fetch_object can cause.
212 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
213 if ( $errno == 2000 || $errno == 2013 ) {
214 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
216 return $row;
220 * @param $res ResultWrapper
221 * @return array|bool
222 * @throws DBUnexpectedError
224 function fetchRow( $res ) {
225 if ( $res instanceof ResultWrapper ) {
226 $res = $res->result;
228 wfSuppressWarnings();
229 $row = mysql_fetch_array( $res );
230 wfRestoreWarnings();
232 $errno = $this->lastErrno();
233 // Unfortunately, mysql_fetch_array does not reset the last errno.
234 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
235 // these are the only errors mysql_fetch_object can cause.
236 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
237 if ( $errno == 2000 || $errno == 2013 ) {
238 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
240 return $row;
244 * @throws DBUnexpectedError
245 * @param $res ResultWrapper
246 * @return int
248 function numRows( $res ) {
249 if ( $res instanceof ResultWrapper ) {
250 $res = $res->result;
252 wfSuppressWarnings();
253 $n = mysql_num_rows( $res );
254 wfRestoreWarnings();
255 // Unfortunately, mysql_num_rows does not reset the last errno.
256 // We are not checking for any errors here, since
257 // these are no errors mysql_num_rows can cause.
258 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
259 // See https://bugzilla.wikimedia.org/42430
260 return $n;
264 * @param $res ResultWrapper
265 * @return int
267 function numFields( $res ) {
268 if ( $res instanceof ResultWrapper ) {
269 $res = $res->result;
271 return mysql_num_fields( $res );
275 * @param $res ResultWrapper
276 * @param $n string
277 * @return string
279 function fieldName( $res, $n ) {
280 if ( $res instanceof ResultWrapper ) {
281 $res = $res->result;
283 return mysql_field_name( $res, $n );
287 * @return int
289 function insertId() {
290 return mysql_insert_id( $this->mConn );
294 * @param $res ResultWrapper
295 * @param $row
296 * @return bool
298 function dataSeek( $res, $row ) {
299 if ( $res instanceof ResultWrapper ) {
300 $res = $res->result;
302 return mysql_data_seek( $res, $row );
306 * @return int
308 function lastErrno() {
309 if ( $this->mConn ) {
310 return mysql_errno( $this->mConn );
311 } else {
312 return mysql_errno();
317 * @return string
319 function lastError() {
320 if ( $this->mConn ) {
321 # Even if it's non-zero, it can still be invalid
322 wfSuppressWarnings();
323 $error = mysql_error( $this->mConn );
324 if ( !$error ) {
325 $error = mysql_error();
327 wfRestoreWarnings();
328 } else {
329 $error = mysql_error();
331 if ( $error ) {
332 $error .= ' (' . $this->mServer . ')';
334 return $error;
338 * @return int
340 function affectedRows() {
341 return mysql_affected_rows( $this->mConn );
345 * @param $table string
346 * @param $uniqueIndexes
347 * @param $rows array
348 * @param $fname string
349 * @return ResultWrapper
351 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
352 return $this->nativeReplace( $table, $rows, $fname );
356 * @param string $table
357 * @param array $rows
358 * @param array $uniqueIndexes
359 * @param array $set
360 * @param string $fname
361 * @param array $options
362 * @return bool
364 public function upsert(
365 $table, array $rows, array $uniqueIndexes, array $set, $fname = __METHOD__
367 if ( !count( $rows ) ) {
368 return true; // nothing to do
370 $rows = is_array( reset( $rows ) ) ? $rows : array( $rows );
372 $table = $this->tableName( $table );
373 $columns = array_keys( $rows[0] );
375 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
376 $rowTuples = array();
377 foreach ( $rows as $row ) {
378 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
380 $sql .= implode( ',', $rowTuples );
381 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, LIST_SET );
383 return (bool)$this->query( $sql, $fname );
387 * Estimate rows in dataset
388 * Returns estimated count, based on EXPLAIN output
389 * Takes same arguments as Database::select()
391 * @param $table string|array
392 * @param $vars string|array
393 * @param $conds string|array
394 * @param $fname string
395 * @param $options string|array
396 * @return int
398 public function estimateRowCount( $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = array() ) {
399 $options['EXPLAIN'] = true;
400 $res = $this->select( $table, $vars, $conds, $fname, $options );
401 if ( $res === false ) {
402 return false;
404 if ( !$this->numRows( $res ) ) {
405 return 0;
408 $rows = 1;
409 foreach ( $res as $plan ) {
410 $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
412 return $rows;
416 * @param $table string
417 * @param $field string
418 * @return bool|MySQLField
420 function fieldInfo( $table, $field ) {
421 $table = $this->tableName( $table );
422 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__, true );
423 if ( !$res ) {
424 return false;
426 $n = mysql_num_fields( $res->result );
427 for ( $i = 0; $i < $n; $i++ ) {
428 $meta = mysql_fetch_field( $res->result, $i );
429 if ( $field == $meta->name ) {
430 return new MySQLField( $meta );
433 return false;
437 * Get information about an index into an object
438 * Returns false if the index does not exist
440 * @param $table string
441 * @param $index string
442 * @param $fname string
443 * @return bool|array|null False or null on failure
445 function indexInfo( $table, $index, $fname = __METHOD__ ) {
446 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
447 # SHOW INDEX should work for 3.x and up:
448 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
449 $table = $this->tableName( $table );
450 $index = $this->indexName( $index );
452 $sql = 'SHOW INDEX FROM ' . $table;
453 $res = $this->query( $sql, $fname );
455 if ( !$res ) {
456 return null;
459 $result = array();
461 foreach ( $res as $row ) {
462 if ( $row->Key_name == $index ) {
463 $result[] = $row;
466 return empty( $result ) ? false : $result;
470 * @param $db
471 * @return bool
473 function selectDB( $db ) {
474 $this->mDBname = $db;
475 return mysql_select_db( $db, $this->mConn );
479 * @param $s string
481 * @return string
483 function strencode( $s ) {
484 $sQuoted = mysql_real_escape_string( $s, $this->mConn );
486 if ( $sQuoted === false ) {
487 $this->ping();
488 $sQuoted = mysql_real_escape_string( $s, $this->mConn );
490 return $sQuoted;
494 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
496 * @param $s string
498 * @return string
500 public function addIdentifierQuotes( $s ) {
501 return "`" . $this->strencode( $s ) . "`";
505 * @param $name string
506 * @return bool
508 public function isQuotedIdentifier( $name ) {
509 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
513 * @return bool
515 function ping() {
516 $ping = mysql_ping( $this->mConn );
517 if ( $ping ) {
518 return true;
521 mysql_close( $this->mConn );
522 $this->mOpened = false;
523 $this->mConn = false;
524 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
525 return true;
529 * Returns slave lag.
531 * This will do a SHOW SLAVE STATUS
533 * @return int
535 function getLag() {
536 if ( !is_null( $this->mFakeSlaveLag ) ) {
537 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
538 return $this->mFakeSlaveLag;
541 return $this->getLagFromSlaveStatus();
545 * @return bool|int
547 function getLagFromSlaveStatus() {
548 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
549 if ( !$res ) {
550 return false;
552 $row = $res->fetchObject();
553 if ( !$row ) {
554 return false;
556 if ( strval( $row->Seconds_Behind_Master ) === '' ) {
557 return false;
558 } else {
559 return intval( $row->Seconds_Behind_Master );
564 * @deprecated in 1.19, use getLagFromSlaveStatus
566 * @return bool|int
568 function getLagFromProcesslist() {
569 wfDeprecated( __METHOD__, '1.19' );
570 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__ );
571 if ( !$res ) {
572 return false;
574 # Find slave SQL thread
575 foreach ( $res as $row ) {
576 /* This should work for most situations - when default db
577 * for thread is not specified, it had no events executed,
578 * and therefore it doesn't know yet how lagged it is.
580 * Relay log I/O thread does not select databases.
582 if ( $row->User == 'system user' &&
583 $row->State != 'Waiting for master to send event' &&
584 $row->State != 'Connecting to master' &&
585 $row->State != 'Queueing master event to the relay log' &&
586 $row->State != 'Waiting for master update' &&
587 $row->State != 'Requesting binlog dump' &&
588 $row->State != 'Waiting to reconnect after a failed master event read' &&
589 $row->State != 'Reconnecting after a failed master event read' &&
590 $row->State != 'Registering slave on master'
592 # This is it, return the time (except -ve)
593 if ( $row->Time > 0x7fffffff ) {
594 return false;
595 } else {
596 return $row->Time;
600 return false;
604 * Wait for the slave to catch up to a given master position.
606 * @param $pos DBMasterPos object
607 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
608 * @return bool|string
610 function masterPosWait( DBMasterPos $pos, $timeout ) {
611 $fname = __METHOD__;
612 wfProfileIn( $fname );
614 # Commit any open transactions
615 if ( $this->mTrxLevel ) {
616 $this->commit( $fname );
619 if ( !is_null( $this->mFakeSlaveLag ) ) {
620 $status = parent::masterPosWait( $pos, $timeout );
621 wfProfileOut( $fname );
622 return $status;
625 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
626 $encFile = $this->addQuotes( $pos->file );
627 $encPos = intval( $pos->pos );
628 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
629 $res = $this->doQuery( $sql );
631 if ( $res && $row = $this->fetchRow( $res ) ) {
632 wfProfileOut( $fname );
633 return $row[0];
635 wfProfileOut( $fname );
636 return false;
640 * Get the position of the master from SHOW SLAVE STATUS
642 * @return MySQLMasterPos|bool
644 function getSlavePos() {
645 if ( !is_null( $this->mFakeSlaveLag ) ) {
646 return parent::getSlavePos();
649 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
650 $row = $this->fetchObject( $res );
652 if ( $row ) {
653 $pos = isset( $row->Exec_master_log_pos ) ? $row->Exec_master_log_pos : $row->Exec_Master_Log_Pos;
654 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
655 } else {
656 return false;
661 * Get the position of the master from SHOW MASTER STATUS
663 * @return MySQLMasterPos|bool
665 function getMasterPos() {
666 if ( $this->mFakeMaster ) {
667 return parent::getMasterPos();
670 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
671 $row = $this->fetchObject( $res );
673 if ( $row ) {
674 return new MySQLMasterPos( $row->File, $row->Position );
675 } else {
676 return false;
681 * @return string
683 function getServerVersion() {
684 return mysql_get_server_info( $this->mConn );
688 * @param $index
689 * @return string
691 function useIndexClause( $index ) {
692 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
696 * @return string
698 function lowPriorityOption() {
699 return 'LOW_PRIORITY';
703 * @return string
705 public function getSoftwareLink() {
706 return '[http://www.mysql.com/ MySQL]';
710 * @param $options array
712 public function setSessionOptions( array $options ) {
713 if ( isset( $options['connTimeout'] ) ) {
714 $timeout = (int)$options['connTimeout'];
715 $this->query( "SET net_read_timeout=$timeout" );
716 $this->query( "SET net_write_timeout=$timeout" );
720 public function streamStatementEnd( &$sql, &$newLine ) {
721 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
722 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
723 $this->delimiter = $m[1];
724 $newLine = '';
726 return parent::streamStatementEnd( $sql, $newLine );
730 * Check to see if a named lock is available. This is non-blocking.
732 * @param string $lockName name of lock to poll
733 * @param string $method name of method calling us
734 * @return Boolean
735 * @since 1.20
737 public function lockIsFree( $lockName, $method ) {
738 $lockName = $this->addQuotes( $lockName );
739 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
740 $row = $this->fetchObject( $result );
741 return ( $row->lockstatus == 1 );
745 * @param $lockName string
746 * @param $method string
747 * @param $timeout int
748 * @return bool
750 public function lock( $lockName, $method, $timeout = 5 ) {
751 $lockName = $this->addQuotes( $lockName );
752 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
753 $row = $this->fetchObject( $result );
755 if ( $row->lockstatus == 1 ) {
756 return true;
757 } else {
758 wfDebug( __METHOD__ . " failed to acquire lock\n" );
759 return false;
764 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
765 * @param $lockName string
766 * @param $method string
767 * @return bool
769 public function unlock( $lockName, $method ) {
770 $lockName = $this->addQuotes( $lockName );
771 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
772 $row = $this->fetchObject( $result );
773 return ( $row->lockstatus == 1 );
777 * @param $read array
778 * @param $write array
779 * @param $method string
780 * @param $lowPriority bool
781 * @return bool
783 public function lockTables( $read, $write, $method, $lowPriority = true ) {
784 $items = array();
786 foreach ( $write as $table ) {
787 $tbl = $this->tableName( $table ) .
788 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
789 ' WRITE';
790 $items[] = $tbl;
792 foreach ( $read as $table ) {
793 $items[] = $this->tableName( $table ) . ' READ';
795 $sql = "LOCK TABLES " . implode( ',', $items );
796 $this->query( $sql, $method );
797 return true;
801 * @param $method string
802 * @return bool
804 public function unlockTables( $method ) {
805 $this->query( "UNLOCK TABLES", $method );
806 return true;
810 * Get search engine class. All subclasses of this
811 * need to implement this if they wish to use searching.
813 * @return String
815 public function getSearchEngine() {
816 return 'SearchMySQL';
820 * @param bool $value
821 * @return mixed
823 public function setBigSelects( $value = true ) {
824 if ( $value === 'default' ) {
825 if ( $this->mDefaultBigSelects === null ) {
826 # Function hasn't been called before so it must already be set to the default
827 return;
828 } else {
829 $value = $this->mDefaultBigSelects;
831 } elseif ( $this->mDefaultBigSelects === null ) {
832 $this->mDefaultBigSelects = (bool)$this->selectField( false, '@@sql_big_selects' );
834 $encValue = $value ? '1' : '0';
835 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
839 * DELETE where the condition is a join. MySql uses multi-table deletes.
840 * @param $delTable string
841 * @param $joinTable string
842 * @param $delVar string
843 * @param $joinVar string
844 * @param $conds array|string
845 * @param bool|string $fname bool
846 * @throws DBUnexpectedError
847 * @return bool|ResultWrapper
849 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__ ) {
850 if ( !$conds ) {
851 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
854 $delTable = $this->tableName( $delTable );
855 $joinTable = $this->tableName( $joinTable );
856 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
858 if ( $conds != '*' ) {
859 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
862 return $this->query( $sql, $fname );
866 * Determines how long the server has been up
868 * @return int
870 function getServerUptime() {
871 $vars = $this->getMysqlStatus( 'Uptime' );
872 return (int)$vars['Uptime'];
876 * Determines if the last failure was due to a deadlock
878 * @return bool
880 function wasDeadlock() {
881 return $this->lastErrno() == 1213;
885 * Determines if the last failure was due to a lock timeout
887 * @return bool
889 function wasLockTimeout() {
890 return $this->lastErrno() == 1205;
894 * Determines if the last query error was something that should be dealt
895 * with by pinging the connection and reissuing the query
897 * @return bool
899 function wasErrorReissuable() {
900 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
904 * Determines if the last failure was due to the database being read-only.
906 * @return bool
908 function wasReadOnlyError() {
909 return $this->lastErrno() == 1223 ||
910 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
914 * @param $oldName
915 * @param $newName
916 * @param $temporary bool
917 * @param $fname string
919 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
920 $tmp = $temporary ? 'TEMPORARY ' : '';
921 $newName = $this->addIdentifierQuotes( $newName );
922 $oldName = $this->addIdentifierQuotes( $oldName );
923 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
924 $this->query( $query, $fname );
928 * List all tables on the database
930 * @param string $prefix Only show tables with this prefix, e.g. mw_
931 * @param string $fname calling function name
932 * @return array
934 function listTables( $prefix = null, $fname = __METHOD__ ) {
935 $result = $this->query( "SHOW TABLES", $fname );
937 $endArray = array();
939 foreach ( $result as $table ) {
940 $vars = get_object_vars( $table );
941 $table = array_pop( $vars );
943 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
944 $endArray[] = $table;
948 return $endArray;
952 * @param $tableName
953 * @param $fName string
954 * @return bool|ResultWrapper
956 public function dropTable( $tableName, $fName = __METHOD__ ) {
957 if ( !$this->tableExists( $tableName, $fName ) ) {
958 return false;
960 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
964 * @return array
966 protected function getDefaultSchemaVars() {
967 $vars = parent::getDefaultSchemaVars();
968 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
969 $vars['wgDBTableOptions'] = str_replace( 'CHARSET=mysql4', 'CHARSET=binary', $vars['wgDBTableOptions'] );
970 return $vars;
974 * Get status information from SHOW STATUS in an associative array
976 * @param $which string
977 * @return array
979 function getMysqlStatus( $which = "%" ) {
980 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
981 $status = array();
983 foreach ( $res as $row ) {
984 $status[$row->Variable_name] = $row->Value;
987 return $status;
993 * Utility class.
994 * @ingroup Database
996 class MySQLField implements Field {
997 private $name, $tablename, $default, $max_length, $nullable,
998 $is_pk, $is_unique, $is_multiple, $is_key, $type;
1000 function __construct( $info ) {
1001 $this->name = $info->name;
1002 $this->tablename = $info->table;
1003 $this->default = $info->def;
1004 $this->max_length = $info->max_length;
1005 $this->nullable = !$info->not_null;
1006 $this->is_pk = $info->primary_key;
1007 $this->is_unique = $info->unique_key;
1008 $this->is_multiple = $info->multiple_key;
1009 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
1010 $this->type = $info->type;
1014 * @return string
1016 function name() {
1017 return $this->name;
1021 * @return string
1023 function tableName() {
1024 return $this->tableName;
1028 * @return string
1030 function type() {
1031 return $this->type;
1035 * @return bool
1037 function isNullable() {
1038 return $this->nullable;
1041 function defaultValue() {
1042 return $this->default;
1046 * @return bool
1048 function isKey() {
1049 return $this->is_key;
1053 * @return bool
1055 function isMultipleKey() {
1056 return $this->is_multiple;
1060 class MySQLMasterPos implements DBMasterPos {
1061 var $file, $pos;
1063 function __construct( $file, $pos ) {
1064 $this->file = $file;
1065 $this->pos = $pos;
1068 function __toString() {
1069 return "{$this->file}/{$this->pos}";