Fix for r48839: log deletion uses a different action
[mediawiki.git] / includes / db / Database.php
blobabd8f201fd313a22b742252ae5f6be2a6ba19a9d
1 <?php
2 /**
3 * @defgroup Database Database
5 * @file
6 * @ingroup Database
7 * This file deals with MySQL interface functions
8 * and query specifics/optimisations
9 */
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 );
18 /**
19 * Database abstraction object
20 * @ingroup Database
22 class Database {
24 #------------------------------------------------------------------------------
25 # Variables
26 #------------------------------------------------------------------------------
28 protected $mLastQuery = '';
29 protected $mDoneWrites = false;
30 protected $mPHPError = false;
32 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
33 protected $mOpened = false;
35 protected $mFailFunction;
36 protected $mTablePrefix;
37 protected $mFlags;
38 protected $mTrxLevel = 0;
39 protected $mErrorCount = 0;
40 protected $mLBInfo = array();
41 protected $mFakeSlaveLag = null, $mFakeMaster = false;
43 #------------------------------------------------------------------------------
44 # Accessors
45 #------------------------------------------------------------------------------
46 # These optionally set a variable and return the previous state
48 /**
49 * Fail function, takes a Database as a parameter
50 * Set to false for default, 1 for ignore errors
52 function failFunction( $function = NULL ) {
53 return wfSetVar( $this->mFailFunction, $function );
56 /**
57 * Output page, used for reporting errors
58 * FALSE means discard output
60 function setOutputPage( $out ) {
61 wfDeprecated( __METHOD__ );
64 /**
65 * Boolean, controls output of large amounts of debug information
67 function debug( $debug = NULL ) {
68 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
71 /**
72 * Turns buffering of SQL result sets on (true) or off (false).
73 * Default is "on" and it should not be changed without good reasons.
75 function bufferResults( $buffer = NULL ) {
76 if ( is_null( $buffer ) ) {
77 return !(bool)( $this->mFlags & DBO_NOBUFFER );
78 } else {
79 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
83 /**
84 * Turns on (false) or off (true) the automatic generation and sending
85 * of a "we're sorry, but there has been a database error" page on
86 * database errors. Default is on (false). When turned off, the
87 * code should use lastErrno() and lastError() to handle the
88 * situation as appropriate.
90 function ignoreErrors( $ignoreErrors = NULL ) {
91 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
94 /**
95 * The current depth of nested transactions
96 * @param $level Integer: , default NULL.
98 function trxLevel( $level = NULL ) {
99 return wfSetVar( $this->mTrxLevel, $level );
103 * Number of errors logged, only useful when errors are ignored
105 function errorCount( $count = NULL ) {
106 return wfSetVar( $this->mErrorCount, $count );
109 function tablePrefix( $prefix = null ) {
110 return wfSetVar( $this->mTablePrefix, $prefix );
114 * Properties passed down from the server info array of the load balancer
116 function getLBInfo( $name = NULL ) {
117 if ( is_null( $name ) ) {
118 return $this->mLBInfo;
119 } else {
120 if ( array_key_exists( $name, $this->mLBInfo ) ) {
121 return $this->mLBInfo[$name];
122 } else {
123 return NULL;
128 function setLBInfo( $name, $value = NULL ) {
129 if ( is_null( $value ) ) {
130 $this->mLBInfo = $name;
131 } else {
132 $this->mLBInfo[$name] = $value;
137 * Set lag time in seconds for a fake slave
139 function setFakeSlaveLag( $lag ) {
140 $this->mFakeSlaveLag = $lag;
144 * Make this connection a fake master
146 function setFakeMaster( $enabled = true ) {
147 $this->mFakeMaster = $enabled;
151 * Returns true if this database supports (and uses) cascading deletes
153 function cascadingDeletes() {
154 return false;
158 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
160 function cleanupTriggers() {
161 return false;
165 * Returns true if this database is strict about what can be put into an IP field.
166 * Specifically, it uses a NULL value instead of an empty string.
168 function strictIPs() {
169 return false;
173 * Returns true if this database uses timestamps rather than integers
175 function realTimestamps() {
176 return false;
180 * Returns true if this database does an implicit sort when doing GROUP BY
182 function implicitGroupby() {
183 return true;
187 * Returns true if this database does an implicit order by when the column has an index
188 * For example: SELECT page_title FROM page LIMIT 1
190 function implicitOrderby() {
191 return true;
195 * Returns true if this database can do a native search on IP columns
196 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
198 function searchableIPs() {
199 return false;
203 * Returns true if this database can use functional indexes
205 function functionalIndexes() {
206 return false;
210 * Return the last query that went through Database::query()
211 * @return String
213 function lastQuery() { return $this->mLastQuery; }
217 * Returns true if the connection may have been used for write queries.
218 * Should return true if unsure.
220 function doneWrites() { return $this->mDoneWrites; }
223 * Is a connection to the database open?
224 * @return Boolean
226 function isOpen() { return $this->mOpened; }
228 function setFlag( $flag ) {
229 $this->mFlags |= $flag;
232 function clearFlag( $flag ) {
233 $this->mFlags &= ~$flag;
236 function getFlag( $flag ) {
237 return !!($this->mFlags & $flag);
241 * General read-only accessor
243 function getProperty( $name ) {
244 return $this->$name;
247 function getWikiID() {
248 if( $this->mTablePrefix ) {
249 return "{$this->mDBname}-{$this->mTablePrefix}";
250 } else {
251 return $this->mDBname;
255 #------------------------------------------------------------------------------
256 # Other functions
257 #------------------------------------------------------------------------------
260 * Constructor.
261 * @param $server String: database server host
262 * @param $user String: database user name
263 * @param $password String: database user password
264 * @param $dbName String: database name
265 * @param $failFunction
266 * @param $flags
267 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
269 function __construct( $server = false, $user = false, $password = false, $dbName = false,
270 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
272 global $wgOut, $wgDBprefix, $wgCommandLineMode;
273 # Can't get a reference if it hasn't been set yet
274 if ( !isset( $wgOut ) ) {
275 $wgOut = NULL;
278 $this->mFailFunction = $failFunction;
279 $this->mFlags = $flags;
281 if ( $this->mFlags & DBO_DEFAULT ) {
282 if ( $wgCommandLineMode ) {
283 $this->mFlags &= ~DBO_TRX;
284 } else {
285 $this->mFlags |= DBO_TRX;
290 // Faster read-only access
291 if ( wfReadOnly() ) {
292 $this->mFlags |= DBO_PERSISTENT;
293 $this->mFlags &= ~DBO_TRX;
296 /** Get the default table prefix*/
297 if ( $tablePrefix == 'get from global' ) {
298 $this->mTablePrefix = $wgDBprefix;
299 } else {
300 $this->mTablePrefix = $tablePrefix;
303 if ( $server ) {
304 $this->open( $server, $user, $password, $dbName );
309 * Same as new Database( ... ), kept for backward compatibility
310 * @param $server String: database server host
311 * @param $user String: database user name
312 * @param $password String: database user password
313 * @param $dbName String: database name
314 * @param failFunction
315 * @param $flags
317 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
319 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
323 * Usually aborts on failure
324 * If the failFunction is set to a non-zero integer, returns success
325 * @param $server String: database server host
326 * @param $user String: database user name
327 * @param $password String: database user password
328 * @param $dbName String: database name
330 function open( $server, $user, $password, $dbName ) {
331 global $wgAllDBsAreLocalhost;
332 wfProfileIn( __METHOD__ );
334 # Test for missing mysql.so
335 # First try to load it
336 if (!@extension_loaded('mysql')) {
337 @dl('mysql.so');
340 # Fail now
341 # Otherwise we get a suppressed fatal error, which is very hard to track down
342 if ( !function_exists( 'mysql_connect' ) ) {
343 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
346 # Debugging hack -- fake cluster
347 if ( $wgAllDBsAreLocalhost ) {
348 $realServer = 'localhost';
349 } else {
350 $realServer = $server;
352 $this->close();
353 $this->mServer = $server;
354 $this->mUser = $user;
355 $this->mPassword = $password;
356 $this->mDBname = $dbName;
358 $success = false;
360 wfProfileIn("dbconnect-$server");
362 # The kernel's default SYN retransmission period is far too slow for us,
363 # so we use a short timeout plus a manual retry. Retrying means that a small
364 # but finite rate of SYN packet loss won't cause user-visible errors.
365 $this->mConn = false;
366 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
367 $numAttempts = 2;
368 } else {
369 $numAttempts = 1;
371 $this->installErrorHandler();
372 for ( $i = 0; $i < $numAttempts && !$this->mConn; $i++ ) {
373 if ( $i > 1 ) {
374 usleep( 1000 );
376 if ( $this->mFlags & DBO_PERSISTENT ) {
377 $this->mConn = mysql_pconnect( $realServer, $user, $password );
378 } else {
379 # Create a new connection...
380 $this->mConn = mysql_connect( $realServer, $user, $password, true );
382 if ($this->mConn === false) {
383 #$iplus = $i + 1;
384 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
387 $phpError = $this->restoreErrorHandler();
388 # Always log connection errors
389 if ( !$this->mConn ) {
390 $error = $this->lastError();
391 if ( !$error ) {
392 $error = $phpError;
394 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
395 wfDebug( "DB connection error\n" );
396 wfDebug( "Server: $server, User: $user, Password: " .
397 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
398 $success = false;
401 wfProfileOut("dbconnect-$server");
403 if ( $dbName != '' && $this->mConn !== false ) {
404 $success = @/**/mysql_select_db( $dbName, $this->mConn );
405 if ( !$success ) {
406 $error = "Error selecting database $dbName on server {$this->mServer} " .
407 "from client host " . wfHostname() . "\n";
408 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
409 wfDebug( $error );
411 } else {
412 # Delay USE query
413 $success = (bool)$this->mConn;
416 if ( $success ) {
417 $version = $this->getServerVersion();
418 if ( version_compare( $version, '4.1' ) >= 0 ) {
419 // Tell the server we're communicating with it in UTF-8.
420 // This may engage various charset conversions.
421 global $wgDBmysql5;
422 if( $wgDBmysql5 ) {
423 $this->query( 'SET NAMES utf8', __METHOD__ );
425 // Turn off strict mode
426 $this->query( "SET sql_mode = ''", __METHOD__ );
429 // Turn off strict mode if it is on
430 } else {
431 $this->reportConnectionError( $phpError );
434 $this->mOpened = $success;
435 wfProfileOut( __METHOD__ );
436 return $success;
439 protected function installErrorHandler() {
440 $this->mPHPError = false;
441 $this->htmlErrors = ini_set( 'html_errors', '0' );
442 set_error_handler( array( $this, 'connectionErrorHandler' ) );
445 protected function restoreErrorHandler() {
446 restore_error_handler();
447 if ( $this->htmlErrors !== false ) {
448 ini_set( 'html_errors', $this->htmlErrors );
450 if ( $this->mPHPError ) {
451 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
452 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
453 return $error;
454 } else {
455 return false;
459 protected function connectionErrorHandler( $errno, $errstr ) {
460 $this->mPHPError = $errstr;
464 * Closes a database connection.
465 * if it is open : commits any open transactions
467 * @return Bool operation success. true if already closed.
469 function close()
471 $this->mOpened = false;
472 if ( $this->mConn ) {
473 if ( $this->trxLevel() ) {
474 $this->immediateCommit();
476 return mysql_close( $this->mConn );
477 } else {
478 return true;
483 * @param $error String: fallback error message, used if none is given by MySQL
485 function reportConnectionError( $error = 'Unknown error' ) {
486 $myError = $this->lastError();
487 if ( $myError ) {
488 $error = $myError;
491 if ( $this->mFailFunction ) {
492 # Legacy error handling method
493 if ( !is_int( $this->mFailFunction ) ) {
494 $ff = $this->mFailFunction;
495 $ff( $this, $error );
497 } else {
498 # New method
499 throw new DBConnectionError( $this, $error );
504 * Determine whether a query writes to the DB.
505 * Should return true if unsure.
507 function isWriteQuery( $sql ) {
508 return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW)\b/i', $sql );
512 * Usually aborts on failure. If errors are explicitly ignored, returns success.
514 * @param $sql String: SQL query
515 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
516 * comment (you can use __METHOD__ or add some extra info)
517 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
518 * maybe best to catch the exception instead?
519 * @return true for a successful write query, ResultWrapper object for a successful read query,
520 * or false on failure if $tempIgnore set
521 * @throws DBQueryError Thrown when the database returns an error of any kind
523 public function query( $sql, $fname = '', $tempIgnore = false ) {
524 global $wgProfiler;
526 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
527 if ( isset( $wgProfiler ) ) {
528 # generalizeSQL will probably cut down the query to reasonable
529 # logging size most of the time. The substr is really just a sanity check.
531 # Who's been wasting my precious column space? -- TS
532 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
534 if ( $isMaster ) {
535 $queryProf = 'query-m: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
536 $totalProf = 'Database::query-master';
537 } else {
538 $queryProf = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
539 $totalProf = 'Database::query';
541 wfProfileIn( $totalProf );
542 wfProfileIn( $queryProf );
545 $this->mLastQuery = $sql;
546 if ( !$this->mDoneWrites && $this->isWriteQuery( $sql ) ) {
547 // Set a flag indicating that writes have been done
548 wfDebug( __METHOD__.": Writes done: $sql\n" );
549 $this->mDoneWrites = true;
552 # Add a comment for easy SHOW PROCESSLIST interpretation
553 #if ( $fname ) {
554 global $wgUser;
555 if ( is_object( $wgUser ) && !($wgUser instanceof StubObject) ) {
556 $userName = $wgUser->getName();
557 if ( mb_strlen( $userName ) > 15 ) {
558 $userName = mb_substr( $userName, 0, 15 ) . '...';
560 $userName = str_replace( '/', '', $userName );
561 } else {
562 $userName = '';
564 $commentedSql = preg_replace('/\s/', " /* $fname $userName */ ", $sql, 1);
565 #} else {
566 # $commentedSql = $sql;
569 # If DBO_TRX is set, start a transaction
570 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() &&
571 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK') {
572 // avoid establishing transactions for SHOW and SET statements too -
573 // that would delay transaction initializations to once connection
574 // is really used by application
575 $sqlstart = substr($sql,0,10); // very much worth it, benchmark certified(tm)
576 if (strpos($sqlstart,"SHOW ")!==0 and strpos($sqlstart,"SET ")!==0)
577 $this->begin();
580 if ( $this->debug() ) {
581 $sqlx = substr( $commentedSql, 0, 500 );
582 $sqlx = strtr( $sqlx, "\t\n", ' ' );
583 if ( $isMaster ) {
584 wfDebug( "SQL-master: $sqlx\n" );
585 } else {
586 wfDebug( "SQL: $sqlx\n" );
590 if ( istainted( $sql ) & TC_MYSQL ) {
591 throw new MWException( 'Tainted query found' );
594 # Do the query and handle errors
595 $ret = $this->doQuery( $commentedSql );
597 # Try reconnecting if the connection was lost
598 if ( false === $ret && $this->wasErrorReissuable() ) {
599 # Transaction is gone, like it or not
600 $this->mTrxLevel = 0;
601 wfDebug( "Connection lost, reconnecting...\n" );
602 if ( $this->ping() ) {
603 wfDebug( "Reconnected\n" );
604 $sqlx = substr( $commentedSql, 0, 500 );
605 $sqlx = strtr( $sqlx, "\t\n", ' ' );
606 global $wgRequestTime;
607 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
608 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
609 $ret = $this->doQuery( $commentedSql );
610 } else {
611 wfDebug( "Failed\n" );
615 if ( false === $ret ) {
616 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
619 if ( isset( $wgProfiler ) ) {
620 wfProfileOut( $queryProf );
621 wfProfileOut( $totalProf );
623 return $this->resultObject( $ret );
627 * The DBMS-dependent part of query()
628 * @param $sql String: SQL query.
629 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
630 * @private
632 /*private*/ function doQuery( $sql ) {
633 if( $this->bufferResults() ) {
634 $ret = mysql_query( $sql, $this->mConn );
635 } else {
636 $ret = mysql_unbuffered_query( $sql, $this->mConn );
638 return $ret;
642 * @param $error String
643 * @param $errno Integer
644 * @param $sql String
645 * @param $fname String
646 * @param $tempIgnore Boolean
648 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
649 global $wgCommandLineMode;
650 # Ignore errors during error handling to avoid infinite recursion
651 $ignore = $this->ignoreErrors( true );
652 ++$this->mErrorCount;
654 if( $ignore || $tempIgnore ) {
655 wfDebug("SQL ERROR (ignored): $error\n");
656 $this->ignoreErrors( $ignore );
657 } else {
658 $sql1line = str_replace( "\n", "\\n", $sql );
659 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
660 wfDebug("SQL ERROR: " . $error . "\n");
661 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
667 * Intended to be compatible with the PEAR::DB wrapper functions.
668 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
670 * ? = scalar value, quoted as necessary
671 * ! = raw SQL bit (a function for instance)
672 * & = filename; reads the file and inserts as a blob
673 * (we don't use this though...)
675 function prepare( $sql, $func = 'Database::prepare' ) {
676 /* MySQL doesn't support prepared statements (yet), so just
677 pack up the query for reference. We'll manually replace
678 the bits later. */
679 return array( 'query' => $sql, 'func' => $func );
682 function freePrepared( $prepared ) {
683 /* No-op for MySQL */
687 * Execute a prepared query with the various arguments
688 * @param $prepared String: the prepared sql
689 * @param $args Mixed: Either an array here, or put scalars as varargs
691 function execute( $prepared, $args = null ) {
692 if( !is_array( $args ) ) {
693 # Pull the var args
694 $args = func_get_args();
695 array_shift( $args );
697 $sql = $this->fillPrepared( $prepared['query'], $args );
698 return $this->query( $sql, $prepared['func'] );
702 * Prepare & execute an SQL statement, quoting and inserting arguments
703 * in the appropriate places.
704 * @param $query String
705 * @param $args ...
707 function safeQuery( $query, $args = null ) {
708 $prepared = $this->prepare( $query, 'Database::safeQuery' );
709 if( !is_array( $args ) ) {
710 # Pull the var args
711 $args = func_get_args();
712 array_shift( $args );
714 $retval = $this->execute( $prepared, $args );
715 $this->freePrepared( $prepared );
716 return $retval;
720 * For faking prepared SQL statements on DBs that don't support
721 * it directly.
722 * @param $preparedQuery String: a 'preparable' SQL statement
723 * @param $args Array of arguments to fill it with
724 * @return string executable SQL
726 function fillPrepared( $preparedQuery, $args ) {
727 reset( $args );
728 $this->preparedArgs =& $args;
729 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
730 array( &$this, 'fillPreparedArg' ), $preparedQuery );
734 * preg_callback func for fillPrepared()
735 * The arguments should be in $this->preparedArgs and must not be touched
736 * while we're doing this.
738 * @param $matches Array
739 * @return String
740 * @private
742 function fillPreparedArg( $matches ) {
743 switch( $matches[1] ) {
744 case '\\?': return '?';
745 case '\\!': return '!';
746 case '\\&': return '&';
748 list( /* $n */ , $arg ) = each( $this->preparedArgs );
749 switch( $matches[1] ) {
750 case '?': return $this->addQuotes( $arg );
751 case '!': return $arg;
752 case '&':
753 # return $this->addQuotes( file_get_contents( $arg ) );
754 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
755 default:
756 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
761 * Free a result object
762 * @param $res Mixed: A SQL result
764 function freeResult( $res ) {
765 if ( $res instanceof ResultWrapper ) {
766 $res = $res->result;
768 if ( !@/**/mysql_free_result( $res ) ) {
769 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
774 * Fetch the next row from the given result object, in object form.
775 * Fields can be retrieved with $row->fieldname, with fields acting like
776 * member variables.
778 * @param $res SQL result object as returned from Database::query(), etc.
779 * @return MySQL row object
780 * @throws DBUnexpectedError Thrown if the database returns an error
782 function fetchObject( $res ) {
783 if ( $res instanceof ResultWrapper ) {
784 $res = $res->result;
786 @/**/$row = mysql_fetch_object( $res );
787 if( $this->lastErrno() ) {
788 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
790 return $row;
794 * Fetch the next row from the given result object, in associative array
795 * form. Fields are retrieved with $row['fieldname'].
797 * @param $res SQL result object as returned from Database::query(), etc.
798 * @return MySQL row object
799 * @throws DBUnexpectedError Thrown if the database returns an error
801 function fetchRow( $res ) {
802 if ( $res instanceof ResultWrapper ) {
803 $res = $res->result;
805 @/**/$row = mysql_fetch_array( $res );
806 if ( $this->lastErrno() ) {
807 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
809 return $row;
813 * Get the number of rows in a result object
814 * @param $res Mixed: A SQL result
816 function numRows( $res ) {
817 if ( $res instanceof ResultWrapper ) {
818 $res = $res->result;
820 @/**/$n = mysql_num_rows( $res );
821 if( $this->lastErrno() ) {
822 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
824 return $n;
828 * Get the number of fields in a result object
829 * See documentation for mysql_num_fields()
830 * @param $res Mixed: A SQL result
832 function numFields( $res ) {
833 if ( $res instanceof ResultWrapper ) {
834 $res = $res->result;
836 return mysql_num_fields( $res );
840 * Get a field name in a result object
841 * See documentation for mysql_field_name():
842 * http://www.php.net/mysql_field_name
843 * @param $res Mixed: A SQL result
844 * @param $n Integer
846 function fieldName( $res, $n ) {
847 if ( $res instanceof ResultWrapper ) {
848 $res = $res->result;
850 return mysql_field_name( $res, $n );
854 * Get the inserted value of an auto-increment row
856 * The value inserted should be fetched from nextSequenceValue()
858 * Example:
859 * $id = $dbw->nextSequenceValue('page_page_id_seq');
860 * $dbw->insert('page',array('page_id' => $id));
861 * $id = $dbw->insertId();
863 function insertId() { return mysql_insert_id( $this->mConn ); }
866 * Change the position of the cursor in a result object
867 * See mysql_data_seek()
868 * @param $res Mixed: A SQL result
869 * @param $row Mixed: Either MySQL row or ResultWrapper
871 function dataSeek( $res, $row ) {
872 if ( $res instanceof ResultWrapper ) {
873 $res = $res->result;
875 return mysql_data_seek( $res, $row );
879 * Get the last error number
880 * See mysql_errno()
882 function lastErrno() {
883 if ( $this->mConn ) {
884 return mysql_errno( $this->mConn );
885 } else {
886 return mysql_errno();
891 * Get a description of the last error
892 * See mysql_error() for more details
894 function lastError() {
895 if ( $this->mConn ) {
896 # Even if it's non-zero, it can still be invalid
897 wfSuppressWarnings();
898 $error = mysql_error( $this->mConn );
899 if ( !$error ) {
900 $error = mysql_error();
902 wfRestoreWarnings();
903 } else {
904 $error = mysql_error();
906 if( $error ) {
907 $error .= ' (' . $this->mServer . ')';
909 return $error;
912 * Get the number of rows affected by the last write query
913 * See mysql_affected_rows() for more details
915 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
918 * Simple UPDATE wrapper
919 * Usually aborts on failure
920 * If errors are explicitly ignored, returns success
922 * This function exists for historical reasons, Database::update() has a more standard
923 * calling convention and feature set
925 function set( $table, $var, $value, $cond, $fname = 'Database::set' ) {
926 $table = $this->tableName( $table );
927 $sql = "UPDATE $table SET $var = '" .
928 $this->strencode( $value ) . "' WHERE ($cond)";
929 return (bool)$this->query( $sql, $fname );
933 * Simple SELECT wrapper, returns a single field, input must be encoded
934 * Usually aborts on failure
935 * If errors are explicitly ignored, returns FALSE on failure
937 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
938 if ( !is_array( $options ) ) {
939 $options = array( $options );
941 $options['LIMIT'] = 1;
943 $res = $this->select( $table, $var, $cond, $fname, $options );
944 if ( $res === false || !$this->numRows( $res ) ) {
945 return false;
947 $row = $this->fetchRow( $res );
948 if ( $row !== false ) {
949 $this->freeResult( $res );
950 return reset( $row );
951 } else {
952 return false;
957 * Returns an optional USE INDEX clause to go after the table, and a
958 * string to go at the end of the query
960 * @private
962 * @param $options Array: associative array of options to be turned into
963 * an SQL query, valid keys are listed in the function.
964 * @return Array
966 function makeSelectOptions( $options ) {
967 $preLimitTail = $postLimitTail = '';
968 $startOpts = '';
970 $noKeyOptions = array();
971 foreach ( $options as $key => $option ) {
972 if ( is_numeric( $key ) ) {
973 $noKeyOptions[$option] = true;
977 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
978 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
979 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
981 //if (isset($options['LIMIT'])) {
982 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
983 // isset($options['OFFSET']) ? $options['OFFSET']
984 // : false);
987 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
988 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
989 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
991 # Various MySQL extensions
992 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
993 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
994 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
995 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
996 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
997 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
998 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
999 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
1001 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1002 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1003 } else {
1004 $useIndex = '';
1007 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1011 * SELECT wrapper
1013 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
1014 * @param $vars Mixed: Array or string, field name(s) to be retrieved
1015 * @param $conds Mixed: Array or string, condition(s) for WHERE
1016 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1017 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1018 * see Database::makeSelectOptions code for list of supported stuff
1019 * @param $join_conds Array: Associative array of table join conditions (optional)
1020 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1021 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
1023 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() )
1025 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1026 return $this->query( $sql, $fname );
1030 * SELECT wrapper
1032 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
1033 * @param $vars Mixed: Array or string, field name(s) to be retrieved
1034 * @param $conds Mixed: Array or string, condition(s) for WHERE
1035 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1036 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1037 * see Database::makeSelectOptions code for list of supported stuff
1038 * @param $join_conds Array: Associative array of table join conditions (optional)
1039 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1040 * @return string, the SQL text
1042 function selectSQLText( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() ) {
1043 if( is_array( $vars ) ) {
1044 $vars = implode( ',', $vars );
1046 if( !is_array( $options ) ) {
1047 $options = array( $options );
1049 if( is_array( $table ) ) {
1050 if ( !empty($join_conds) || ( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) )
1051 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
1052 else
1053 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1054 } elseif ($table!='') {
1055 if ($table{0}==' ') {
1056 $from = ' FROM ' . $table;
1057 } else {
1058 $from = ' FROM ' . $this->tableName( $table );
1060 } else {
1061 $from = '';
1064 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1066 if( !empty( $conds ) ) {
1067 if ( is_array( $conds ) ) {
1068 $conds = $this->makeList( $conds, LIST_AND );
1070 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1071 } else {
1072 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1075 if (isset($options['LIMIT']))
1076 $sql = $this->limitResult($sql, $options['LIMIT'],
1077 isset($options['OFFSET']) ? $options['OFFSET'] : false);
1078 $sql = "$sql $postLimitTail";
1080 if (isset($options['EXPLAIN'])) {
1081 $sql = 'EXPLAIN ' . $sql;
1083 return $sql;
1087 * Single row SELECT wrapper
1088 * Aborts or returns FALSE on error
1090 * @param $table String: table name
1091 * @param $vars String: the selected variables
1092 * @param $conds Array: a condition map, terms are ANDed together.
1093 * Items with numeric keys are taken to be literal conditions
1094 * Takes an array of selected variables, and a condition map, which is ANDed
1095 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1096 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1097 * $obj- >page_id is the ID of the Astronomy article
1098 * @param $fname String: Calling functio name
1099 * @param $options Array
1100 * @param $join_conds Array
1102 * @todo migrate documentation to phpdocumentor format
1104 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array(), $join_conds = array() ) {
1105 $options['LIMIT'] = 1;
1106 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1107 if ( $res === false )
1108 return false;
1109 if ( !$this->numRows($res) ) {
1110 $this->freeResult($res);
1111 return false;
1113 $obj = $this->fetchObject( $res );
1114 $this->freeResult( $res );
1115 return $obj;
1120 * Estimate rows in dataset
1121 * Returns estimated count, based on EXPLAIN output
1122 * Takes same arguments as Database::select()
1125 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
1126 $options['EXPLAIN']=true;
1127 $res = $this->select ($table, $vars, $conds, $fname, $options );
1128 if ( $res === false )
1129 return false;
1130 if (!$this->numRows($res)) {
1131 $this->freeResult($res);
1132 return 0;
1135 $rows=1;
1137 while( $plan = $this->fetchObject( $res ) ) {
1138 $rows *= ($plan->rows > 0)?$plan->rows:1; // avoid resetting to zero
1141 $this->freeResult($res);
1142 return $rows;
1147 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1148 * It's only slightly flawed. Don't use for anything important.
1150 * @param $sql String: A SQL Query
1152 static function generalizeSQL( $sql ) {
1153 # This does the same as the regexp below would do, but in such a way
1154 # as to avoid crashing php on some large strings.
1155 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1157 $sql = str_replace ( "\\\\", '', $sql);
1158 $sql = str_replace ( "\\'", '', $sql);
1159 $sql = str_replace ( "\\\"", '', $sql);
1160 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1161 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1163 # All newlines, tabs, etc replaced by single space
1164 $sql = preg_replace ( '/\s+/', ' ', $sql);
1166 # All numbers => N
1167 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1169 return $sql;
1173 * Determines whether a field exists in a table
1174 * Usually aborts on failure
1175 * If errors are explicitly ignored, returns NULL on failure
1177 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1178 $table = $this->tableName( $table );
1179 $res = $this->query( 'DESCRIBE '.$table, $fname );
1180 if ( !$res ) {
1181 return NULL;
1184 $found = false;
1186 while ( $row = $this->fetchObject( $res ) ) {
1187 if ( $row->Field == $field ) {
1188 $found = true;
1189 break;
1192 return $found;
1196 * Determines whether an index exists
1197 * Usually aborts on failure
1198 * If errors are explicitly ignored, returns NULL on failure
1200 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1201 $info = $this->indexInfo( $table, $index, $fname );
1202 if ( is_null( $info ) ) {
1203 return NULL;
1204 } else {
1205 return $info !== false;
1211 * Get information about an index into an object
1212 * Returns false if the index does not exist
1214 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1215 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1216 # SHOW INDEX should work for 3.x and up:
1217 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1218 $table = $this->tableName( $table );
1219 $index = $this->indexName( $index );
1220 $sql = 'SHOW INDEX FROM '.$table;
1221 $res = $this->query( $sql, $fname );
1222 if ( !$res ) {
1223 return NULL;
1226 $result = array();
1227 while ( $row = $this->fetchObject( $res ) ) {
1228 if ( $row->Key_name == $index ) {
1229 $result[] = $row;
1232 $this->freeResult($res);
1234 return empty($result) ? false : $result;
1238 * Query whether a given table exists
1240 function tableExists( $table ) {
1241 $table = $this->tableName( $table );
1242 $old = $this->ignoreErrors( true );
1243 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1244 $this->ignoreErrors( $old );
1245 if( $res ) {
1246 $this->freeResult( $res );
1247 return true;
1248 } else {
1249 return false;
1254 * mysql_fetch_field() wrapper
1255 * Returns false if the field doesn't exist
1257 * @param $table
1258 * @param $field
1260 function fieldInfo( $table, $field ) {
1261 $table = $this->tableName( $table );
1262 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1263 $n = mysql_num_fields( $res->result );
1264 for( $i = 0; $i < $n; $i++ ) {
1265 $meta = mysql_fetch_field( $res->result, $i );
1266 if( $field == $meta->name ) {
1267 return new MySQLField($meta);
1270 return false;
1274 * mysql_field_type() wrapper
1276 function fieldType( $res, $index ) {
1277 if ( $res instanceof ResultWrapper ) {
1278 $res = $res->result;
1280 return mysql_field_type( $res, $index );
1284 * Determines if a given index is unique
1286 function indexUnique( $table, $index ) {
1287 $indexInfo = $this->indexInfo( $table, $index );
1288 if ( !$indexInfo ) {
1289 return NULL;
1291 return !$indexInfo[0]->Non_unique;
1295 * INSERT wrapper, inserts an array into a table
1297 * $a may be a single associative array, or an array of these with numeric keys, for
1298 * multi-row insert.
1300 * Usually aborts on failure
1301 * If errors are explicitly ignored, returns success
1303 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1304 # No rows to insert, easy just return now
1305 if ( !count( $a ) ) {
1306 return true;
1309 $table = $this->tableName( $table );
1310 if ( !is_array( $options ) ) {
1311 $options = array( $options );
1313 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1314 $multi = true;
1315 $keys = array_keys( $a[0] );
1316 } else {
1317 $multi = false;
1318 $keys = array_keys( $a );
1321 $sql = 'INSERT ' . implode( ' ', $options ) .
1322 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1324 if ( $multi ) {
1325 $first = true;
1326 foreach ( $a as $row ) {
1327 if ( $first ) {
1328 $first = false;
1329 } else {
1330 $sql .= ',';
1332 $sql .= '(' . $this->makeList( $row ) . ')';
1334 } else {
1335 $sql .= '(' . $this->makeList( $a ) . ')';
1337 return (bool)$this->query( $sql, $fname );
1341 * Make UPDATE options for the Database::update function
1343 * @private
1344 * @param $options Array: The options passed to Database::update
1345 * @return string
1347 function makeUpdateOptions( $options ) {
1348 if( !is_array( $options ) ) {
1349 $options = array( $options );
1351 $opts = array();
1352 if ( in_array( 'LOW_PRIORITY', $options ) )
1353 $opts[] = $this->lowPriorityOption();
1354 if ( in_array( 'IGNORE', $options ) )
1355 $opts[] = 'IGNORE';
1356 return implode(' ', $opts);
1360 * UPDATE wrapper, takes a condition array and a SET array
1362 * @param $table String: The table to UPDATE
1363 * @param $values Array: An array of values to SET
1364 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
1365 * @param $fname String: The Class::Function calling this function
1366 * (for the log)
1367 * @param $options Array: An array of UPDATE options, can be one or
1368 * more of IGNORE, LOW_PRIORITY
1369 * @return Boolean
1371 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1372 $table = $this->tableName( $table );
1373 $opts = $this->makeUpdateOptions( $options );
1374 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1375 if ( $conds != '*' ) {
1376 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1378 return $this->query( $sql, $fname );
1382 * Makes an encoded list of strings from an array
1383 * $mode:
1384 * LIST_COMMA - comma separated, no field names
1385 * LIST_AND - ANDed WHERE clause (without the WHERE)
1386 * LIST_OR - ORed WHERE clause (without the WHERE)
1387 * LIST_SET - comma separated with field names, like a SET clause
1388 * LIST_NAMES - comma separated field names
1390 function makeList( $a, $mode = LIST_COMMA ) {
1391 if ( !is_array( $a ) ) {
1392 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1395 $first = true;
1396 $list = '';
1397 foreach ( $a as $field => $value ) {
1398 if ( !$first ) {
1399 if ( $mode == LIST_AND ) {
1400 $list .= ' AND ';
1401 } elseif($mode == LIST_OR) {
1402 $list .= ' OR ';
1403 } else {
1404 $list .= ',';
1406 } else {
1407 $first = false;
1409 if ( ($mode == LIST_AND || $mode == LIST_OR) && is_numeric( $field ) ) {
1410 $list .= "($value)";
1411 } elseif ( ($mode == LIST_SET) && is_numeric( $field ) ) {
1412 $list .= "$value";
1413 } elseif ( ($mode == LIST_AND || $mode == LIST_OR) && is_array($value) ) {
1414 if( count( $value ) == 0 ) {
1415 throw new MWException( __METHOD__.': empty input' );
1416 } elseif( count( $value ) == 1 ) {
1417 // Special-case single values, as IN isn't terribly efficient
1418 // Don't necessarily assume the single key is 0; we don't
1419 // enforce linear numeric ordering on other arrays here.
1420 $value = array_values( $value );
1421 $list .= $field." = ".$this->addQuotes( $value[0] );
1422 } else {
1423 $list .= $field." IN (".$this->makeList($value).") ";
1425 } elseif( $value === null ) {
1426 if ( $mode == LIST_AND || $mode == LIST_OR ) {
1427 $list .= "$field IS ";
1428 } elseif ( $mode == LIST_SET ) {
1429 $list .= "$field = ";
1431 $list .= 'NULL';
1432 } else {
1433 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1434 $list .= "$field = ";
1436 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1439 return $list;
1443 * Change the current database
1445 function selectDB( $db ) {
1446 $this->mDBname = $db;
1447 return mysql_select_db( $db, $this->mConn );
1451 * Get the current DB name
1453 function getDBname() {
1454 return $this->mDBname;
1458 * Get the server hostname or IP address
1460 function getServer() {
1461 return $this->mServer;
1465 * Format a table name ready for use in constructing an SQL query
1467 * This does two important things: it quotes the table names to clean them up,
1468 * and it adds a table prefix if only given a table name with no quotes.
1470 * All functions of this object which require a table name call this function
1471 * themselves. Pass the canonical name to such functions. This is only needed
1472 * when calling query() directly.
1474 * @param $name String: database table name
1475 * @return String: full database name
1477 function tableName( $name ) {
1478 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1479 # Skip the entire process when we have a string quoted on both ends.
1480 # Note that we check the end so that we will still quote any use of
1481 # use of `database`.table. But won't break things if someone wants
1482 # to query a database table with a dot in the name.
1483 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) return $name;
1485 # Lets test for any bits of text that should never show up in a table
1486 # name. Basically anything like JOIN or ON which are actually part of
1487 # SQL queries, but may end up inside of the table value to combine
1488 # sql. Such as how the API is doing.
1489 # Note that we use a whitespace test rather than a \b test to avoid
1490 # any remote case where a word like on may be inside of a table name
1491 # surrounded by symbols which may be considered word breaks.
1492 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) return $name;
1494 # Split database and table into proper variables.
1495 # We reverse the explode so that database.table and table both output
1496 # the correct table.
1497 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1498 if( isset( $dbDetails[1] ) ) @list( $table, $database ) = $dbDetails;
1499 else @list( $table ) = $dbDetails;
1500 $prefix = $this->mTablePrefix; # Default prefix
1502 # A database name has been specified in input. Quote the table name
1503 # because we don't want any prefixes added.
1504 if( isset($database) ) $table = ( $table[0] == '`' ? $table : "`{$table}`" );
1506 # Note that we use the long format because php will complain in in_array if
1507 # the input is not an array, and will complain in is_array if it is not set.
1508 if( !isset( $database ) # Don't use shared database if pre selected.
1509 && isset( $wgSharedDB ) # We have a shared database
1510 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1511 && isset( $wgSharedTables )
1512 && is_array( $wgSharedTables )
1513 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1514 $database = $wgSharedDB;
1515 $prefix = isset( $wgSharedPrefix ) ? $wgSharedPrefix : $prefix;
1518 # Quote the $database and $table and apply the prefix if not quoted.
1519 if( isset($database) ) $database = ( $database[0] == '`' ? $database : "`{$database}`" );
1520 $table = ( $table[0] == '`' ? $table : "`{$prefix}{$table}`" );
1522 # Merge our database and table into our final table name.
1523 $tableName = ( isset($database) ? "{$database}.{$table}" : "{$table}" );
1525 # We're finished, return.
1526 return $tableName;
1530 * Fetch a number of table names into an array
1531 * This is handy when you need to construct SQL for joins
1533 * Example:
1534 * extract($dbr->tableNames('user','watchlist'));
1535 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1536 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1538 public function tableNames() {
1539 $inArray = func_get_args();
1540 $retVal = array();
1541 foreach ( $inArray as $name ) {
1542 $retVal[$name] = $this->tableName( $name );
1544 return $retVal;
1548 * Fetch a number of table names into an zero-indexed numerical array
1549 * This is handy when you need to construct SQL for joins
1551 * Example:
1552 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1553 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1554 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1556 public function tableNamesN() {
1557 $inArray = func_get_args();
1558 $retVal = array();
1559 foreach ( $inArray as $name ) {
1560 $retVal[] = $this->tableName( $name );
1562 return $retVal;
1566 * @private
1568 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1569 $ret = array();
1570 $retJOIN = array();
1571 $use_index_safe = is_array($use_index) ? $use_index : array();
1572 $join_conds_safe = is_array($join_conds) ? $join_conds : array();
1573 foreach ( $tables as $table ) {
1574 // Is there a JOIN and INDEX clause for this table?
1575 if ( isset($join_conds_safe[$table]) && isset($use_index_safe[$table]) ) {
1576 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1577 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1578 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND) . ')';
1579 $retJOIN[] = $tableClause;
1580 // Is there an INDEX clause?
1581 } else if ( isset($use_index_safe[$table]) ) {
1582 $tableClause = $this->tableName( $table );
1583 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1584 $ret[] = $tableClause;
1585 // Is there a JOIN clause?
1586 } else if ( isset($join_conds_safe[$table]) ) {
1587 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1588 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND) . ')';
1589 $retJOIN[] = $tableClause;
1590 } else {
1591 $tableClause = $this->tableName( $table );
1592 $ret[] = $tableClause;
1595 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1596 $straightJoins = !empty($ret) ? implode( ',', $ret ) : "";
1597 $otherJoins = !empty($retJOIN) ? implode( ' ', $retJOIN ) : "";
1598 // Compile our final table clause
1599 return implode(' ',array($straightJoins,$otherJoins) );
1603 * Get the name of an index in a given table
1605 function indexName( $index ) {
1606 // Backwards-compatibility hack
1607 $renamed = array(
1608 'ar_usertext_timestamp' => 'usertext_timestamp',
1609 'un_user_id' => 'user_id',
1610 'un_user_ip' => 'user_ip',
1612 if( isset( $renamed[$index] ) ) {
1613 return $renamed[$index];
1614 } else {
1615 return $index;
1620 * Wrapper for addslashes()
1621 * @param $s String: to be slashed.
1622 * @return String: slashed string.
1624 function strencode( $s ) {
1625 return mysql_real_escape_string( $s, $this->mConn );
1629 * If it's a string, adds quotes and backslashes
1630 * Otherwise returns as-is
1632 function addQuotes( $s ) {
1633 if ( $s === null ) {
1634 return 'NULL';
1635 } else {
1636 # This will also quote numeric values. This should be harmless,
1637 # and protects against weird problems that occur when they really
1638 # _are_ strings such as article titles and string->number->string
1639 # conversion is not 1:1.
1640 return "'" . $this->strencode( $s ) . "'";
1645 * Escape string for safe LIKE usage
1647 function escapeLike( $s ) {
1648 $s=str_replace('\\','\\\\',$s);
1649 $s=$this->strencode( $s );
1650 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1651 return $s;
1655 * Returns an appropriately quoted sequence value for inserting a new row.
1656 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1657 * subclass will return an integer, and save the value for insertId()
1659 function nextSequenceValue( $seqName ) {
1660 return NULL;
1664 * USE INDEX clause
1665 * PostgreSQL doesn't have them and returns ""
1667 function useIndexClause( $index ) {
1668 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
1672 * REPLACE query wrapper
1673 * PostgreSQL simulates this with a DELETE followed by INSERT
1674 * $row is the row to insert, an associative array
1675 * $uniqueIndexes is an array of indexes. Each element may be either a
1676 * field name or an array of field names
1678 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1679 * However if you do this, you run the risk of encountering errors which wouldn't have
1680 * occurred in MySQL
1682 * @todo migrate comment to phodocumentor format
1684 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1685 $table = $this->tableName( $table );
1687 # Single row case
1688 if ( !is_array( reset( $rows ) ) ) {
1689 $rows = array( $rows );
1692 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1693 $first = true;
1694 foreach ( $rows as $row ) {
1695 if ( $first ) {
1696 $first = false;
1697 } else {
1698 $sql .= ',';
1700 $sql .= '(' . $this->makeList( $row ) . ')';
1702 return $this->query( $sql, $fname );
1706 * DELETE where the condition is a join
1707 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1709 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1710 * join condition matches, set $conds='*'
1712 * DO NOT put the join condition in $conds
1714 * @param $delTable String: The table to delete from.
1715 * @param $joinTable String: The other table.
1716 * @param $delVar String: The variable to join on, in the first table.
1717 * @param $joinVar String: The variable to join on, in the second table.
1718 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
1719 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1721 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1722 if ( !$conds ) {
1723 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1726 $delTable = $this->tableName( $delTable );
1727 $joinTable = $this->tableName( $joinTable );
1728 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1729 if ( $conds != '*' ) {
1730 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1733 return $this->query( $sql, $fname );
1737 * Returns the size of a text field, or -1 for "unlimited"
1739 function textFieldSize( $table, $field ) {
1740 $table = $this->tableName( $table );
1741 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1742 $res = $this->query( $sql, 'Database::textFieldSize' );
1743 $row = $this->fetchObject( $res );
1744 $this->freeResult( $res );
1746 $m = array();
1747 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
1748 $size = $m[1];
1749 } else {
1750 $size = -1;
1752 return $size;
1756 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1758 function lowPriorityOption() {
1759 return 'LOW_PRIORITY';
1763 * DELETE query wrapper
1765 * Use $conds == "*" to delete all rows
1767 function delete( $table, $conds, $fname = 'Database::delete' ) {
1768 if ( !$conds ) {
1769 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1771 $table = $this->tableName( $table );
1772 $sql = "DELETE FROM $table";
1773 if ( $conds != '*' ) {
1774 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1776 return $this->query( $sql, $fname );
1780 * INSERT SELECT wrapper
1781 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1782 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1783 * $conds may be "*" to copy the whole table
1784 * srcTable may be an array of tables.
1786 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1787 $insertOptions = array(), $selectOptions = array() )
1789 $destTable = $this->tableName( $destTable );
1790 if ( is_array( $insertOptions ) ) {
1791 $insertOptions = implode( ' ', $insertOptions );
1793 if( !is_array( $selectOptions ) ) {
1794 $selectOptions = array( $selectOptions );
1796 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1797 if( is_array( $srcTable ) ) {
1798 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1799 } else {
1800 $srcTable = $this->tableName( $srcTable );
1802 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1803 " SELECT $startOpts " . implode( ',', $varMap ) .
1804 " FROM $srcTable $useIndex ";
1805 if ( $conds != '*' ) {
1806 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1808 $sql .= " $tailOpts";
1809 return $this->query( $sql, $fname );
1813 * Construct a LIMIT query with optional offset
1814 * This is used for query pages
1815 * @param $sql String: SQL query we will append the limit too
1816 * @param $limit Integer: the SQL limit
1817 * @param $offset Integer the SQL offset (default false)
1819 function limitResult($sql, $limit, $offset=false) {
1820 if( !is_numeric($limit) ) {
1821 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1823 return "$sql LIMIT "
1824 . ( (is_numeric($offset) && $offset != 0) ? "{$offset}," : "" )
1825 . "{$limit} ";
1827 function limitResultForUpdate($sql, $num) {
1828 return $this->limitResult($sql, $num, 0);
1832 * Returns an SQL expression for a simple conditional.
1833 * Uses IF on MySQL.
1835 * @param $cond String: SQL expression which will result in a boolean value
1836 * @param $trueVal String: SQL expression to return if true
1837 * @param $falseVal String: SQL expression to return if false
1838 * @return String: SQL fragment
1840 function conditional( $cond, $trueVal, $falseVal ) {
1841 return " IF($cond, $trueVal, $falseVal) ";
1845 * Returns a comand for str_replace function in SQL query.
1846 * Uses REPLACE() in MySQL
1848 * @param $orig String: column to modify
1849 * @param $old String: column to seek
1850 * @param $new String: column to replace with
1852 function strreplace( $orig, $old, $new ) {
1853 return "REPLACE({$orig}, {$old}, {$new})";
1857 * Determines if the last failure was due to a deadlock
1859 function wasDeadlock() {
1860 return $this->lastErrno() == 1213;
1864 * Determines if the last query error was something that should be dealt
1865 * with by pinging the connection and reissuing the query
1867 function wasErrorReissuable() {
1868 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
1872 * Perform a deadlock-prone transaction.
1874 * This function invokes a callback function to perform a set of write
1875 * queries. If a deadlock occurs during the processing, the transaction
1876 * will be rolled back and the callback function will be called again.
1878 * Usage:
1879 * $dbw->deadlockLoop( callback, ... );
1881 * Extra arguments are passed through to the specified callback function.
1883 * Returns whatever the callback function returned on its successful,
1884 * iteration, or false on error, for example if the retry limit was
1885 * reached.
1887 function deadlockLoop() {
1888 $myFname = 'Database::deadlockLoop';
1890 $this->begin();
1891 $args = func_get_args();
1892 $function = array_shift( $args );
1893 $oldIgnore = $this->ignoreErrors( true );
1894 $tries = DEADLOCK_TRIES;
1895 if ( is_array( $function ) ) {
1896 $fname = $function[0];
1897 } else {
1898 $fname = $function;
1900 do {
1901 $retVal = call_user_func_array( $function, $args );
1902 $error = $this->lastError();
1903 $errno = $this->lastErrno();
1904 $sql = $this->lastQuery();
1906 if ( $errno ) {
1907 if ( $this->wasDeadlock() ) {
1908 # Retry
1909 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1910 } else {
1911 $this->reportQueryError( $error, $errno, $sql, $fname );
1914 } while( $this->wasDeadlock() && --$tries > 0 );
1915 $this->ignoreErrors( $oldIgnore );
1916 if ( $tries <= 0 ) {
1917 $this->query( 'ROLLBACK', $myFname );
1918 $this->reportQueryError( $error, $errno, $sql, $fname );
1919 return false;
1920 } else {
1921 $this->query( 'COMMIT', $myFname );
1922 return $retVal;
1927 * Do a SELECT MASTER_POS_WAIT()
1929 * @param $pos MySQLMasterPos object
1930 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
1932 function masterPosWait( MySQLMasterPos $pos, $timeout ) {
1933 $fname = 'Database::masterPosWait';
1934 wfProfileIn( $fname );
1936 # Commit any open transactions
1937 if ( $this->mTrxLevel ) {
1938 $this->immediateCommit();
1941 if ( !is_null( $this->mFakeSlaveLag ) ) {
1942 $wait = intval( ( $pos->pos - microtime(true) + $this->mFakeSlaveLag ) * 1e6 );
1943 if ( $wait > $timeout * 1e6 ) {
1944 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1945 wfProfileOut( $fname );
1946 return -1;
1947 } elseif ( $wait > 0 ) {
1948 wfDebug( "Fake slave waiting $wait us\n" );
1949 usleep( $wait );
1950 wfProfileOut( $fname );
1951 return 1;
1952 } else {
1953 wfDebug( "Fake slave up to date ($wait us)\n" );
1954 wfProfileOut( $fname );
1955 return 0;
1959 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1960 $encFile = $this->addQuotes( $pos->file );
1961 $encPos = intval( $pos->pos );
1962 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
1963 $res = $this->doQuery( $sql );
1964 if ( $res && $row = $this->fetchRow( $res ) ) {
1965 $this->freeResult( $res );
1966 wfProfileOut( $fname );
1967 return $row[0];
1968 } else {
1969 wfProfileOut( $fname );
1970 return false;
1975 * Get the position of the master from SHOW SLAVE STATUS
1977 function getSlavePos() {
1978 if ( !is_null( $this->mFakeSlaveLag ) ) {
1979 $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag );
1980 wfDebug( __METHOD__.": fake slave pos = $pos\n" );
1981 return $pos;
1983 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1984 $row = $this->fetchObject( $res );
1985 if ( $row ) {
1986 $pos = isset($row->Exec_master_log_pos) ? $row->Exec_master_log_pos : $row->Exec_Master_Log_Pos;
1987 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
1988 } else {
1989 return false;
1994 * Get the position of the master from SHOW MASTER STATUS
1996 function getMasterPos() {
1997 if ( $this->mFakeMaster ) {
1998 return new MySQLMasterPos( 'fake', microtime( true ) );
2000 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
2001 $row = $this->fetchObject( $res );
2002 if ( $row ) {
2003 return new MySQLMasterPos( $row->File, $row->Position );
2004 } else {
2005 return false;
2010 * Begin a transaction, committing any previously open transaction
2012 function begin( $fname = 'Database::begin' ) {
2013 $this->query( 'BEGIN', $fname );
2014 $this->mTrxLevel = 1;
2018 * End a transaction
2020 function commit( $fname = 'Database::commit' ) {
2021 $this->query( 'COMMIT', $fname );
2022 $this->mTrxLevel = 0;
2026 * Rollback a transaction.
2027 * No-op on non-transactional databases.
2029 function rollback( $fname = 'Database::rollback' ) {
2030 $this->query( 'ROLLBACK', $fname, true );
2031 $this->mTrxLevel = 0;
2035 * Begin a transaction, committing any previously open transaction
2036 * @deprecated use begin()
2038 function immediateBegin( $fname = 'Database::immediateBegin' ) {
2039 $this->begin();
2043 * Commit transaction, if one is open
2044 * @deprecated use commit()
2046 function immediateCommit( $fname = 'Database::immediateCommit' ) {
2047 $this->commit();
2051 * Return MW-style timestamp used for MySQL schema
2053 function timestamp( $ts=0 ) {
2054 return wfTimestamp(TS_MW,$ts);
2058 * Local database timestamp format or null
2060 function timestampOrNull( $ts = null ) {
2061 if( is_null( $ts ) ) {
2062 return null;
2063 } else {
2064 return $this->timestamp( $ts );
2069 * @todo document
2071 function resultObject( $result ) {
2072 if( empty( $result ) ) {
2073 return false;
2074 } elseif ( $result instanceof ResultWrapper ) {
2075 return $result;
2076 } elseif ( $result === true ) {
2077 // Successful write query
2078 return $result;
2079 } else {
2080 return new ResultWrapper( $this, $result );
2085 * Return aggregated value alias
2087 function aggregateValue ($valuedata,$valuename='value') {
2088 return $valuename;
2092 * @return String: wikitext of a link to the server software's web site
2094 function getSoftwareLink() {
2095 return "[http://www.mysql.com/ MySQL]";
2099 * @return String: Version information from the database
2101 function getServerVersion() {
2102 return mysql_get_server_info( $this->mConn );
2106 * Ping the server and try to reconnect if it there is no connection
2108 function ping() {
2109 if( !function_exists( 'mysql_ping' ) ) {
2110 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
2111 return true;
2113 $ping = mysql_ping( $this->mConn );
2114 if ( $ping ) {
2115 return true;
2118 // Need to reconnect manually in MySQL client 5.0.13+
2119 if ( version_compare( mysql_get_client_info(), '5.0.13', '>=' ) ) {
2120 mysql_close( $this->mConn );
2121 $this->mOpened = false;
2122 $this->mConn = false;
2123 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
2124 return true;
2126 return false;
2130 * Get slave lag.
2131 * At the moment, this will only work if the DB user has the PROCESS privilege
2133 function getLag() {
2134 if ( !is_null( $this->mFakeSlaveLag ) ) {
2135 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
2136 return $this->mFakeSlaveLag;
2138 $res = $this->query( 'SHOW PROCESSLIST' );
2139 # Find slave SQL thread
2140 while ( $row = $this->fetchObject( $res ) ) {
2141 /* This should work for most situations - when default db
2142 * for thread is not specified, it had no events executed,
2143 * and therefore it doesn't know yet how lagged it is.
2145 * Relay log I/O thread does not select databases.
2147 if ( $row->User == 'system user' &&
2148 $row->State != 'Waiting for master to send event' &&
2149 $row->State != 'Connecting to master' &&
2150 $row->State != 'Queueing master event to the relay log' &&
2151 $row->State != 'Waiting for master update' &&
2152 $row->State != 'Requesting binlog dump'
2154 # This is it, return the time (except -ve)
2155 if ( $row->Time > 0x7fffffff ) {
2156 return false;
2157 } else {
2158 return $row->Time;
2162 return false;
2166 * Get status information from SHOW STATUS in an associative array
2168 function getStatus($which="%") {
2169 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2170 $status = array();
2171 while ( $row = $this->fetchObject( $res ) ) {
2172 $status[$row->Variable_name] = $row->Value;
2174 return $status;
2178 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2180 function maxListLen() {
2181 return 0;
2184 function encodeBlob($b) {
2185 return $b;
2188 function decodeBlob($b) {
2189 return $b;
2193 * Override database's default connection timeout.
2194 * May be useful for very long batch queries such as
2195 * full-wiki dumps, where a single query reads out
2196 * over hours or days.
2197 * @param $timeout Integer in seconds
2199 public function setTimeout( $timeout ) {
2200 $this->query( "SET net_read_timeout=$timeout" );
2201 $this->query( "SET net_write_timeout=$timeout" );
2205 * Read and execute SQL commands from a file.
2206 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2207 * @param $filename String: File name to open
2208 * @param $lineCallback Callback: Optional function called before reading each line
2209 * @param $resultCallback Callback: Optional function called for each MySQL result
2211 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2212 $fp = fopen( $filename, 'r' );
2213 if ( false === $fp ) {
2214 throw new MWException( "Could not open \"{$filename}\".\n" );
2216 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2217 fclose( $fp );
2218 return $error;
2222 * Read and execute commands from an open file handle
2223 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2224 * @param $fp String: File handle
2225 * @param $lineCallback Callback: Optional function called before reading each line
2226 * @param $resultCallback Callback: Optional function called for each MySQL result
2228 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2229 $cmd = "";
2230 $done = false;
2231 $dollarquote = false;
2233 while ( ! feof( $fp ) ) {
2234 if ( $lineCallback ) {
2235 call_user_func( $lineCallback );
2237 $line = trim( fgets( $fp, 1024 ) );
2238 $sl = strlen( $line ) - 1;
2240 if ( $sl < 0 ) { continue; }
2241 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2243 ## Allow dollar quoting for function declarations
2244 if (substr($line,0,4) == '$mw$') {
2245 if ($dollarquote) {
2246 $dollarquote = false;
2247 $done = true;
2249 else {
2250 $dollarquote = true;
2253 else if (!$dollarquote) {
2254 if ( ';' == $line{$sl} && ($sl < 2 || ';' != $line{$sl - 1})) {
2255 $done = true;
2256 $line = substr( $line, 0, $sl );
2260 if ( '' != $cmd ) { $cmd .= ' '; }
2261 $cmd .= "$line\n";
2263 if ( $done ) {
2264 $cmd = str_replace(';;', ";", $cmd);
2265 $cmd = $this->replaceVars( $cmd );
2266 $res = $this->query( $cmd, __METHOD__ );
2267 if ( $resultCallback ) {
2268 call_user_func( $resultCallback, $res, $this );
2271 if ( false === $res ) {
2272 $err = $this->lastError();
2273 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2276 $cmd = '';
2277 $done = false;
2280 return true;
2285 * Replace variables in sourced SQL
2287 protected function replaceVars( $ins ) {
2288 $varnames = array(
2289 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2290 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2291 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2294 // Ordinary variables
2295 foreach ( $varnames as $var ) {
2296 if( isset( $GLOBALS[$var] ) ) {
2297 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2298 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2299 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2300 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2304 // Table prefixes
2305 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2306 array( $this, 'tableNameCallback' ), $ins );
2308 // Index names
2309 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2310 array( $this, 'indexNameCallback' ), $ins );
2311 return $ins;
2315 * Table name callback
2316 * @private
2318 protected function tableNameCallback( $matches ) {
2319 return $this->tableName( $matches[1] );
2323 * Index name callback
2325 protected function indexNameCallback( $matches ) {
2326 return $this->indexName( $matches[1] );
2330 * Build a concatenation list to feed into a SQL query
2332 function buildConcat( $stringList ) {
2333 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2337 * Acquire a lock
2339 * Abstracted from Filestore::lock() so child classes can implement for
2340 * their own needs.
2342 * @param $lockName String: Name of lock to aquire
2343 * @param $method String: Name of method calling us
2344 * @return bool
2346 public function lock( $lockName, $method ) {
2347 $lockName = $this->addQuotes( $lockName );
2348 $result = $this->query( "SELECT GET_LOCK($lockName, 5) AS lockstatus", $method );
2349 $row = $this->fetchObject( $result );
2350 $this->freeResult( $result );
2352 if( $row->lockstatus == 1 ) {
2353 return true;
2354 } else {
2355 wfDebug( __METHOD__." failed to acquire lock\n" );
2356 return false;
2360 * Release a lock.
2362 * @todo fixme - Figure out a way to return a bool
2363 * based on successful lock release.
2365 * @param $lockName String: Name of lock to release
2366 * @param $method String: Name of method calling us
2368 public function unlock( $lockName, $method ) {
2369 $lockName = $this->addQuotes( $lockName );
2370 $result = $this->query( "SELECT RELEASE_LOCK($lockName)", $method );
2371 $this->freeResult( $result );
2375 * Get search engine class. All subclasses of this
2376 * need to implement this if they wish to use searching.
2378 * @return String
2380 public function getSearchEngine() {
2381 return "SearchMySQL";
2386 * Database abstraction object for mySQL
2387 * Inherit all methods and properties of Database::Database()
2389 * @ingroup Database
2390 * @see Database
2392 class DatabaseMysql extends Database {
2393 # Inherit all
2396 /******************************************************************************
2397 * Utility classes
2398 *****************************************************************************/
2401 * Utility class.
2402 * @ingroup Database
2404 class DBObject {
2405 public $mData;
2407 function DBObject($data) {
2408 $this->mData = $data;
2411 function isLOB() {
2412 return false;
2415 function data() {
2416 return $this->mData;
2421 * Utility class
2422 * @ingroup Database
2424 * This allows us to distinguish a blob from a normal string and an array of strings
2426 class Blob {
2427 private $mData;
2428 function __construct($data) {
2429 $this->mData = $data;
2431 function fetch() {
2432 return $this->mData;
2437 * Utility class.
2438 * @ingroup Database
2440 class MySQLField {
2441 private $name, $tablename, $default, $max_length, $nullable,
2442 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2443 function __construct ($info) {
2444 $this->name = $info->name;
2445 $this->tablename = $info->table;
2446 $this->default = $info->def;
2447 $this->max_length = $info->max_length;
2448 $this->nullable = !$info->not_null;
2449 $this->is_pk = $info->primary_key;
2450 $this->is_unique = $info->unique_key;
2451 $this->is_multiple = $info->multiple_key;
2452 $this->is_key = ($this->is_pk || $this->is_unique || $this->is_multiple);
2453 $this->type = $info->type;
2456 function name() {
2457 return $this->name;
2460 function tableName() {
2461 return $this->tableName;
2464 function defaultValue() {
2465 return $this->default;
2468 function maxLength() {
2469 return $this->max_length;
2472 function nullable() {
2473 return $this->nullable;
2476 function isKey() {
2477 return $this->is_key;
2480 function isMultipleKey() {
2481 return $this->is_multiple;
2484 function type() {
2485 return $this->type;
2489 /******************************************************************************
2490 * Error classes
2491 *****************************************************************************/
2494 * Database error base class
2495 * @ingroup Database
2497 class DBError extends MWException {
2498 public $db;
2501 * Construct a database error
2502 * @param $db Database object which threw the error
2503 * @param $error A simple error message to be used for debugging
2505 function __construct( Database &$db, $error ) {
2506 $this->db =& $db;
2507 parent::__construct( $error );
2512 * @ingroup Database
2514 class DBConnectionError extends DBError {
2515 public $error;
2517 function __construct( Database &$db, $error = 'unknown error' ) {
2518 $msg = 'DB connection error';
2519 if ( trim( $error ) != '' ) {
2520 $msg .= ": $error";
2522 $this->error = $error;
2523 parent::__construct( $db, $msg );
2526 function useOutputPage() {
2527 // Not likely to work
2528 return false;
2531 function useMessageCache() {
2532 // Not likely to work
2533 return false;
2536 function getText() {
2537 return $this->getMessage() . "\n";
2540 function getLogMessage() {
2541 # Don't send to the exception log
2542 return false;
2545 function getPageTitle() {
2546 global $wgSitename, $wgLang;
2547 $header = "$wgSitename has a problem";
2548 if ( $wgLang instanceof Language ) {
2549 $header = htmlspecialchars( $wgLang->getMessage( 'dberr-header' ) );
2552 return $header;
2555 function getHTML() {
2556 global $wgLang, $wgMessageCache, $wgUseFileCache;
2558 $sorry = 'Sorry! This site is experiencing technical difficulties.';
2559 $again = 'Try waiting a few minutes and reloading.';
2560 $info = '(Can\'t contact the database server: $1)';
2562 if ( $wgLang instanceof Language ) {
2563 $sorry = htmlspecialchars( $wgLang->getMessage( 'dberr-problems' ) );
2564 $again = htmlspecialchars( $wgLang->getMessage( 'dberr-again' ) );
2565 $info = htmlspecialchars( $wgLang->getMessage( 'dberr-info' ) );
2568 # No database access
2569 if ( is_object( $wgMessageCache ) ) {
2570 $wgMessageCache->disable();
2573 if ( trim( $this->error ) == '' ) {
2574 $this->error = $this->db->getProperty('mServer');
2577 $noconnect = "<p><strong>$sorry</strong><br />$again</p><p><small>$info</small></p>";
2578 $text = str_replace( '$1', $this->error, $noconnect );
2581 if ( $GLOBALS['wgShowExceptionDetails'] ) {
2582 $text .= '</p><p>Backtrace:</p><p>' .
2583 nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
2584 "</p>\n";
2587 $extra = $this->searchForm();
2589 if( $wgUseFileCache ) {
2590 $cache = $this->fileCachedPage();
2591 # Cached version on file system?
2592 if( $cache !== null ) {
2593 # Hack: extend the body for error messages
2594 $cache = str_replace( array('</html>','</body>'), '', $cache );
2595 # Add cache notice...
2596 $cachederror = "This is a cached copy of the requested page, and may not be up to date. ";
2597 # Localize it if possible...
2598 if( $wgLang instanceof Language ) {
2599 $cachederror = htmlspecialchars( $wgLang->getMessage( 'dberr-cachederror' ) );
2601 $warning = "<div style='color:red;font-size:150%;font-weight:bold;'>$cachederror</div>";
2602 # Output cached page with notices on bottom and re-close body
2603 return "{$cache}{$warning}<hr />$text<hr />$extra</body></html>";
2606 # Headers needed here - output is just the error message
2607 return $this->htmlHeader()."$text<hr />$extra".$this->htmlFooter();
2610 function searchForm() {
2611 global $wgSitename, $wgServer, $wgLang, $wgInputEncoding;
2612 $usegoogle = "You can try searching via Google in the meantime.";
2613 $outofdate = "Note that their indexes of our content may be out of date.";
2614 $googlesearch = "Search";
2616 if ( $wgLang instanceof Language ) {
2617 $usegoogle = htmlspecialchars( $wgLang->getMessage( 'dberr-usegoogle' ) );
2618 $outofdate = htmlspecialchars( $wgLang->getMessage( 'dberr-outofdate' ) );
2619 $googlesearch = htmlspecialchars( $wgLang->getMessage( 'searchbutton' ) );
2622 $search = htmlspecialchars(@$_REQUEST['search']);
2624 $trygoogle = <<<EOT
2625 <div style="margin: 1.5em">$usegoogle<br />
2626 <small>$outofdate</small></div>
2627 <!-- SiteSearch Google -->
2628 <form method="get" action="http://www.google.com/search" id="googlesearch">
2629 <input type="hidden" name="domains" value="$wgServer" />
2630 <input type="hidden" name="num" value="50" />
2631 <input type="hidden" name="ie" value="$wgInputEncoding" />
2632 <input type="hidden" name="oe" value="$wgInputEncoding" />
2634 <img src="http://www.google.com/logos/Logo_40wht.gif" alt="" style="float:left; margin-left: 1.5em; margin-right: 1.5em;" />
2636 <input type="text" name="q" size="31" maxlength="255" value="$search" />
2637 <input type="submit" name="btnG" value="$googlesearch" />
2638 <div>
2639 <input type="radio" name="sitesearch" id="gwiki" value="$wgServer" checked="checked" /><label for="gwiki">$wgSitename</label>
2640 <input type="radio" name="sitesearch" id="gWWW" value="" /><label for="gWWW">WWW</label>
2641 </div>
2642 </form>
2643 <!-- SiteSearch Google -->
2644 EOT;
2645 return $trygoogle;
2648 function fileCachedPage() {
2649 global $wgTitle, $title, $wgLang, $wgOut;
2650 if( $wgOut->isDisabled() ) return; // Done already?
2651 $mainpage = 'Main Page';
2652 if ( $wgLang instanceof Language ) {
2653 $mainpage = htmlspecialchars( $wgLang->getMessage( 'mainpage' ) );
2656 if($wgTitle) {
2657 $t =& $wgTitle;
2658 } elseif($title) {
2659 $t = Title::newFromURL( $title );
2660 } else {
2661 $t = Title::newFromText( $mainpage );
2664 $cache = new HTMLFileCache( $t );
2665 if( $cache->isFileCached() ) {
2666 return $cache->fetchPageText();
2667 } else {
2668 return '';
2672 function htmlBodyOnly() {
2673 return true;
2679 * @ingroup Database
2681 class DBQueryError extends DBError {
2682 public $error, $errno, $sql, $fname;
2684 function __construct( Database &$db, $error, $errno, $sql, $fname ) {
2685 $message = "A database error has occurred\n" .
2686 "Query: $sql\n" .
2687 "Function: $fname\n" .
2688 "Error: $errno $error\n";
2690 parent::__construct( $db, $message );
2691 $this->error = $error;
2692 $this->errno = $errno;
2693 $this->sql = $sql;
2694 $this->fname = $fname;
2697 function getText() {
2698 if ( $this->useMessageCache() ) {
2699 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2700 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) ) . "\n";
2701 } else {
2702 return $this->getMessage();
2706 function getSQL() {
2707 global $wgShowSQLErrors;
2708 if( !$wgShowSQLErrors ) {
2709 return $this->msg( 'sqlhidden', 'SQL hidden' );
2710 } else {
2711 return $this->sql;
2715 function getLogMessage() {
2716 # Don't send to the exception log
2717 return false;
2720 function getPageTitle() {
2721 return $this->msg( 'databaseerror', 'Database error' );
2724 function getHTML() {
2725 if ( $this->useMessageCache() ) {
2726 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2727 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) );
2728 } else {
2729 return nl2br( htmlspecialchars( $this->getMessage() ) );
2735 * @ingroup Database
2737 class DBUnexpectedError extends DBError {}
2741 * Result wrapper for grabbing data queried by someone else
2742 * @ingroup Database
2744 class ResultWrapper implements Iterator {
2745 var $db, $result, $pos = 0, $currentRow = null;
2748 * Create a new result object from a result resource and a Database object
2750 function ResultWrapper( $database, $result ) {
2751 $this->db = $database;
2752 if ( $result instanceof ResultWrapper ) {
2753 $this->result = $result->result;
2754 } else {
2755 $this->result = $result;
2760 * Get the number of rows in a result object
2762 function numRows() {
2763 return $this->db->numRows( $this->result );
2767 * Fetch the next row from the given result object, in object form.
2768 * Fields can be retrieved with $row->fieldname, with fields acting like
2769 * member variables.
2771 * @param $res SQL result object as returned from Database::query(), etc.
2772 * @return MySQL row object
2773 * @throws DBUnexpectedError Thrown if the database returns an error
2775 function fetchObject() {
2776 return $this->db->fetchObject( $this->result );
2780 * Fetch the next row from the given result object, in associative array
2781 * form. Fields are retrieved with $row['fieldname'].
2783 * @param $res SQL result object as returned from Database::query(), etc.
2784 * @return MySQL row object
2785 * @throws DBUnexpectedError Thrown if the database returns an error
2787 function fetchRow() {
2788 return $this->db->fetchRow( $this->result );
2792 * Free a result object
2794 function free() {
2795 $this->db->freeResult( $this->result );
2796 unset( $this->result );
2797 unset( $this->db );
2801 * Change the position of the cursor in a result object
2802 * See mysql_data_seek()
2804 function seek( $row ) {
2805 $this->db->dataSeek( $this->result, $row );
2808 /*********************
2809 * Iterator functions
2810 * Note that using these in combination with the non-iterator functions
2811 * above may cause rows to be skipped or repeated.
2814 function rewind() {
2815 if ($this->numRows()) {
2816 $this->db->dataSeek($this->result, 0);
2818 $this->pos = 0;
2819 $this->currentRow = null;
2822 function current() {
2823 if ( is_null( $this->currentRow ) ) {
2824 $this->next();
2826 return $this->currentRow;
2829 function key() {
2830 return $this->pos;
2833 function next() {
2834 $this->pos++;
2835 $this->currentRow = $this->fetchObject();
2836 return $this->currentRow;
2839 function valid() {
2840 return $this->current() !== false;
2844 class MySQLMasterPos {
2845 var $file, $pos;
2847 function __construct( $file, $pos ) {
2848 $this->file = $file;
2849 $this->pos = $pos;
2852 function __toString() {
2853 return "{$this->file}/{$this->pos}";