3 * @defgroup Database Database
7 * This file deals with MySQL interface functions
8 * and query specifics/optimisations
11 /** Number of times to re-try an operation in case of deadlock */
12 define( 'DEADLOCK_TRIES', 4 );
13 /** Minimum time to wait before retry, in microseconds */
14 define( 'DEADLOCK_DELAY_MIN', 500000 );
15 /** Maximum time to wait before retry */
16 define( 'DEADLOCK_DELAY_MAX', 1500000 );
19 * Database abstraction object
22 abstract class DatabaseBase
{
24 #------------------------------------------------------------------------------
26 #------------------------------------------------------------------------------
28 protected $mLastQuery = '';
29 protected $mDoneWrites = false;
30 protected $mPHPError = false;
32 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
33 protected $mOpened = false;
35 protected $mFailFunction;
36 protected $mTablePrefix;
38 protected $mTrxLevel = 0;
39 protected $mErrorCount = 0;
40 protected $mLBInfo = array();
41 protected $mFakeSlaveLag = null, $mFakeMaster = false;
42 protected $mDefaultBigSelects = null;
44 #------------------------------------------------------------------------------
46 #------------------------------------------------------------------------------
47 # These optionally set a variable and return the previous state
50 * Fail function, takes a Database as a parameter
51 * Set to false for default, 1 for ignore errors
53 function failFunction( $function = NULL ) {
54 return wfSetVar( $this->mFailFunction
, $function );
58 * Output page, used for reporting errors
59 * FALSE means discard output
61 function setOutputPage( $out ) {
62 wfDeprecated( __METHOD__
);
66 * Boolean, controls output of large amounts of debug information
68 function debug( $debug = NULL ) {
69 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
73 * Turns buffering of SQL result sets on (true) or off (false).
74 * Default is "on" and it should not be changed without good reasons.
76 function bufferResults( $buffer = NULL ) {
77 if ( is_null( $buffer ) ) {
78 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
80 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
85 * Turns on (false) or off (true) the automatic generation and sending
86 * of a "we're sorry, but there has been a database error" page on
87 * database errors. Default is on (false). When turned off, the
88 * code should use lastErrno() and lastError() to handle the
89 * situation as appropriate.
91 function ignoreErrors( $ignoreErrors = NULL ) {
92 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
96 * The current depth of nested transactions
97 * @param $level Integer: , default NULL.
99 function trxLevel( $level = NULL ) {
100 return wfSetVar( $this->mTrxLevel
, $level );
104 * Number of errors logged, only useful when errors are ignored
106 function errorCount( $count = NULL ) {
107 return wfSetVar( $this->mErrorCount
, $count );
110 function tablePrefix( $prefix = null ) {
111 return wfSetVar( $this->mTablePrefix
, $prefix );
115 * Properties passed down from the server info array of the load balancer
117 function getLBInfo( $name = NULL ) {
118 if ( is_null( $name ) ) {
119 return $this->mLBInfo
;
121 if ( array_key_exists( $name, $this->mLBInfo
) ) {
122 return $this->mLBInfo
[$name];
129 function setLBInfo( $name, $value = NULL ) {
130 if ( is_null( $value ) ) {
131 $this->mLBInfo
= $name;
133 $this->mLBInfo
[$name] = $value;
138 * Set lag time in seconds for a fake slave
140 function setFakeSlaveLag( $lag ) {
141 $this->mFakeSlaveLag
= $lag;
145 * Make this connection a fake master
147 function setFakeMaster( $enabled = true ) {
148 $this->mFakeMaster
= $enabled;
152 * Returns true if this database supports (and uses) cascading deletes
154 function cascadingDeletes() {
159 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
161 function cleanupTriggers() {
166 * Returns true if this database is strict about what can be put into an IP field.
167 * Specifically, it uses a NULL value instead of an empty string.
169 function strictIPs() {
174 * Returns true if this database uses timestamps rather than integers
176 function realTimestamps() {
181 * Returns true if this database does an implicit sort when doing GROUP BY
183 function implicitGroupby() {
188 * Returns true if this database does an implicit order by when the column has an index
189 * For example: SELECT page_title FROM page LIMIT 1
191 function implicitOrderby() {
196 * Returns true if this database can do a native search on IP columns
197 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
199 function searchableIPs() {
204 * Returns true if this database can use functional indexes
206 function functionalIndexes() {
211 * Return the last query that went through Database::query()
214 function lastQuery() { return $this->mLastQuery
; }
218 * Returns true if the connection may have been used for write queries.
219 * Should return true if unsure.
221 function doneWrites() { return $this->mDoneWrites
; }
224 * Is a connection to the database open?
227 function isOpen() { return $this->mOpened
; }
229 function setFlag( $flag ) {
230 $this->mFlags |
= $flag;
233 function clearFlag( $flag ) {
234 $this->mFlags
&= ~
$flag;
237 function getFlag( $flag ) {
238 return !!($this->mFlags
& $flag);
242 * General read-only accessor
244 function getProperty( $name ) {
248 function getWikiID() {
249 if( $this->mTablePrefix
) {
250 return "{$this->mDBname}-{$this->mTablePrefix}";
252 return $this->mDBname
;
256 #------------------------------------------------------------------------------
258 #------------------------------------------------------------------------------
262 * @param $server String: database server host
263 * @param $user String: database user name
264 * @param $password String: database user password
265 * @param $dbName String: database name
266 * @param $failFunction
268 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
270 function __construct( $server = false, $user = false, $password = false, $dbName = false,
271 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
273 global $wgOut, $wgDBprefix, $wgCommandLineMode;
274 # Can't get a reference if it hasn't been set yet
275 if ( !isset( $wgOut ) ) {
279 $this->mFailFunction
= $failFunction;
280 $this->mFlags
= $flags;
282 if ( $this->mFlags
& DBO_DEFAULT
) {
283 if ( $wgCommandLineMode ) {
284 $this->mFlags
&= ~DBO_TRX
;
286 $this->mFlags |
= DBO_TRX
;
291 // Faster read-only access
292 if ( wfReadOnly() ) {
293 $this->mFlags |= DBO_PERSISTENT;
294 $this->mFlags &= ~DBO_TRX;
297 /** Get the default table prefix*/
298 if ( $tablePrefix == 'get from global' ) {
299 $this->mTablePrefix
= $wgDBprefix;
301 $this->mTablePrefix
= $tablePrefix;
305 $this->open( $server, $user, $password, $dbName );
310 * Same as new DatabaseMysql( ... ), kept for backward compatibility
311 * @param $server String: database server host
312 * @param $user String: database user name
313 * @param $password String: database user password
314 * @param $dbName String: database name
315 * @param failFunction
318 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
320 return new DatabaseMysql( $server, $user, $password, $dbName, $failFunction, $flags );
324 * Usually aborts on failure
325 * If the failFunction is set to a non-zero integer, returns success
326 * @param $server String: database server host
327 * @param $user String: database user name
328 * @param $password String: database user password
329 * @param $dbName String: database name
331 function open( $server, $user, $password, $dbName ) {
332 global $wgAllDBsAreLocalhost;
333 wfProfileIn( __METHOD__
);
335 # Test for missing mysql.so
336 # First try to load it
337 if (!@extension_loaded
('mysql')) {
342 # Otherwise we get a suppressed fatal error, which is very hard to track down
343 if ( !function_exists( 'mysql_connect' ) ) {
344 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
347 # Debugging hack -- fake cluster
348 if ( $wgAllDBsAreLocalhost ) {
349 $realServer = 'localhost';
351 $realServer = $server;
354 $this->mServer
= $server;
355 $this->mUser
= $user;
356 $this->mPassword
= $password;
357 $this->mDBname
= $dbName;
361 wfProfileIn("dbconnect-$server");
363 # The kernel's default SYN retransmission period is far too slow for us,
364 # so we use a short timeout plus a manual retry. Retrying means that a small
365 # but finite rate of SYN packet loss won't cause user-visible errors.
366 $this->mConn
= false;
367 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
372 $this->installErrorHandler();
373 for ( $i = 0; $i < $numAttempts && !$this->mConn
; $i++
) {
377 if ( $this->mFlags
& DBO_PERSISTENT
) {
378 $this->mConn
= mysql_pconnect( $realServer, $user, $password );
380 # Create a new connection...
381 $this->mConn
= mysql_connect( $realServer, $user, $password, true );
383 if ($this->mConn
=== false) {
385 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
388 $phpError = $this->restoreErrorHandler();
389 # Always log connection errors
390 if ( !$this->mConn
) {
391 $error = $this->lastError();
395 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
396 wfDebug( "DB connection error\n" );
397 wfDebug( "Server: $server, User: $user, Password: " .
398 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
402 wfProfileOut("dbconnect-$server");
404 if ( $dbName != '' && $this->mConn
!== false ) {
405 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
407 $error = "Error selecting database $dbName on server {$this->mServer} " .
408 "from client host " . wfHostname() . "\n";
409 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
414 $success = (bool)$this->mConn
;
418 $version = $this->getServerVersion();
419 if ( version_compare( $version, '4.1' ) >= 0 ) {
420 // Tell the server we're communicating with it in UTF-8.
421 // This may engage various charset conversions.
424 $this->query( 'SET NAMES utf8', __METHOD__
);
426 // Turn off strict mode
427 $this->query( "SET sql_mode = ''", __METHOD__
);
430 // Turn off strict mode if it is on
432 $this->reportConnectionError( $phpError );
435 $this->mOpened
= $success;
436 wfProfileOut( __METHOD__
);
440 protected function installErrorHandler() {
441 $this->mPHPError
= false;
442 $this->htmlErrors
= ini_set( 'html_errors', '0' );
443 set_error_handler( array( $this, 'connectionErrorHandler' ) );
446 protected function restoreErrorHandler() {
447 restore_error_handler();
448 if ( $this->htmlErrors
!== false ) {
449 ini_set( 'html_errors', $this->htmlErrors
);
451 if ( $this->mPHPError
) {
452 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
453 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
460 protected function connectionErrorHandler( $errno, $errstr ) {
461 $this->mPHPError
= $errstr;
465 * Closes a database connection.
466 * if it is open : commits any open transactions
468 * @return Bool operation success. true if already closed.
472 $this->mOpened
= false;
473 if ( $this->mConn
) {
474 if ( $this->trxLevel() ) {
475 $this->immediateCommit();
477 return mysql_close( $this->mConn
);
484 * @param $error String: fallback error message, used if none is given by MySQL
486 function reportConnectionError( $error = 'Unknown error' ) {
487 $myError = $this->lastError();
492 if ( $this->mFailFunction
) {
493 # Legacy error handling method
494 if ( !is_int( $this->mFailFunction
) ) {
495 $ff = $this->mFailFunction
;
496 $ff( $this, $error );
500 throw new DBConnectionError( $this, $error );
505 * Determine whether a query writes to the DB.
506 * Should return true if unsure.
508 function isWriteQuery( $sql ) {
509 return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW)\b/i', $sql );
513 * Usually aborts on failure. If errors are explicitly ignored, returns success.
515 * @param $sql String: SQL query
516 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
517 * comment (you can use __METHOD__ or add some extra info)
518 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
519 * maybe best to catch the exception instead?
520 * @return true for a successful write query, ResultWrapper object for a successful read query,
521 * or false on failure if $tempIgnore set
522 * @throws DBQueryError Thrown when the database returns an error of any kind
524 public function query( $sql, $fname = '', $tempIgnore = false ) {
527 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
528 if ( isset( $wgProfiler ) ) {
529 # generalizeSQL will probably cut down the query to reasonable
530 # logging size most of the time. The substr is really just a sanity check.
532 # Who's been wasting my precious column space? -- TS
533 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
536 $queryProf = 'query-m: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
537 $totalProf = 'Database::query-master';
539 $queryProf = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
540 $totalProf = 'Database::query';
542 wfProfileIn( $totalProf );
543 wfProfileIn( $queryProf );
546 $this->mLastQuery
= $sql;
547 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
548 // Set a flag indicating that writes have been done
549 wfDebug( __METHOD__
.": Writes done: $sql\n" );
550 $this->mDoneWrites
= true;
553 # Add a comment for easy SHOW PROCESSLIST interpretation
556 if ( is_object( $wgUser ) && !($wgUser instanceof StubObject
) ) {
557 $userName = $wgUser->getName();
558 if ( mb_strlen( $userName ) > 15 ) {
559 $userName = mb_substr( $userName, 0, 15 ) . '...';
561 $userName = str_replace( '/', '', $userName );
565 $commentedSql = preg_replace('/\s/', " /* $fname $userName */ ", $sql, 1);
567 # $commentedSql = $sql;
570 # If DBO_TRX is set, start a transaction
571 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
572 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK') {
573 // avoid establishing transactions for SHOW and SET statements too -
574 // that would delay transaction initializations to once connection
575 // is really used by application
576 $sqlstart = substr($sql,0,10); // very much worth it, benchmark certified(tm)
577 if (strpos($sqlstart,"SHOW ")!==0 and strpos($sqlstart,"SET ")!==0)
581 if ( $this->debug() ) {
582 $sqlx = substr( $commentedSql, 0, 500 );
583 $sqlx = strtr( $sqlx, "\t\n", ' ' );
585 wfDebug( "SQL-master: $sqlx\n" );
587 wfDebug( "SQL: $sqlx\n" );
591 if ( istainted( $sql ) & TC_MYSQL
) {
592 throw new MWException( 'Tainted query found' );
595 # Do the query and handle errors
596 $ret = $this->doQuery( $commentedSql );
598 # Try reconnecting if the connection was lost
599 if ( false === $ret && $this->wasErrorReissuable() ) {
600 # Transaction is gone, like it or not
601 $this->mTrxLevel
= 0;
602 wfDebug( "Connection lost, reconnecting...\n" );
603 if ( $this->ping() ) {
604 wfDebug( "Reconnected\n" );
605 $sqlx = substr( $commentedSql, 0, 500 );
606 $sqlx = strtr( $sqlx, "\t\n", ' ' );
607 global $wgRequestTime;
608 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
609 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
610 $ret = $this->doQuery( $commentedSql );
612 wfDebug( "Failed\n" );
616 if ( false === $ret ) {
617 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
620 if ( isset( $wgProfiler ) ) {
621 wfProfileOut( $queryProf );
622 wfProfileOut( $totalProf );
624 return $this->resultObject( $ret );
628 * The DBMS-dependent part of query()
629 * @param $sql String: SQL query.
630 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
633 /*private*/ function doQuery( $sql ) {
634 if( $this->bufferResults() ) {
635 $ret = mysql_query( $sql, $this->mConn
);
637 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
643 * @param $error String
644 * @param $errno Integer
646 * @param $fname String
647 * @param $tempIgnore Boolean
649 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
650 global $wgCommandLineMode;
651 # Ignore errors during error handling to avoid infinite recursion
652 $ignore = $this->ignoreErrors( true );
653 ++
$this->mErrorCount
;
655 if( $ignore ||
$tempIgnore ) {
656 wfDebug("SQL ERROR (ignored): $error\n");
657 $this->ignoreErrors( $ignore );
659 $sql1line = str_replace( "\n", "\\n", $sql );
660 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
661 wfDebug("SQL ERROR: " . $error . "\n");
662 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
668 * Intended to be compatible with the PEAR::DB wrapper functions.
669 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
671 * ? = scalar value, quoted as necessary
672 * ! = raw SQL bit (a function for instance)
673 * & = filename; reads the file and inserts as a blob
674 * (we don't use this though...)
676 function prepare( $sql, $func = 'Database::prepare' ) {
677 /* MySQL doesn't support prepared statements (yet), so just
678 pack up the query for reference. We'll manually replace
680 return array( 'query' => $sql, 'func' => $func );
683 function freePrepared( $prepared ) {
684 /* No-op for MySQL */
688 * Execute a prepared query with the various arguments
689 * @param $prepared String: the prepared sql
690 * @param $args Mixed: Either an array here, or put scalars as varargs
692 function execute( $prepared, $args = null ) {
693 if( !is_array( $args ) ) {
695 $args = func_get_args();
696 array_shift( $args );
698 $sql = $this->fillPrepared( $prepared['query'], $args );
699 return $this->query( $sql, $prepared['func'] );
703 * Prepare & execute an SQL statement, quoting and inserting arguments
704 * in the appropriate places.
705 * @param $query String
708 function safeQuery( $query, $args = null ) {
709 $prepared = $this->prepare( $query, 'Database::safeQuery' );
710 if( !is_array( $args ) ) {
712 $args = func_get_args();
713 array_shift( $args );
715 $retval = $this->execute( $prepared, $args );
716 $this->freePrepared( $prepared );
721 * For faking prepared SQL statements on DBs that don't support
723 * @param $preparedQuery String: a 'preparable' SQL statement
724 * @param $args Array of arguments to fill it with
725 * @return string executable SQL
727 function fillPrepared( $preparedQuery, $args ) {
729 $this->preparedArgs
=& $args;
730 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
731 array( &$this, 'fillPreparedArg' ), $preparedQuery );
735 * preg_callback func for fillPrepared()
736 * The arguments should be in $this->preparedArgs and must not be touched
737 * while we're doing this.
739 * @param $matches Array
743 function fillPreparedArg( $matches ) {
744 switch( $matches[1] ) {
745 case '\\?': return '?';
746 case '\\!': return '!';
747 case '\\&': return '&';
749 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
750 switch( $matches[1] ) {
751 case '?': return $this->addQuotes( $arg );
752 case '!': return $arg;
754 # return $this->addQuotes( file_get_contents( $arg ) );
755 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
757 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
762 * Free a result object
763 * @param $res Mixed: A SQL result
765 function freeResult( $res ) {
766 if ( $res instanceof ResultWrapper
) {
769 if ( !@/**/mysql_free_result( $res ) ) {
770 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
775 * Fetch the next row from the given result object, in object form.
776 * Fields can be retrieved with $row->fieldname, with fields acting like
779 * @param $res SQL result object as returned from Database::query(), etc.
780 * @return MySQL row object
781 * @throws DBUnexpectedError Thrown if the database returns an error
783 function fetchObject( $res ) {
784 if ( $res instanceof ResultWrapper
) {
787 @/**/$row = mysql_fetch_object( $res );
788 if( $this->lastErrno() ) {
789 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
795 * Fetch the next row from the given result object, in associative array
796 * form. Fields are retrieved with $row['fieldname'].
798 * @param $res SQL result object as returned from Database::query(), etc.
799 * @return MySQL row object
800 * @throws DBUnexpectedError Thrown if the database returns an error
802 function fetchRow( $res ) {
803 if ( $res instanceof ResultWrapper
) {
806 @/**/$row = mysql_fetch_array( $res );
807 if ( $this->lastErrno() ) {
808 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
814 * Get the number of rows in a result object
815 * @param $res Mixed: A SQL result
817 function numRows( $res ) {
818 if ( $res instanceof ResultWrapper
) {
821 @/**/$n = mysql_num_rows( $res );
822 if( $this->lastErrno() ) {
823 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
829 * Get the number of fields in a result object
830 * See documentation for mysql_num_fields()
831 * @param $res Mixed: A SQL result
833 function numFields( $res ) {
834 if ( $res instanceof ResultWrapper
) {
837 return mysql_num_fields( $res );
841 * Get a field name in a result object
842 * See documentation for mysql_field_name():
843 * http://www.php.net/mysql_field_name
844 * @param $res Mixed: A SQL result
847 function fieldName( $res, $n ) {
848 if ( $res instanceof ResultWrapper
) {
851 return mysql_field_name( $res, $n );
855 * Get the inserted value of an auto-increment row
857 * The value inserted should be fetched from nextSequenceValue()
860 * $id = $dbw->nextSequenceValue('page_page_id_seq');
861 * $dbw->insert('page',array('page_id' => $id));
862 * $id = $dbw->insertId();
864 function insertId() { return mysql_insert_id( $this->mConn
); }
867 * Change the position of the cursor in a result object
868 * See mysql_data_seek()
869 * @param $res Mixed: A SQL result
870 * @param $row Mixed: Either MySQL row or ResultWrapper
872 function dataSeek( $res, $row ) {
873 if ( $res instanceof ResultWrapper
) {
876 return mysql_data_seek( $res, $row );
880 * Get the last error number
883 function lastErrno() {
884 if ( $this->mConn
) {
885 return mysql_errno( $this->mConn
);
887 return mysql_errno();
892 * Get a description of the last error
893 * See mysql_error() for more details
895 function lastError() {
896 if ( $this->mConn
) {
897 # Even if it's non-zero, it can still be invalid
898 wfSuppressWarnings();
899 $error = mysql_error( $this->mConn
);
901 $error = mysql_error();
905 $error = mysql_error();
908 $error .= ' (' . $this->mServer
. ')';
913 * Get the number of rows affected by the last write query
914 * See mysql_affected_rows() for more details
916 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
919 * Simple UPDATE wrapper
920 * Usually aborts on failure
921 * If errors are explicitly ignored, returns success
923 * This function exists for historical reasons, Database::update() has a more standard
924 * calling convention and feature set
926 function set( $table, $var, $value, $cond, $fname = 'Database::set' ) {
927 $table = $this->tableName( $table );
928 $sql = "UPDATE $table SET $var = '" .
929 $this->strencode( $value ) . "' WHERE ($cond)";
930 return (bool)$this->query( $sql, $fname );
934 * Simple SELECT wrapper, returns a single field, input must be encoded
935 * Usually aborts on failure
936 * If errors are explicitly ignored, returns FALSE on failure
938 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
939 if ( !is_array( $options ) ) {
940 $options = array( $options );
942 $options['LIMIT'] = 1;
944 $res = $this->select( $table, $var, $cond, $fname, $options );
945 if ( $res === false ||
!$this->numRows( $res ) ) {
948 $row = $this->fetchRow( $res );
949 if ( $row !== false ) {
950 $this->freeResult( $res );
951 return reset( $row );
958 * Returns an optional USE INDEX clause to go after the table, and a
959 * string to go at the end of the query
963 * @param $options Array: associative array of options to be turned into
964 * an SQL query, valid keys are listed in the function.
967 function makeSelectOptions( $options ) {
968 $preLimitTail = $postLimitTail = '';
971 $noKeyOptions = array();
972 foreach ( $options as $key => $option ) {
973 if ( is_numeric( $key ) ) {
974 $noKeyOptions[$option] = true;
978 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
979 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
980 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
982 //if (isset($options['LIMIT'])) {
983 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
984 // isset($options['OFFSET']) ? $options['OFFSET']
988 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
989 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
990 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
992 # Various MySQL extensions
993 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
994 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
995 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
996 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
997 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
998 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
999 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
1000 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
1002 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1003 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1008 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1014 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
1015 * @param $vars Mixed: Array or string, field name(s) to be retrieved
1016 * @param $conds Mixed: Array or string, condition(s) for WHERE
1017 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1018 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1019 * see Database::makeSelectOptions code for list of supported stuff
1020 * @param $join_conds Array: Associative array of table join conditions (optional)
1021 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1022 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
1024 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() )
1026 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1027 return $this->query( $sql, $fname );
1033 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
1034 * @param $vars Mixed: Array or string, field name(s) to be retrieved
1035 * @param $conds Mixed: Array or string, condition(s) for WHERE
1036 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1037 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1038 * see Database::makeSelectOptions code for list of supported stuff
1039 * @param $join_conds Array: Associative array of table join conditions (optional)
1040 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1041 * @return string, the SQL text
1043 function selectSQLText( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() ) {
1044 if( is_array( $vars ) ) {
1045 $vars = implode( ',', $vars );
1047 if( !is_array( $options ) ) {
1048 $options = array( $options );
1050 if( is_array( $table ) ) {
1051 if ( !empty($join_conds) ||
( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) )
1052 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
1054 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1055 } elseif ($table!='') {
1056 if ($table{0}==' ') {
1057 $from = ' FROM ' . $table;
1059 $from = ' FROM ' . $this->tableName( $table );
1065 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1067 if( !empty( $conds ) ) {
1068 if ( is_array( $conds ) ) {
1069 $conds = $this->makeList( $conds, LIST_AND
);
1071 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1073 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1076 if (isset($options['LIMIT']))
1077 $sql = $this->limitResult($sql, $options['LIMIT'],
1078 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
1079 $sql = "$sql $postLimitTail";
1081 if (isset($options['EXPLAIN'])) {
1082 $sql = 'EXPLAIN ' . $sql;
1088 * Single row SELECT wrapper
1089 * Aborts or returns FALSE on error
1091 * @param $table String: table name
1092 * @param $vars String: the selected variables
1093 * @param $conds Array: a condition map, terms are ANDed together.
1094 * Items with numeric keys are taken to be literal conditions
1095 * Takes an array of selected variables, and a condition map, which is ANDed
1096 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1097 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1098 * $obj- >page_id is the ID of the Astronomy article
1099 * @param $fname String: Calling functio name
1100 * @param $options Array
1101 * @param $join_conds Array
1103 * @todo migrate documentation to phpdocumentor format
1105 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array(), $join_conds = array() ) {
1106 $options['LIMIT'] = 1;
1107 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1108 if ( $res === false )
1110 if ( !$this->numRows($res) ) {
1111 $this->freeResult($res);
1114 $obj = $this->fetchObject( $res );
1115 $this->freeResult( $res );
1121 * Estimate rows in dataset
1122 * Returns estimated count, based on EXPLAIN output
1123 * Takes same arguments as Database::select()
1126 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
1127 $options['EXPLAIN']=true;
1128 $res = $this->select ($table, $vars, $conds, $fname, $options );
1129 if ( $res === false )
1131 if (!$this->numRows($res)) {
1132 $this->freeResult($res);
1138 while( $plan = $this->fetchObject( $res ) ) {
1139 $rows *= ($plan->rows
> 0)?
$plan->rows
:1; // avoid resetting to zero
1142 $this->freeResult($res);
1148 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1149 * It's only slightly flawed. Don't use for anything important.
1151 * @param $sql String: A SQL Query
1153 static function generalizeSQL( $sql ) {
1154 # This does the same as the regexp below would do, but in such a way
1155 # as to avoid crashing php on some large strings.
1156 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1158 $sql = str_replace ( "\\\\", '', $sql);
1159 $sql = str_replace ( "\\'", '', $sql);
1160 $sql = str_replace ( "\\\"", '', $sql);
1161 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1162 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1164 # All newlines, tabs, etc replaced by single space
1165 $sql = preg_replace ( '/\s+/', ' ', $sql);
1168 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1174 * Determines whether a field exists in a table
1175 * Usually aborts on failure
1176 * If errors are explicitly ignored, returns NULL on failure
1178 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1179 $table = $this->tableName( $table );
1180 $res = $this->query( 'DESCRIBE '.$table, $fname );
1187 while ( $row = $this->fetchObject( $res ) ) {
1188 if ( $row->Field
== $field ) {
1197 * Determines whether an index exists
1198 * Usually aborts on failure
1199 * If errors are explicitly ignored, returns NULL on failure
1201 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1202 $info = $this->indexInfo( $table, $index, $fname );
1203 if ( is_null( $info ) ) {
1206 return $info !== false;
1212 * Get information about an index into an object
1213 * Returns false if the index does not exist
1215 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1216 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1217 # SHOW INDEX should work for 3.x and up:
1218 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1219 $table = $this->tableName( $table );
1220 $index = $this->indexName( $index );
1221 $sql = 'SHOW INDEX FROM '.$table;
1222 $res = $this->query( $sql, $fname );
1228 while ( $row = $this->fetchObject( $res ) ) {
1229 if ( $row->Key_name
== $index ) {
1233 $this->freeResult($res);
1235 return empty($result) ?
false : $result;
1239 * Query whether a given table exists
1241 function tableExists( $table ) {
1242 $table = $this->tableName( $table );
1243 $old = $this->ignoreErrors( true );
1244 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1245 $this->ignoreErrors( $old );
1247 $this->freeResult( $res );
1255 * mysql_fetch_field() wrapper
1256 * Returns false if the field doesn't exist
1261 function fieldInfo( $table, $field ) {
1262 $table = $this->tableName( $table );
1263 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1264 $n = mysql_num_fields( $res->result
);
1265 for( $i = 0; $i < $n; $i++
) {
1266 $meta = mysql_fetch_field( $res->result
, $i );
1267 if( $field == $meta->name
) {
1268 return new MySQLField($meta);
1275 * mysql_field_type() wrapper
1277 function fieldType( $res, $index ) {
1278 if ( $res instanceof ResultWrapper
) {
1279 $res = $res->result
;
1281 return mysql_field_type( $res, $index );
1285 * Determines if a given index is unique
1287 function indexUnique( $table, $index ) {
1288 $indexInfo = $this->indexInfo( $table, $index );
1289 if ( !$indexInfo ) {
1292 return !$indexInfo[0]->Non_unique
;
1296 * INSERT wrapper, inserts an array into a table
1298 * $a may be a single associative array, or an array of these with numeric keys, for
1301 * Usually aborts on failure
1302 * If errors are explicitly ignored, returns success
1304 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1305 # No rows to insert, easy just return now
1306 if ( !count( $a ) ) {
1310 $table = $this->tableName( $table );
1311 if ( !is_array( $options ) ) {
1312 $options = array( $options );
1314 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1316 $keys = array_keys( $a[0] );
1319 $keys = array_keys( $a );
1322 $sql = 'INSERT ' . implode( ' ', $options ) .
1323 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1327 foreach ( $a as $row ) {
1333 $sql .= '(' . $this->makeList( $row ) . ')';
1336 $sql .= '(' . $this->makeList( $a ) . ')';
1338 return (bool)$this->query( $sql, $fname );
1342 * Make UPDATE options for the Database::update function
1345 * @param $options Array: The options passed to Database::update
1348 function makeUpdateOptions( $options ) {
1349 if( !is_array( $options ) ) {
1350 $options = array( $options );
1353 if ( in_array( 'LOW_PRIORITY', $options ) )
1354 $opts[] = $this->lowPriorityOption();
1355 if ( in_array( 'IGNORE', $options ) )
1357 return implode(' ', $opts);
1361 * UPDATE wrapper, takes a condition array and a SET array
1363 * @param $table String: The table to UPDATE
1364 * @param $values Array: An array of values to SET
1365 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
1366 * @param $fname String: The Class::Function calling this function
1368 * @param $options Array: An array of UPDATE options, can be one or
1369 * more of IGNORE, LOW_PRIORITY
1372 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1373 $table = $this->tableName( $table );
1374 $opts = $this->makeUpdateOptions( $options );
1375 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1376 if ( $conds != '*' ) {
1377 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1379 return $this->query( $sql, $fname );
1383 * Makes an encoded list of strings from an array
1385 * LIST_COMMA - comma separated, no field names
1386 * LIST_AND - ANDed WHERE clause (without the WHERE)
1387 * LIST_OR - ORed WHERE clause (without the WHERE)
1388 * LIST_SET - comma separated with field names, like a SET clause
1389 * LIST_NAMES - comma separated field names
1391 function makeList( $a, $mode = LIST_COMMA
) {
1392 if ( !is_array( $a ) ) {
1393 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1398 foreach ( $a as $field => $value ) {
1400 if ( $mode == LIST_AND
) {
1402 } elseif($mode == LIST_OR
) {
1410 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1411 $list .= "($value)";
1412 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
1414 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array($value) ) {
1415 if( count( $value ) == 0 ) {
1416 throw new MWException( __METHOD__
.': empty input' );
1417 } elseif( count( $value ) == 1 ) {
1418 // Special-case single values, as IN isn't terribly efficient
1419 // Don't necessarily assume the single key is 0; we don't
1420 // enforce linear numeric ordering on other arrays here.
1421 $value = array_values( $value );
1422 $list .= $field." = ".$this->addQuotes( $value[0] );
1424 $list .= $field." IN (".$this->makeList($value).") ";
1426 } elseif( $value === null ) {
1427 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1428 $list .= "$field IS ";
1429 } elseif ( $mode == LIST_SET
) {
1430 $list .= "$field = ";
1434 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1435 $list .= "$field = ";
1437 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1444 * Bitwise operations
1447 function bitNot($field) {
1448 return '~'.$bitField;
1451 function bitAnd($fieldLeft, $fieldRight) {
1452 return $fieldLeft.'&'.$fieldRight;
1455 function bitOr($fieldLeft, $fieldRight) {
1456 return $fieldLeft.'|'.$fieldRight;
1460 * Change the current database
1462 function selectDB( $db ) {
1463 $this->mDBname
= $db;
1464 return mysql_select_db( $db, $this->mConn
);
1468 * Get the current DB name
1470 function getDBname() {
1471 return $this->mDBname
;
1475 * Get the server hostname or IP address
1477 function getServer() {
1478 return $this->mServer
;
1482 * Format a table name ready for use in constructing an SQL query
1484 * This does two important things: it quotes the table names to clean them up,
1485 * and it adds a table prefix if only given a table name with no quotes.
1487 * All functions of this object which require a table name call this function
1488 * themselves. Pass the canonical name to such functions. This is only needed
1489 * when calling query() directly.
1491 * @param $name String: database table name
1492 * @return String: full database name
1494 function tableName( $name ) {
1495 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1496 # Skip the entire process when we have a string quoted on both ends.
1497 # Note that we check the end so that we will still quote any use of
1498 # use of `database`.table. But won't break things if someone wants
1499 # to query a database table with a dot in the name.
1500 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) return $name;
1502 # Lets test for any bits of text that should never show up in a table
1503 # name. Basically anything like JOIN or ON which are actually part of
1504 # SQL queries, but may end up inside of the table value to combine
1505 # sql. Such as how the API is doing.
1506 # Note that we use a whitespace test rather than a \b test to avoid
1507 # any remote case where a word like on may be inside of a table name
1508 # surrounded by symbols which may be considered word breaks.
1509 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) return $name;
1511 # Split database and table into proper variables.
1512 # We reverse the explode so that database.table and table both output
1513 # the correct table.
1514 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1515 if( isset( $dbDetails[1] ) ) @list
( $table, $database ) = $dbDetails;
1516 else @list
( $table ) = $dbDetails;
1517 $prefix = $this->mTablePrefix
; # Default prefix
1519 # A database name has been specified in input. Quote the table name
1520 # because we don't want any prefixes added.
1521 if( isset($database) ) $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
1523 # Note that we use the long format because php will complain in in_array if
1524 # the input is not an array, and will complain in is_array if it is not set.
1525 if( !isset( $database ) # Don't use shared database if pre selected.
1526 && isset( $wgSharedDB ) # We have a shared database
1527 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1528 && isset( $wgSharedTables )
1529 && is_array( $wgSharedTables )
1530 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1531 $database = $wgSharedDB;
1532 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1535 # Quote the $database and $table and apply the prefix if not quoted.
1536 if( isset($database) ) $database = ( $database[0] == '`' ?
$database : "`{$database}`" );
1537 $table = ( $table[0] == '`' ?
$table : "`{$prefix}{$table}`" );
1539 # Merge our database and table into our final table name.
1540 $tableName = ( isset($database) ?
"{$database}.{$table}" : "{$table}" );
1542 # We're finished, return.
1547 * Fetch a number of table names into an array
1548 * This is handy when you need to construct SQL for joins
1551 * extract($dbr->tableNames('user','watchlist'));
1552 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1553 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1555 public function tableNames() {
1556 $inArray = func_get_args();
1558 foreach ( $inArray as $name ) {
1559 $retVal[$name] = $this->tableName( $name );
1565 * Fetch a number of table names into an zero-indexed numerical array
1566 * This is handy when you need to construct SQL for joins
1569 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1570 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1571 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1573 public function tableNamesN() {
1574 $inArray = func_get_args();
1576 foreach ( $inArray as $name ) {
1577 $retVal[] = $this->tableName( $name );
1585 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1588 $use_index_safe = is_array($use_index) ?
$use_index : array();
1589 $join_conds_safe = is_array($join_conds) ?
$join_conds : array();
1590 foreach ( $tables as $table ) {
1591 // Is there a JOIN and INDEX clause for this table?
1592 if ( isset($join_conds_safe[$table]) && isset($use_index_safe[$table]) ) {
1593 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1594 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1595 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
) . ')';
1596 $retJOIN[] = $tableClause;
1597 // Is there an INDEX clause?
1598 } else if ( isset($use_index_safe[$table]) ) {
1599 $tableClause = $this->tableName( $table );
1600 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1601 $ret[] = $tableClause;
1602 // Is there a JOIN clause?
1603 } else if ( isset($join_conds_safe[$table]) ) {
1604 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1605 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
) . ')';
1606 $retJOIN[] = $tableClause;
1608 $tableClause = $this->tableName( $table );
1609 $ret[] = $tableClause;
1612 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1613 $straightJoins = !empty($ret) ?
implode( ',', $ret ) : "";
1614 $otherJoins = !empty($retJOIN) ?
implode( ' ', $retJOIN ) : "";
1615 // Compile our final table clause
1616 return implode(' ',array($straightJoins,$otherJoins) );
1620 * Get the name of an index in a given table
1622 function indexName( $index ) {
1623 // Backwards-compatibility hack
1625 'ar_usertext_timestamp' => 'usertext_timestamp',
1626 'un_user_id' => 'user_id',
1627 'un_user_ip' => 'user_ip',
1629 if( isset( $renamed[$index] ) ) {
1630 return $renamed[$index];
1637 * Wrapper for addslashes()
1638 * @param $s String: to be slashed.
1639 * @return String: slashed string.
1641 function strencode( $s ) {
1642 return mysql_real_escape_string( $s, $this->mConn
);
1646 * If it's a string, adds quotes and backslashes
1647 * Otherwise returns as-is
1649 function addQuotes( $s ) {
1650 if ( $s === null ) {
1653 # This will also quote numeric values. This should be harmless,
1654 # and protects against weird problems that occur when they really
1655 # _are_ strings such as article titles and string->number->string
1656 # conversion is not 1:1.
1657 return "'" . $this->strencode( $s ) . "'";
1662 * Escape string for safe LIKE usage
1664 function escapeLike( $s ) {
1665 $s=str_replace('\\','\\\\',$s);
1666 $s=$this->strencode( $s );
1667 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1672 * Returns an appropriately quoted sequence value for inserting a new row.
1673 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1674 * subclass will return an integer, and save the value for insertId()
1676 function nextSequenceValue( $seqName ) {
1682 * PostgreSQL doesn't have them and returns ""
1684 function useIndexClause( $index ) {
1685 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
1689 * REPLACE query wrapper
1690 * PostgreSQL simulates this with a DELETE followed by INSERT
1691 * $row is the row to insert, an associative array
1692 * $uniqueIndexes is an array of indexes. Each element may be either a
1693 * field name or an array of field names
1695 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1696 * However if you do this, you run the risk of encountering errors which wouldn't have
1699 * @todo migrate comment to phodocumentor format
1701 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1702 $table = $this->tableName( $table );
1705 if ( !is_array( reset( $rows ) ) ) {
1706 $rows = array( $rows );
1709 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1711 foreach ( $rows as $row ) {
1717 $sql .= '(' . $this->makeList( $row ) . ')';
1719 return $this->query( $sql, $fname );
1723 * DELETE where the condition is a join
1724 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1726 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1727 * join condition matches, set $conds='*'
1729 * DO NOT put the join condition in $conds
1731 * @param $delTable String: The table to delete from.
1732 * @param $joinTable String: The other table.
1733 * @param $delVar String: The variable to join on, in the first table.
1734 * @param $joinVar String: The variable to join on, in the second table.
1735 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
1736 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1738 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1740 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1743 $delTable = $this->tableName( $delTable );
1744 $joinTable = $this->tableName( $joinTable );
1745 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1746 if ( $conds != '*' ) {
1747 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1750 return $this->query( $sql, $fname );
1754 * Returns the size of a text field, or -1 for "unlimited"
1756 function textFieldSize( $table, $field ) {
1757 $table = $this->tableName( $table );
1758 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1759 $res = $this->query( $sql, 'Database::textFieldSize' );
1760 $row = $this->fetchObject( $res );
1761 $this->freeResult( $res );
1764 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1773 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1775 function lowPriorityOption() {
1776 return 'LOW_PRIORITY';
1780 * DELETE query wrapper
1782 * Use $conds == "*" to delete all rows
1784 function delete( $table, $conds, $fname = 'Database::delete' ) {
1786 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1788 $table = $this->tableName( $table );
1789 $sql = "DELETE FROM $table";
1790 if ( $conds != '*' ) {
1791 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1793 return $this->query( $sql, $fname );
1797 * INSERT SELECT wrapper
1798 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1799 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1800 * $conds may be "*" to copy the whole table
1801 * srcTable may be an array of tables.
1803 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1804 $insertOptions = array(), $selectOptions = array() )
1806 $destTable = $this->tableName( $destTable );
1807 if ( is_array( $insertOptions ) ) {
1808 $insertOptions = implode( ' ', $insertOptions );
1810 if( !is_array( $selectOptions ) ) {
1811 $selectOptions = array( $selectOptions );
1813 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1814 if( is_array( $srcTable ) ) {
1815 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1817 $srcTable = $this->tableName( $srcTable );
1819 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1820 " SELECT $startOpts " . implode( ',', $varMap ) .
1821 " FROM $srcTable $useIndex ";
1822 if ( $conds != '*' ) {
1823 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1825 $sql .= " $tailOpts";
1826 return $this->query( $sql, $fname );
1830 * Construct a LIMIT query with optional offset
1831 * This is used for query pages
1832 * @param $sql String: SQL query we will append the limit too
1833 * @param $limit Integer: the SQL limit
1834 * @param $offset Integer the SQL offset (default false)
1836 function limitResult($sql, $limit, $offset=false) {
1837 if( !is_numeric($limit) ) {
1838 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1840 return "$sql LIMIT "
1841 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1844 function limitResultForUpdate($sql, $num) {
1845 return $this->limitResult($sql, $num, 0);
1849 * Construct a UNION query
1850 * This is used for providing overload point for other DB abstractions
1851 * not compatible with the MySQL syntax.
1852 * @param $sqls Array: SQL statements to combine
1853 * @param $all Boolean: use UNION ALL
1854 * @return String: SQL fragment
1856 function unionQueries($sqls, $all) {
1857 $glue = $all ?
') UNION ALL (' : ') UNION (';
1858 return '('.implode( $glue, $sqls ) . ')';
1862 * Returns an SQL expression for a simple conditional.
1865 * @param $cond String: SQL expression which will result in a boolean value
1866 * @param $trueVal String: SQL expression to return if true
1867 * @param $falseVal String: SQL expression to return if false
1868 * @return String: SQL fragment
1870 function conditional( $cond, $trueVal, $falseVal ) {
1871 return " IF($cond, $trueVal, $falseVal) ";
1875 * Returns a comand for str_replace function in SQL query.
1876 * Uses REPLACE() in MySQL
1878 * @param $orig String: column to modify
1879 * @param $old String: column to seek
1880 * @param $new String: column to replace with
1882 function strreplace( $orig, $old, $new ) {
1883 return "REPLACE({$orig}, {$old}, {$new})";
1887 * Determines if the last failure was due to a deadlock
1889 function wasDeadlock() {
1890 return $this->lastErrno() == 1213;
1894 * Determines if the last query error was something that should be dealt
1895 * with by pinging the connection and reissuing the query
1897 function wasErrorReissuable() {
1898 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
1902 * Perform a deadlock-prone transaction.
1904 * This function invokes a callback function to perform a set of write
1905 * queries. If a deadlock occurs during the processing, the transaction
1906 * will be rolled back and the callback function will be called again.
1909 * $dbw->deadlockLoop( callback, ... );
1911 * Extra arguments are passed through to the specified callback function.
1913 * Returns whatever the callback function returned on its successful,
1914 * iteration, or false on error, for example if the retry limit was
1917 function deadlockLoop() {
1918 $myFname = 'Database::deadlockLoop';
1921 $args = func_get_args();
1922 $function = array_shift( $args );
1923 $oldIgnore = $this->ignoreErrors( true );
1924 $tries = DEADLOCK_TRIES
;
1925 if ( is_array( $function ) ) {
1926 $fname = $function[0];
1931 $retVal = call_user_func_array( $function, $args );
1932 $error = $this->lastError();
1933 $errno = $this->lastErrno();
1934 $sql = $this->lastQuery();
1937 if ( $this->wasDeadlock() ) {
1939 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1941 $this->reportQueryError( $error, $errno, $sql, $fname );
1944 } while( $this->wasDeadlock() && --$tries > 0 );
1945 $this->ignoreErrors( $oldIgnore );
1946 if ( $tries <= 0 ) {
1947 $this->query( 'ROLLBACK', $myFname );
1948 $this->reportQueryError( $error, $errno, $sql, $fname );
1951 $this->query( 'COMMIT', $myFname );
1957 * Do a SELECT MASTER_POS_WAIT()
1959 * @param $pos MySQLMasterPos object
1960 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
1962 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
1963 $fname = 'Database::masterPosWait';
1964 wfProfileIn( $fname );
1966 # Commit any open transactions
1967 if ( $this->mTrxLevel
) {
1968 $this->immediateCommit();
1971 if ( !is_null( $this->mFakeSlaveLag
) ) {
1972 $wait = intval( ( $pos->pos
- microtime(true) +
$this->mFakeSlaveLag
) * 1e6
);
1973 if ( $wait > $timeout * 1e6
) {
1974 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1975 wfProfileOut( $fname );
1977 } elseif ( $wait > 0 ) {
1978 wfDebug( "Fake slave waiting $wait us\n" );
1980 wfProfileOut( $fname );
1983 wfDebug( "Fake slave up to date ($wait us)\n" );
1984 wfProfileOut( $fname );
1989 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1990 $encFile = $this->addQuotes( $pos->file
);
1991 $encPos = intval( $pos->pos
);
1992 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
1993 $res = $this->doQuery( $sql );
1994 if ( $res && $row = $this->fetchRow( $res ) ) {
1995 $this->freeResult( $res );
1996 wfProfileOut( $fname );
1999 wfProfileOut( $fname );
2005 * Get the position of the master from SHOW SLAVE STATUS
2007 function getSlavePos() {
2008 if ( !is_null( $this->mFakeSlaveLag
) ) {
2009 $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag
);
2010 wfDebug( __METHOD__
.": fake slave pos = $pos\n" );
2013 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
2014 $row = $this->fetchObject( $res );
2016 $pos = isset($row->Exec_master_log_pos
) ?
$row->Exec_master_log_pos
: $row->Exec_Master_Log_Pos
;
2017 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
2024 * Get the position of the master from SHOW MASTER STATUS
2026 function getMasterPos() {
2027 if ( $this->mFakeMaster
) {
2028 return new MySQLMasterPos( 'fake', microtime( true ) );
2030 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
2031 $row = $this->fetchObject( $res );
2033 return new MySQLMasterPos( $row->File
, $row->Position
);
2040 * Begin a transaction, committing any previously open transaction
2042 function begin( $fname = 'Database::begin' ) {
2043 $this->query( 'BEGIN', $fname );
2044 $this->mTrxLevel
= 1;
2050 function commit( $fname = 'Database::commit' ) {
2051 $this->query( 'COMMIT', $fname );
2052 $this->mTrxLevel
= 0;
2056 * Rollback a transaction.
2057 * No-op on non-transactional databases.
2059 function rollback( $fname = 'Database::rollback' ) {
2060 $this->query( 'ROLLBACK', $fname, true );
2061 $this->mTrxLevel
= 0;
2065 * Begin a transaction, committing any previously open transaction
2066 * @deprecated use begin()
2068 function immediateBegin( $fname = 'Database::immediateBegin' ) {
2073 * Commit transaction, if one is open
2074 * @deprecated use commit()
2076 function immediateCommit( $fname = 'Database::immediateCommit' ) {
2081 * Return MW-style timestamp used for MySQL schema
2083 function timestamp( $ts=0 ) {
2084 return wfTimestamp(TS_MW
,$ts);
2088 * Local database timestamp format or null
2090 function timestampOrNull( $ts = null ) {
2091 if( is_null( $ts ) ) {
2094 return $this->timestamp( $ts );
2101 function resultObject( $result ) {
2102 if( empty( $result ) ) {
2104 } elseif ( $result instanceof ResultWrapper
) {
2106 } elseif ( $result === true ) {
2107 // Successful write query
2110 return new ResultWrapper( $this, $result );
2115 * Return aggregated value alias
2117 function aggregateValue ($valuedata,$valuename='value') {
2122 * @return String: wikitext of a link to the server software's web site
2124 function getSoftwareLink() {
2125 return "[http://www.mysql.com/ MySQL]";
2129 * @return String: Version information from the database
2131 function getServerVersion() {
2132 return mysql_get_server_info( $this->mConn
);
2136 * Ping the server and try to reconnect if it there is no connection
2139 if( !function_exists( 'mysql_ping' ) ) {
2140 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
2143 $ping = mysql_ping( $this->mConn
);
2148 // Need to reconnect manually in MySQL client 5.0.13+
2149 if ( version_compare( mysql_get_client_info(), '5.0.13', '>=' ) ) {
2150 mysql_close( $this->mConn
);
2151 $this->mOpened
= false;
2152 $this->mConn
= false;
2153 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
2161 * At the moment, this will only work if the DB user has the PROCESS privilege
2164 if ( !is_null( $this->mFakeSlaveLag
) ) {
2165 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
2166 return $this->mFakeSlaveLag
;
2168 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__
);
2169 # Find slave SQL thread
2170 while ( $row = $this->fetchObject( $res ) ) {
2171 /* This should work for most situations - when default db
2172 * for thread is not specified, it had no events executed,
2173 * and therefore it doesn't know yet how lagged it is.
2175 * Relay log I/O thread does not select databases.
2177 if ( $row->User
== 'system user' &&
2178 $row->State
!= 'Waiting for master to send event' &&
2179 $row->State
!= 'Connecting to master' &&
2180 $row->State
!= 'Queueing master event to the relay log' &&
2181 $row->State
!= 'Waiting for master update' &&
2182 $row->State
!= 'Requesting binlog dump'
2184 # This is it, return the time (except -ve)
2185 if ( $row->Time
> 0x7fffffff ) {
2196 * Get status information from SHOW STATUS in an associative array
2198 function getStatus($which="%") {
2199 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2201 while ( $row = $this->fetchObject( $res ) ) {
2202 $status[$row->Variable_name
] = $row->Value
;
2208 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2210 function maxListLen() {
2214 function encodeBlob($b) {
2218 function decodeBlob($b) {
2223 * Override database's default connection timeout.
2224 * May be useful for very long batch queries such as
2225 * full-wiki dumps, where a single query reads out
2226 * over hours or days.
2227 * @param $timeout Integer in seconds
2229 public function setTimeout( $timeout ) {
2230 $this->query( "SET net_read_timeout=$timeout" );
2231 $this->query( "SET net_write_timeout=$timeout" );
2235 * Read and execute SQL commands from a file.
2236 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2237 * @param $filename String: File name to open
2238 * @param $lineCallback Callback: Optional function called before reading each line
2239 * @param $resultCallback Callback: Optional function called for each MySQL result
2241 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2242 $fp = fopen( $filename, 'r' );
2243 if ( false === $fp ) {
2244 throw new MWException( "Could not open \"{$filename}\".\n" );
2246 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2252 * Read and execute commands from an open file handle
2253 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2254 * @param $fp String: File handle
2255 * @param $lineCallback Callback: Optional function called before reading each line
2256 * @param $resultCallback Callback: Optional function called for each MySQL result
2258 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2261 $dollarquote = false;
2263 while ( ! feof( $fp ) ) {
2264 if ( $lineCallback ) {
2265 call_user_func( $lineCallback );
2267 $line = trim( fgets( $fp, 1024 ) );
2268 $sl = strlen( $line ) - 1;
2270 if ( $sl < 0 ) { continue; }
2271 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2273 ## Allow dollar quoting for function declarations
2274 if (substr($line,0,4) == '$mw$') {
2276 $dollarquote = false;
2280 $dollarquote = true;
2283 else if (!$dollarquote) {
2284 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
2286 $line = substr( $line, 0, $sl );
2290 if ( '' != $cmd ) { $cmd .= ' '; }
2294 $cmd = str_replace(';;', ";", $cmd);
2295 $cmd = $this->replaceVars( $cmd );
2296 $res = $this->query( $cmd, __METHOD__
);
2297 if ( $resultCallback ) {
2298 call_user_func( $resultCallback, $res, $this );
2301 if ( false === $res ) {
2302 $err = $this->lastError();
2303 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2315 * Replace variables in sourced SQL
2317 protected function replaceVars( $ins ) {
2319 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2320 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2321 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2324 // Ordinary variables
2325 foreach ( $varnames as $var ) {
2326 if( isset( $GLOBALS[$var] ) ) {
2327 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2328 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2329 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2330 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2335 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2336 array( $this, 'tableNameCallback' ), $ins );
2339 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2340 array( $this, 'indexNameCallback' ), $ins );
2345 * Table name callback
2348 protected function tableNameCallback( $matches ) {
2349 return $this->tableName( $matches[1] );
2353 * Index name callback
2355 protected function indexNameCallback( $matches ) {
2356 return $this->indexName( $matches[1] );
2360 * Build a concatenation list to feed into a SQL query
2362 function buildConcat( $stringList ) {
2363 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2369 * Abstracted from Filestore::lock() so child classes can implement for
2372 * @param $lockName String: Name of lock to aquire
2373 * @param $method String: Name of method calling us
2376 public function lock( $lockName, $method ) {
2377 $lockName = $this->addQuotes( $lockName );
2378 $result = $this->query( "SELECT GET_LOCK($lockName, 5) AS lockstatus", $method );
2379 $row = $this->fetchObject( $result );
2380 $this->freeResult( $result );
2382 if( $row->lockstatus
== 1 ) {
2385 wfDebug( __METHOD__
." failed to acquire lock\n" );
2392 * @todo fixme - Figure out a way to return a bool
2393 * based on successful lock release.
2395 * @param $lockName String: Name of lock to release
2396 * @param $method String: Name of method calling us
2398 public function unlock( $lockName, $method ) {
2399 $lockName = $this->addQuotes( $lockName );
2400 $result = $this->query( "SELECT RELEASE_LOCK($lockName)", $method );
2401 $this->freeResult( $result );
2405 * Get search engine class. All subclasses of this
2406 * need to implement this if they wish to use searching.
2410 public function getSearchEngine() {
2411 return "SearchMySQL";
2415 * Allow or deny "big selects" for this session only. This is done by setting
2416 * the sql_big_selects session variable.
2418 * This is a MySQL-specific feature.
2420 * @param mixed $value true for allow, false for deny, or "default" to restore the initial value
2422 public function setBigSelects( $value = true ) {
2423 if ( $value === 'default' ) {
2424 if ( $this->mDefaultBigSelects
=== null ) {
2425 # Function hasn't been called before so it must already be set to the default
2428 $value = $this->mDefaultBigSelects
;
2430 } elseif ( $this->mDefaultBigSelects
=== null ) {
2431 $this->mDefaultBigSelects
= (bool)$this->selectField( false, '@@sql_big_selects' );
2433 $encValue = $value ?
'1' : '0';
2434 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
2439 * Database abstraction object for mySQL
2440 * Inherit all methods and properties of Database::Database()
2445 class DatabaseMysql
extends DatabaseBase
{
2450 * Legacy support: Database == DatabaseMysql
2452 class Database
extends DatabaseMysql
{}
2454 /******************************************************************************
2456 *****************************************************************************/
2465 function DBObject($data) {
2466 $this->mData
= $data;
2474 return $this->mData
;
2482 * This allows us to distinguish a blob from a normal string and an array of strings
2486 function __construct($data) {
2487 $this->mData
= $data;
2490 return $this->mData
;
2499 private $name, $tablename, $default, $max_length, $nullable,
2500 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2501 function __construct ($info) {
2502 $this->name
= $info->name
;
2503 $this->tablename
= $info->table
;
2504 $this->default = $info->def
;
2505 $this->max_length
= $info->max_length
;
2506 $this->nullable
= !$info->not_null
;
2507 $this->is_pk
= $info->primary_key
;
2508 $this->is_unique
= $info->unique_key
;
2509 $this->is_multiple
= $info->multiple_key
;
2510 $this->is_key
= ($this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
2511 $this->type
= $info->type
;
2518 function tableName() {
2519 return $this->tableName
;
2522 function defaultValue() {
2523 return $this->default;
2526 function maxLength() {
2527 return $this->max_length
;
2530 function nullable() {
2531 return $this->nullable
;
2535 return $this->is_key
;
2538 function isMultipleKey() {
2539 return $this->is_multiple
;
2547 /******************************************************************************
2549 *****************************************************************************/
2552 * Database error base class
2555 class DBError
extends MWException
{
2559 * Construct a database error
2560 * @param $db Database object which threw the error
2561 * @param $error A simple error message to be used for debugging
2563 function __construct( DatabaseBase
&$db, $error ) {
2565 parent
::__construct( $error );
2572 class DBConnectionError
extends DBError
{
2575 function __construct( DatabaseBase
&$db, $error = 'unknown error' ) {
2576 $msg = 'DB connection error';
2577 if ( trim( $error ) != '' ) {
2580 $this->error
= $error;
2581 parent
::__construct( $db, $msg );
2584 function useOutputPage() {
2585 // Not likely to work
2589 function useMessageCache() {
2590 // Not likely to work
2594 function getText() {
2595 return $this->getMessage() . "\n";
2598 function getLogMessage() {
2599 # Don't send to the exception log
2603 function getPageTitle() {
2604 global $wgSitename, $wgLang;
2605 $header = "$wgSitename has a problem";
2606 if ( $wgLang instanceof Language
) {
2607 $header = htmlspecialchars( $wgLang->getMessage( 'dberr-header' ) );
2613 function getHTML() {
2614 global $wgLang, $wgMessageCache, $wgUseFileCache;
2616 $sorry = 'Sorry! This site is experiencing technical difficulties.';
2617 $again = 'Try waiting a few minutes and reloading.';
2618 $info = '(Can\'t contact the database server: $1)';
2620 if ( $wgLang instanceof Language
) {
2621 $sorry = htmlspecialchars( $wgLang->getMessage( 'dberr-problems' ) );
2622 $again = htmlspecialchars( $wgLang->getMessage( 'dberr-again' ) );
2623 $info = htmlspecialchars( $wgLang->getMessage( 'dberr-info' ) );
2626 # No database access
2627 if ( is_object( $wgMessageCache ) ) {
2628 $wgMessageCache->disable();
2631 if ( trim( $this->error
) == '' ) {
2632 $this->error
= $this->db
->getProperty('mServer');
2635 $noconnect = "<p><strong>$sorry</strong><br />$again</p><p><small>$info</small></p>";
2636 $text = str_replace( '$1', $this->error
, $noconnect );
2639 if ( $GLOBALS['wgShowExceptionDetails'] ) {
2640 $text .= '</p><p>Backtrace:</p><p>' .
2641 nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
2645 $extra = $this->searchForm();
2647 if( $wgUseFileCache ) {
2649 $cache = $this->fileCachedPage();
2650 # Cached version on file system?
2651 if( $cache !== null ) {
2652 # Hack: extend the body for error messages
2653 $cache = str_replace( array('</html>','</body>'), '', $cache );
2654 # Add cache notice...
2655 $cachederror = "This is a cached copy of the requested page, and may not be up to date. ";
2656 # Localize it if possible...
2657 if( $wgLang instanceof Language
) {
2658 $cachederror = htmlspecialchars( $wgLang->getMessage( 'dberr-cachederror' ) );
2660 $warning = "<div style='color:red;font-size:150%;font-weight:bold;'>$cachederror</div>";
2661 # Output cached page with notices on bottom and re-close body
2662 return "{$cache}{$warning}<hr />$text<hr />$extra</body></html>";
2664 } catch( MWException
$e ) {
2665 // Do nothing, just use the default page
2668 # Headers needed here - output is just the error message
2669 return $this->htmlHeader()."$text<hr />$extra".$this->htmlFooter();
2672 function searchForm() {
2673 global $wgSitename, $wgServer, $wgLang, $wgInputEncoding;
2674 $usegoogle = "You can try searching via Google in the meantime.";
2675 $outofdate = "Note that their indexes of our content may be out of date.";
2676 $googlesearch = "Search";
2678 if ( $wgLang instanceof Language
) {
2679 $usegoogle = htmlspecialchars( $wgLang->getMessage( 'dberr-usegoogle' ) );
2680 $outofdate = htmlspecialchars( $wgLang->getMessage( 'dberr-outofdate' ) );
2681 $googlesearch = htmlspecialchars( $wgLang->getMessage( 'searchbutton' ) );
2684 $search = htmlspecialchars(@$_REQUEST['search']);
2687 <div style="margin: 1.5em">$usegoogle<br />
2688 <small>$outofdate</small></div>
2689 <!-- SiteSearch Google -->
2690 <form method="get" action="http://www.google.com/search" id="googlesearch">
2691 <input type="hidden" name="domains" value="$wgServer" />
2692 <input type="hidden" name="num" value="50" />
2693 <input type="hidden" name="ie" value="$wgInputEncoding" />
2694 <input type="hidden" name="oe" value="$wgInputEncoding" />
2696 <img src="http://www.google.com/logos/Logo_40wht.gif" alt="" style="float:left; margin-left: 1.5em; margin-right: 1.5em;" />
2698 <input type="text" name="q" size="31" maxlength="255" value="$search" />
2699 <input type="submit" name="btnG" value="$googlesearch" />
2701 <input type="radio" name="sitesearch" id="gwiki" value="$wgServer" checked="checked" /><label for="gwiki">$wgSitename</label>
2702 <input type="radio" name="sitesearch" id="gWWW" value="" /><label for="gWWW">WWW</label>
2705 <!-- SiteSearch Google -->
2710 function fileCachedPage() {
2711 global $wgTitle, $title, $wgLang, $wgOut;
2712 if( $wgOut->isDisabled() ) return; // Done already?
2713 $mainpage = 'Main Page';
2714 if ( $wgLang instanceof Language
) {
2715 $mainpage = htmlspecialchars( $wgLang->getMessage( 'mainpage' ) );
2720 } elseif( $title ) {
2721 $t = Title
::newFromURL( $title );
2723 $t = Title
::newFromText( $mainpage );
2726 $cache = new HTMLFileCache( $t );
2727 if( $cache->isFileCached() ) {
2728 return $cache->fetchPageText();
2734 function htmlBodyOnly() {
2743 class DBQueryError
extends DBError
{
2744 public $error, $errno, $sql, $fname;
2746 function __construct( DatabaseBase
&$db, $error, $errno, $sql, $fname ) {
2747 $message = "A database error has occurred\n" .
2749 "Function: $fname\n" .
2750 "Error: $errno $error\n";
2752 parent
::__construct( $db, $message );
2753 $this->error
= $error;
2754 $this->errno
= $errno;
2756 $this->fname
= $fname;
2759 function getText() {
2760 if ( $this->useMessageCache() ) {
2761 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2762 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
2764 return $this->getMessage();
2769 global $wgShowSQLErrors;
2770 if( !$wgShowSQLErrors ) {
2771 return $this->msg( 'sqlhidden', 'SQL hidden' );
2777 function getLogMessage() {
2778 # Don't send to the exception log
2782 function getPageTitle() {
2783 return $this->msg( 'databaseerror', 'Database error' );
2786 function getHTML() {
2787 if ( $this->useMessageCache() ) {
2788 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2789 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
2791 return nl2br( htmlspecialchars( $this->getMessage() ) );
2799 class DBUnexpectedError
extends DBError
{}
2803 * Result wrapper for grabbing data queried by someone else
2806 class ResultWrapper
implements Iterator
{
2807 var $db, $result, $pos = 0, $currentRow = null;
2810 * Create a new result object from a result resource and a Database object
2812 function ResultWrapper( $database, $result ) {
2813 $this->db
= $database;
2814 if ( $result instanceof ResultWrapper
) {
2815 $this->result
= $result->result
;
2817 $this->result
= $result;
2822 * Get the number of rows in a result object
2824 function numRows() {
2825 return $this->db
->numRows( $this );
2829 * Fetch the next row from the given result object, in object form.
2830 * Fields can be retrieved with $row->fieldname, with fields acting like
2833 * @param $res SQL result object as returned from Database::query(), etc.
2834 * @return MySQL row object
2835 * @throws DBUnexpectedError Thrown if the database returns an error
2837 function fetchObject() {
2838 return $this->db
->fetchObject( $this );
2842 * Fetch the next row from the given result object, in associative array
2843 * form. Fields are retrieved with $row['fieldname'].
2845 * @param $res SQL result object as returned from Database::query(), etc.
2846 * @return MySQL row object
2847 * @throws DBUnexpectedError Thrown if the database returns an error
2849 function fetchRow() {
2850 return $this->db
->fetchRow( $this );
2854 * Free a result object
2857 $this->db
->freeResult( $this );
2858 unset( $this->result
);
2863 * Change the position of the cursor in a result object
2864 * See mysql_data_seek()
2866 function seek( $row ) {
2867 $this->db
->dataSeek( $this, $row );
2870 /*********************
2871 * Iterator functions
2872 * Note that using these in combination with the non-iterator functions
2873 * above may cause rows to be skipped or repeated.
2877 if ($this->numRows()) {
2878 $this->db
->dataSeek($this, 0);
2881 $this->currentRow
= null;
2884 function current() {
2885 if ( is_null( $this->currentRow
) ) {
2888 return $this->currentRow
;
2897 $this->currentRow
= $this->fetchObject();
2898 return $this->currentRow
;
2902 return $this->current() !== false;
2906 class MySQLMasterPos
{
2909 function __construct( $file, $pos ) {
2910 $this->file
= $file;
2914 function __toString() {
2915 return "{$this->file}/{$this->pos}";