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
24 #------------------------------------------------------------------------------
26 #------------------------------------------------------------------------------
28 protected $mLastQuery = '';
29 protected $mPHPError = false;
31 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
32 protected $mOpened = false;
34 protected $mFailFunction;
35 protected $mTablePrefix;
37 protected $mTrxLevel = 0;
38 protected $mErrorCount = 0;
39 protected $mLBInfo = array();
40 protected $mFakeSlaveLag = null, $mFakeMaster = false;
42 #------------------------------------------------------------------------------
44 #------------------------------------------------------------------------------
45 # These optionally set a variable and return the previous state
48 * Fail function, takes a Database as a parameter
49 * Set to false for default, 1 for ignore errors
51 function failFunction( $function = NULL ) {
52 return wfSetVar( $this->mFailFunction
, $function );
56 * Output page, used for reporting errors
57 * FALSE means discard output
59 function setOutputPage( $out ) {
60 wfDeprecated( __METHOD__
);
64 * Boolean, controls output of large amounts of debug information
66 function debug( $debug = NULL ) {
67 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
71 * Turns buffering of SQL result sets on (true) or off (false).
72 * Default is "on" and it should not be changed without good reasons.
74 function bufferResults( $buffer = NULL ) {
75 if ( is_null( $buffer ) ) {
76 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
78 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
83 * Turns on (false) or off (true) the automatic generation and sending
84 * of a "we're sorry, but there has been a database error" page on
85 * database errors. Default is on (false). When turned off, the
86 * code should use lastErrno() and lastError() to handle the
87 * situation as appropriate.
89 function ignoreErrors( $ignoreErrors = NULL ) {
90 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
94 * The current depth of nested transactions
95 * @param $level Integer: , default NULL.
97 function trxLevel( $level = NULL ) {
98 return wfSetVar( $this->mTrxLevel
, $level );
102 * Number of errors logged, only useful when errors are ignored
104 function errorCount( $count = NULL ) {
105 return wfSetVar( $this->mErrorCount
, $count );
108 function tablePrefix( $prefix = null ) {
109 return wfSetVar( $this->mTablePrefix
, $prefix );
113 * Properties passed down from the server info array of the load balancer
115 function getLBInfo( $name = NULL ) {
116 if ( is_null( $name ) ) {
117 return $this->mLBInfo
;
119 if ( array_key_exists( $name, $this->mLBInfo
) ) {
120 return $this->mLBInfo
[$name];
127 function setLBInfo( $name, $value = NULL ) {
128 if ( is_null( $value ) ) {
129 $this->mLBInfo
= $name;
131 $this->mLBInfo
[$name] = $value;
136 * Set lag time in seconds for a fake slave
138 function setFakeSlaveLag( $lag ) {
139 $this->mFakeSlaveLag
= $lag;
143 * Make this connection a fake master
145 function setFakeMaster( $enabled = true ) {
146 $this->mFakeMaster
= $enabled;
150 * Returns true if this database supports (and uses) cascading deletes
152 function cascadingDeletes() {
157 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
159 function cleanupTriggers() {
164 * Returns true if this database is strict about what can be put into an IP field.
165 * Specifically, it uses a NULL value instead of an empty string.
167 function strictIPs() {
172 * Returns true if this database uses timestamps rather than integers
174 function realTimestamps() {
179 * Returns true if this database does an implicit sort when doing GROUP BY
181 function implicitGroupby() {
186 * Returns true if this database does an implicit order by when the column has an index
187 * For example: SELECT page_title FROM page LIMIT 1
189 function implicitOrderby() {
194 * Returns true if this database can do a native search on IP columns
195 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
197 function searchableIPs() {
202 * Returns true if this database can use functional indexes
204 function functionalIndexes() {
209 * Return the last query that went through Database::query()
212 function lastQuery() { return $this->mLastQuery
; }
215 * Is a connection to the database open?
218 function isOpen() { return $this->mOpened
; }
220 function setFlag( $flag ) {
221 $this->mFlags |
= $flag;
224 function clearFlag( $flag ) {
225 $this->mFlags
&= ~
$flag;
228 function getFlag( $flag ) {
229 return !!($this->mFlags
& $flag);
233 * General read-only accessor
235 function getProperty( $name ) {
239 function getWikiID() {
240 if( $this->mTablePrefix
) {
241 return "{$this->mDBname}-{$this->mTablePrefix}";
243 return $this->mDBname
;
247 #------------------------------------------------------------------------------
249 #------------------------------------------------------------------------------
253 * @param $server String: database server host
254 * @param $user String: database user name
255 * @param $password String: database user password
256 * @param $dbName String: database name
257 * @param $failFunction
259 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
261 function __construct( $server = false, $user = false, $password = false, $dbName = false,
262 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
264 global $wgOut, $wgDBprefix, $wgCommandLineMode;
265 # Can't get a reference if it hasn't been set yet
266 if ( !isset( $wgOut ) ) {
270 $this->mFailFunction
= $failFunction;
271 $this->mFlags
= $flags;
273 if ( $this->mFlags
& DBO_DEFAULT
) {
274 if ( $wgCommandLineMode ) {
275 $this->mFlags
&= ~DBO_TRX
;
277 $this->mFlags |
= DBO_TRX
;
282 // Faster read-only access
283 if ( wfReadOnly() ) {
284 $this->mFlags |= DBO_PERSISTENT;
285 $this->mFlags &= ~DBO_TRX;
288 /** Get the default table prefix*/
289 if ( $tablePrefix == 'get from global' ) {
290 $this->mTablePrefix
= $wgDBprefix;
292 $this->mTablePrefix
= $tablePrefix;
296 $this->open( $server, $user, $password, $dbName );
301 * Same as new Database( ... ), kept for backward compatibility
302 * @param $server String: database server host
303 * @param $user String: database user name
304 * @param $password String: database user password
305 * @param $dbName String: database name
306 * @param failFunction
309 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
311 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
315 * Usually aborts on failure
316 * If the failFunction is set to a non-zero integer, returns success
317 * @param $server String: database server host
318 * @param $user String: database user name
319 * @param $password String: database user password
320 * @param $dbName String: database name
322 function open( $server, $user, $password, $dbName ) {
323 global $wgAllDBsAreLocalhost;
324 wfProfileIn( __METHOD__
);
326 # Test for missing mysql.so
327 # First try to load it
328 if (!@extension_loaded
('mysql')) {
333 # Otherwise we get a suppressed fatal error, which is very hard to track down
334 if ( !function_exists( 'mysql_connect' ) ) {
335 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
338 # Debugging hack -- fake cluster
339 if ( $wgAllDBsAreLocalhost ) {
340 $realServer = 'localhost';
342 $realServer = $server;
345 $this->mServer
= $server;
346 $this->mUser
= $user;
347 $this->mPassword
= $password;
348 $this->mDBname
= $dbName;
352 wfProfileIn("dbconnect-$server");
354 # The kernel's default SYN retransmission period is far too slow for us,
355 # so we use a short timeout plus a manual retry. Retrying means that a small
356 # but finite rate of SYN packet loss won't cause user-visible errors.
357 $this->mConn
= false;
358 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
363 $this->installErrorHandler();
364 for ( $i = 0; $i < $numAttempts && !$this->mConn
; $i++
) {
368 if ( $this->mFlags
& DBO_PERSISTENT
) {
369 $this->mConn
= mysql_pconnect( $realServer, $user, $password );
371 # Create a new connection...
372 $this->mConn
= mysql_connect( $realServer, $user, $password, true );
374 if ($this->mConn
=== false) {
376 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
379 $phpError = $this->restoreErrorHandler();
380 # Always log connection errors
381 if ( !$this->mConn
) {
382 $error = $this->lastError();
386 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
387 wfDebug( "DB connection error\n" );
388 wfDebug( "Server: $server, User: $user, Password: " .
389 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
393 wfProfileOut("dbconnect-$server");
395 if ( $dbName != '' && $this->mConn
!== false ) {
396 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
398 $error = "Error selecting database $dbName on server {$this->mServer} " .
399 "from client host " . wfHostname() . "\n";
400 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
405 $success = (bool)$this->mConn
;
409 $version = $this->getServerVersion();
410 if ( version_compare( $version, '4.1' ) >= 0 ) {
411 // Tell the server we're communicating with it in UTF-8.
412 // This may engage various charset conversions.
415 $this->query( 'SET NAMES utf8', __METHOD__
);
417 // Turn off strict mode
418 $this->query( "SET sql_mode = ''", __METHOD__
);
421 // Turn off strict mode if it is on
423 $this->reportConnectionError( $phpError );
426 $this->mOpened
= $success;
427 wfProfileOut( __METHOD__
);
431 protected function installErrorHandler() {
432 $this->mPHPError
= false;
433 $this->htmlErrors
= ini_set( 'html_errors', '0' );
434 set_error_handler( array( $this, 'connectionErrorHandler' ) );
437 protected function restoreErrorHandler() {
438 restore_error_handler();
439 if ( $this->htmlErrors
!== false ) {
440 ini_set( 'html_errors', $this->htmlErrors
);
442 if ( $this->mPHPError
) {
443 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
444 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
451 protected function connectionErrorHandler( $errno, $errstr ) {
452 $this->mPHPError
= $errstr;
456 * Closes a database connection.
457 * if it is open : commits any open transactions
459 * @return Bool operation success. true if already closed.
463 $this->mOpened
= false;
464 if ( $this->mConn
) {
465 if ( $this->trxLevel() ) {
466 $this->immediateCommit();
468 return mysql_close( $this->mConn
);
475 * @param $error String: fallback error message, used if none is given by MySQL
477 function reportConnectionError( $error = 'Unknown error' ) {
478 $myError = $this->lastError();
483 if ( $this->mFailFunction
) {
484 # Legacy error handling method
485 if ( !is_int( $this->mFailFunction
) ) {
486 $ff = $this->mFailFunction
;
487 $ff( $this, $error );
491 throw new DBConnectionError( $this, $error );
496 * Usually aborts on failure. If errors are explicitly ignored, returns success.
498 * @param $sql String: SQL query
499 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
500 * comment (you can use __METHOD__ or add some extra info)
501 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
502 * maybe best to catch the exception instead?
503 * @return true for a successful write query, ResultWrapper object for a successful read query,
504 * or false on failure if $tempIgnore set
505 * @throws DBQueryError Thrown when the database returns an error of any kind
507 public function query( $sql, $fname = '', $tempIgnore = false ) {
510 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
511 if ( isset( $wgProfiler ) ) {
512 # generalizeSQL will probably cut down the query to reasonable
513 # logging size most of the time. The substr is really just a sanity check.
515 # Who's been wasting my precious column space? -- TS
516 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
519 $queryProf = 'query-m: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
520 $totalProf = 'Database::query-master';
522 $queryProf = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
523 $totalProf = 'Database::query';
525 wfProfileIn( $totalProf );
526 wfProfileIn( $queryProf );
529 $this->mLastQuery
= $sql;
531 # Add a comment for easy SHOW PROCESSLIST interpretation
534 if ( is_object( $wgUser ) && !($wgUser instanceof StubObject
) ) {
535 $userName = $wgUser->getName();
536 if ( mb_strlen( $userName ) > 15 ) {
537 $userName = mb_substr( $userName, 0, 15 ) . '...';
539 $userName = str_replace( '/', '', $userName );
543 $commentedSql = preg_replace('/\s/', " /* $fname $userName */ ", $sql, 1);
545 # $commentedSql = $sql;
548 # If DBO_TRX is set, start a transaction
549 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
550 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK') {
551 // avoid establishing transactions for SHOW and SET statements too -
552 // that would delay transaction initializations to once connection
553 // is really used by application
554 $sqlstart = substr($sql,0,10); // very much worth it, benchmark certified(tm)
555 if (strpos($sqlstart,"SHOW ")!==0 and strpos($sqlstart,"SET ")!==0)
559 if ( $this->debug() ) {
560 $sqlx = substr( $commentedSql, 0, 500 );
561 $sqlx = strtr( $sqlx, "\t\n", ' ' );
563 wfDebug( "SQL-master: $sqlx\n" );
565 wfDebug( "SQL: $sqlx\n" );
569 if ( istainted( $sql ) & TC_MYSQL
) {
570 throw new MWException( 'Tainted query found' );
573 # Do the query and handle errors
574 $ret = $this->doQuery( $commentedSql );
576 # Try reconnecting if the connection was lost
577 if ( false === $ret && $this->wasErrorReissuable() ) {
578 # Transaction is gone, like it or not
579 $this->mTrxLevel
= 0;
580 wfDebug( "Connection lost, reconnecting...\n" );
581 if ( $this->ping() ) {
582 wfDebug( "Reconnected\n" );
583 $sqlx = substr( $commentedSql, 0, 500 );
584 $sqlx = strtr( $sqlx, "\t\n", ' ' );
585 global $wgRequestTime;
586 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
587 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
588 $ret = $this->doQuery( $commentedSql );
590 wfDebug( "Failed\n" );
594 if ( false === $ret ) {
595 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
598 if ( isset( $wgProfiler ) ) {
599 wfProfileOut( $queryProf );
600 wfProfileOut( $totalProf );
602 return $this->resultObject( $ret );
606 * The DBMS-dependent part of query()
607 * @param $sql String: SQL query.
608 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
611 /*private*/ function doQuery( $sql ) {
612 if( $this->bufferResults() ) {
613 $ret = mysql_query( $sql, $this->mConn
);
615 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
621 * @param $error String
622 * @param $errno Integer
624 * @param $fname String
625 * @param $tempIgnore Boolean
627 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
628 global $wgCommandLineMode;
629 # Ignore errors during error handling to avoid infinite recursion
630 $ignore = $this->ignoreErrors( true );
631 ++
$this->mErrorCount
;
633 if( $ignore ||
$tempIgnore ) {
634 wfDebug("SQL ERROR (ignored): $error\n");
635 $this->ignoreErrors( $ignore );
637 $sql1line = str_replace( "\n", "\\n", $sql );
638 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
639 wfDebug("SQL ERROR: " . $error . "\n");
640 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
646 * Intended to be compatible with the PEAR::DB wrapper functions.
647 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
649 * ? = scalar value, quoted as necessary
650 * ! = raw SQL bit (a function for instance)
651 * & = filename; reads the file and inserts as a blob
652 * (we don't use this though...)
654 function prepare( $sql, $func = 'Database::prepare' ) {
655 /* MySQL doesn't support prepared statements (yet), so just
656 pack up the query for reference. We'll manually replace
658 return array( 'query' => $sql, 'func' => $func );
661 function freePrepared( $prepared ) {
662 /* No-op for MySQL */
666 * Execute a prepared query with the various arguments
667 * @param $prepared String: the prepared sql
668 * @param $args Mixed: Either an array here, or put scalars as varargs
670 function execute( $prepared, $args = null ) {
671 if( !is_array( $args ) ) {
673 $args = func_get_args();
674 array_shift( $args );
676 $sql = $this->fillPrepared( $prepared['query'], $args );
677 return $this->query( $sql, $prepared['func'] );
681 * Prepare & execute an SQL statement, quoting and inserting arguments
682 * in the appropriate places.
683 * @param $query String
686 function safeQuery( $query, $args = null ) {
687 $prepared = $this->prepare( $query, 'Database::safeQuery' );
688 if( !is_array( $args ) ) {
690 $args = func_get_args();
691 array_shift( $args );
693 $retval = $this->execute( $prepared, $args );
694 $this->freePrepared( $prepared );
699 * For faking prepared SQL statements on DBs that don't support
701 * @param $preparedQuery String: a 'preparable' SQL statement
702 * @param $args Array of arguments to fill it with
703 * @return string executable SQL
705 function fillPrepared( $preparedQuery, $args ) {
707 $this->preparedArgs
=& $args;
708 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
709 array( &$this, 'fillPreparedArg' ), $preparedQuery );
713 * preg_callback func for fillPrepared()
714 * The arguments should be in $this->preparedArgs and must not be touched
715 * while we're doing this.
717 * @param $matches Array
721 function fillPreparedArg( $matches ) {
722 switch( $matches[1] ) {
723 case '\\?': return '?';
724 case '\\!': return '!';
725 case '\\&': return '&';
727 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
728 switch( $matches[1] ) {
729 case '?': return $this->addQuotes( $arg );
730 case '!': return $arg;
732 # return $this->addQuotes( file_get_contents( $arg ) );
733 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
735 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
740 * Free a result object
741 * @param $res Mixed: A SQL result
743 function freeResult( $res ) {
744 if ( $res instanceof ResultWrapper
) {
747 if ( !@/**/mysql_free_result( $res ) ) {
748 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
753 * Fetch the next row from the given result object, in object form.
754 * Fields can be retrieved with $row->fieldname, with fields acting like
757 * @param $res SQL result object as returned from Database::query(), etc.
758 * @return MySQL row object
759 * @throws DBUnexpectedError Thrown if the database returns an error
761 function fetchObject( $res ) {
762 if ( $res instanceof ResultWrapper
) {
765 @/**/$row = mysql_fetch_object( $res );
766 if( $this->lastErrno() ) {
767 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
773 * Fetch the next row from the given result object, in associative array
774 * form. Fields are retrieved with $row['fieldname'].
776 * @param $res SQL result object as returned from Database::query(), etc.
777 * @return MySQL row object
778 * @throws DBUnexpectedError Thrown if the database returns an error
780 function fetchRow( $res ) {
781 if ( $res instanceof ResultWrapper
) {
784 @/**/$row = mysql_fetch_array( $res );
785 if ( $this->lastErrno() ) {
786 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
792 * Get the number of rows in a result object
793 * @param $res Mixed: A SQL result
795 function numRows( $res ) {
796 if ( $res instanceof ResultWrapper
) {
799 @/**/$n = mysql_num_rows( $res );
800 if( $this->lastErrno() ) {
801 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
807 * Get the number of fields in a result object
808 * See documentation for mysql_num_fields()
809 * @param $res Mixed: A SQL result
811 function numFields( $res ) {
812 if ( $res instanceof ResultWrapper
) {
815 return mysql_num_fields( $res );
819 * Get a field name in a result object
820 * See documentation for mysql_field_name():
821 * http://www.php.net/mysql_field_name
822 * @param $res Mixed: A SQL result
825 function fieldName( $res, $n ) {
826 if ( $res instanceof ResultWrapper
) {
829 return mysql_field_name( $res, $n );
833 * Get the inserted value of an auto-increment row
835 * The value inserted should be fetched from nextSequenceValue()
838 * $id = $dbw->nextSequenceValue('page_page_id_seq');
839 * $dbw->insert('page',array('page_id' => $id));
840 * $id = $dbw->insertId();
842 function insertId() { return mysql_insert_id( $this->mConn
); }
845 * Change the position of the cursor in a result object
846 * See mysql_data_seek()
847 * @param $res Mixed: A SQL result
848 * @param $row Mixed: Either MySQL row or ResultWrapper
850 function dataSeek( $res, $row ) {
851 if ( $res instanceof ResultWrapper
) {
854 return mysql_data_seek( $res, $row );
858 * Get the last error number
861 function lastErrno() {
862 if ( $this->mConn
) {
863 return mysql_errno( $this->mConn
);
865 return mysql_errno();
870 * Get a description of the last error
871 * See mysql_error() for more details
873 function lastError() {
874 if ( $this->mConn
) {
875 # Even if it's non-zero, it can still be invalid
876 wfSuppressWarnings();
877 $error = mysql_error( $this->mConn
);
879 $error = mysql_error();
883 $error = mysql_error();
886 $error .= ' (' . $this->mServer
. ')';
891 * Get the number of rows affected by the last write query
892 * See mysql_affected_rows() for more details
894 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
897 * Simple UPDATE wrapper
898 * Usually aborts on failure
899 * If errors are explicitly ignored, returns success
901 * This function exists for historical reasons, Database::update() has a more standard
902 * calling convention and feature set
904 function set( $table, $var, $value, $cond, $fname = 'Database::set' ) {
905 $table = $this->tableName( $table );
906 $sql = "UPDATE $table SET $var = '" .
907 $this->strencode( $value ) . "' WHERE ($cond)";
908 return (bool)$this->query( $sql, $fname );
912 * Simple SELECT wrapper, returns a single field, input must be encoded
913 * Usually aborts on failure
914 * If errors are explicitly ignored, returns FALSE on failure
916 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
917 if ( !is_array( $options ) ) {
918 $options = array( $options );
920 $options['LIMIT'] = 1;
922 $res = $this->select( $table, $var, $cond, $fname, $options );
923 if ( $res === false ||
!$this->numRows( $res ) ) {
926 $row = $this->fetchRow( $res );
927 if ( $row !== false ) {
928 $this->freeResult( $res );
929 return reset( $row );
936 * Returns an optional USE INDEX clause to go after the table, and a
937 * string to go at the end of the query
941 * @param $options Array: associative array of options to be turned into
942 * an SQL query, valid keys are listed in the function.
945 function makeSelectOptions( $options ) {
946 $preLimitTail = $postLimitTail = '';
949 $noKeyOptions = array();
950 foreach ( $options as $key => $option ) {
951 if ( is_numeric( $key ) ) {
952 $noKeyOptions[$option] = true;
956 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
957 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
958 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
960 //if (isset($options['LIMIT'])) {
961 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
962 // isset($options['OFFSET']) ? $options['OFFSET']
966 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
967 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
968 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
970 # Various MySQL extensions
971 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
972 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
973 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
974 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
975 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
976 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
977 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
978 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
980 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
981 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
986 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
992 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
993 * @param $vars Mixed: Array or string, field name(s) to be retrieved
994 * @param $conds Mixed: Array or string, condition(s) for WHERE
995 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
996 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
997 * see Database::makeSelectOptions code for list of supported stuff
998 * @param $join_conds Array: Associative array of table join conditions (optional)
999 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1000 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
1002 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() )
1004 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1005 return $this->query( $sql, $fname );
1011 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
1012 * @param $vars Mixed: Array or string, field name(s) to be retrieved
1013 * @param $conds Mixed: Array or string, condition(s) for WHERE
1014 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1015 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1016 * see Database::makeSelectOptions code for list of supported stuff
1017 * @param $join_conds Array: Associative array of table join conditions (optional)
1018 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1019 * @return string, the SQL text
1021 function selectSQLText( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() ) {
1022 if( is_array( $vars ) ) {
1023 $vars = implode( ',', $vars );
1025 if( !is_array( $options ) ) {
1026 $options = array( $options );
1028 if( is_array( $table ) ) {
1029 if ( !empty($join_conds) ||
( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) )
1030 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
1032 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1033 } elseif ($table!='') {
1034 if ($table{0}==' ') {
1035 $from = ' FROM ' . $table;
1037 $from = ' FROM ' . $this->tableName( $table );
1043 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1045 if( !empty( $conds ) ) {
1046 if ( is_array( $conds ) ) {
1047 $conds = $this->makeList( $conds, LIST_AND
);
1049 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1051 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1054 if (isset($options['LIMIT']))
1055 $sql = $this->limitResult($sql, $options['LIMIT'],
1056 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
1057 $sql = "$sql $postLimitTail";
1059 if (isset($options['EXPLAIN'])) {
1060 $sql = 'EXPLAIN ' . $sql;
1066 * Single row SELECT wrapper
1067 * Aborts or returns FALSE on error
1069 * @param $table String: table name
1070 * @param $vars String: the selected variables
1071 * @param $conds Array: a condition map, terms are ANDed together.
1072 * Items with numeric keys are taken to be literal conditions
1073 * Takes an array of selected variables, and a condition map, which is ANDed
1074 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1075 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1076 * $obj- >page_id is the ID of the Astronomy article
1077 * @param $fname String: Calling functio name
1078 * @param $options Array
1079 * @param $join_conds Array
1081 * @todo migrate documentation to phpdocumentor format
1083 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array(), $join_conds = array() ) {
1084 $options['LIMIT'] = 1;
1085 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1086 if ( $res === false )
1088 if ( !$this->numRows($res) ) {
1089 $this->freeResult($res);
1092 $obj = $this->fetchObject( $res );
1093 $this->freeResult( $res );
1099 * Estimate rows in dataset
1100 * Returns estimated count, based on EXPLAIN output
1101 * Takes same arguments as Database::select()
1104 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
1105 $options['EXPLAIN']=true;
1106 $res = $this->select ($table, $vars, $conds, $fname, $options );
1107 if ( $res === false )
1109 if (!$this->numRows($res)) {
1110 $this->freeResult($res);
1116 while( $plan = $this->fetchObject( $res ) ) {
1117 $rows *= ($plan->rows
> 0)?
$plan->rows
:1; // avoid resetting to zero
1120 $this->freeResult($res);
1126 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1127 * It's only slightly flawed. Don't use for anything important.
1129 * @param $sql String: A SQL Query
1131 static function generalizeSQL( $sql ) {
1132 # This does the same as the regexp below would do, but in such a way
1133 # as to avoid crashing php on some large strings.
1134 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1136 $sql = str_replace ( "\\\\", '', $sql);
1137 $sql = str_replace ( "\\'", '', $sql);
1138 $sql = str_replace ( "\\\"", '', $sql);
1139 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1140 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1142 # All newlines, tabs, etc replaced by single space
1143 $sql = preg_replace ( '/\s+/', ' ', $sql);
1146 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1152 * Determines whether a field exists in a table
1153 * Usually aborts on failure
1154 * If errors are explicitly ignored, returns NULL on failure
1156 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1157 $table = $this->tableName( $table );
1158 $res = $this->query( 'DESCRIBE '.$table, $fname );
1165 while ( $row = $this->fetchObject( $res ) ) {
1166 if ( $row->Field
== $field ) {
1175 * Determines whether an index exists
1176 * Usually aborts on failure
1177 * If errors are explicitly ignored, returns NULL on failure
1179 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1180 $info = $this->indexInfo( $table, $index, $fname );
1181 if ( is_null( $info ) ) {
1184 return $info !== false;
1190 * Get information about an index into an object
1191 * Returns false if the index does not exist
1193 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1194 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1195 # SHOW INDEX should work for 3.x and up:
1196 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1197 $table = $this->tableName( $table );
1198 $index = $this->indexName( $index );
1199 $sql = 'SHOW INDEX FROM '.$table;
1200 $res = $this->query( $sql, $fname );
1206 while ( $row = $this->fetchObject( $res ) ) {
1207 if ( $row->Key_name
== $index ) {
1211 $this->freeResult($res);
1213 return empty($result) ?
false : $result;
1217 * Query whether a given table exists
1219 function tableExists( $table ) {
1220 $table = $this->tableName( $table );
1221 $old = $this->ignoreErrors( true );
1222 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1223 $this->ignoreErrors( $old );
1225 $this->freeResult( $res );
1233 * mysql_fetch_field() wrapper
1234 * Returns false if the field doesn't exist
1239 function fieldInfo( $table, $field ) {
1240 $table = $this->tableName( $table );
1241 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1242 $n = mysql_num_fields( $res->result
);
1243 for( $i = 0; $i < $n; $i++
) {
1244 $meta = mysql_fetch_field( $res->result
, $i );
1245 if( $field == $meta->name
) {
1246 return new MySQLField($meta);
1253 * mysql_field_type() wrapper
1255 function fieldType( $res, $index ) {
1256 if ( $res instanceof ResultWrapper
) {
1257 $res = $res->result
;
1259 return mysql_field_type( $res, $index );
1263 * Determines if a given index is unique
1265 function indexUnique( $table, $index ) {
1266 $indexInfo = $this->indexInfo( $table, $index );
1267 if ( !$indexInfo ) {
1270 return !$indexInfo[0]->Non_unique
;
1274 * INSERT wrapper, inserts an array into a table
1276 * $a may be a single associative array, or an array of these with numeric keys, for
1279 * Usually aborts on failure
1280 * If errors are explicitly ignored, returns success
1282 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1283 # No rows to insert, easy just return now
1284 if ( !count( $a ) ) {
1288 $table = $this->tableName( $table );
1289 if ( !is_array( $options ) ) {
1290 $options = array( $options );
1292 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1294 $keys = array_keys( $a[0] );
1297 $keys = array_keys( $a );
1300 $sql = 'INSERT ' . implode( ' ', $options ) .
1301 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1305 foreach ( $a as $row ) {
1311 $sql .= '(' . $this->makeList( $row ) . ')';
1314 $sql .= '(' . $this->makeList( $a ) . ')';
1316 return (bool)$this->query( $sql, $fname );
1320 * Make UPDATE options for the Database::update function
1323 * @param $options Array: The options passed to Database::update
1326 function makeUpdateOptions( $options ) {
1327 if( !is_array( $options ) ) {
1328 $options = array( $options );
1331 if ( in_array( 'LOW_PRIORITY', $options ) )
1332 $opts[] = $this->lowPriorityOption();
1333 if ( in_array( 'IGNORE', $options ) )
1335 return implode(' ', $opts);
1339 * UPDATE wrapper, takes a condition array and a SET array
1341 * @param $table String: The table to UPDATE
1342 * @param $values Array: An array of values to SET
1343 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
1344 * @param $fname String: The Class::Function calling this function
1346 * @param $options Array: An array of UPDATE options, can be one or
1347 * more of IGNORE, LOW_PRIORITY
1350 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1351 $table = $this->tableName( $table );
1352 $opts = $this->makeUpdateOptions( $options );
1353 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1354 if ( $conds != '*' ) {
1355 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1357 return $this->query( $sql, $fname );
1361 * Makes an encoded list of strings from an array
1363 * LIST_COMMA - comma separated, no field names
1364 * LIST_AND - ANDed WHERE clause (without the WHERE)
1365 * LIST_OR - ORed WHERE clause (without the WHERE)
1366 * LIST_SET - comma separated with field names, like a SET clause
1367 * LIST_NAMES - comma separated field names
1369 function makeList( $a, $mode = LIST_COMMA
) {
1370 if ( !is_array( $a ) ) {
1371 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1376 foreach ( $a as $field => $value ) {
1378 if ( $mode == LIST_AND
) {
1380 } elseif($mode == LIST_OR
) {
1388 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1389 $list .= "($value)";
1390 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
1392 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array($value) ) {
1393 if( count( $value ) == 0 ) {
1394 throw new MWException( __METHOD__
.': empty input' );
1395 } elseif( count( $value ) == 1 ) {
1396 // Special-case single values, as IN isn't terribly efficient
1397 // Don't necessarily assume the single key is 0; we don't
1398 // enforce linear numeric ordering on other arrays here.
1399 $value = array_values( $value );
1400 $list .= $field." = ".$this->addQuotes( $value[0] );
1402 $list .= $field." IN (".$this->makeList($value).") ";
1404 } elseif( $value === null ) {
1405 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1406 $list .= "$field IS ";
1407 } elseif ( $mode == LIST_SET
) {
1408 $list .= "$field = ";
1412 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1413 $list .= "$field = ";
1415 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1422 * Change the current database
1424 function selectDB( $db ) {
1425 $this->mDBname
= $db;
1426 return mysql_select_db( $db, $this->mConn
);
1430 * Get the current DB name
1432 function getDBname() {
1433 return $this->mDBname
;
1437 * Get the server hostname or IP address
1439 function getServer() {
1440 return $this->mServer
;
1444 * Format a table name ready for use in constructing an SQL query
1446 * This does two important things: it quotes the table names to clean them up,
1447 * and it adds a table prefix if only given a table name with no quotes.
1449 * All functions of this object which require a table name call this function
1450 * themselves. Pass the canonical name to such functions. This is only needed
1451 * when calling query() directly.
1453 * @param $name String: database table name
1454 * @return String: full database name
1456 function tableName( $name ) {
1457 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1458 # Skip the entire process when we have a string quoted on both ends.
1459 # Note that we check the end so that we will still quote any use of
1460 # use of `database`.table. But won't break things if someone wants
1461 # to query a database table with a dot in the name.
1462 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) return $name;
1464 # Lets test for any bits of text that should never show up in a table
1465 # name. Basically anything like JOIN or ON which are actually part of
1466 # SQL queries, but may end up inside of the table value to combine
1467 # sql. Such as how the API is doing.
1468 # Note that we use a whitespace test rather than a \b test to avoid
1469 # any remote case where a word like on may be inside of a table name
1470 # surrounded by symbols which may be considered word breaks.
1471 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) return $name;
1473 # Split database and table into proper variables.
1474 # We reverse the explode so that database.table and table both output
1475 # the correct table.
1476 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1477 if( isset( $dbDetails[1] ) ) @list
( $table, $database ) = $dbDetails;
1478 else @list
( $table ) = $dbDetails;
1479 $prefix = $this->mTablePrefix
; # Default prefix
1481 # A database name has been specified in input. Quote the table name
1482 # because we don't want any prefixes added.
1483 if( isset($database) ) $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
1485 # Note that we use the long format because php will complain in in_array if
1486 # the input is not an array, and will complain in is_array if it is not set.
1487 if( !isset( $database ) # Don't use shared database if pre selected.
1488 && isset( $wgSharedDB ) # We have a shared database
1489 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1490 && isset( $wgSharedTables )
1491 && is_array( $wgSharedTables )
1492 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1493 $database = $wgSharedDB;
1494 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1497 # Quote the $database and $table and apply the prefix if not quoted.
1498 if( isset($database) ) $database = ( $database[0] == '`' ?
$database : "`{$database}`" );
1499 $table = ( $table[0] == '`' ?
$table : "`{$prefix}{$table}`" );
1501 # Merge our database and table into our final table name.
1502 $tableName = ( isset($database) ?
"{$database}.{$table}" : "{$table}" );
1504 # We're finished, return.
1509 * Fetch a number of table names into an array
1510 * This is handy when you need to construct SQL for joins
1513 * extract($dbr->tableNames('user','watchlist'));
1514 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1515 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1517 public function tableNames() {
1518 $inArray = func_get_args();
1520 foreach ( $inArray as $name ) {
1521 $retVal[$name] = $this->tableName( $name );
1527 * Fetch a number of table names into an zero-indexed numerical array
1528 * This is handy when you need to construct SQL for joins
1531 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1532 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1533 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1535 public function tableNamesN() {
1536 $inArray = func_get_args();
1538 foreach ( $inArray as $name ) {
1539 $retVal[] = $this->tableName( $name );
1547 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1550 $use_index_safe = is_array($use_index) ?
$use_index : array();
1551 $join_conds_safe = is_array($join_conds) ?
$join_conds : array();
1552 foreach ( $tables as $table ) {
1553 // Is there a JOIN and INDEX clause for this table?
1554 if ( isset($join_conds_safe[$table]) && isset($use_index_safe[$table]) ) {
1555 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1556 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1557 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
) . ')';
1558 $retJOIN[] = $tableClause;
1559 // Is there an INDEX clause?
1560 } else if ( isset($use_index_safe[$table]) ) {
1561 $tableClause = $this->tableName( $table );
1562 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1563 $ret[] = $tableClause;
1564 // Is there a JOIN clause?
1565 } else if ( isset($join_conds_safe[$table]) ) {
1566 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1567 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
) . ')';
1568 $retJOIN[] = $tableClause;
1570 $tableClause = $this->tableName( $table );
1571 $ret[] = $tableClause;
1574 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1575 $straightJoins = !empty($ret) ?
implode( ',', $ret ) : "";
1576 $otherJoins = !empty($retJOIN) ?
implode( ' ', $retJOIN ) : "";
1577 // Compile our final table clause
1578 return implode(' ',array($straightJoins,$otherJoins) );
1582 * Get the name of an index in a given table
1584 function indexName( $index ) {
1585 // Backwards-compatibility hack
1587 'ar_usertext_timestamp' => 'usertext_timestamp',
1588 'un_user_id' => 'user_id',
1589 'un_user_ip' => 'user_ip',
1591 if( isset( $renamed[$index] ) ) {
1592 return $renamed[$index];
1599 * Wrapper for addslashes()
1600 * @param $s String: to be slashed.
1601 * @return String: slashed string.
1603 function strencode( $s ) {
1604 return mysql_real_escape_string( $s, $this->mConn
);
1608 * If it's a string, adds quotes and backslashes
1609 * Otherwise returns as-is
1611 function addQuotes( $s ) {
1612 if ( $s === null ) {
1615 # This will also quote numeric values. This should be harmless,
1616 # and protects against weird problems that occur when they really
1617 # _are_ strings such as article titles and string->number->string
1618 # conversion is not 1:1.
1619 return "'" . $this->strencode( $s ) . "'";
1624 * Escape string for safe LIKE usage
1626 function escapeLike( $s ) {
1627 $s=str_replace('\\','\\\\',$s);
1628 $s=$this->strencode( $s );
1629 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1634 * Returns an appropriately quoted sequence value for inserting a new row.
1635 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1636 * subclass will return an integer, and save the value for insertId()
1638 function nextSequenceValue( $seqName ) {
1644 * PostgreSQL doesn't have them and returns ""
1646 function useIndexClause( $index ) {
1647 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
1651 * REPLACE query wrapper
1652 * PostgreSQL simulates this with a DELETE followed by INSERT
1653 * $row is the row to insert, an associative array
1654 * $uniqueIndexes is an array of indexes. Each element may be either a
1655 * field name or an array of field names
1657 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1658 * However if you do this, you run the risk of encountering errors which wouldn't have
1661 * @todo migrate comment to phodocumentor format
1663 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1664 $table = $this->tableName( $table );
1667 if ( !is_array( reset( $rows ) ) ) {
1668 $rows = array( $rows );
1671 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1673 foreach ( $rows as $row ) {
1679 $sql .= '(' . $this->makeList( $row ) . ')';
1681 return $this->query( $sql, $fname );
1685 * DELETE where the condition is a join
1686 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1688 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1689 * join condition matches, set $conds='*'
1691 * DO NOT put the join condition in $conds
1693 * @param $delTable String: The table to delete from.
1694 * @param $joinTable String: The other table.
1695 * @param $delVar String: The variable to join on, in the first table.
1696 * @param $joinVar String: The variable to join on, in the second table.
1697 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
1698 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1700 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1702 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1705 $delTable = $this->tableName( $delTable );
1706 $joinTable = $this->tableName( $joinTable );
1707 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1708 if ( $conds != '*' ) {
1709 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1712 return $this->query( $sql, $fname );
1716 * Returns the size of a text field, or -1 for "unlimited"
1718 function textFieldSize( $table, $field ) {
1719 $table = $this->tableName( $table );
1720 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1721 $res = $this->query( $sql, 'Database::textFieldSize' );
1722 $row = $this->fetchObject( $res );
1723 $this->freeResult( $res );
1726 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1735 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1737 function lowPriorityOption() {
1738 return 'LOW_PRIORITY';
1742 * DELETE query wrapper
1744 * Use $conds == "*" to delete all rows
1746 function delete( $table, $conds, $fname = 'Database::delete' ) {
1748 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1750 $table = $this->tableName( $table );
1751 $sql = "DELETE FROM $table";
1752 if ( $conds != '*' ) {
1753 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1755 return $this->query( $sql, $fname );
1759 * INSERT SELECT wrapper
1760 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1761 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1762 * $conds may be "*" to copy the whole table
1763 * srcTable may be an array of tables.
1765 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1766 $insertOptions = array(), $selectOptions = array() )
1768 $destTable = $this->tableName( $destTable );
1769 if ( is_array( $insertOptions ) ) {
1770 $insertOptions = implode( ' ', $insertOptions );
1772 if( !is_array( $selectOptions ) ) {
1773 $selectOptions = array( $selectOptions );
1775 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1776 if( is_array( $srcTable ) ) {
1777 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1779 $srcTable = $this->tableName( $srcTable );
1781 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1782 " SELECT $startOpts " . implode( ',', $varMap ) .
1783 " FROM $srcTable $useIndex ";
1784 if ( $conds != '*' ) {
1785 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1787 $sql .= " $tailOpts";
1788 return $this->query( $sql, $fname );
1792 * Construct a LIMIT query with optional offset
1793 * This is used for query pages
1794 * @param $sql String: SQL query we will append the limit too
1795 * @param $limit Integer: the SQL limit
1796 * @param $offset Integer the SQL offset (default false)
1798 function limitResult($sql, $limit, $offset=false) {
1799 if( !is_numeric($limit) ) {
1800 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1802 return "$sql LIMIT "
1803 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1806 function limitResultForUpdate($sql, $num) {
1807 return $this->limitResult($sql, $num, 0);
1811 * Returns an SQL expression for a simple conditional.
1814 * @param $cond String: SQL expression which will result in a boolean value
1815 * @param $trueVal String: SQL expression to return if true
1816 * @param $falseVal String: SQL expression to return if false
1817 * @return String: SQL fragment
1819 function conditional( $cond, $trueVal, $falseVal ) {
1820 return " IF($cond, $trueVal, $falseVal) ";
1824 * Returns a comand for str_replace function in SQL query.
1825 * Uses REPLACE() in MySQL
1827 * @param $orig String: column to modify
1828 * @param $old String: column to seek
1829 * @param $new String: column to replace with
1831 function strreplace( $orig, $old, $new ) {
1832 return "REPLACE({$orig}, {$old}, {$new})";
1836 * Determines if the last failure was due to a deadlock
1838 function wasDeadlock() {
1839 return $this->lastErrno() == 1213;
1843 * Determines if the last query error was something that should be dealt
1844 * with by pinging the connection and reissuing the query
1846 function wasErrorReissuable() {
1847 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
1851 * Perform a deadlock-prone transaction.
1853 * This function invokes a callback function to perform a set of write
1854 * queries. If a deadlock occurs during the processing, the transaction
1855 * will be rolled back and the callback function will be called again.
1858 * $dbw->deadlockLoop( callback, ... );
1860 * Extra arguments are passed through to the specified callback function.
1862 * Returns whatever the callback function returned on its successful,
1863 * iteration, or false on error, for example if the retry limit was
1866 function deadlockLoop() {
1867 $myFname = 'Database::deadlockLoop';
1870 $args = func_get_args();
1871 $function = array_shift( $args );
1872 $oldIgnore = $this->ignoreErrors( true );
1873 $tries = DEADLOCK_TRIES
;
1874 if ( is_array( $function ) ) {
1875 $fname = $function[0];
1880 $retVal = call_user_func_array( $function, $args );
1881 $error = $this->lastError();
1882 $errno = $this->lastErrno();
1883 $sql = $this->lastQuery();
1886 if ( $this->wasDeadlock() ) {
1888 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1890 $this->reportQueryError( $error, $errno, $sql, $fname );
1893 } while( $this->wasDeadlock() && --$tries > 0 );
1894 $this->ignoreErrors( $oldIgnore );
1895 if ( $tries <= 0 ) {
1896 $this->query( 'ROLLBACK', $myFname );
1897 $this->reportQueryError( $error, $errno, $sql, $fname );
1900 $this->query( 'COMMIT', $myFname );
1906 * Do a SELECT MASTER_POS_WAIT()
1908 * @param $pos MySQLMasterPos object
1909 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
1911 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
1912 $fname = 'Database::masterPosWait';
1913 wfProfileIn( $fname );
1915 # Commit any open transactions
1916 if ( $this->mTrxLevel
) {
1917 $this->immediateCommit();
1920 if ( !is_null( $this->mFakeSlaveLag
) ) {
1921 $wait = intval( ( $pos->pos
- microtime(true) +
$this->mFakeSlaveLag
) * 1e6
);
1922 if ( $wait > $timeout * 1e6
) {
1923 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1924 wfProfileOut( $fname );
1926 } elseif ( $wait > 0 ) {
1927 wfDebug( "Fake slave waiting $wait us\n" );
1929 wfProfileOut( $fname );
1932 wfDebug( "Fake slave up to date ($wait us)\n" );
1933 wfProfileOut( $fname );
1938 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1939 $encFile = $this->addQuotes( $pos->file
);
1940 $encPos = intval( $pos->pos
);
1941 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
1942 $res = $this->doQuery( $sql );
1943 if ( $res && $row = $this->fetchRow( $res ) ) {
1944 $this->freeResult( $res );
1945 wfProfileOut( $fname );
1948 wfProfileOut( $fname );
1954 * Get the position of the master from SHOW SLAVE STATUS
1956 function getSlavePos() {
1957 if ( !is_null( $this->mFakeSlaveLag
) ) {
1958 $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag
);
1959 wfDebug( __METHOD__
.": fake slave pos = $pos\n" );
1962 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1963 $row = $this->fetchObject( $res );
1965 $pos = isset($row->Exec_master_log_pos
) ?
$row->Exec_master_log_pos
: $row->Exec_Master_Log_Pos
;
1966 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
1973 * Get the position of the master from SHOW MASTER STATUS
1975 function getMasterPos() {
1976 if ( $this->mFakeMaster
) {
1977 return new MySQLMasterPos( 'fake', microtime( true ) );
1979 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1980 $row = $this->fetchObject( $res );
1982 return new MySQLMasterPos( $row->File
, $row->Position
);
1989 * Begin a transaction, committing any previously open transaction
1991 function begin( $fname = 'Database::begin' ) {
1992 $this->query( 'BEGIN', $fname );
1993 $this->mTrxLevel
= 1;
1999 function commit( $fname = 'Database::commit' ) {
2000 $this->query( 'COMMIT', $fname );
2001 $this->mTrxLevel
= 0;
2005 * Rollback a transaction.
2006 * No-op on non-transactional databases.
2008 function rollback( $fname = 'Database::rollback' ) {
2009 $this->query( 'ROLLBACK', $fname, true );
2010 $this->mTrxLevel
= 0;
2014 * Begin a transaction, committing any previously open transaction
2015 * @deprecated use begin()
2017 function immediateBegin( $fname = 'Database::immediateBegin' ) {
2022 * Commit transaction, if one is open
2023 * @deprecated use commit()
2025 function immediateCommit( $fname = 'Database::immediateCommit' ) {
2030 * Return MW-style timestamp used for MySQL schema
2032 function timestamp( $ts=0 ) {
2033 return wfTimestamp(TS_MW
,$ts);
2037 * Local database timestamp format or null
2039 function timestampOrNull( $ts = null ) {
2040 if( is_null( $ts ) ) {
2043 return $this->timestamp( $ts );
2050 function resultObject( $result ) {
2051 if( empty( $result ) ) {
2053 } elseif ( $result instanceof ResultWrapper
) {
2055 } elseif ( $result === true ) {
2056 // Successful write query
2059 return new ResultWrapper( $this, $result );
2064 * Return aggregated value alias
2066 function aggregateValue ($valuedata,$valuename='value') {
2071 * @return String: wikitext of a link to the server software's web site
2073 function getSoftwareLink() {
2074 return "[http://www.mysql.com/ MySQL]";
2078 * @return String: Version information from the database
2080 function getServerVersion() {
2081 return mysql_get_server_info( $this->mConn
);
2085 * Ping the server and try to reconnect if it there is no connection
2088 if( !function_exists( 'mysql_ping' ) ) {
2089 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
2092 $ping = mysql_ping( $this->mConn
);
2097 // Need to reconnect manually in MySQL client 5.0.13+
2098 if ( version_compare( mysql_get_client_info(), '5.0.13', '>=' ) ) {
2099 mysql_close( $this->mConn
);
2100 $this->mOpened
= false;
2101 $this->mConn
= false;
2102 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
2110 * At the moment, this will only work if the DB user has the PROCESS privilege
2113 if ( !is_null( $this->mFakeSlaveLag
) ) {
2114 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
2115 return $this->mFakeSlaveLag
;
2117 $res = $this->query( 'SHOW PROCESSLIST' );
2118 # Find slave SQL thread
2119 while ( $row = $this->fetchObject( $res ) ) {
2120 /* This should work for most situations - when default db
2121 * for thread is not specified, it had no events executed,
2122 * and therefore it doesn't know yet how lagged it is.
2124 * Relay log I/O thread does not select databases.
2126 if ( $row->User
== 'system user' &&
2127 $row->State
!= 'Waiting for master to send event' &&
2128 $row->State
!= 'Connecting to master' &&
2129 $row->State
!= 'Queueing master event to the relay log' &&
2130 $row->State
!= 'Waiting for master update' &&
2131 $row->State
!= 'Requesting binlog dump'
2133 # This is it, return the time (except -ve)
2134 if ( $row->Time
> 0x7fffffff ) {
2145 * Get status information from SHOW STATUS in an associative array
2147 function getStatus($which="%") {
2148 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2150 while ( $row = $this->fetchObject( $res ) ) {
2151 $status[$row->Variable_name
] = $row->Value
;
2157 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2159 function maxListLen() {
2163 function encodeBlob($b) {
2167 function decodeBlob($b) {
2172 * Override database's default connection timeout.
2173 * May be useful for very long batch queries such as
2174 * full-wiki dumps, where a single query reads out
2175 * over hours or days.
2176 * @param $timeout Integer in seconds
2178 public function setTimeout( $timeout ) {
2179 $this->query( "SET net_read_timeout=$timeout" );
2180 $this->query( "SET net_write_timeout=$timeout" );
2184 * Read and execute SQL commands from a file.
2185 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2186 * @param $filename String: File name to open
2187 * @param $lineCallback Callback: Optional function called before reading each line
2188 * @param $resultCallback Callback: Optional function called for each MySQL result
2190 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2191 $fp = fopen( $filename, 'r' );
2192 if ( false === $fp ) {
2193 throw new MWException( "Could not open \"{$filename}\".\n" );
2195 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2201 * Read and execute commands from an open file handle
2202 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2203 * @param $fp String: File handle
2204 * @param $lineCallback Callback: Optional function called before reading each line
2205 * @param $resultCallback Callback: Optional function called for each MySQL result
2207 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2210 $dollarquote = false;
2212 while ( ! feof( $fp ) ) {
2213 if ( $lineCallback ) {
2214 call_user_func( $lineCallback );
2216 $line = trim( fgets( $fp, 1024 ) );
2217 $sl = strlen( $line ) - 1;
2219 if ( $sl < 0 ) { continue; }
2220 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2222 ## Allow dollar quoting for function declarations
2223 if (substr($line,0,4) == '$mw$') {
2225 $dollarquote = false;
2229 $dollarquote = true;
2232 else if (!$dollarquote) {
2233 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
2235 $line = substr( $line, 0, $sl );
2239 if ( '' != $cmd ) { $cmd .= ' '; }
2243 $cmd = str_replace(';;', ";", $cmd);
2244 $cmd = $this->replaceVars( $cmd );
2245 $res = $this->query( $cmd, __METHOD__
);
2246 if ( $resultCallback ) {
2247 call_user_func( $resultCallback, $res, $this );
2250 if ( false === $res ) {
2251 $err = $this->lastError();
2252 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2264 * Replace variables in sourced SQL
2266 protected function replaceVars( $ins ) {
2268 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2269 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2270 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2273 // Ordinary variables
2274 foreach ( $varnames as $var ) {
2275 if( isset( $GLOBALS[$var] ) ) {
2276 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2277 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2278 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2279 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2284 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2285 array( $this, 'tableNameCallback' ), $ins );
2288 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2289 array( $this, 'indexNameCallback' ), $ins );
2294 * Table name callback
2297 protected function tableNameCallback( $matches ) {
2298 return $this->tableName( $matches[1] );
2302 * Index name callback
2304 protected function indexNameCallback( $matches ) {
2305 return $this->indexName( $matches[1] );
2309 * Build a concatenation list to feed into a SQL query
2311 function buildConcat( $stringList ) {
2312 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2318 * Abstracted from Filestore::lock() so child classes can implement for
2321 * @param $lockName String: Name of lock to aquire
2322 * @param $method String: Name of method calling us
2325 public function lock( $lockName, $method ) {
2326 $lockName = $this->addQuotes( $lockName );
2327 $result = $this->query( "SELECT GET_LOCK($lockName, 5) AS lockstatus", $method );
2328 $row = $this->fetchObject( $result );
2329 $this->freeResult( $result );
2331 if( $row->lockstatus
== 1 ) {
2334 wfDebug( __METHOD__
." failed to acquire lock\n" );
2341 * @todo fixme - Figure out a way to return a bool
2342 * based on successful lock release.
2344 * @param $lockName String: Name of lock to release
2345 * @param $method String: Name of method calling us
2347 public function unlock( $lockName, $method ) {
2348 $lockName = $this->addQuotes( $lockName );
2349 $result = $this->query( "SELECT RELEASE_LOCK($lockName)", $method );
2350 $this->freeResult( $result );
2354 * Get search engine class. All subclasses of this
2355 * need to implement this if they wish to use searching.
2359 public function getSearchEngine() {
2360 return "SearchMySQL";
2365 * Database abstraction object for mySQL
2366 * Inherit all methods and properties of Database::Database()
2371 class DatabaseMysql
extends Database
{
2375 /******************************************************************************
2377 *****************************************************************************/
2386 function DBObject($data) {
2387 $this->mData
= $data;
2395 return $this->mData
;
2403 * This allows us to distinguish a blob from a normal string and an array of strings
2407 function __construct($data) {
2408 $this->mData
= $data;
2411 return $this->mData
;
2420 private $name, $tablename, $default, $max_length, $nullable,
2421 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2422 function __construct ($info) {
2423 $this->name
= $info->name
;
2424 $this->tablename
= $info->table
;
2425 $this->default = $info->def
;
2426 $this->max_length
= $info->max_length
;
2427 $this->nullable
= !$info->not_null
;
2428 $this->is_pk
= $info->primary_key
;
2429 $this->is_unique
= $info->unique_key
;
2430 $this->is_multiple
= $info->multiple_key
;
2431 $this->is_key
= ($this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
2432 $this->type
= $info->type
;
2439 function tableName() {
2440 return $this->tableName
;
2443 function defaultValue() {
2444 return $this->default;
2447 function maxLength() {
2448 return $this->max_length
;
2451 function nullable() {
2452 return $this->nullable
;
2456 return $this->is_key
;
2459 function isMultipleKey() {
2460 return $this->is_multiple
;
2468 /******************************************************************************
2470 *****************************************************************************/
2473 * Database error base class
2476 class DBError
extends MWException
{
2480 * Construct a database error
2481 * @param $db Database object which threw the error
2482 * @param $error A simple error message to be used for debugging
2484 function __construct( Database
&$db, $error ) {
2486 parent
::__construct( $error );
2493 class DBConnectionError
extends DBError
{
2496 function __construct( Database
&$db, $error = 'unknown error' ) {
2497 $msg = 'DB connection error';
2498 if ( trim( $error ) != '' ) {
2501 $this->error
= $error;
2502 parent
::__construct( $db, $msg );
2505 function useOutputPage() {
2506 // Not likely to work
2510 function useMessageCache() {
2511 // Not likely to work
2515 function getText() {
2516 return $this->getMessage() . "\n";
2519 function getLogMessage() {
2520 # Don't send to the exception log
2524 function getPageTitle() {
2525 global $wgSitename, $wgLang;
2526 $header = "$wgSitename has a problem";
2527 if ( $wgLang instanceof Language
) {
2528 $header = htmlspecialchars( $wgLang->getMessage( 'dberr-header' ) );
2534 function getHTML() {
2535 global $wgLang, $wgMessageCache, $wgUseFileCache;
2537 $sorry = 'Sorry! This site is experiencing technical difficulties.';
2538 $again = 'Try waiting a few minutes and reloading.';
2539 $info = '(Can\'t contact the database server: $1)';
2541 if ( $wgLang instanceof Language
) {
2542 $sorry = htmlspecialchars( $wgLang->getMessage( 'dberr-problems' ) );
2543 $again = htmlspecialchars( $wgLang->getMessage( 'dberr-again' ) );
2544 $info = htmlspecialchars( $wgLang->getMessage( 'dberr-info' ) );
2547 # No database access
2548 if ( is_object( $wgMessageCache ) ) {
2549 $wgMessageCache->disable();
2552 if ( trim( $this->error
) == '' ) {
2553 $this->error
= $this->db
->getProperty('mServer');
2556 $noconnect = "<p><strong>$sorry</strong><br />$again</p><p><small>$info</small></p>";
2557 $text = str_replace( '$1', $this->error
, $noconnect );
2560 if ( $GLOBALS['wgShowExceptionDetails'] ) {
2561 $text .= '</p><p>Backtrace:</p><p>' .
2562 nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
2566 $extra = $this->searchForm();
2568 if($wgUseFileCache) {
2569 $cache = $this->fileCachedPage();
2570 if ( $cache !== null ) $extra = $cache;
2573 return $text . '<hr />' . $extra;
2576 function searchForm() {
2577 global $wgSitename, $wgServer, $wgLang, $wgInputEncoding;
2578 $usegoogle = "You can try searching via Google in the meantime.";
2579 $outofdate = "Note that their indexes of our content may be out of date.";
2580 $googlesearch = "Search";
2582 if ( $wgLang instanceof Language
) {
2583 $usegoogle = htmlspecialchars( $wgLang->getMessage( 'dberr-usegoogle' ) );
2584 $outofdate = htmlspecialchars( $wgLang->getMessage( 'dberr-outofdate' ) );
2585 $googlesearch = htmlspecialchars( $wgLang->getMessage( 'searchbutton' ) );
2588 $search = htmlspecialchars(@$_REQUEST['search']);
2591 <div style="margin: 1.5em">$usegoogle<br />
2592 <small>$outofdate</small></div>
2593 <!-- SiteSearch Google -->
2594 <form method="get" action="http://www.google.com/search" id="googlesearch">
2595 <input type="hidden" name="domains" value="$wgServer" />
2596 <input type="hidden" name="num" value="50" />
2597 <input type="hidden" name="ie" value="$wgInputEncoding" />
2598 <input type="hidden" name="oe" value="$wgInputEncoding" />
2600 <img src="http://www.google.com/logos/Logo_40wht.gif" style="float:left; margin-left: 1.5em; margin-right: 1.5em;" />
2602 <input type="text" name="q" size="31" maxlength="255" value="$search" />
2603 <input type="submit" name="btnG" value="$googlesearch" />
2605 <input type="radio" name="sitesearch" id="gwiki" value="$wgServer" checked="checked" /><label for="gwiki">$wgSitename</label>
2606 <input type="radio" name="sitesearch" id="gWWW" value="" /><label for="gWWW">WWW</label>
2609 <!-- SiteSearch Google -->
2614 function fileCachedPage() {
2615 global $wgTitle, $title, $wgLang;
2617 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
2618 $mainpage = 'Main Page';
2619 if ( $wgLang instanceof Language
) {
2620 $cachederror = htmlspecialchars( $wgLang->getMessage( 'dberr-cachederror' ) );
2621 $mainpage = htmlspecialchars( $wgLang->getMessage( 'mainpage' ) );
2627 $t = Title
::newFromURL( $title );
2629 $t = Title
::newFromText( $mainpage );
2632 $cache = new HTMLFileCache( $t );
2633 if( $cache->isFileCached() ) {
2634 $warning = "<div style='color:red;font-size:150%;font-weight:bold;'>$cachederror</div>";
2635 return $warning . $cache->fetchPageText();
2646 class DBQueryError
extends DBError
{
2647 public $error, $errno, $sql, $fname;
2649 function __construct( Database
&$db, $error, $errno, $sql, $fname ) {
2650 $message = "A database error has occurred\n" .
2652 "Function: $fname\n" .
2653 "Error: $errno $error\n";
2655 parent
::__construct( $db, $message );
2656 $this->error
= $error;
2657 $this->errno
= $errno;
2659 $this->fname
= $fname;
2662 function getText() {
2663 if ( $this->useMessageCache() ) {
2664 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2665 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
2667 return $this->getMessage();
2672 global $wgShowSQLErrors;
2673 if( !$wgShowSQLErrors ) {
2674 return $this->msg( 'sqlhidden', 'SQL hidden' );
2680 function getLogMessage() {
2681 # Don't send to the exception log
2685 function getPageTitle() {
2686 return $this->msg( 'databaseerror', 'Database error' );
2689 function getHTML() {
2690 if ( $this->useMessageCache() ) {
2691 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2692 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
2694 return nl2br( htmlspecialchars( $this->getMessage() ) );
2702 class DBUnexpectedError
extends DBError
{}
2706 * Result wrapper for grabbing data queried by someone else
2709 class ResultWrapper
implements Iterator
{
2710 var $db, $result, $pos = 0, $currentRow = null;
2713 * Create a new result object from a result resource and a Database object
2715 function ResultWrapper( $database, $result ) {
2716 $this->db
= $database;
2717 if ( $result instanceof ResultWrapper
) {
2718 $this->result
= $result->result
;
2720 $this->result
= $result;
2725 * Get the number of rows in a result object
2727 function numRows() {
2728 return $this->db
->numRows( $this->result
);
2732 * Fetch the next row from the given result object, in object form.
2733 * Fields can be retrieved with $row->fieldname, with fields acting like
2736 * @param $res SQL result object as returned from Database::query(), etc.
2737 * @return MySQL row object
2738 * @throws DBUnexpectedError Thrown if the database returns an error
2740 function fetchObject() {
2741 return $this->db
->fetchObject( $this->result
);
2745 * Fetch the next row from the given result object, in associative array
2746 * form. Fields are retrieved with $row['fieldname'].
2748 * @param $res SQL result object as returned from Database::query(), etc.
2749 * @return MySQL row object
2750 * @throws DBUnexpectedError Thrown if the database returns an error
2752 function fetchRow() {
2753 return $this->db
->fetchRow( $this->result
);
2757 * Free a result object
2760 $this->db
->freeResult( $this->result
);
2761 unset( $this->result
);
2766 * Change the position of the cursor in a result object
2767 * See mysql_data_seek()
2769 function seek( $row ) {
2770 $this->db
->dataSeek( $this->result
, $row );
2773 /*********************
2774 * Iterator functions
2775 * Note that using these in combination with the non-iterator functions
2776 * above may cause rows to be skipped or repeated.
2780 if ($this->numRows()) {
2781 $this->db
->dataSeek($this->result
, 0);
2784 $this->currentRow
= null;
2787 function current() {
2788 if ( is_null( $this->currentRow
) ) {
2791 return $this->currentRow
;
2800 $this->currentRow
= $this->fetchObject();
2801 return $this->currentRow
;
2805 return $this->current() !== false;
2809 class MySQLMasterPos
{
2812 function __construct( $file, $pos ) {
2813 $this->file
= $file;
2817 function __toString() {
2818 return "{$this->file}/{$this->pos}";