add global declarations
[mediawiki.git] / includes / Database.php
blob904e2bd3b1b328b0feb69ee266342ba22216f3fc
1 <?php
2 /**
3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
5 * @package MediaWiki
6 */
8 /** See Database::makeList() */
9 define( 'LIST_COMMA', 0 );
10 define( 'LIST_AND', 1 );
11 define( 'LIST_SET', 2 );
12 define( 'LIST_NAMES', 3);
13 define( 'LIST_OR', 4);
15 /** Number of times to re-try an operation in case of deadlock */
16 define( 'DEADLOCK_TRIES', 4 );
17 /** Minimum time to wait before retry, in microseconds */
18 define( 'DEADLOCK_DELAY_MIN', 500000 );
19 /** Maximum time to wait before retry */
20 define( 'DEADLOCK_DELAY_MAX', 1500000 );
22 class DBObject {
23 var $mData;
25 function DBObject($data) {
26 $this->mData = $data;
29 function isLOB() {
30 return false;
33 function data() {
34 return $this->mData;
38 /**
39 * Database abstraction object
40 * @package MediaWiki
42 class Database {
44 #------------------------------------------------------------------------------
45 # Variables
46 #------------------------------------------------------------------------------
47 /**#@+
48 * @private
50 var $mLastQuery = '';
52 var $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
53 var $mOut, $mOpened = false;
55 var $mFailFunction;
56 var $mTablePrefix;
57 var $mFlags;
58 var $mTrxLevel = 0;
59 var $mErrorCount = 0;
60 var $mLBInfo = array();
61 /**#@-*/
63 #------------------------------------------------------------------------------
64 # Accessors
65 #------------------------------------------------------------------------------
66 # These optionally set a variable and return the previous state
68 /**
69 * Fail function, takes a Database as a parameter
70 * Set to false for default, 1 for ignore errors
72 function failFunction( $function = NULL ) {
73 return wfSetVar( $this->mFailFunction, $function );
76 /**
77 * Output page, used for reporting errors
78 * FALSE means discard output
80 function &setOutputPage( &$out ) {
81 $this->mOut =& $out;
84 /**
85 * Boolean, controls output of large amounts of debug information
87 function debug( $debug = NULL ) {
88 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
91 /**
92 * Turns buffering of SQL result sets on (true) or off (false).
93 * Default is "on" and it should not be changed without good reasons.
95 function bufferResults( $buffer = NULL ) {
96 if ( is_null( $buffer ) ) {
97 return !(bool)( $this->mFlags & DBO_NOBUFFER );
98 } else {
99 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
104 * Turns on (false) or off (true) the automatic generation and sending
105 * of a "we're sorry, but there has been a database error" page on
106 * database errors. Default is on (false). When turned off, the
107 * code should use wfLastErrno() and wfLastError() to handle the
108 * situation as appropriate.
110 function ignoreErrors( $ignoreErrors = NULL ) {
111 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
115 * The current depth of nested transactions
116 * @param $level Integer: , default NULL.
118 function trxLevel( $level = NULL ) {
119 return wfSetVar( $this->mTrxLevel, $level );
123 * Number of errors logged, only useful when errors are ignored
125 function errorCount( $count = NULL ) {
126 return wfSetVar( $this->mErrorCount, $count );
130 * Properties passed down from the server info array of the load balancer
132 function getLBInfo( $name = NULL ) {
133 if ( is_null( $name ) ) {
134 return $this->mLBInfo;
135 } else {
136 if ( array_key_exists( $name, $this->mLBInfo ) ) {
137 return $this->mLBInfo[$name];
138 } else {
139 return NULL;
144 function setLBInfo( $name, $value = NULL ) {
145 if ( is_null( $value ) ) {
146 $this->mLBInfo = $name;
147 } else {
148 $this->mLBInfo[$name] = $value;
152 /**#@+
153 * Get function
155 function lastQuery() { return $this->mLastQuery; }
156 function isOpen() { return $this->mOpened; }
157 /**#@-*/
159 function setFlag( $flag ) {
160 $this->mFlags |= $flag;
163 function clearFlag( $flag ) {
164 $this->mFlags &= ~$flag;
167 function getFlag( $flag ) {
168 return !!($this->mFlags & $flag);
171 #------------------------------------------------------------------------------
172 # Other functions
173 #------------------------------------------------------------------------------
175 /**@{{
176 * @param string $server database server host
177 * @param string $user database user name
178 * @param string $password database user password
179 * @param string $dbname database name
183 * @param failFunction
184 * @param $flags
185 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
187 function Database( $server = false, $user = false, $password = false, $dbName = false,
188 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
190 global $wgOut, $wgDBprefix, $wgCommandLineMode;
191 # Can't get a reference if it hasn't been set yet
192 if ( !isset( $wgOut ) ) {
193 $wgOut = NULL;
195 $this->mOut =& $wgOut;
197 $this->mFailFunction = $failFunction;
198 $this->mFlags = $flags;
200 if ( $this->mFlags & DBO_DEFAULT ) {
201 if ( $wgCommandLineMode ) {
202 $this->mFlags &= ~DBO_TRX;
203 } else {
204 $this->mFlags |= DBO_TRX;
209 // Faster read-only access
210 if ( wfReadOnly() ) {
211 $this->mFlags |= DBO_PERSISTENT;
212 $this->mFlags &= ~DBO_TRX;
215 /** Get the default table prefix*/
216 if ( $tablePrefix == 'get from global' ) {
217 $this->mTablePrefix = $wgDBprefix;
218 } else {
219 $this->mTablePrefix = $tablePrefix;
222 if ( $server ) {
223 $this->open( $server, $user, $password, $dbName );
228 * @static
229 * @param failFunction
230 * @param $flags
232 function newFromParams( $server, $user, $password, $dbName,
233 $failFunction = false, $flags = 0 )
235 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
239 * Usually aborts on failure
240 * If the failFunction is set to a non-zero integer, returns success
242 function open( $server, $user, $password, $dbName ) {
243 global $wguname;
245 # Test for missing mysql.so
246 # First try to load it
247 if (!@extension_loaded('mysql')) {
248 @dl('mysql.so');
251 # Otherwise we get a suppressed fatal error, which is very hard to track down
252 if ( !function_exists( 'mysql_connect' ) ) {
253 wfDie( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
256 $this->close();
257 $this->mServer = $server;
258 $this->mUser = $user;
259 $this->mPassword = $password;
260 $this->mDBname = $dbName;
262 $success = false;
264 if ( $this->mFlags & DBO_PERSISTENT ) {
265 @/**/$this->mConn = mysql_pconnect( $server, $user, $password );
266 } else {
267 # Create a new connection...
268 @/**/$this->mConn = mysql_connect( $server, $user, $password, true );
271 if ( $dbName != '' ) {
272 if ( $this->mConn !== false ) {
273 $success = @/**/mysql_select_db( $dbName, $this->mConn );
274 if ( !$success ) {
275 $error = "Error selecting database $dbName on server {$this->mServer} " .
276 "from client host {$wguname['nodename']}\n";
277 wfDebug( $error );
279 } else {
280 wfDebug( "DB connection error\n" );
281 wfDebug( "Server: $server, User: $user, Password: " .
282 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
283 $success = false;
285 } else {
286 # Delay USE query
287 $success = (bool)$this->mConn;
290 if ( !$success ) {
291 $this->reportConnectionError();
294 global $wgDBmysql5;
295 if( $wgDBmysql5 ) {
296 // Tell the server we're communicating with it in UTF-8.
297 // This may engage various charset conversions.
298 $this->query( 'SET NAMES utf8' );
301 $this->mOpened = $success;
302 return $success;
304 /**@}}*/
307 * Closes a database connection.
308 * if it is open : commits any open transactions
310 * @return bool operation success. true if already closed.
312 function close()
314 $this->mOpened = false;
315 if ( $this->mConn ) {
316 if ( $this->trxLevel() ) {
317 $this->immediateCommit();
319 return mysql_close( $this->mConn );
320 } else {
321 return true;
326 * @private
327 * @param string $error fallback error message, used if none is given by MySQL
329 function reportConnectionError( $error = 'Unknown error' ) {
330 $myError = $this->lastError();
331 if ( $myError ) {
332 $error = $myError;
335 if ( $this->mFailFunction ) {
336 if ( !is_int( $this->mFailFunction ) ) {
337 $ff = $this->mFailFunction;
338 $ff( $this, $error );
340 } else {
341 wfEmergencyAbort( $this, $error );
346 * Usually aborts on failure
347 * If errors are explicitly ignored, returns success
349 function query( $sql, $fname = '', $tempIgnore = false ) {
350 global $wgProfiling;
352 if ( $wgProfiling ) {
353 # generalizeSQL will probably cut down the query to reasonable
354 # logging size most of the time. The substr is really just a sanity check.
356 # Who's been wasting my precious column space? -- TS
357 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
359 if ( is_null( $this->getLBInfo( 'master' ) ) ) {
360 $queryProf = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
361 $totalProf = 'Database::query';
362 } else {
363 $queryProf = 'query-m: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
364 $totalProf = 'Database::query-master';
366 wfProfileIn( $totalProf );
367 wfProfileIn( $queryProf );
370 $this->mLastQuery = $sql;
372 # Add a comment for easy SHOW PROCESSLIST interpretation
373 if ( $fname ) {
374 $commentedSql = preg_replace("/\s/", " /* $fname */ ", $sql, 1);
375 } else {
376 $commentedSql = $sql;
379 # If DBO_TRX is set, start a transaction
380 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() && $sql != 'BEGIN' ) {
381 $this->begin();
384 if ( $this->debug() ) {
385 $sqlx = substr( $commentedSql, 0, 500 );
386 $sqlx = strtr( $sqlx, "\t\n", ' ' );
387 wfDebug( "SQL: $sqlx\n" );
390 # Do the query and handle errors
391 $ret = $this->doQuery( $commentedSql );
393 # Try reconnecting if the connection was lost
394 if ( false === $ret && ( $this->lastErrno() == 2013 || $this->lastErrno() == 2006 ) ) {
395 # Transaction is gone, like it or not
396 $this->mTrxLevel = 0;
397 wfDebug( "Connection lost, reconnecting...\n" );
398 if ( $this->ping() ) {
399 wfDebug( "Reconnected\n" );
400 $ret = $this->doQuery( $commentedSql );
401 } else {
402 wfDebug( "Failed\n" );
406 if ( false === $ret ) {
407 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
410 if ( $wgProfiling ) {
411 wfProfileOut( $queryProf );
412 wfProfileOut( $totalProf );
414 return $ret;
418 * The DBMS-dependent part of query()
419 * @param string $sql SQL query.
421 function doQuery( $sql ) {
422 if( $this->bufferResults() ) {
423 $ret = mysql_query( $sql, $this->mConn );
424 } else {
425 $ret = mysql_unbuffered_query( $sql, $this->mConn );
427 return $ret;
431 * @param $error
432 * @param $errno
433 * @param $sql
434 * @param string $fname
435 * @param bool $tempIgnore
437 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
438 global $wgCommandLineMode, $wgFullyInitialised, $wgColorErrors;
439 # Ignore errors during error handling to avoid infinite recursion
440 $ignore = $this->ignoreErrors( true );
441 ++$this->mErrorCount;
443 if( $ignore || $tempIgnore ) {
444 wfDebug("SQL ERROR (ignored): $error\n");
445 } else {
446 $sql1line = str_replace( "\n", "\\n", $sql );
447 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
448 wfDebug("SQL ERROR: " . $error . "\n");
449 if ( $wgCommandLineMode || !$this->mOut || empty( $wgFullyInitialised ) ) {
450 $message = "A database error has occurred\n" .
451 "Query: $sql\n" .
452 "Function: $fname\n" .
453 "Error: $errno $error\n";
454 if ( !$wgCommandLineMode ) {
455 $message = nl2br( $message );
457 if( $wgCommandLineMode && $wgColorErrors && !wfIsWindows() && posix_isatty(1) ) {
458 $color = 31; // bright red!
459 $message = "\x1b[1;{$color}m{$message}\x1b[0m";
461 wfDebugDieBacktrace( $message );
462 } else {
463 // this calls wfAbruptExit()
464 $this->mOut->databaseError( $fname, $sql, $error, $errno );
467 $this->ignoreErrors( $ignore );
472 * Intended to be compatible with the PEAR::DB wrapper functions.
473 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
475 * ? = scalar value, quoted as necessary
476 * ! = raw SQL bit (a function for instance)
477 * & = filename; reads the file and inserts as a blob
478 * (we don't use this though...)
480 function prepare( $sql, $func = 'Database::prepare' ) {
481 /* MySQL doesn't support prepared statements (yet), so just
482 pack up the query for reference. We'll manually replace
483 the bits later. */
484 return array( 'query' => $sql, 'func' => $func );
487 function freePrepared( $prepared ) {
488 /* No-op for MySQL */
492 * Execute a prepared query with the various arguments
493 * @param string $prepared the prepared sql
494 * @param mixed $args Either an array here, or put scalars as varargs
496 function execute( $prepared, $args = null ) {
497 if( !is_array( $args ) ) {
498 # Pull the var args
499 $args = func_get_args();
500 array_shift( $args );
502 $sql = $this->fillPrepared( $prepared['query'], $args );
503 return $this->query( $sql, $prepared['func'] );
507 * Prepare & execute an SQL statement, quoting and inserting arguments
508 * in the appropriate places.
509 * @param string $query
510 * @param string $args ...
512 function safeQuery( $query, $args = null ) {
513 $prepared = $this->prepare( $query, 'Database::safeQuery' );
514 if( !is_array( $args ) ) {
515 # Pull the var args
516 $args = func_get_args();
517 array_shift( $args );
519 $retval = $this->execute( $prepared, $args );
520 $this->freePrepared( $prepared );
521 return $retval;
525 * For faking prepared SQL statements on DBs that don't support
526 * it directly.
527 * @param string $preparedSql - a 'preparable' SQL statement
528 * @param array $args - array of arguments to fill it with
529 * @return string executable SQL
531 function fillPrepared( $preparedQuery, $args ) {
532 reset( $args );
533 $this->preparedArgs =& $args;
534 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
535 array( &$this, 'fillPreparedArg' ), $preparedQuery );
539 * preg_callback func for fillPrepared()
540 * The arguments should be in $this->preparedArgs and must not be touched
541 * while we're doing this.
543 * @param array $matches
544 * @return string
545 * @private
547 function fillPreparedArg( $matches ) {
548 switch( $matches[1] ) {
549 case '\\?': return '?';
550 case '\\!': return '!';
551 case '\\&': return '&';
553 list( $n, $arg ) = each( $this->preparedArgs );
554 switch( $matches[1] ) {
555 case '?': return $this->addQuotes( $arg );
556 case '!': return $arg;
557 case '&':
558 # return $this->addQuotes( file_get_contents( $arg ) );
559 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
560 default:
561 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
565 /**#@+
566 * @param mixed $res A SQL result
569 * Free a result object
571 function freeResult( $res ) {
572 if ( !@/**/mysql_free_result( $res ) ) {
573 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
578 * Fetch the next row from the given result object, in object form
580 function fetchObject( $res ) {
581 @/**/$row = mysql_fetch_object( $res );
582 if( mysql_errno() ) {
583 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
585 return $row;
589 * Fetch the next row from the given result object
590 * Returns an array
592 function fetchRow( $res ) {
593 @/**/$row = mysql_fetch_array( $res );
594 if (mysql_errno() ) {
595 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
597 return $row;
601 * Get the number of rows in a result object
603 function numRows( $res ) {
604 @/**/$n = mysql_num_rows( $res );
605 if( mysql_errno() ) {
606 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
608 return $n;
612 * Get the number of fields in a result object
613 * See documentation for mysql_num_fields()
615 function numFields( $res ) { return mysql_num_fields( $res ); }
618 * Get a field name in a result object
619 * See documentation for mysql_field_name():
620 * http://www.php.net/mysql_field_name
622 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
625 * Get the inserted value of an auto-increment row
627 * The value inserted should be fetched from nextSequenceValue()
629 * Example:
630 * $id = $dbw->nextSequenceValue('page_page_id_seq');
631 * $dbw->insert('page',array('page_id' => $id));
632 * $id = $dbw->insertId();
634 function insertId() { return mysql_insert_id( $this->mConn ); }
637 * Change the position of the cursor in a result object
638 * See mysql_data_seek()
640 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
643 * Get the last error number
644 * See mysql_errno()
646 function lastErrno() {
647 if ( $this->mConn ) {
648 return mysql_errno( $this->mConn );
649 } else {
650 return mysql_errno();
655 * Get a description of the last error
656 * See mysql_error() for more details
658 function lastError() {
659 if ( $this->mConn ) {
660 # Even if it's non-zero, it can still be invalid
661 wfSuppressWarnings();
662 $error = mysql_error( $this->mConn );
663 if ( !$error ) {
664 $error = mysql_error();
666 wfRestoreWarnings();
667 } else {
668 $error = mysql_error();
670 if( $error ) {
671 $error .= ' (' . $this->mServer . ')';
673 return $error;
676 * Get the number of rows affected by the last write query
677 * See mysql_affected_rows() for more details
679 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
680 /**#@-*/ // end of template : @param $result
683 * Simple UPDATE wrapper
684 * Usually aborts on failure
685 * If errors are explicitly ignored, returns success
687 * This function exists for historical reasons, Database::update() has a more standard
688 * calling convention and feature set
690 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
692 $table = $this->tableName( $table );
693 $sql = "UPDATE $table SET $var = '" .
694 $this->strencode( $value ) . "' WHERE ($cond)";
695 return (bool)$this->query( $sql, $fname );
699 * Simple SELECT wrapper, returns a single field, input must be encoded
700 * Usually aborts on failure
701 * If errors are explicitly ignored, returns FALSE on failure
703 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
704 if ( !is_array( $options ) ) {
705 $options = array( $options );
707 $options['LIMIT'] = 1;
709 $res = $this->select( $table, $var, $cond, $fname, $options );
710 if ( $res === false || !$this->numRows( $res ) ) {
711 return false;
713 $row = $this->fetchRow( $res );
714 if ( $row !== false ) {
715 $this->freeResult( $res );
716 return $row[0];
717 } else {
718 return false;
723 * Returns an optional USE INDEX clause to go after the table, and a
724 * string to go at the end of the query
726 * @private
728 * @param array $options an associative array of options to be turned into
729 * an SQL query, valid keys are listed in the function.
730 * @return array
732 function makeSelectOptions( $options ) {
733 $tailOpts = '';
734 $startOpts = '';
736 $noKeyOptions = array();
737 foreach ( $options as $key => $option ) {
738 if ( is_numeric( $key ) ) {
739 $noKeyOptions[$option] = true;
743 if ( isset( $options['GROUP BY'] ) ) $tailOpts .= " GROUP BY {$options['GROUP BY']}";
744 if ( isset( $options['ORDER BY'] ) ) $tailOpts .= " ORDER BY {$options['ORDER BY']}";
746 if (isset($options['LIMIT'])) {
747 $tailOpts .= $this->limitResult('', $options['LIMIT'],
748 isset($options['OFFSET']) ? $options['OFFSET'] : false);
751 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
752 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
753 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
755 # Various MySQL extensions
756 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
757 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
758 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
759 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
760 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
761 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
762 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
764 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
765 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
766 } else {
767 $useIndex = '';
770 return array( $startOpts, $useIndex, $tailOpts );
774 * SELECT wrapper
776 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
778 if( is_array( $vars ) ) {
779 $vars = implode( ',', $vars );
781 if( !is_array( $options ) ) {
782 $options = array( $options );
784 if( is_array( $table ) ) {
785 if ( @is_array( $options['USE INDEX'] ) )
786 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
787 else
788 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
789 } elseif ($table!='') {
790 $from = ' FROM ' . $this->tableName( $table );
791 } else {
792 $from = '';
795 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
797 if( !empty( $conds ) ) {
798 if ( is_array( $conds ) ) {
799 $conds = $this->makeList( $conds, LIST_AND );
801 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $tailOpts";
802 } else {
803 $sql = "SELECT $startOpts $vars $from $useIndex $tailOpts";
806 return $this->query( $sql, $fname );
810 * Single row SELECT wrapper
811 * Aborts or returns FALSE on error
813 * $vars: the selected variables
814 * $conds: a condition map, terms are ANDed together.
815 * Items with numeric keys are taken to be literal conditions
816 * Takes an array of selected variables, and a condition map, which is ANDed
817 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
818 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
819 * $obj- >page_id is the ID of the Astronomy article
821 * @todo migrate documentation to phpdocumentor format
823 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
824 $options['LIMIT'] = 1;
825 $res = $this->select( $table, $vars, $conds, $fname, $options );
826 if ( $res === false )
827 return false;
828 if ( !$this->numRows($res) ) {
829 $this->freeResult($res);
830 return false;
832 $obj = $this->fetchObject( $res );
833 $this->freeResult( $res );
834 return $obj;
839 * Removes most variables from an SQL query and replaces them with X or N for numbers.
840 * It's only slightly flawed. Don't use for anything important.
842 * @param string $sql A SQL Query
843 * @static
845 function generalizeSQL( $sql ) {
846 # This does the same as the regexp below would do, but in such a way
847 # as to avoid crashing php on some large strings.
848 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
850 $sql = str_replace ( "\\\\", '', $sql);
851 $sql = str_replace ( "\\'", '', $sql);
852 $sql = str_replace ( "\\\"", '', $sql);
853 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
854 $sql = preg_replace ('/".*"/s', "'X'", $sql);
856 # All newlines, tabs, etc replaced by single space
857 $sql = preg_replace ( "/\s+/", ' ', $sql);
859 # All numbers => N
860 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
862 return $sql;
866 * Determines whether a field exists in a table
867 * Usually aborts on failure
868 * If errors are explicitly ignored, returns NULL on failure
870 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
871 $table = $this->tableName( $table );
872 $res = $this->query( 'DESCRIBE '.$table, $fname );
873 if ( !$res ) {
874 return NULL;
877 $found = false;
879 while ( $row = $this->fetchObject( $res ) ) {
880 if ( $row->Field == $field ) {
881 $found = true;
882 break;
885 return $found;
889 * Determines whether an index exists
890 * Usually aborts on failure
891 * If errors are explicitly ignored, returns NULL on failure
893 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
894 $info = $this->indexInfo( $table, $index, $fname );
895 if ( is_null( $info ) ) {
896 return NULL;
897 } else {
898 return $info !== false;
904 * Get information about an index into an object
905 * Returns false if the index does not exist
907 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
908 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
909 # SHOW INDEX should work for 3.x and up:
910 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
911 $table = $this->tableName( $table );
912 $sql = 'SHOW INDEX FROM '.$table;
913 $res = $this->query( $sql, $fname );
914 if ( !$res ) {
915 return NULL;
918 while ( $row = $this->fetchObject( $res ) ) {
919 if ( $row->Key_name == $index ) {
920 return $row;
923 return false;
927 * Query whether a given table exists
929 function tableExists( $table ) {
930 $table = $this->tableName( $table );
931 $old = $this->ignoreErrors( true );
932 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
933 $this->ignoreErrors( $old );
934 if( $res ) {
935 $this->freeResult( $res );
936 return true;
937 } else {
938 return false;
943 * mysql_fetch_field() wrapper
944 * Returns false if the field doesn't exist
946 * @param $table
947 * @param $field
949 function fieldInfo( $table, $field ) {
950 $table = $this->tableName( $table );
951 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
952 $n = mysql_num_fields( $res );
953 for( $i = 0; $i < $n; $i++ ) {
954 $meta = mysql_fetch_field( $res, $i );
955 if( $field == $meta->name ) {
956 return $meta;
959 return false;
963 * mysql_field_type() wrapper
965 function fieldType( $res, $index ) {
966 return mysql_field_type( $res, $index );
970 * Determines if a given index is unique
972 function indexUnique( $table, $index ) {
973 $indexInfo = $this->indexInfo( $table, $index );
974 if ( !$indexInfo ) {
975 return NULL;
977 return !$indexInfo->Non_unique;
981 * INSERT wrapper, inserts an array into a table
983 * $a may be a single associative array, or an array of these with numeric keys, for
984 * multi-row insert.
986 * Usually aborts on failure
987 * If errors are explicitly ignored, returns success
989 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
990 # No rows to insert, easy just return now
991 if ( !count( $a ) ) {
992 return true;
995 $table = $this->tableName( $table );
996 if ( !is_array( $options ) ) {
997 $options = array( $options );
999 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1000 $multi = true;
1001 $keys = array_keys( $a[0] );
1002 } else {
1003 $multi = false;
1004 $keys = array_keys( $a );
1007 $sql = 'INSERT ' . implode( ' ', $options ) .
1008 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1010 if ( $multi ) {
1011 $first = true;
1012 foreach ( $a as $row ) {
1013 if ( $first ) {
1014 $first = false;
1015 } else {
1016 $sql .= ',';
1018 $sql .= '(' . $this->makeList( $row ) . ')';
1020 } else {
1021 $sql .= '(' . $this->makeList( $a ) . ')';
1023 return (bool)$this->query( $sql, $fname );
1027 * Make UPDATE options for the Database::update function
1029 * @private
1030 * @param array $options The options passed to Database::update
1031 * @return string
1033 function makeUpdateOptions( $options ) {
1034 if( !is_array( $options ) ) {
1035 $options = array( $options );
1037 $opts = array();
1038 if ( in_array( 'LOW_PRIORITY', $options ) )
1039 $opts[] = $this->lowPriorityOption();
1040 if ( in_array( 'IGNORE', $options ) )
1041 $opts[] = 'IGNORE';
1042 return implode(' ', $opts);
1046 * UPDATE wrapper, takes a condition array and a SET array
1048 * @param string $table The table to UPDATE
1049 * @param array $values An array of values to SET
1050 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1051 * @param string $fname The Class::Function calling this function
1052 * (for the log)
1053 * @param array $options An array of UPDATE options, can be one or
1054 * more of IGNORE, LOW_PRIORITY
1056 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1057 $table = $this->tableName( $table );
1058 $opts = $this->makeUpdateOptions( $options );
1059 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1060 if ( $conds != '*' ) {
1061 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1063 $this->query( $sql, $fname );
1067 * Makes a wfStrencoded list from an array
1068 * $mode:
1069 * LIST_COMMA - comma separated, no field names
1070 * LIST_AND - ANDed WHERE clause (without the WHERE)
1071 * LIST_OR - ORed WHERE clause (without the WHERE)
1072 * LIST_SET - comma separated with field names, like a SET clause
1073 * LIST_NAMES - comma separated field names
1075 function makeList( $a, $mode = LIST_COMMA ) {
1076 if ( !is_array( $a ) ) {
1077 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
1080 $first = true;
1081 $list = '';
1082 foreach ( $a as $field => $value ) {
1083 if ( !$first ) {
1084 if ( $mode == LIST_AND ) {
1085 $list .= ' AND ';
1086 } elseif($mode == LIST_OR) {
1087 $list .= ' OR ';
1088 } else {
1089 $list .= ',';
1091 } else {
1092 $first = false;
1094 if ( ($mode == LIST_AND || $mode == LIST_OR) && is_numeric( $field ) ) {
1095 $list .= "($value)";
1096 } elseif ( ($mode == LIST_AND || $mode == LIST_OR) && is_array ($value) ) {
1097 $list .= $field." IN (".$this->makeList($value).") ";
1098 } else {
1099 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1100 $list .= "$field = ";
1102 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1105 return $list;
1109 * Change the current database
1111 function selectDB( $db ) {
1112 $this->mDBname = $db;
1113 return mysql_select_db( $db, $this->mConn );
1117 * Format a table name ready for use in constructing an SQL query
1119 * This does two important things: it quotes table names which as necessary,
1120 * and it adds a table prefix if there is one.
1122 * All functions of this object which require a table name call this function
1123 * themselves. Pass the canonical name to such functions. This is only needed
1124 * when calling query() directly.
1126 * @param string $name database table name
1128 function tableName( $name ) {
1129 global $wgSharedDB;
1130 # Skip quoted literals
1131 if ( $name{0} != '`' ) {
1132 if ( $this->mTablePrefix !== '' && strpos( '.', $name ) === false ) {
1133 $name = "{$this->mTablePrefix}$name";
1135 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1136 $name = "`$wgSharedDB`.`$name`";
1137 } else {
1138 # Standard quoting
1139 $name = "`$name`";
1142 return $name;
1146 * Fetch a number of table names into an array
1147 * This is handy when you need to construct SQL for joins
1149 * Example:
1150 * extract($dbr->tableNames('user','watchlist'));
1151 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1152 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1154 function tableNames() {
1155 $inArray = func_get_args();
1156 $retVal = array();
1157 foreach ( $inArray as $name ) {
1158 $retVal[$name] = $this->tableName( $name );
1160 return $retVal;
1164 * @private
1166 function tableNamesWithUseIndex( $tables, $use_index ) {
1167 $ret = array();
1169 foreach ( $tables as $table )
1170 if ( @$use_index[$table] !== null )
1171 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1172 else
1173 $ret[] = $this->tableName( $table );
1175 return implode( ',', $ret );
1179 * Wrapper for addslashes()
1180 * @param string $s String to be slashed.
1181 * @return string slashed string.
1183 function strencode( $s ) {
1184 return addslashes( $s );
1188 * If it's a string, adds quotes and backslashes
1189 * Otherwise returns as-is
1191 function addQuotes( $s ) {
1192 if ( is_null( $s ) ) {
1193 return 'NULL';
1194 } else {
1195 # This will also quote numeric values. This should be harmless,
1196 # and protects against weird problems that occur when they really
1197 # _are_ strings such as article titles and string->number->string
1198 # conversion is not 1:1.
1199 return "'" . $this->strencode( $s ) . "'";
1204 * Escape string for safe LIKE usage
1206 function escapeLike( $s ) {
1207 $s=$this->strencode( $s );
1208 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1209 return $s;
1213 * Returns an appropriately quoted sequence value for inserting a new row.
1214 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1215 * subclass will return an integer, and save the value for insertId()
1217 function nextSequenceValue( $seqName ) {
1218 return NULL;
1222 * USE INDEX clause
1223 * PostgreSQL doesn't have them and returns ""
1225 function useIndexClause( $index ) {
1226 return "FORCE INDEX ($index)";
1230 * REPLACE query wrapper
1231 * PostgreSQL simulates this with a DELETE followed by INSERT
1232 * $row is the row to insert, an associative array
1233 * $uniqueIndexes is an array of indexes. Each element may be either a
1234 * field name or an array of field names
1236 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1237 * However if you do this, you run the risk of encountering errors which wouldn't have
1238 * occurred in MySQL
1240 * @todo migrate comment to phodocumentor format
1242 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1243 $table = $this->tableName( $table );
1245 # Single row case
1246 if ( !is_array( reset( $rows ) ) ) {
1247 $rows = array( $rows );
1250 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1251 $first = true;
1252 foreach ( $rows as $row ) {
1253 if ( $first ) {
1254 $first = false;
1255 } else {
1256 $sql .= ',';
1258 $sql .= '(' . $this->makeList( $row ) . ')';
1260 return $this->query( $sql, $fname );
1264 * DELETE where the condition is a join
1265 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1267 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1268 * join condition matches, set $conds='*'
1270 * DO NOT put the join condition in $conds
1272 * @param string $delTable The table to delete from.
1273 * @param string $joinTable The other table.
1274 * @param string $delVar The variable to join on, in the first table.
1275 * @param string $joinVar The variable to join on, in the second table.
1276 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1278 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1279 if ( !$conds ) {
1280 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1283 $delTable = $this->tableName( $delTable );
1284 $joinTable = $this->tableName( $joinTable );
1285 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1286 if ( $conds != '*' ) {
1287 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1290 return $this->query( $sql, $fname );
1294 * Returns the size of a text field, or -1 for "unlimited"
1296 function textFieldSize( $table, $field ) {
1297 $table = $this->tableName( $table );
1298 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1299 $res = $this->query( $sql, 'Database::textFieldSize' );
1300 $row = $this->fetchObject( $res );
1301 $this->freeResult( $res );
1303 if ( preg_match( "/\((.*)\)/", $row->Type, $m ) ) {
1304 $size = $m[1];
1305 } else {
1306 $size = -1;
1308 return $size;
1312 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1314 function lowPriorityOption() {
1315 return 'LOW_PRIORITY';
1319 * DELETE query wrapper
1321 * Use $conds == "*" to delete all rows
1323 function delete( $table, $conds, $fname = 'Database::delete' ) {
1324 if ( !$conds ) {
1325 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1327 $table = $this->tableName( $table );
1328 $sql = "DELETE FROM $table";
1329 if ( $conds != '*' ) {
1330 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1332 return $this->query( $sql, $fname );
1336 * INSERT SELECT wrapper
1337 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1338 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1339 * $conds may be "*" to copy the whole table
1340 * srcTable may be an array of tables.
1342 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1343 $insertOptions = array(), $selectOptions = array() )
1345 $destTable = $this->tableName( $destTable );
1346 if ( is_array( $insertOptions ) ) {
1347 $insertOptions = implode( ' ', $insertOptions );
1349 if( !is_array( $selectOptions ) ) {
1350 $selectOptions = array( $selectOptions );
1352 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1353 if( is_array( $srcTable ) ) {
1354 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1355 } else {
1356 $srcTable = $this->tableName( $srcTable );
1358 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1359 " SELECT $startOpts " . implode( ',', $varMap ) .
1360 " FROM $srcTable $useIndex ";
1361 if ( $conds != '*' ) {
1362 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1364 $sql .= " $tailOpts";
1365 return $this->query( $sql, $fname );
1369 * Construct a LIMIT query with optional offset
1370 * This is used for query pages
1371 * $sql string SQL query we will append the limit too
1372 * $limit integer the SQL limit
1373 * $offset integer the SQL offset (default false)
1375 function limitResult($sql, $limit, $offset=false) {
1376 if( !is_numeric($limit) ) {
1377 wfDie( "Invalid non-numeric limit passed to limitResult()\n" );
1379 return " $sql LIMIT "
1380 . ( (is_numeric($offset) && $offset != 0) ? "{$offset}," : "" )
1381 . "{$limit} ";
1383 function limitResultForUpdate($sql, $num) {
1384 return $this->limitResult($sql, $num, 0);
1388 * Returns an SQL expression for a simple conditional.
1389 * Uses IF on MySQL.
1391 * @param string $cond SQL expression which will result in a boolean value
1392 * @param string $trueVal SQL expression to return if true
1393 * @param string $falseVal SQL expression to return if false
1394 * @return string SQL fragment
1396 function conditional( $cond, $trueVal, $falseVal ) {
1397 return " IF($cond, $trueVal, $falseVal) ";
1401 * Determines if the last failure was due to a deadlock
1403 function wasDeadlock() {
1404 return $this->lastErrno() == 1213;
1408 * Perform a deadlock-prone transaction.
1410 * This function invokes a callback function to perform a set of write
1411 * queries. If a deadlock occurs during the processing, the transaction
1412 * will be rolled back and the callback function will be called again.
1414 * Usage:
1415 * $dbw->deadlockLoop( callback, ... );
1417 * Extra arguments are passed through to the specified callback function.
1419 * Returns whatever the callback function returned on its successful,
1420 * iteration, or false on error, for example if the retry limit was
1421 * reached.
1423 function deadlockLoop() {
1424 $myFname = 'Database::deadlockLoop';
1426 $this->begin();
1427 $args = func_get_args();
1428 $function = array_shift( $args );
1429 $oldIgnore = $this->ignoreErrors( true );
1430 $tries = DEADLOCK_TRIES;
1431 if ( is_array( $function ) ) {
1432 $fname = $function[0];
1433 } else {
1434 $fname = $function;
1436 do {
1437 $retVal = call_user_func_array( $function, $args );
1438 $error = $this->lastError();
1439 $errno = $this->lastErrno();
1440 $sql = $this->lastQuery();
1442 if ( $errno ) {
1443 if ( $this->wasDeadlock() ) {
1444 # Retry
1445 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1446 } else {
1447 $this->reportQueryError( $error, $errno, $sql, $fname );
1450 } while( $this->wasDeadlock() && --$tries > 0 );
1451 $this->ignoreErrors( $oldIgnore );
1452 if ( $tries <= 0 ) {
1453 $this->query( 'ROLLBACK', $myFname );
1454 $this->reportQueryError( $error, $errno, $sql, $fname );
1455 return false;
1456 } else {
1457 $this->query( 'COMMIT', $myFname );
1458 return $retVal;
1463 * Do a SELECT MASTER_POS_WAIT()
1465 * @param string $file the binlog file
1466 * @param string $pos the binlog position
1467 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1469 function masterPosWait( $file, $pos, $timeout ) {
1470 $fname = 'Database::masterPosWait';
1471 wfProfileIn( $fname );
1474 # Commit any open transactions
1475 $this->immediateCommit();
1477 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1478 $encFile = $this->strencode( $file );
1479 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1480 $res = $this->doQuery( $sql );
1481 if ( $res && $row = $this->fetchRow( $res ) ) {
1482 $this->freeResult( $res );
1483 wfProfileOut( $fname );
1484 return $row[0];
1485 } else {
1486 wfProfileOut( $fname );
1487 return false;
1492 * Get the position of the master from SHOW SLAVE STATUS
1494 function getSlavePos() {
1495 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1496 $row = $this->fetchObject( $res );
1497 if ( $row ) {
1498 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1499 } else {
1500 return array( false, false );
1505 * Get the position of the master from SHOW MASTER STATUS
1507 function getMasterPos() {
1508 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1509 $row = $this->fetchObject( $res );
1510 if ( $row ) {
1511 return array( $row->File, $row->Position );
1512 } else {
1513 return array( false, false );
1518 * Begin a transaction, or if a transaction has already started, continue it
1520 function begin( $fname = 'Database::begin' ) {
1521 if ( !$this->mTrxLevel ) {
1522 $this->immediateBegin( $fname );
1523 } else {
1524 $this->mTrxLevel++;
1529 * End a transaction, or decrement the nest level if transactions are nested
1531 function commit( $fname = 'Database::commit' ) {
1532 if ( $this->mTrxLevel ) {
1533 $this->mTrxLevel--;
1535 if ( !$this->mTrxLevel ) {
1536 $this->immediateCommit( $fname );
1541 * Rollback a transaction
1543 function rollback( $fname = 'Database::rollback' ) {
1544 $this->query( 'ROLLBACK', $fname );
1545 $this->mTrxLevel = 0;
1549 * Begin a transaction, committing any previously open transaction
1551 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1552 $this->query( 'BEGIN', $fname );
1553 $this->mTrxLevel = 1;
1557 * Commit transaction, if one is open
1559 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1560 $this->query( 'COMMIT', $fname );
1561 $this->mTrxLevel = 0;
1565 * Return MW-style timestamp used for MySQL schema
1567 function timestamp( $ts=0 ) {
1568 return wfTimestamp(TS_MW,$ts);
1572 * Local database timestamp format or null
1574 function timestampOrNull( $ts = null ) {
1575 if( is_null( $ts ) ) {
1576 return null;
1577 } else {
1578 return $this->timestamp( $ts );
1583 * @todo document
1585 function resultObject( $result ) {
1586 if( empty( $result ) ) {
1587 return NULL;
1588 } else {
1589 return new ResultWrapper( $this, $result );
1594 * Return aggregated value alias
1596 function aggregateValue ($valuedata,$valuename='value') {
1597 return $valuename;
1601 * @return string wikitext of a link to the server software's web site
1603 function getSoftwareLink() {
1604 return "[http://www.mysql.com/ MySQL]";
1608 * @return string Version information from the database
1610 function getServerVersion() {
1611 return mysql_get_server_info();
1615 * Ping the server and try to reconnect if it there is no connection
1617 function ping() {
1618 if( function_exists( 'mysql_ping' ) ) {
1619 return mysql_ping( $this->mConn );
1620 } else {
1621 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1622 return true;
1627 * Get slave lag.
1628 * At the moment, this will only work if the DB user has the PROCESS privilege
1630 function getLag() {
1631 $res = $this->query( 'SHOW PROCESSLIST' );
1632 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1633 # dubious, but unfortunately there's no easy rigorous way
1634 $slaveThreads = 0;
1635 while ( $row = $this->fetchObject( $res ) ) {
1636 if ( $row->User == 'system user' ) {
1637 if ( ++$slaveThreads == 2 ) {
1638 # This is it, return the time (except -ve)
1639 if ( $row->Time > 0x7fffffff ) {
1640 return false;
1641 } else {
1642 return $row->Time;
1647 return false;
1651 * Get status information from SHOW STATUS in an associative array
1653 function getStatus($which="%") {
1654 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1655 $status = array();
1656 while ( $row = $this->fetchObject( $res ) ) {
1657 $status[$row->Variable_name] = $row->Value;
1659 return $status;
1663 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1665 function maxListLen() {
1666 return 0;
1669 function encodeBlob($b) {
1670 return $b;
1674 * Read and execute SQL commands from a file.
1675 * Returns true on success, error string on failure
1677 function sourceFile( $filename ) {
1678 $fp = fopen( $filename, 'r' );
1679 if ( false === $fp ) {
1680 return "Could not open \"{$fname}\".\n";
1683 $cmd = "";
1684 $done = false;
1685 $dollarquote = false;
1687 while ( ! feof( $fp ) ) {
1688 $line = trim( fgets( $fp, 1024 ) );
1689 $sl = strlen( $line ) - 1;
1691 if ( $sl < 0 ) { continue; }
1692 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
1694 ## Allow dollar quoting for function declarations
1695 if (substr($line,0,4) == '$mw$') {
1696 if ($dollarquote) {
1697 $dollarquote = false;
1698 $done = true;
1700 else {
1701 $dollarquote = true;
1704 else if (!$dollarquote) {
1705 if ( ';' == $line{$sl} && ($sl < 2 || ';' != $line{$sl - 1})) {
1706 $done = true;
1707 $line = substr( $line, 0, $sl );
1711 if ( '' != $cmd ) { $cmd .= ' '; }
1712 $cmd .= "$line\n";
1714 if ( $done ) {
1715 $cmd = str_replace(';;', ";", $cmd);
1716 $cmd = $this->replaceVars( $cmd );
1717 $res = $this->query( $cmd, 'dbsource', true );
1719 if ( false === $res ) {
1720 $err = $this->lastError();
1721 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1724 $cmd = '';
1725 $done = false;
1728 fclose( $fp );
1729 return true;
1733 * Replace variables in sourced SQL
1735 function replaceVars( $ins ) {
1736 $varnames = array(
1737 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
1738 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
1739 'wgDBadminuser', 'wgDBadminpassword',
1742 // Ordinary variables
1743 foreach ( $varnames as $var ) {
1744 if( isset( $GLOBALS[$var] ) ) {
1745 $val = addslashes( $GLOBALS[$var] );
1746 $ins = str_replace( '{$' . $var . '}', $val, $ins );
1747 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
1748 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
1752 // Table prefixes
1753 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
1754 array( &$this, 'tableNameCallback' ), $ins );
1755 return $ins;
1759 * Table name callback
1760 * @private
1762 function tableNameCallback( $matches ) {
1763 return $this->tableName( $matches[1] );
1769 * Database abstraction object for mySQL
1770 * Inherit all methods and properties of Database::Database()
1772 * @package MediaWiki
1773 * @see Database
1775 class DatabaseMysql extends Database {
1776 # Inherit all
1781 * Result wrapper for grabbing data queried by someone else
1783 * @package MediaWiki
1785 class ResultWrapper {
1786 var $db, $result;
1789 * @todo document
1791 function ResultWrapper( &$database, $result ) {
1792 $this->db =& $database;
1793 $this->result =& $result;
1797 * @todo document
1799 function numRows() {
1800 return $this->db->numRows( $this->result );
1804 * @todo document
1806 function fetchObject() {
1807 return $this->db->fetchObject( $this->result );
1811 * @todo document
1813 function &fetchRow() {
1814 return $this->db->fetchRow( $this->result );
1818 * @todo document
1820 function free() {
1821 $this->db->freeResult( $this->result );
1822 unset( $this->result );
1823 unset( $this->db );
1826 function seek( $row ) {
1827 $this->db->dataSeek( $this->result, $row );
1833 #------------------------------------------------------------------------------
1834 # Global functions
1835 #------------------------------------------------------------------------------
1838 * Standard fail function, called by default when a connection cannot be
1839 * established.
1840 * Displays the file cache if possible
1842 function wfEmergencyAbort( &$conn, $error ) {
1843 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
1844 global $wgSitename, $wgServer, $wgMessageCache, $wgLogo;
1846 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1847 # Hard coding strings instead.
1849 $noconnect = "<h1><img src='$wgLogo' style='float:left;margin-right:1em' alt=''>$wgSitename has a problem</h1><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>";
1850 $mainpage = 'Main Page';
1851 $searchdisabled = <<<EOT
1852 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1853 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1854 EOT;
1856 $googlesearch = "
1857 <!-- SiteSearch Google -->
1858 <FORM method=GET action=\"http://www.google.com/search\">
1859 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1860 <A HREF=\"http://www.google.com/\">
1861 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1862 border=\"0\" ALT=\"Google\"></A>
1863 </td>
1864 <td>
1865 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1866 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1867 <font size=-1>
1868 <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 />
1869 <input type='hidden' name='ie' value='$2'>
1870 <input type='hidden' name='oe' value='$2'>
1871 </font>
1872 </td></tr></TABLE>
1873 </FORM>
1874 <!-- SiteSearch Google -->";
1875 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1878 if( !headers_sent() ) {
1879 header( 'HTTP/1.0 500 Internal Server Error' );
1880 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1881 /* Don't cache error pages! They cause no end of trouble... */
1882 header( 'Cache-control: none' );
1883 header( 'Pragma: nocache' );
1886 # No database access
1887 if ( is_object( $wgMessageCache ) ) {
1888 $wgMessageCache->disable();
1891 if ( trim( $error ) == '' ) {
1892 $error = $this->mServer;
1895 wfLogDBError( "Connection error: $error\n" );
1897 $text = str_replace( '$1', $error, $noconnect );
1898 $text .= wfGetSiteNotice();
1900 if($wgUseFileCache) {
1901 if($wgTitle) {
1902 $t =& $wgTitle;
1903 } else {
1904 if($title) {
1905 $t = Title::newFromURL( $title );
1906 } elseif (@/**/$_REQUEST['search']) {
1907 $search = $_REQUEST['search'];
1908 echo $searchdisabled;
1909 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1910 $wgInputEncoding ), $googlesearch );
1911 wfErrorExit();
1912 } else {
1913 $t = Title::newFromText( $mainpage );
1917 $cache = new CacheManager( $t );
1918 if( $cache->isFileCached() ) {
1919 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1920 $cachederror . "</b></p>\n";
1922 $tag = '<div id="article">';
1923 $text = str_replace(
1924 $tag,
1925 $tag . $msg,
1926 $cache->fetchPageText() );
1930 echo $text;
1931 wfErrorExit();