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 # Do the query and handle errors
570 $ret = $this->doQuery( $commentedSql );
572 # Try reconnecting if the connection was lost
573 if ( false === $ret && $this->wasErrorReissuable() ) {
574 # Transaction is gone, like it or not
575 $this->mTrxLevel
= 0;
576 wfDebug( "Connection lost, reconnecting...\n" );
577 if ( $this->ping() ) {
578 wfDebug( "Reconnected\n" );
579 $sqlx = substr( $commentedSql, 0, 500 );
580 $sqlx = strtr( $sqlx, "\t\n", ' ' );
581 global $wgRequestTime;
582 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
583 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
584 $ret = $this->doQuery( $commentedSql );
586 wfDebug( "Failed\n" );
590 if ( false === $ret ) {
591 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
594 if ( isset( $wgProfiler ) ) {
595 wfProfileOut( $queryProf );
596 wfProfileOut( $totalProf );
598 return $this->resultObject( $ret );
602 * The DBMS-dependent part of query()
603 * @param $sql String: SQL query.
604 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
607 /*private*/ function doQuery( $sql ) {
608 if( $this->bufferResults() ) {
609 $ret = mysql_query( $sql, $this->mConn
);
611 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
617 * @param $error String
618 * @param $errno Integer
620 * @param $fname String
621 * @param $tempIgnore Boolean
623 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
624 global $wgCommandLineMode;
625 # Ignore errors during error handling to avoid infinite recursion
626 $ignore = $this->ignoreErrors( true );
627 ++
$this->mErrorCount
;
629 if( $ignore ||
$tempIgnore ) {
630 wfDebug("SQL ERROR (ignored): $error\n");
631 $this->ignoreErrors( $ignore );
633 $sql1line = str_replace( "\n", "\\n", $sql );
634 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
635 wfDebug("SQL ERROR: " . $error . "\n");
636 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
642 * Intended to be compatible with the PEAR::DB wrapper functions.
643 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
645 * ? = scalar value, quoted as necessary
646 * ! = raw SQL bit (a function for instance)
647 * & = filename; reads the file and inserts as a blob
648 * (we don't use this though...)
650 function prepare( $sql, $func = 'Database::prepare' ) {
651 /* MySQL doesn't support prepared statements (yet), so just
652 pack up the query for reference. We'll manually replace
654 return array( 'query' => $sql, 'func' => $func );
657 function freePrepared( $prepared ) {
658 /* No-op for MySQL */
662 * Execute a prepared query with the various arguments
663 * @param $prepared String: the prepared sql
664 * @param $args Mixed: Either an array here, or put scalars as varargs
666 function execute( $prepared, $args = null ) {
667 if( !is_array( $args ) ) {
669 $args = func_get_args();
670 array_shift( $args );
672 $sql = $this->fillPrepared( $prepared['query'], $args );
673 return $this->query( $sql, $prepared['func'] );
677 * Prepare & execute an SQL statement, quoting and inserting arguments
678 * in the appropriate places.
679 * @param $query String
682 function safeQuery( $query, $args = null ) {
683 $prepared = $this->prepare( $query, 'Database::safeQuery' );
684 if( !is_array( $args ) ) {
686 $args = func_get_args();
687 array_shift( $args );
689 $retval = $this->execute( $prepared, $args );
690 $this->freePrepared( $prepared );
695 * For faking prepared SQL statements on DBs that don't support
697 * @param $preparedQuery String: a 'preparable' SQL statement
698 * @param $args Array of arguments to fill it with
699 * @return string executable SQL
701 function fillPrepared( $preparedQuery, $args ) {
703 $this->preparedArgs
=& $args;
704 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
705 array( &$this, 'fillPreparedArg' ), $preparedQuery );
709 * preg_callback func for fillPrepared()
710 * The arguments should be in $this->preparedArgs and must not be touched
711 * while we're doing this.
713 * @param $matches Array
717 function fillPreparedArg( $matches ) {
718 switch( $matches[1] ) {
719 case '\\?': return '?';
720 case '\\!': return '!';
721 case '\\&': return '&';
723 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
724 switch( $matches[1] ) {
725 case '?': return $this->addQuotes( $arg );
726 case '!': return $arg;
728 # return $this->addQuotes( file_get_contents( $arg ) );
729 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
731 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
736 * Free a result object
737 * @param $res Mixed: A SQL result
739 function freeResult( $res ) {
740 if ( $res instanceof ResultWrapper
) {
743 if ( !@/**/mysql_free_result( $res ) ) {
744 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
749 * Fetch the next row from the given result object, in object form.
750 * Fields can be retrieved with $row->fieldname, with fields acting like
753 * @param $res SQL result object as returned from Database::query(), etc.
754 * @return MySQL row object
755 * @throws DBUnexpectedError Thrown if the database returns an error
757 function fetchObject( $res ) {
758 if ( $res instanceof ResultWrapper
) {
761 @/**/$row = mysql_fetch_object( $res );
762 if( $this->lastErrno() ) {
763 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
769 * Fetch the next row from the given result object, in associative array
770 * form. Fields are retrieved with $row['fieldname'].
772 * @param $res SQL result object as returned from Database::query(), etc.
773 * @return MySQL row object
774 * @throws DBUnexpectedError Thrown if the database returns an error
776 function fetchRow( $res ) {
777 if ( $res instanceof ResultWrapper
) {
780 @/**/$row = mysql_fetch_array( $res );
781 if ( $this->lastErrno() ) {
782 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
788 * Get the number of rows in a result object
789 * @param $res Mixed: A SQL result
791 function numRows( $res ) {
792 if ( $res instanceof ResultWrapper
) {
795 @/**/$n = mysql_num_rows( $res );
796 if( $this->lastErrno() ) {
797 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
803 * Get the number of fields in a result object
804 * See documentation for mysql_num_fields()
805 * @param $res Mixed: A SQL result
807 function numFields( $res ) {
808 if ( $res instanceof ResultWrapper
) {
811 return mysql_num_fields( $res );
815 * Get a field name in a result object
816 * See documentation for mysql_field_name():
817 * http://www.php.net/mysql_field_name
818 * @param $res Mixed: A SQL result
821 function fieldName( $res, $n ) {
822 if ( $res instanceof ResultWrapper
) {
825 return mysql_field_name( $res, $n );
829 * Get the inserted value of an auto-increment row
831 * The value inserted should be fetched from nextSequenceValue()
834 * $id = $dbw->nextSequenceValue('page_page_id_seq');
835 * $dbw->insert('page',array('page_id' => $id));
836 * $id = $dbw->insertId();
838 function insertId() { return mysql_insert_id( $this->mConn
); }
841 * Change the position of the cursor in a result object
842 * See mysql_data_seek()
843 * @param $res Mixed: A SQL result
844 * @param $row Mixed: Either MySQL row or ResultWrapper
846 function dataSeek( $res, $row ) {
847 if ( $res instanceof ResultWrapper
) {
850 return mysql_data_seek( $res, $row );
854 * Get the last error number
857 function lastErrno() {
858 if ( $this->mConn
) {
859 return mysql_errno( $this->mConn
);
861 return mysql_errno();
866 * Get a description of the last error
867 * See mysql_error() for more details
869 function lastError() {
870 if ( $this->mConn
) {
871 # Even if it's non-zero, it can still be invalid
872 wfSuppressWarnings();
873 $error = mysql_error( $this->mConn
);
875 $error = mysql_error();
879 $error = mysql_error();
882 $error .= ' (' . $this->mServer
. ')';
887 * Get the number of rows affected by the last write query
888 * See mysql_affected_rows() for more details
890 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
893 * Simple UPDATE wrapper
894 * Usually aborts on failure
895 * If errors are explicitly ignored, returns success
897 * This function exists for historical reasons, Database::update() has a more standard
898 * calling convention and feature set
900 function set( $table, $var, $value, $cond, $fname = 'Database::set' ) {
901 $table = $this->tableName( $table );
902 $sql = "UPDATE $table SET $var = '" .
903 $this->strencode( $value ) . "' WHERE ($cond)";
904 return (bool)$this->query( $sql, $fname );
908 * Simple SELECT wrapper, returns a single field, input must be encoded
909 * Usually aborts on failure
910 * If errors are explicitly ignored, returns FALSE on failure
912 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
913 if ( !is_array( $options ) ) {
914 $options = array( $options );
916 $options['LIMIT'] = 1;
918 $res = $this->select( $table, $var, $cond, $fname, $options );
919 if ( $res === false ||
!$this->numRows( $res ) ) {
922 $row = $this->fetchRow( $res );
923 if ( $row !== false ) {
924 $this->freeResult( $res );
925 return reset( $row );
932 * Returns an optional USE INDEX clause to go after the table, and a
933 * string to go at the end of the query
937 * @param $options Array: associative array of options to be turned into
938 * an SQL query, valid keys are listed in the function.
941 function makeSelectOptions( $options ) {
942 $preLimitTail = $postLimitTail = '';
945 $noKeyOptions = array();
946 foreach ( $options as $key => $option ) {
947 if ( is_numeric( $key ) ) {
948 $noKeyOptions[$option] = true;
952 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
953 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
954 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
956 //if (isset($options['LIMIT'])) {
957 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
958 // isset($options['OFFSET']) ? $options['OFFSET']
962 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
963 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
964 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
966 # Various MySQL extensions
967 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
968 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
969 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
970 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
971 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
972 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
973 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
974 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
976 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
977 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
982 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
988 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
989 * @param $vars Mixed: Array or string, field name(s) to be retrieved
990 * @param $conds Mixed: Array or string, condition(s) for WHERE
991 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
992 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
993 * see Database::makeSelectOptions code for list of supported stuff
994 * @param $join_conds Array: Associative array of table join conditions (optional)
995 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
996 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
998 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() )
1000 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1001 return $this->query( $sql, $fname );
1007 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
1008 * @param $vars Mixed: Array or string, field name(s) to be retrieved
1009 * @param $conds Mixed: Array or string, condition(s) for WHERE
1010 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1011 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1012 * see Database::makeSelectOptions code for list of supported stuff
1013 * @param $join_conds Array: Associative array of table join conditions (optional)
1014 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1015 * @return string, the SQL text
1017 function selectSQLText( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() ) {
1018 if( is_array( $vars ) ) {
1019 $vars = implode( ',', $vars );
1021 if( !is_array( $options ) ) {
1022 $options = array( $options );
1024 if( is_array( $table ) ) {
1025 if ( !empty($join_conds) ||
( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) )
1026 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
1028 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1029 } elseif ($table!='') {
1030 if ($table{0}==' ') {
1031 $from = ' FROM ' . $table;
1033 $from = ' FROM ' . $this->tableName( $table );
1039 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1041 if( !empty( $conds ) ) {
1042 if ( is_array( $conds ) ) {
1043 $conds = $this->makeList( $conds, LIST_AND
);
1045 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1047 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1050 if (isset($options['LIMIT']))
1051 $sql = $this->limitResult($sql, $options['LIMIT'],
1052 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
1053 $sql = "$sql $postLimitTail";
1055 if (isset($options['EXPLAIN'])) {
1056 $sql = 'EXPLAIN ' . $sql;
1062 * Single row SELECT wrapper
1063 * Aborts or returns FALSE on error
1065 * @param $table String: table name
1066 * @param $vars String: the selected variables
1067 * @param $conds Array: a condition map, terms are ANDed together.
1068 * Items with numeric keys are taken to be literal conditions
1069 * Takes an array of selected variables, and a condition map, which is ANDed
1070 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1071 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1072 * $obj- >page_id is the ID of the Astronomy article
1073 * @param $fname String: Calling functio name
1074 * @param $options Array
1075 * @param $join_conds Array
1077 * @todo migrate documentation to phpdocumentor format
1079 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array(), $join_conds = array() ) {
1080 $options['LIMIT'] = 1;
1081 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1082 if ( $res === false )
1084 if ( !$this->numRows($res) ) {
1085 $this->freeResult($res);
1088 $obj = $this->fetchObject( $res );
1089 $this->freeResult( $res );
1095 * Estimate rows in dataset
1096 * Returns estimated count, based on EXPLAIN output
1097 * Takes same arguments as Database::select()
1100 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
1101 $options['EXPLAIN']=true;
1102 $res = $this->select ($table, $vars, $conds, $fname, $options );
1103 if ( $res === false )
1105 if (!$this->numRows($res)) {
1106 $this->freeResult($res);
1112 while( $plan = $this->fetchObject( $res ) ) {
1113 $rows *= ($plan->rows
> 0)?
$plan->rows
:1; // avoid resetting to zero
1116 $this->freeResult($res);
1122 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1123 * It's only slightly flawed. Don't use for anything important.
1125 * @param $sql String: A SQL Query
1127 static function generalizeSQL( $sql ) {
1128 # This does the same as the regexp below would do, but in such a way
1129 # as to avoid crashing php on some large strings.
1130 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1132 $sql = str_replace ( "\\\\", '', $sql);
1133 $sql = str_replace ( "\\'", '', $sql);
1134 $sql = str_replace ( "\\\"", '', $sql);
1135 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1136 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1138 # All newlines, tabs, etc replaced by single space
1139 $sql = preg_replace ( '/\s+/', ' ', $sql);
1142 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1148 * Determines whether a field exists in a table
1149 * Usually aborts on failure
1150 * If errors are explicitly ignored, returns NULL on failure
1152 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1153 $table = $this->tableName( $table );
1154 $res = $this->query( 'DESCRIBE '.$table, $fname );
1161 while ( $row = $this->fetchObject( $res ) ) {
1162 if ( $row->Field
== $field ) {
1171 * Determines whether an index exists
1172 * Usually aborts on failure
1173 * If errors are explicitly ignored, returns NULL on failure
1175 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1176 $info = $this->indexInfo( $table, $index, $fname );
1177 if ( is_null( $info ) ) {
1180 return $info !== false;
1186 * Get information about an index into an object
1187 * Returns false if the index does not exist
1189 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1190 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1191 # SHOW INDEX should work for 3.x and up:
1192 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1193 $table = $this->tableName( $table );
1194 $index = $this->indexName( $index );
1195 $sql = 'SHOW INDEX FROM '.$table;
1196 $res = $this->query( $sql, $fname );
1202 while ( $row = $this->fetchObject( $res ) ) {
1203 if ( $row->Key_name
== $index ) {
1207 $this->freeResult($res);
1209 return empty($result) ?
false : $result;
1213 * Query whether a given table exists
1215 function tableExists( $table ) {
1216 $table = $this->tableName( $table );
1217 $old = $this->ignoreErrors( true );
1218 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1219 $this->ignoreErrors( $old );
1221 $this->freeResult( $res );
1229 * mysql_fetch_field() wrapper
1230 * Returns false if the field doesn't exist
1235 function fieldInfo( $table, $field ) {
1236 $table = $this->tableName( $table );
1237 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1238 $n = mysql_num_fields( $res->result
);
1239 for( $i = 0; $i < $n; $i++
) {
1240 $meta = mysql_fetch_field( $res->result
, $i );
1241 if( $field == $meta->name
) {
1242 return new MySQLField($meta);
1249 * mysql_field_type() wrapper
1251 function fieldType( $res, $index ) {
1252 if ( $res instanceof ResultWrapper
) {
1253 $res = $res->result
;
1255 return mysql_field_type( $res, $index );
1259 * Determines if a given index is unique
1261 function indexUnique( $table, $index ) {
1262 $indexInfo = $this->indexInfo( $table, $index );
1263 if ( !$indexInfo ) {
1266 return !$indexInfo[0]->Non_unique
;
1270 * INSERT wrapper, inserts an array into a table
1272 * $a may be a single associative array, or an array of these with numeric keys, for
1275 * Usually aborts on failure
1276 * If errors are explicitly ignored, returns success
1278 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1279 # No rows to insert, easy just return now
1280 if ( !count( $a ) ) {
1284 $table = $this->tableName( $table );
1285 if ( !is_array( $options ) ) {
1286 $options = array( $options );
1288 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1290 $keys = array_keys( $a[0] );
1293 $keys = array_keys( $a );
1296 $sql = 'INSERT ' . implode( ' ', $options ) .
1297 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1301 foreach ( $a as $row ) {
1307 $sql .= '(' . $this->makeList( $row ) . ')';
1310 $sql .= '(' . $this->makeList( $a ) . ')';
1312 return (bool)$this->query( $sql, $fname );
1316 * Make UPDATE options for the Database::update function
1319 * @param $options Array: The options passed to Database::update
1322 function makeUpdateOptions( $options ) {
1323 if( !is_array( $options ) ) {
1324 $options = array( $options );
1327 if ( in_array( 'LOW_PRIORITY', $options ) )
1328 $opts[] = $this->lowPriorityOption();
1329 if ( in_array( 'IGNORE', $options ) )
1331 return implode(' ', $opts);
1335 * UPDATE wrapper, takes a condition array and a SET array
1337 * @param $table String: The table to UPDATE
1338 * @param $values Array: An array of values to SET
1339 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
1340 * @param $fname String: The Class::Function calling this function
1342 * @param $options Array: An array of UPDATE options, can be one or
1343 * more of IGNORE, LOW_PRIORITY
1346 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1347 $table = $this->tableName( $table );
1348 $opts = $this->makeUpdateOptions( $options );
1349 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1350 if ( $conds != '*' ) {
1351 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1353 return $this->query( $sql, $fname );
1357 * Makes an encoded list of strings from an array
1359 * LIST_COMMA - comma separated, no field names
1360 * LIST_AND - ANDed WHERE clause (without the WHERE)
1361 * LIST_OR - ORed WHERE clause (without the WHERE)
1362 * LIST_SET - comma separated with field names, like a SET clause
1363 * LIST_NAMES - comma separated field names
1365 function makeList( $a, $mode = LIST_COMMA
) {
1366 if ( !is_array( $a ) ) {
1367 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1372 foreach ( $a as $field => $value ) {
1374 if ( $mode == LIST_AND
) {
1376 } elseif($mode == LIST_OR
) {
1384 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1385 $list .= "($value)";
1386 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
1388 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array($value) ) {
1389 if( count( $value ) == 0 ) {
1390 throw new MWException( __METHOD__
.': empty input' );
1391 } elseif( count( $value ) == 1 ) {
1392 // Special-case single values, as IN isn't terribly efficient
1393 // Don't necessarily assume the single key is 0; we don't
1394 // enforce linear numeric ordering on other arrays here.
1395 $value = array_values( $value );
1396 $list .= $field." = ".$this->addQuotes( $value[0] );
1398 $list .= $field." IN (".$this->makeList($value).") ";
1400 } elseif( is_null($value) ) {
1401 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1402 $list .= "$field IS ";
1403 } elseif ( $mode == LIST_SET
) {
1404 $list .= "$field = ";
1408 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1409 $list .= "$field = ";
1411 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1418 * Change the current database
1420 function selectDB( $db ) {
1421 $this->mDBname
= $db;
1422 return mysql_select_db( $db, $this->mConn
);
1426 * Get the current DB name
1428 function getDBname() {
1429 return $this->mDBname
;
1433 * Get the server hostname or IP address
1435 function getServer() {
1436 return $this->mServer
;
1440 * Format a table name ready for use in constructing an SQL query
1442 * This does two important things: it quotes the table names to clean them up,
1443 * and it adds a table prefix if only given a table name with no quotes.
1445 * All functions of this object which require a table name call this function
1446 * themselves. Pass the canonical name to such functions. This is only needed
1447 * when calling query() directly.
1449 * @param $name String: database table name
1450 * @return String: full database name
1452 function tableName( $name ) {
1453 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1454 # Skip the entire process when we have a string quoted on both ends.
1455 # Note that we check the end so that we will still quote any use of
1456 # use of `database`.table. But won't break things if someone wants
1457 # to query a database table with a dot in the name.
1458 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) return $name;
1460 # Lets test for any bits of text that should never show up in a table
1461 # name. Basically anything like JOIN or ON which are actually part of
1462 # SQL queries, but may end up inside of the table value to combine
1463 # sql. Such as how the API is doing.
1464 # Note that we use a whitespace test rather than a \b test to avoid
1465 # any remote case where a word like on may be inside of a table name
1466 # surrounded by symbols which may be considered word breaks.
1467 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) return $name;
1469 # Split database and table into proper variables.
1470 # We reverse the explode so that database.table and table both output
1471 # the correct table.
1472 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1473 if( isset( $dbDetails[1] ) ) @list
( $table, $database ) = $dbDetails;
1474 else @list
( $table ) = $dbDetails;
1475 $prefix = $this->mTablePrefix
; # Default prefix
1477 # A database name has been specified in input. Quote the table name
1478 # because we don't want any prefixes added.
1479 if( isset($database) ) $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
1481 # Note that we use the long format because php will complain in in_array if
1482 # the input is not an array, and will complain in is_array if it is not set.
1483 if( !isset( $database ) # Don't use shared database if pre selected.
1484 && isset( $wgSharedDB ) # We have a shared database
1485 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1486 && isset( $wgSharedTables )
1487 && is_array( $wgSharedTables )
1488 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1489 $database = $wgSharedDB;
1490 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1493 # Quote the $database and $table and apply the prefix if not quoted.
1494 if( isset($database) ) $database = ( $database[0] == '`' ?
$database : "`{$database}`" );
1495 $table = ( $table[0] == '`' ?
$table : "`{$prefix}{$table}`" );
1497 # Merge our database and table into our final table name.
1498 $tableName = ( isset($database) ?
"{$database}.{$table}" : "{$table}" );
1500 # We're finished, return.
1505 * Fetch a number of table names into an array
1506 * This is handy when you need to construct SQL for joins
1509 * extract($dbr->tableNames('user','watchlist'));
1510 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1511 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1513 public function tableNames() {
1514 $inArray = func_get_args();
1516 foreach ( $inArray as $name ) {
1517 $retVal[$name] = $this->tableName( $name );
1523 * Fetch a number of table names into an zero-indexed numerical array
1524 * This is handy when you need to construct SQL for joins
1527 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1528 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1529 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1531 public function tableNamesN() {
1532 $inArray = func_get_args();
1534 foreach ( $inArray as $name ) {
1535 $retVal[] = $this->tableName( $name );
1543 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1546 $use_index_safe = is_array($use_index) ?
$use_index : array();
1547 $join_conds_safe = is_array($join_conds) ?
$join_conds : array();
1548 foreach ( $tables as $table ) {
1549 // Is there a JOIN and INDEX clause for this table?
1550 if ( isset($join_conds_safe[$table]) && isset($use_index_safe[$table]) ) {
1551 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1552 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1553 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
) . ')';
1554 $retJOIN[] = $tableClause;
1555 // Is there an INDEX clause?
1556 } else if ( isset($use_index_safe[$table]) ) {
1557 $tableClause = $this->tableName( $table );
1558 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1559 $ret[] = $tableClause;
1560 // Is there a JOIN clause?
1561 } else if ( isset($join_conds_safe[$table]) ) {
1562 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1563 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
) . ')';
1564 $retJOIN[] = $tableClause;
1566 $tableClause = $this->tableName( $table );
1567 $ret[] = $tableClause;
1570 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1571 $straightJoins = !empty($ret) ?
implode( ',', $ret ) : "";
1572 $otherJoins = !empty($retJOIN) ?
implode( ' ', $retJOIN ) : "";
1573 // Compile our final table clause
1574 return implode(' ',array($straightJoins,$otherJoins) );
1578 * Get the name of an index in a given table
1580 function indexName( $index ) {
1581 // Backwards-compatibility hack
1582 if ( $index == 'ar_usertext_timestamp' ) {
1583 return 'usertext_timestamp';
1590 * Wrapper for addslashes()
1591 * @param $s String: to be slashed.
1592 * @return String: slashed string.
1594 function strencode( $s ) {
1595 return mysql_real_escape_string( $s, $this->mConn
);
1599 * If it's a string, adds quotes and backslashes
1600 * Otherwise returns as-is
1602 function addQuotes( $s ) {
1603 if ( is_null( $s ) ) {
1606 # This will also quote numeric values. This should be harmless,
1607 # and protects against weird problems that occur when they really
1608 # _are_ strings such as article titles and string->number->string
1609 # conversion is not 1:1.
1610 return "'" . $this->strencode( $s ) . "'";
1615 * Escape string for safe LIKE usage
1617 function escapeLike( $s ) {
1618 $s=$this->strencode( $s );
1619 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1624 * Returns an appropriately quoted sequence value for inserting a new row.
1625 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1626 * subclass will return an integer, and save the value for insertId()
1628 function nextSequenceValue( $seqName ) {
1634 * PostgreSQL doesn't have them and returns ""
1636 function useIndexClause( $index ) {
1637 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
1641 * REPLACE query wrapper
1642 * PostgreSQL simulates this with a DELETE followed by INSERT
1643 * $row is the row to insert, an associative array
1644 * $uniqueIndexes is an array of indexes. Each element may be either a
1645 * field name or an array of field names
1647 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1648 * However if you do this, you run the risk of encountering errors which wouldn't have
1651 * @todo migrate comment to phodocumentor format
1653 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1654 $table = $this->tableName( $table );
1657 if ( !is_array( reset( $rows ) ) ) {
1658 $rows = array( $rows );
1661 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1663 foreach ( $rows as $row ) {
1669 $sql .= '(' . $this->makeList( $row ) . ')';
1671 return $this->query( $sql, $fname );
1675 * DELETE where the condition is a join
1676 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1678 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1679 * join condition matches, set $conds='*'
1681 * DO NOT put the join condition in $conds
1683 * @param $delTable String: The table to delete from.
1684 * @param $joinTable String: The other table.
1685 * @param $delVar String: The variable to join on, in the first table.
1686 * @param $joinVar String: The variable to join on, in the second table.
1687 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
1688 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1690 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1692 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1695 $delTable = $this->tableName( $delTable );
1696 $joinTable = $this->tableName( $joinTable );
1697 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1698 if ( $conds != '*' ) {
1699 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1702 return $this->query( $sql, $fname );
1706 * Returns the size of a text field, or -1 for "unlimited"
1708 function textFieldSize( $table, $field ) {
1709 $table = $this->tableName( $table );
1710 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1711 $res = $this->query( $sql, 'Database::textFieldSize' );
1712 $row = $this->fetchObject( $res );
1713 $this->freeResult( $res );
1716 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1725 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1727 function lowPriorityOption() {
1728 return 'LOW_PRIORITY';
1732 * DELETE query wrapper
1734 * Use $conds == "*" to delete all rows
1736 function delete( $table, $conds, $fname = 'Database::delete' ) {
1738 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1740 $table = $this->tableName( $table );
1741 $sql = "DELETE FROM $table";
1742 if ( $conds != '*' ) {
1743 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1745 return $this->query( $sql, $fname );
1749 * INSERT SELECT wrapper
1750 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1751 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1752 * $conds may be "*" to copy the whole table
1753 * srcTable may be an array of tables.
1755 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1756 $insertOptions = array(), $selectOptions = array() )
1758 $destTable = $this->tableName( $destTable );
1759 if ( is_array( $insertOptions ) ) {
1760 $insertOptions = implode( ' ', $insertOptions );
1762 if( !is_array( $selectOptions ) ) {
1763 $selectOptions = array( $selectOptions );
1765 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1766 if( is_array( $srcTable ) ) {
1767 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1769 $srcTable = $this->tableName( $srcTable );
1771 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1772 " SELECT $startOpts " . implode( ',', $varMap ) .
1773 " FROM $srcTable $useIndex ";
1774 if ( $conds != '*' ) {
1775 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1777 $sql .= " $tailOpts";
1778 return $this->query( $sql, $fname );
1782 * Construct a LIMIT query with optional offset
1783 * This is used for query pages
1784 * @param $sql String: SQL query we will append the limit too
1785 * @param $limit Integer: the SQL limit
1786 * @param $offset Integer the SQL offset (default false)
1788 function limitResult($sql, $limit, $offset=false) {
1789 if( !is_numeric($limit) ) {
1790 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1792 return "$sql LIMIT "
1793 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1796 function limitResultForUpdate($sql, $num) {
1797 return $this->limitResult($sql, $num, 0);
1801 * Returns an SQL expression for a simple conditional.
1804 * @param $cond String: SQL expression which will result in a boolean value
1805 * @param $trueVal String: SQL expression to return if true
1806 * @param $falseVal String: SQL expression to return if false
1807 * @return String: SQL fragment
1809 function conditional( $cond, $trueVal, $falseVal ) {
1810 return " IF($cond, $trueVal, $falseVal) ";
1814 * Returns a comand for str_replace function in SQL query.
1815 * Uses REPLACE() in MySQL
1817 * @param $orig String: column to modify
1818 * @param $old String: column to seek
1819 * @param $new String: column to replace with
1821 function strreplace( $orig, $old, $new ) {
1822 return "REPLACE({$orig}, {$old}, {$new})";
1826 * Determines if the last failure was due to a deadlock
1828 function wasDeadlock() {
1829 return $this->lastErrno() == 1213;
1833 * Determines if the last query error was something that should be dealt
1834 * with by pinging the connection and reissuing the query
1836 function wasErrorReissuable() {
1837 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
1841 * Perform a deadlock-prone transaction.
1843 * This function invokes a callback function to perform a set of write
1844 * queries. If a deadlock occurs during the processing, the transaction
1845 * will be rolled back and the callback function will be called again.
1848 * $dbw->deadlockLoop( callback, ... );
1850 * Extra arguments are passed through to the specified callback function.
1852 * Returns whatever the callback function returned on its successful,
1853 * iteration, or false on error, for example if the retry limit was
1856 function deadlockLoop() {
1857 $myFname = 'Database::deadlockLoop';
1860 $args = func_get_args();
1861 $function = array_shift( $args );
1862 $oldIgnore = $this->ignoreErrors( true );
1863 $tries = DEADLOCK_TRIES
;
1864 if ( is_array( $function ) ) {
1865 $fname = $function[0];
1870 $retVal = call_user_func_array( $function, $args );
1871 $error = $this->lastError();
1872 $errno = $this->lastErrno();
1873 $sql = $this->lastQuery();
1876 if ( $this->wasDeadlock() ) {
1878 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1880 $this->reportQueryError( $error, $errno, $sql, $fname );
1883 } while( $this->wasDeadlock() && --$tries > 0 );
1884 $this->ignoreErrors( $oldIgnore );
1885 if ( $tries <= 0 ) {
1886 $this->query( 'ROLLBACK', $myFname );
1887 $this->reportQueryError( $error, $errno, $sql, $fname );
1890 $this->query( 'COMMIT', $myFname );
1896 * Do a SELECT MASTER_POS_WAIT()
1898 * @param $pos MySQLMasterPos object
1899 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
1901 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
1902 $fname = 'Database::masterPosWait';
1903 wfProfileIn( $fname );
1905 # Commit any open transactions
1906 if ( $this->mTrxLevel
) {
1907 $this->immediateCommit();
1910 if ( !is_null( $this->mFakeSlaveLag
) ) {
1911 $wait = intval( ( $pos->pos
- microtime(true) +
$this->mFakeSlaveLag
) * 1e6
);
1912 if ( $wait > $timeout * 1e6
) {
1913 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1914 wfProfileOut( $fname );
1916 } elseif ( $wait > 0 ) {
1917 wfDebug( "Fake slave waiting $wait us\n" );
1919 wfProfileOut( $fname );
1922 wfDebug( "Fake slave up to date ($wait us)\n" );
1923 wfProfileOut( $fname );
1928 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1929 $encFile = $this->addQuotes( $pos->file
);
1930 $encPos = intval( $pos->pos
);
1931 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
1932 $res = $this->doQuery( $sql );
1933 if ( $res && $row = $this->fetchRow( $res ) ) {
1934 $this->freeResult( $res );
1935 wfProfileOut( $fname );
1938 wfProfileOut( $fname );
1944 * Get the position of the master from SHOW SLAVE STATUS
1946 function getSlavePos() {
1947 if ( !is_null( $this->mFakeSlaveLag
) ) {
1948 $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag
);
1949 wfDebug( __METHOD__
.": fake slave pos = $pos\n" );
1952 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1953 $row = $this->fetchObject( $res );
1955 $pos = isset($row->Exec_master_log_pos
) ?
$row->Exec_master_log_pos
: $row->Exec_Master_Log_Pos
;
1956 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
1963 * Get the position of the master from SHOW MASTER STATUS
1965 function getMasterPos() {
1966 if ( $this->mFakeMaster
) {
1967 return new MySQLMasterPos( 'fake', microtime( true ) );
1969 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1970 $row = $this->fetchObject( $res );
1972 return new MySQLMasterPos( $row->File
, $row->Position
);
1979 * Begin a transaction, committing any previously open transaction
1981 function begin( $fname = 'Database::begin' ) {
1982 $this->query( 'BEGIN', $fname );
1983 $this->mTrxLevel
= 1;
1989 function commit( $fname = 'Database::commit' ) {
1990 $this->query( 'COMMIT', $fname );
1991 $this->mTrxLevel
= 0;
1995 * Rollback a transaction.
1996 * No-op on non-transactional databases.
1998 function rollback( $fname = 'Database::rollback' ) {
1999 $this->query( 'ROLLBACK', $fname, true );
2000 $this->mTrxLevel
= 0;
2004 * Begin a transaction, committing any previously open transaction
2005 * @deprecated use begin()
2007 function immediateBegin( $fname = 'Database::immediateBegin' ) {
2012 * Commit transaction, if one is open
2013 * @deprecated use commit()
2015 function immediateCommit( $fname = 'Database::immediateCommit' ) {
2020 * Return MW-style timestamp used for MySQL schema
2022 function timestamp( $ts=0 ) {
2023 return wfTimestamp(TS_MW
,$ts);
2027 * Local database timestamp format or null
2029 function timestampOrNull( $ts = null ) {
2030 if( is_null( $ts ) ) {
2033 return $this->timestamp( $ts );
2040 function resultObject( $result ) {
2041 if( empty( $result ) ) {
2043 } elseif ( $result instanceof ResultWrapper
) {
2045 } elseif ( $result === true ) {
2046 // Successful write query
2049 return new ResultWrapper( $this, $result );
2054 * Return aggregated value alias
2056 function aggregateValue ($valuedata,$valuename='value') {
2061 * @return String: wikitext of a link to the server software's web site
2063 function getSoftwareLink() {
2064 return "[http://www.mysql.com/ MySQL]";
2068 * @return String: Version information from the database
2070 function getServerVersion() {
2071 return mysql_get_server_info( $this->mConn
);
2075 * Ping the server and try to reconnect if it there is no connection
2078 if( !function_exists( 'mysql_ping' ) ) {
2079 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
2082 $ping = mysql_ping( $this->mConn
);
2087 // Need to reconnect manually in MySQL client 5.0.13+
2088 if ( version_compare( mysql_get_client_info(), '5.0.13', '>=' ) ) {
2089 mysql_close( $this->mConn
);
2090 $this->mOpened
= false;
2091 $this->mConn
= false;
2092 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
2100 * At the moment, this will only work if the DB user has the PROCESS privilege
2103 if ( !is_null( $this->mFakeSlaveLag
) ) {
2104 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
2105 return $this->mFakeSlaveLag
;
2107 $res = $this->query( 'SHOW PROCESSLIST' );
2108 # Find slave SQL thread
2109 while ( $row = $this->fetchObject( $res ) ) {
2110 /* This should work for most situations - when default db
2111 * for thread is not specified, it had no events executed,
2112 * and therefore it doesn't know yet how lagged it is.
2114 * Relay log I/O thread does not select databases.
2116 if ( $row->User
== 'system user' &&
2117 $row->State
!= 'Waiting for master to send event' &&
2118 $row->State
!= 'Connecting to master' &&
2119 $row->State
!= 'Queueing master event to the relay log' &&
2120 $row->State
!= 'Waiting for master update' &&
2121 $row->State
!= 'Requesting binlog dump'
2123 # This is it, return the time (except -ve)
2124 if ( $row->Time
> 0x7fffffff ) {
2135 * Get status information from SHOW STATUS in an associative array
2137 function getStatus($which="%") {
2138 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2140 while ( $row = $this->fetchObject( $res ) ) {
2141 $status[$row->Variable_name
] = $row->Value
;
2147 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2149 function maxListLen() {
2153 function encodeBlob($b) {
2157 function decodeBlob($b) {
2162 * Override database's default connection timeout.
2163 * May be useful for very long batch queries such as
2164 * full-wiki dumps, where a single query reads out
2165 * over hours or days.
2166 * @param $timeout Integer in seconds
2168 public function setTimeout( $timeout ) {
2169 $this->query( "SET net_read_timeout=$timeout" );
2170 $this->query( "SET net_write_timeout=$timeout" );
2174 * Read and execute SQL commands from a file.
2175 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2176 * @param $filename String: File name to open
2177 * @param $lineCallback Callback: Optional function called before reading each line
2178 * @param $resultCallback Callback: Optional function called for each MySQL result
2180 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2181 $fp = fopen( $filename, 'r' );
2182 if ( false === $fp ) {
2183 throw new MWException( "Could not open \"{$filename}\".\n" );
2185 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2191 * Read and execute commands from an open file handle
2192 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2193 * @param $fp String: File handle
2194 * @param $lineCallback Callback: Optional function called before reading each line
2195 * @param $resultCallback Callback: Optional function called for each MySQL result
2197 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2200 $dollarquote = false;
2202 while ( ! feof( $fp ) ) {
2203 if ( $lineCallback ) {
2204 call_user_func( $lineCallback );
2206 $line = trim( fgets( $fp, 1024 ) );
2207 $sl = strlen( $line ) - 1;
2209 if ( $sl < 0 ) { continue; }
2210 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2212 ## Allow dollar quoting for function declarations
2213 if (substr($line,0,4) == '$mw$') {
2215 $dollarquote = false;
2219 $dollarquote = true;
2222 else if (!$dollarquote) {
2223 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
2225 $line = substr( $line, 0, $sl );
2229 if ( '' != $cmd ) { $cmd .= ' '; }
2233 $cmd = str_replace(';;', ";", $cmd);
2234 $cmd = $this->replaceVars( $cmd );
2235 $res = $this->query( $cmd, __METHOD__
);
2236 if ( $resultCallback ) {
2237 call_user_func( $resultCallback, $res, $this );
2240 if ( false === $res ) {
2241 $err = $this->lastError();
2242 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2254 * Replace variables in sourced SQL
2256 protected function replaceVars( $ins ) {
2258 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2259 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2260 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2263 // Ordinary variables
2264 foreach ( $varnames as $var ) {
2265 if( isset( $GLOBALS[$var] ) ) {
2266 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2267 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2268 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2269 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2274 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2275 array( $this, 'tableNameCallback' ), $ins );
2278 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2279 array( $this, 'indexNameCallback' ), $ins );
2284 * Table name callback
2287 protected function tableNameCallback( $matches ) {
2288 return $this->tableName( $matches[1] );
2292 * Index name callback
2294 protected function indexNameCallback( $matches ) {
2295 return $this->indexName( $matches[1] );
2299 * Build a concatenation list to feed into a SQL query
2301 function buildConcat( $stringList ) {
2302 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2308 * Abstracted from Filestore::lock() so child classes can implement for
2311 * @param $lockName String: Name of lock to aquire
2312 * @param $method String: Name of method calling us
2315 public function lock( $lockName, $method ) {
2316 $lockName = $this->addQuotes( $lockName );
2317 $result = $this->query( "SELECT GET_LOCK($lockName, 5) AS lockstatus", $method );
2318 $row = $this->fetchObject( $result );
2319 $this->freeResult( $result );
2321 if( $row->lockstatus
== 1 ) {
2324 wfDebug( __METHOD__
." failed to acquire lock\n" );
2331 * @todo fixme - Figure out a way to return a bool
2332 * based on successful lock release.
2334 * @param $lockName String: Name of lock to release
2335 * @param $method String: Name of method calling us
2337 public function unlock( $lockName, $method ) {
2338 $lockName = $this->addQuotes( $lockName );
2339 $result = $this->query( "SELECT RELEASE_LOCK($lockName)", $method );
2340 $this->freeResult( $result );
2344 * Get search engine class. All subclasses of this
2345 * need to implement this if they wish to use searching.
2349 public function getSearchEngine() {
2350 return "SearchMySQL";
2355 * Database abstraction object for mySQL
2356 * Inherit all methods and properties of Database::Database()
2361 class DatabaseMysql
extends Database
{
2365 /******************************************************************************
2367 *****************************************************************************/
2376 function DBObject($data) {
2377 $this->mData
= $data;
2385 return $this->mData
;
2393 * This allows us to distinguish a blob from a normal string and an array of strings
2397 function __construct($data) {
2398 $this->mData
= $data;
2401 return $this->mData
;
2410 private $name, $tablename, $default, $max_length, $nullable,
2411 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2412 function __construct ($info) {
2413 $this->name
= $info->name
;
2414 $this->tablename
= $info->table
;
2415 $this->default = $info->def
;
2416 $this->max_length
= $info->max_length
;
2417 $this->nullable
= !$info->not_null
;
2418 $this->is_pk
= $info->primary_key
;
2419 $this->is_unique
= $info->unique_key
;
2420 $this->is_multiple
= $info->multiple_key
;
2421 $this->is_key
= ($this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
2422 $this->type
= $info->type
;
2429 function tableName() {
2430 return $this->tableName
;
2433 function defaultValue() {
2434 return $this->default;
2437 function maxLength() {
2438 return $this->max_length
;
2441 function nullable() {
2442 return $this->nullable
;
2446 return $this->is_key
;
2449 function isMultipleKey() {
2450 return $this->is_multiple
;
2458 /******************************************************************************
2460 *****************************************************************************/
2463 * Database error base class
2466 class DBError
extends MWException
{
2470 * Construct a database error
2471 * @param $db Database object which threw the error
2472 * @param $error A simple error message to be used for debugging
2474 function __construct( Database
&$db, $error ) {
2476 parent
::__construct( $error );
2483 class DBConnectionError
extends DBError
{
2486 function __construct( Database
&$db, $error = 'unknown error' ) {
2487 $msg = 'DB connection error';
2488 if ( trim( $error ) != '' ) {
2491 $this->error
= $error;
2492 parent
::__construct( $db, $msg );
2495 function useOutputPage() {
2496 // Not likely to work
2500 function useMessageCache() {
2501 // Not likely to work
2505 function getText() {
2506 return $this->getMessage() . "\n";
2509 function getLogMessage() {
2510 # Don't send to the exception log
2514 function getPageTitle() {
2516 return "$wgSitename has a problem";
2519 function getHTML() {
2520 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding;
2521 global $wgSitename, $wgServer, $wgMessageCache;
2523 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
2524 # Hard coding strings instead.
2526 $noconnect = "<p><strong>Sorry! This site is experiencing technical difficulties.</strong></p><p>Try waiting a few minutes and reloading.</p><p><small>(Can't contact the database server: $1)</small></p>";
2527 $mainpage = 'Main Page';
2528 $searchdisabled = <<<EOT
2529 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
2530 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
2534 <!-- SiteSearch Google -->
2535 <FORM method=GET action=\"http://www.google.com/search\">
2536 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
2537 <A HREF=\"http://www.google.com/\">
2538 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
2539 border=\"0\" ALT=\"Google\"></A>
2542 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
2543 <INPUT type=submit name=btnG VALUE=\"Google Search\">
2545 <input type=hidden name=domains value=\"$wgServer\"><br /><input type=radio name=sitesearch value=\"\"> WWW <input type=radio name=sitesearch value=\"$wgServer\" checked> $wgServer <br />
2546 <input type='hidden' name='ie' value='$2'>
2547 <input type='hidden' name='oe' value='$2'>
2551 <!-- SiteSearch Google -->";
2552 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
2554 # No database access
2555 if ( is_object( $wgMessageCache ) ) {
2556 $wgMessageCache->disable();
2559 if ( trim( $this->error
) == '' ) {
2560 $this->error
= $this->db
->getProperty('mServer');
2563 $text = str_replace( '$1', $this->error
, $noconnect );
2566 if ( $GLOBALS['wgShowExceptionDetails'] ) {
2567 $text .= '</p><p>Backtrace:</p><p>' .
2568 nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
2572 if($wgUseFileCache) {
2577 $t = Title
::newFromURL( $title );
2578 } elseif (@/**/$_REQUEST['search']) {
2579 $search = $_REQUEST['search'];
2580 return $searchdisabled .
2581 str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
2582 $wgInputEncoding ), $googlesearch );
2584 $t = Title
::newFromText( $mainpage );
2588 $cache = new HTMLFileCache( $t );
2589 if( $cache->isFileCached() ) {
2590 // @todo, FIXME: $msg is not defined on the next line.
2591 $msg = '<p style="color: red"><b>'.$text."<br />\n" .
2592 $cachederror . "</b></p>\n";
2594 $tag = '<div id="article">';
2595 $text = str_replace(
2598 $cache->fetchPageText() );
2609 class DBQueryError
extends DBError
{
2610 public $error, $errno, $sql, $fname;
2612 function __construct( Database
&$db, $error, $errno, $sql, $fname ) {
2613 $message = "A database error has occurred\n" .
2615 "Function: $fname\n" .
2616 "Error: $errno $error\n";
2618 parent
::__construct( $db, $message );
2619 $this->error
= $error;
2620 $this->errno
= $errno;
2622 $this->fname
= $fname;
2625 function getText() {
2626 if ( $this->useMessageCache() ) {
2627 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2628 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
2630 return $this->getMessage();
2635 global $wgShowSQLErrors;
2636 if( !$wgShowSQLErrors ) {
2637 return $this->msg( 'sqlhidden', 'SQL hidden' );
2643 function getLogMessage() {
2644 # Don't send to the exception log
2648 function getPageTitle() {
2649 return $this->msg( 'databaseerror', 'Database error' );
2652 function getHTML() {
2653 if ( $this->useMessageCache() ) {
2654 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2655 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
2657 return nl2br( htmlspecialchars( $this->getMessage() ) );
2665 class DBUnexpectedError
extends DBError
{}
2669 * Result wrapper for grabbing data queried by someone else
2672 class ResultWrapper
implements Iterator
{
2673 var $db, $result, $pos = 0, $currentRow = null;
2676 * Create a new result object from a result resource and a Database object
2678 function ResultWrapper( $database, $result ) {
2679 $this->db
= $database;
2680 if ( $result instanceof ResultWrapper
) {
2681 $this->result
= $result->result
;
2683 $this->result
= $result;
2688 * Get the number of rows in a result object
2690 function numRows() {
2691 return $this->db
->numRows( $this->result
);
2695 * Fetch the next row from the given result object, in object form.
2696 * Fields can be retrieved with $row->fieldname, with fields acting like
2699 * @param $res SQL result object as returned from Database::query(), etc.
2700 * @return MySQL row object
2701 * @throws DBUnexpectedError Thrown if the database returns an error
2703 function fetchObject() {
2704 return $this->db
->fetchObject( $this->result
);
2708 * Fetch the next row from the given result object, in associative array
2709 * form. Fields are retrieved with $row['fieldname'].
2711 * @param $res SQL result object as returned from Database::query(), etc.
2712 * @return MySQL row object
2713 * @throws DBUnexpectedError Thrown if the database returns an error
2715 function fetchRow() {
2716 return $this->db
->fetchRow( $this->result
);
2720 * Free a result object
2723 $this->db
->freeResult( $this->result
);
2724 unset( $this->result
);
2729 * Change the position of the cursor in a result object
2730 * See mysql_data_seek()
2732 function seek( $row ) {
2733 $this->db
->dataSeek( $this->result
, $row );
2736 /*********************
2737 * Iterator functions
2738 * Note that using these in combination with the non-iterator functions
2739 * above may cause rows to be skipped or repeated.
2743 if ($this->numRows()) {
2744 $this->db
->dataSeek($this->result
, 0);
2747 $this->currentRow
= null;
2750 function current() {
2751 if ( is_null( $this->currentRow
) ) {
2754 return $this->currentRow
;
2763 $this->currentRow
= $this->fetchObject();
2764 return $this->currentRow
;
2768 return $this->current() !== false;
2772 class MySQLMasterPos
{
2775 function __construct( $file, $pos ) {
2776 $this->file
= $file;
2780 function __toString() {
2781 return "{$this->file}/{$this->pos}";