3 * @defgroup Database Database
7 * This file deals with MySQL interface functions
8 * and query specifics/optimisations
11 /** Number of times to re-try an operation in case of deadlock */
12 define( 'DEADLOCK_TRIES', 4 );
13 /** Minimum time to wait before retry, in microseconds */
14 define( 'DEADLOCK_DELAY_MIN', 500000 );
15 /** Maximum time to wait before retry */
16 define( 'DEADLOCK_DELAY_MAX', 1500000 );
19 * Database abstraction object
24 #------------------------------------------------------------------------------
26 #------------------------------------------------------------------------------
28 protected $mLastQuery = '';
29 protected $mPHPError = false;
31 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
32 protected $mOpened = false;
34 protected $mFailFunction;
35 protected $mTablePrefix;
37 protected $mTrxLevel = 0;
38 protected $mErrorCount = 0;
39 protected $mLBInfo = array();
40 protected $mFakeSlaveLag = null, $mFakeMaster = false;
42 #------------------------------------------------------------------------------
44 #------------------------------------------------------------------------------
45 # These optionally set a variable and return the previous state
48 * Fail function, takes a Database as a parameter
49 * Set to false for default, 1 for ignore errors
51 function failFunction( $function = NULL ) {
52 return wfSetVar( $this->mFailFunction
, $function );
56 * Output page, used for reporting errors
57 * FALSE means discard output
59 function setOutputPage( $out ) {
60 wfDeprecated( __METHOD__
);
64 * Boolean, controls output of large amounts of debug information
66 function debug( $debug = NULL ) {
67 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
71 * Turns buffering of SQL result sets on (true) or off (false).
72 * Default is "on" and it should not be changed without good reasons.
74 function bufferResults( $buffer = NULL ) {
75 if ( is_null( $buffer ) ) {
76 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
78 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
83 * Turns on (false) or off (true) the automatic generation and sending
84 * of a "we're sorry, but there has been a database error" page on
85 * database errors. Default is on (false). When turned off, the
86 * code should use lastErrno() and lastError() to handle the
87 * situation as appropriate.
89 function ignoreErrors( $ignoreErrors = NULL ) {
90 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
94 * The current depth of nested transactions
95 * @param $level Integer: , default NULL.
97 function trxLevel( $level = NULL ) {
98 return wfSetVar( $this->mTrxLevel
, $level );
102 * Number of errors logged, only useful when errors are ignored
104 function errorCount( $count = NULL ) {
105 return wfSetVar( $this->mErrorCount
, $count );
108 function tablePrefix( $prefix = null ) {
109 return wfSetVar( $this->mTablePrefix
, $prefix );
113 * Properties passed down from the server info array of the load balancer
115 function getLBInfo( $name = NULL ) {
116 if ( is_null( $name ) ) {
117 return $this->mLBInfo
;
119 if ( array_key_exists( $name, $this->mLBInfo
) ) {
120 return $this->mLBInfo
[$name];
127 function setLBInfo( $name, $value = NULL ) {
128 if ( is_null( $value ) ) {
129 $this->mLBInfo
= $name;
131 $this->mLBInfo
[$name] = $value;
136 * Set lag time in seconds for a fake slave
138 function setFakeSlaveLag( $lag ) {
139 $this->mFakeSlaveLag
= $lag;
143 * Make this connection a fake master
145 function setFakeMaster( $enabled = true ) {
146 $this->mFakeMaster
= $enabled;
150 * Returns true if this database supports (and uses) cascading deletes
152 function cascadingDeletes() {
157 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
159 function cleanupTriggers() {
164 * Returns true if this database is strict about what can be put into an IP field.
165 * Specifically, it uses a NULL value instead of an empty string.
167 function strictIPs() {
172 * Returns true if this database uses timestamps rather than integers
174 function realTimestamps() {
179 * Returns true if this database does an implicit sort when doing GROUP BY
181 function implicitGroupby() {
186 * Returns true if this database does an implicit order by when the column has an index
187 * For example: SELECT page_title FROM page LIMIT 1
189 function implicitOrderby() {
194 * Returns true if this database can do a native search on IP columns
195 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
197 function searchableIPs() {
202 * Returns true if this database can use functional indexes
204 function functionalIndexes() {
209 * Return the last query that went through Database::query()
212 function lastQuery() { return $this->mLastQuery
; }
215 * Is a connection to the database open?
218 function isOpen() { return $this->mOpened
; }
220 function setFlag( $flag ) {
221 $this->mFlags |
= $flag;
224 function clearFlag( $flag ) {
225 $this->mFlags
&= ~
$flag;
228 function getFlag( $flag ) {
229 return !!($this->mFlags
& $flag);
233 * General read-only accessor
235 function getProperty( $name ) {
239 function getWikiID() {
240 if( $this->mTablePrefix
) {
241 return "{$this->mDBname}-{$this->mTablePrefix}";
243 return $this->mDBname
;
247 #------------------------------------------------------------------------------
249 #------------------------------------------------------------------------------
253 * @param $server String: database server host
254 * @param $user String: database user name
255 * @param $password String: database user password
256 * @param $dbName String: database name
257 * @param $failFunction
259 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
261 function __construct( $server = false, $user = false, $password = false, $dbName = false,
262 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
264 global $wgOut, $wgDBprefix, $wgCommandLineMode;
265 # Can't get a reference if it hasn't been set yet
266 if ( !isset( $wgOut ) ) {
270 $this->mFailFunction
= $failFunction;
271 $this->mFlags
= $flags;
273 if ( $this->mFlags
& DBO_DEFAULT
) {
274 if ( $wgCommandLineMode ) {
275 $this->mFlags
&= ~DBO_TRX
;
277 $this->mFlags |
= DBO_TRX
;
282 // Faster read-only access
283 if ( wfReadOnly() ) {
284 $this->mFlags |= DBO_PERSISTENT;
285 $this->mFlags &= ~DBO_TRX;
288 /** Get the default table prefix*/
289 if ( $tablePrefix == 'get from global' ) {
290 $this->mTablePrefix
= $wgDBprefix;
292 $this->mTablePrefix
= $tablePrefix;
296 $this->open( $server, $user, $password, $dbName );
301 * Same as new Database( ... ), kept for backward compatibility
302 * @param $server String: database server host
303 * @param $user String: database user name
304 * @param $password String: database user password
305 * @param $dbName String: database name
306 * @param failFunction
309 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
311 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
315 * Usually aborts on failure
316 * If the failFunction is set to a non-zero integer, returns success
317 * @param $server String: database server host
318 * @param $user String: database user name
319 * @param $password String: database user password
320 * @param $dbName String: database name
322 function open( $server, $user, $password, $dbName ) {
323 global $wgAllDBsAreLocalhost;
324 wfProfileIn( __METHOD__
);
326 # Test for missing mysql.so
327 # First try to load it
328 if (!@extension_loaded
('mysql')) {
333 # Otherwise we get a suppressed fatal error, which is very hard to track down
334 if ( !function_exists( 'mysql_connect' ) ) {
335 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
338 # Debugging hack -- fake cluster
339 if ( $wgAllDBsAreLocalhost ) {
340 $realServer = 'localhost';
342 $realServer = $server;
345 $this->mServer
= $server;
346 $this->mUser
= $user;
347 $this->mPassword
= $password;
348 $this->mDBname
= $dbName;
352 wfProfileIn("dbconnect-$server");
354 # The kernel's default SYN retransmission period is far too slow for us,
355 # so we use a short timeout plus a manual retry. Retrying means that a small
356 # but finite rate of SYN packet loss won't cause user-visible errors.
357 $this->mConn
= false;
358 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
363 $this->installErrorHandler();
364 for ( $i = 0; $i < $numAttempts && !$this->mConn
; $i++
) {
368 if ( $this->mFlags
& DBO_PERSISTENT
) {
369 $this->mConn
= mysql_pconnect( $realServer, $user, $password );
371 # Create a new connection...
372 $this->mConn
= mysql_connect( $realServer, $user, $password, true );
374 if ($this->mConn
=== false) {
376 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
379 $phpError = $this->restoreErrorHandler();
380 # Always log connection errors
381 if ( !$this->mConn
) {
382 $error = $this->lastError();
386 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
387 wfDebug( "DB connection error\n" );
388 wfDebug( "Server: $server, User: $user, Password: " .
389 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
393 wfProfileOut("dbconnect-$server");
395 if ( $dbName != '' && $this->mConn
!== false ) {
396 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
398 $error = "Error selecting database $dbName on server {$this->mServer} " .
399 "from client host " . wfHostname() . "\n";
400 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
405 $success = (bool)$this->mConn
;
409 $version = $this->getServerVersion();
410 if ( version_compare( $version, '4.1' ) >= 0 ) {
411 // Tell the server we're communicating with it in UTF-8.
412 // This may engage various charset conversions.
415 $this->query( 'SET NAMES utf8', __METHOD__
);
417 // Turn off strict mode
418 $this->query( "SET sql_mode = ''", __METHOD__
);
421 // Turn off strict mode if it is on
423 $this->reportConnectionError( $phpError );
426 $this->mOpened
= $success;
427 wfProfileOut( __METHOD__
);
431 protected function installErrorHandler() {
432 $this->mPHPError
= false;
433 $this->htmlErrors
= ini_set( 'html_errors', '0' );
434 set_error_handler( array( $this, 'connectionErrorHandler' ) );
437 protected function restoreErrorHandler() {
438 restore_error_handler();
439 if ( $this->htmlErrors
!== false ) {
440 ini_set( 'html_errors', $this->htmlErrors
);
442 if ( $this->mPHPError
) {
443 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
444 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
451 protected function connectionErrorHandler( $errno, $errstr ) {
452 $this->mPHPError
= $errstr;
456 * Closes a database connection.
457 * if it is open : commits any open transactions
459 * @return Bool operation success. true if already closed.
463 $this->mOpened
= false;
464 if ( $this->mConn
) {
465 if ( $this->trxLevel() ) {
466 $this->immediateCommit();
468 return mysql_close( $this->mConn
);
475 * @param $error String: fallback error message, used if none is given by MySQL
477 function reportConnectionError( $error = 'Unknown error' ) {
478 $myError = $this->lastError();
483 if ( $this->mFailFunction
) {
484 # Legacy error handling method
485 if ( !is_int( $this->mFailFunction
) ) {
486 $ff = $this->mFailFunction
;
487 $ff( $this, $error );
491 throw new DBConnectionError( $this, $error );
496 * Usually aborts on failure. If errors are explicitly ignored, returns success.
498 * @param $sql String: SQL query
499 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
500 * comment (you can use __METHOD__ or add some extra info)
501 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
502 * maybe best to catch the exception instead?
503 * @return true for a successful write query, ResultWrapper object for a successful read query,
504 * or false on failure if $tempIgnore set
505 * @throws DBQueryError Thrown when the database returns an error of any kind
507 public function query( $sql, $fname = '', $tempIgnore = false ) {
510 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
511 if ( isset( $wgProfiler ) ) {
512 # generalizeSQL will probably cut down the query to reasonable
513 # logging size most of the time. The substr is really just a sanity check.
515 # Who's been wasting my precious column space? -- TS
516 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
519 $queryProf = 'query-m: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
520 $totalProf = 'Database::query-master';
522 $queryProf = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
523 $totalProf = 'Database::query';
525 wfProfileIn( $totalProf );
526 wfProfileIn( $queryProf );
529 $this->mLastQuery
= $sql;
531 # Add a comment for easy SHOW PROCESSLIST interpretation
534 if ( is_object( $wgUser ) && !($wgUser instanceof StubObject
) ) {
535 $userName = $wgUser->getName();
536 if ( mb_strlen( $userName ) > 15 ) {
537 $userName = mb_substr( $userName, 0, 15 ) . '...';
539 $userName = str_replace( '/', '', $userName );
543 $commentedSql = preg_replace('/\s/', " /* $fname $userName */ ", $sql, 1);
545 # $commentedSql = $sql;
548 # If DBO_TRX is set, start a transaction
549 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
550 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK') {
551 // avoid establishing transactions for SHOW and SET statements too -
552 // that would delay transaction initializations to once connection
553 // is really used by application
554 $sqlstart = substr($sql,0,10); // very much worth it, benchmark certified(tm)
555 if (strpos($sqlstart,"SHOW ")!==0 and strpos($sqlstart,"SET ")!==0)
559 if ( $this->debug() ) {
560 $sqlx = substr( $commentedSql, 0, 500 );
561 $sqlx = strtr( $sqlx, "\t\n", ' ' );
563 wfDebug( "SQL-master: $sqlx\n" );
565 wfDebug( "SQL: $sqlx\n" );
569 # Do the query and handle errors
570 $ret = $this->doQuery( $commentedSql );
572 # Try reconnecting if the connection was lost
573 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
574 # Transaction is gone, like it or not
575 $this->mTrxLevel
= 0;
576 wfDebug( "Connection lost, reconnecting...\n" );
577 if ( $this->ping() ) {
578 wfDebug( "Reconnected\n" );
579 $sqlx = substr( $commentedSql, 0, 500 );
580 $sqlx = strtr( $sqlx, "\t\n", ' ' );
581 global $wgRequestTime;
582 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
583 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
584 $ret = $this->doQuery( $commentedSql );
586 wfDebug( "Failed\n" );
590 if ( false === $ret ) {
591 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
594 if ( isset( $wgProfiler ) ) {
595 wfProfileOut( $queryProf );
596 wfProfileOut( $totalProf );
598 return $this->resultObject( $ret );
602 * The DBMS-dependent part of query()
603 * @param $sql String: SQL query.
604 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
607 /*private*/ function doQuery( $sql ) {
608 if( $this->bufferResults() ) {
609 $ret = mysql_query( $sql, $this->mConn
);
611 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
617 * @param $error String
618 * @param $errno Integer
620 * @param $fname String
621 * @param $tempIgnore Boolean
623 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
624 global $wgCommandLineMode;
625 # Ignore errors during error handling to avoid infinite recursion
626 $ignore = $this->ignoreErrors( true );
627 ++
$this->mErrorCount
;
629 if( $ignore ||
$tempIgnore ) {
630 wfDebug("SQL ERROR (ignored): $error\n");
631 $this->ignoreErrors( $ignore );
633 $sql1line = str_replace( "\n", "\\n", $sql );
634 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
635 wfDebug("SQL ERROR: " . $error . "\n");
636 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
642 * Intended to be compatible with the PEAR::DB wrapper functions.
643 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
645 * ? = scalar value, quoted as necessary
646 * ! = raw SQL bit (a function for instance)
647 * & = filename; reads the file and inserts as a blob
648 * (we don't use this though...)
650 function prepare( $sql, $func = 'Database::prepare' ) {
651 /* MySQL doesn't support prepared statements (yet), so just
652 pack up the query for reference. We'll manually replace
654 return array( 'query' => $sql, 'func' => $func );
657 function freePrepared( $prepared ) {
658 /* No-op for MySQL */
662 * Execute a prepared query with the various arguments
663 * @param $prepared String: the prepared sql
664 * @param $args Mixed: Either an array here, or put scalars as varargs
666 function execute( $prepared, $args = null ) {
667 if( !is_array( $args ) ) {
669 $args = func_get_args();
670 array_shift( $args );
672 $sql = $this->fillPrepared( $prepared['query'], $args );
673 return $this->query( $sql, $prepared['func'] );
677 * Prepare & execute an SQL statement, quoting and inserting arguments
678 * in the appropriate places.
679 * @param $query String
682 function safeQuery( $query, $args = null ) {
683 $prepared = $this->prepare( $query, 'Database::safeQuery' );
684 if( !is_array( $args ) ) {
686 $args = func_get_args();
687 array_shift( $args );
689 $retval = $this->execute( $prepared, $args );
690 $this->freePrepared( $prepared );
695 * For faking prepared SQL statements on DBs that don't support
697 * @param $preparedQuery String: a 'preparable' SQL statement
698 * @param $args Array of arguments to fill it with
699 * @return string executable SQL
701 function fillPrepared( $preparedQuery, $args ) {
703 $this->preparedArgs
=& $args;
704 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
705 array( &$this, 'fillPreparedArg' ), $preparedQuery );
709 * preg_callback func for fillPrepared()
710 * The arguments should be in $this->preparedArgs and must not be touched
711 * while we're doing this.
713 * @param $matches Array
717 function fillPreparedArg( $matches ) {
718 switch( $matches[1] ) {
719 case '\\?': return '?';
720 case '\\!': return '!';
721 case '\\&': return '&';
723 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
724 switch( $matches[1] ) {
725 case '?': return $this->addQuotes( $arg );
726 case '!': return $arg;
728 # return $this->addQuotes( file_get_contents( $arg ) );
729 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
731 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
736 * Free a result object
737 * @param $res Mixed: A SQL result
739 function freeResult( $res ) {
740 if ( $res instanceof ResultWrapper
) {
743 if ( !@/**/mysql_free_result( $res ) ) {
744 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
749 * Fetch the next row from the given result object, in object form.
750 * Fields can be retrieved with $row->fieldname, with fields acting like
753 * @param $res SQL result object as returned from Database::query(), etc.
754 * @return MySQL row object
755 * @throws DBUnexpectedError Thrown if the database returns an error
757 function fetchObject( $res ) {
758 if ( $res instanceof ResultWrapper
) {
761 @/**/$row = mysql_fetch_object( $res );
762 if( $this->lastErrno() ) {
763 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
769 * Fetch the next row from the given result object, in associative array
770 * form. Fields are retrieved with $row['fieldname'].
772 * @param $res SQL result object as returned from Database::query(), etc.
773 * @return MySQL row object
774 * @throws DBUnexpectedError Thrown if the database returns an error
776 function fetchRow( $res ) {
777 if ( $res instanceof ResultWrapper
) {
780 @/**/$row = mysql_fetch_array( $res );
781 if ( $this->lastErrno() ) {
782 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
788 * Get the number of rows in a result object
789 * @param $res Mixed: A SQL result
791 function numRows( $res ) {
792 if ( $res instanceof ResultWrapper
) {
795 @/**/$n = mysql_num_rows( $res );
796 if( $this->lastErrno() ) {
797 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
803 * Get the number of fields in a result object
804 * See documentation for mysql_num_fields()
805 * @param $res Mixed: A SQL result
807 function numFields( $res ) {
808 if ( $res instanceof ResultWrapper
) {
811 return mysql_num_fields( $res );
815 * Get a field name in a result object
816 * See documentation for mysql_field_name():
817 * http://www.php.net/mysql_field_name
818 * @param $res Mixed: A SQL result
821 function fieldName( $res, $n ) {
822 if ( $res instanceof ResultWrapper
) {
825 return mysql_field_name( $res, $n );
829 * Get the inserted value of an auto-increment row
831 * The value inserted should be fetched from nextSequenceValue()
834 * $id = $dbw->nextSequenceValue('page_page_id_seq');
835 * $dbw->insert('page',array('page_id' => $id));
836 * $id = $dbw->insertId();
838 function insertId() { return mysql_insert_id( $this->mConn
); }
841 * Change the position of the cursor in a result object
842 * See mysql_data_seek()
843 * @param $res Mixed: A SQL result
844 * @param $row Mixed: Either MySQL row or ResultWrapper
846 function dataSeek( $res, $row ) {
847 if ( $res instanceof ResultWrapper
) {
850 return mysql_data_seek( $res, $row );
854 * Get the last error number
857 function lastErrno() {
858 if ( $this->mConn
) {
859 return mysql_errno( $this->mConn
);
861 return mysql_errno();
866 * Get a description of the last error
867 * See mysql_error() for more details
869 function lastError() {
870 if ( $this->mConn
) {
871 # Even if it's non-zero, it can still be invalid
872 wfSuppressWarnings();
873 $error = mysql_error( $this->mConn
);
875 $error = mysql_error();
879 $error = mysql_error();
882 $error .= ' (' . $this->mServer
. ')';
887 * Get the number of rows affected by the last write query
888 * See mysql_affected_rows() for more details
890 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
893 * Simple UPDATE wrapper
894 * Usually aborts on failure
895 * If errors are explicitly ignored, returns success
897 * This function exists for historical reasons, Database::update() has a more standard
898 * calling convention and feature set
900 function set( $table, $var, $value, $cond, $fname = 'Database::set' ) {
901 $table = $this->tableName( $table );
902 $sql = "UPDATE $table SET $var = '" .
903 $this->strencode( $value ) . "' WHERE ($cond)";
904 return (bool)$this->query( $sql, $fname );
908 * Simple SELECT wrapper, returns a single field, input must be encoded
909 * Usually aborts on failure
910 * If errors are explicitly ignored, returns FALSE on failure
912 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
913 if ( !is_array( $options ) ) {
914 $options = array( $options );
916 $options['LIMIT'] = 1;
918 $res = $this->select( $table, $var, $cond, $fname, $options );
919 if ( $res === false ||
!$this->numRows( $res ) ) {
922 $row = $this->fetchRow( $res );
923 if ( $row !== false ) {
924 $this->freeResult( $res );
932 * Returns an optional USE INDEX clause to go after the table, and a
933 * string to go at the end of the query
937 * @param $options Array: associative array of options to be turned into
938 * an SQL query, valid keys are listed in the function.
941 function makeSelectOptions( $options ) {
942 $preLimitTail = $postLimitTail = '';
945 $noKeyOptions = array();
946 foreach ( $options as $key => $option ) {
947 if ( is_numeric( $key ) ) {
948 $noKeyOptions[$option] = true;
952 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
953 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
954 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
956 //if (isset($options['LIMIT'])) {
957 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
958 // isset($options['OFFSET']) ? $options['OFFSET']
962 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
963 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
964 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
966 # Various MySQL extensions
967 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
968 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
969 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
970 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
971 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
972 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
973 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
974 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
976 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
977 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
982 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
988 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
989 * @param $vars Mixed: Array or string, field name(s) to be retrieved
990 * @param $conds Mixed: Array or string, condition(s) for WHERE
991 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
992 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
993 * see Database::makeSelectOptions code for list of supported stuff
994 * @param $join_conds Array: Associative array of table join conditions (optional)
995 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
996 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
998 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() )
1000 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1001 return $this->query( $sql, $fname );
1007 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
1008 * @param $vars Mixed: Array or string, field name(s) to be retrieved
1009 * @param $conds Mixed: Array or string, condition(s) for WHERE
1010 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1011 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1012 * see Database::makeSelectOptions code for list of supported stuff
1013 * @param $join_conds Array: Associative array of table join conditions (optional)
1014 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1015 * @return string, the SQL text
1017 function selectSQLText( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() ) {
1018 if( is_array( $vars ) ) {
1019 $vars = implode( ',', $vars );
1021 if( !is_array( $options ) ) {
1022 $options = array( $options );
1024 if( is_array( $table ) ) {
1025 if ( !empty($join_conds) ||
( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) )
1026 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
1028 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1029 } elseif ($table!='') {
1030 if ($table{0}==' ') {
1031 $from = ' FROM ' . $table;
1033 $from = ' FROM ' . $this->tableName( $table );
1039 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1041 if( !empty( $conds ) ) {
1042 if ( is_array( $conds ) ) {
1043 $conds = $this->makeList( $conds, LIST_AND
);
1045 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1047 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1050 if (isset($options['LIMIT']))
1051 $sql = $this->limitResult($sql, $options['LIMIT'],
1052 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
1053 $sql = "$sql $postLimitTail";
1055 if (isset($options['EXPLAIN'])) {
1056 $sql = 'EXPLAIN ' . $sql;
1062 * Single row SELECT wrapper
1063 * Aborts or returns FALSE on error
1065 * @param $table String: table name
1066 * @param $vars String: the selected variables
1067 * @param $conds Array: a condition map, terms are ANDed together.
1068 * Items with numeric keys are taken to be literal conditions
1069 * Takes an array of selected variables, and a condition map, which is ANDed
1070 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1071 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1072 * $obj- >page_id is the ID of the Astronomy article
1073 * @param $fname String: Calling functio name
1074 * @param $options Array
1075 * @param $join_conds Array
1077 * @todo migrate documentation to phpdocumentor format
1079 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array(), $join_conds = array() ) {
1080 $options['LIMIT'] = 1;
1081 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1082 if ( $res === false )
1084 if ( !$this->numRows($res) ) {
1085 $this->freeResult($res);
1088 $obj = $this->fetchObject( $res );
1089 $this->freeResult( $res );
1095 * Estimate rows in dataset
1096 * Returns estimated count, based on EXPLAIN output
1097 * Takes same arguments as Database::select()
1100 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
1101 $options['EXPLAIN']=true;
1102 $res = $this->select ($table, $vars, $conds, $fname, $options );
1103 if ( $res === false )
1105 if (!$this->numRows($res)) {
1106 $this->freeResult($res);
1112 while( $plan = $this->fetchObject( $res ) ) {
1113 $rows *= ($plan->rows
> 0)?
$plan->rows
:1; // avoid resetting to zero
1116 $this->freeResult($res);
1122 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1123 * It's only slightly flawed. Don't use for anything important.
1125 * @param $sql String: A SQL Query
1127 static function generalizeSQL( $sql ) {
1128 # This does the same as the regexp below would do, but in such a way
1129 # as to avoid crashing php on some large strings.
1130 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1132 $sql = str_replace ( "\\\\", '', $sql);
1133 $sql = str_replace ( "\\'", '', $sql);
1134 $sql = str_replace ( "\\\"", '', $sql);
1135 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1136 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1138 # All newlines, tabs, etc replaced by single space
1139 $sql = preg_replace ( '/\s+/', ' ', $sql);
1142 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1148 * Determines whether a field exists in a table
1149 * Usually aborts on failure
1150 * If errors are explicitly ignored, returns NULL on failure
1152 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1153 $table = $this->tableName( $table );
1154 $res = $this->query( 'DESCRIBE '.$table, $fname );
1161 while ( $row = $this->fetchObject( $res ) ) {
1162 if ( $row->Field
== $field ) {
1171 * Determines whether an index exists
1172 * Usually aborts on failure
1173 * If errors are explicitly ignored, returns NULL on failure
1175 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1176 $info = $this->indexInfo( $table, $index, $fname );
1177 if ( is_null( $info ) ) {
1180 return $info !== false;
1186 * Get information about an index into an object
1187 * Returns false if the index does not exist
1189 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1190 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1191 # SHOW INDEX should work for 3.x and up:
1192 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1193 $table = $this->tableName( $table );
1194 $sql = 'SHOW INDEX FROM '.$table;
1195 $res = $this->query( $sql, $fname );
1201 while ( $row = $this->fetchObject( $res ) ) {
1202 if ( $row->Key_name
== $index ) {
1206 $this->freeResult($res);
1208 return empty($result) ?
false : $result;
1212 * Query whether a given table exists
1214 function tableExists( $table ) {
1215 $table = $this->tableName( $table );
1216 $old = $this->ignoreErrors( true );
1217 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1218 $this->ignoreErrors( $old );
1220 $this->freeResult( $res );
1228 * mysql_fetch_field() wrapper
1229 * Returns false if the field doesn't exist
1234 function fieldInfo( $table, $field ) {
1235 $table = $this->tableName( $table );
1236 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1237 $n = mysql_num_fields( $res->result
);
1238 for( $i = 0; $i < $n; $i++
) {
1239 $meta = mysql_fetch_field( $res->result
, $i );
1240 if( $field == $meta->name
) {
1241 return new MySQLField($meta);
1248 * mysql_field_type() wrapper
1250 function fieldType( $res, $index ) {
1251 if ( $res instanceof ResultWrapper
) {
1252 $res = $res->result
;
1254 return mysql_field_type( $res, $index );
1258 * Determines if a given index is unique
1260 function indexUnique( $table, $index ) {
1261 $indexInfo = $this->indexInfo( $table, $index );
1262 if ( !$indexInfo ) {
1265 return !$indexInfo[0]->Non_unique
;
1269 * INSERT wrapper, inserts an array into a table
1271 * $a may be a single associative array, or an array of these with numeric keys, for
1274 * Usually aborts on failure
1275 * If errors are explicitly ignored, returns success
1277 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1278 # No rows to insert, easy just return now
1279 if ( !count( $a ) ) {
1283 $table = $this->tableName( $table );
1284 if ( !is_array( $options ) ) {
1285 $options = array( $options );
1287 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1289 $keys = array_keys( $a[0] );
1292 $keys = array_keys( $a );
1295 $sql = 'INSERT ' . implode( ' ', $options ) .
1296 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1300 foreach ( $a as $row ) {
1306 $sql .= '(' . $this->makeList( $row ) . ')';
1309 $sql .= '(' . $this->makeList( $a ) . ')';
1311 return (bool)$this->query( $sql, $fname );
1315 * Make UPDATE options for the Database::update function
1318 * @param $options Array: The options passed to Database::update
1321 function makeUpdateOptions( $options ) {
1322 if( !is_array( $options ) ) {
1323 $options = array( $options );
1326 if ( in_array( 'LOW_PRIORITY', $options ) )
1327 $opts[] = $this->lowPriorityOption();
1328 if ( in_array( 'IGNORE', $options ) )
1330 return implode(' ', $opts);
1334 * UPDATE wrapper, takes a condition array and a SET array
1336 * @param $table String: The table to UPDATE
1337 * @param $values Array: An array of values to SET
1338 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
1339 * @param $fname String: The Class::Function calling this function
1341 * @param $options Array: An array of UPDATE options, can be one or
1342 * more of IGNORE, LOW_PRIORITY
1345 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1346 $table = $this->tableName( $table );
1347 $opts = $this->makeUpdateOptions( $options );
1348 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1349 if ( $conds != '*' ) {
1350 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1352 return $this->query( $sql, $fname );
1356 * Makes an encoded list of strings from an array
1358 * LIST_COMMA - comma separated, no field names
1359 * LIST_AND - ANDed WHERE clause (without the WHERE)
1360 * LIST_OR - ORed WHERE clause (without the WHERE)
1361 * LIST_SET - comma separated with field names, like a SET clause
1362 * LIST_NAMES - comma separated field names
1364 function makeList( $a, $mode = LIST_COMMA
) {
1365 if ( !is_array( $a ) ) {
1366 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1371 foreach ( $a as $field => $value ) {
1373 if ( $mode == LIST_AND
) {
1375 } elseif($mode == LIST_OR
) {
1383 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1384 $list .= "($value)";
1385 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
1387 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array($value) ) {
1388 if( count( $value ) == 0 ) {
1389 throw new MWException( __METHOD__
.': empty input' );
1390 } elseif( count( $value ) == 1 ) {
1391 // Special-case single values, as IN isn't terribly efficient
1392 // Don't necessarily assume the single key is 0; we don't
1393 // enforce linear numeric ordering on other arrays here.
1394 $value = array_values( $value );
1395 $list .= $field." = ".$this->addQuotes( $value[0] );
1397 $list .= $field." IN (".$this->makeList($value).") ";
1399 } elseif( is_null($value) ) {
1400 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1401 $list .= "$field IS ";
1402 } elseif ( $mode == LIST_SET
) {
1403 $list .= "$field = ";
1407 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1408 $list .= "$field = ";
1410 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1417 * Change the current database
1419 function selectDB( $db ) {
1420 $this->mDBname
= $db;
1421 return mysql_select_db( $db, $this->mConn
);
1425 * Get the current DB name
1427 function getDBname() {
1428 return $this->mDBname
;
1432 * Get the server hostname or IP address
1434 function getServer() {
1435 return $this->mServer
;
1439 * Format a table name ready for use in constructing an SQL query
1441 * This does two important things: it quotes the table names to clean them up,
1442 * and it adds a table prefix if only given a table name with no quotes.
1444 * All functions of this object which require a table name call this function
1445 * themselves. Pass the canonical name to such functions. This is only needed
1446 * when calling query() directly.
1448 * @param $name String: database table name
1449 * @return String: full database name
1451 function tableName( $name ) {
1452 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1453 # Skip the entire process when we have a string quoted on both ends.
1454 # Note that we check the end so that we will still quote any use of
1455 # use of `database`.table. But won't break things if someone wants
1456 # to query a database table with a dot in the name.
1457 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) return $name;
1459 # Lets test for any bits of text that should never show up in a table
1460 # name. Basically anything like JOIN or ON which are actually part of
1461 # SQL queries, but may end up inside of the table value to combine
1462 # sql. Such as how the API is doing.
1463 # Note that we use a whitespace test rather than a \b test to avoid
1464 # any remote case where a word like on may be inside of a table name
1465 # surrounded by symbols which may be considered word breaks.
1466 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) return $name;
1468 # Split database and table into proper variables.
1469 # We reverse the explode so that database.table and table both output
1470 # the correct table.
1471 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1472 if( isset( $dbDetails[1] ) ) @list
( $table, $database ) = $dbDetails;
1473 else @list
( $table ) = $dbDetails;
1474 $prefix = $this->mTablePrefix
; # Default prefix
1476 # A database name has been specified in input. Quote the table name
1477 # because we don't want any prefixes added.
1478 if( isset($database) ) $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
1480 # Note that we use the long format because php will complain in in_array if
1481 # the input is not an array, and will complain in is_array if it is not set.
1482 if( !isset( $database ) # Don't use shared database if pre selected.
1483 && isset( $wgSharedDB ) # We have a shared database
1484 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1485 && isset( $wgSharedTables )
1486 && is_array( $wgSharedTables )
1487 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1488 $database = $wgSharedDB;
1489 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1492 # Quote the $database and $table and apply the prefix if not quoted.
1493 if( isset($database) ) $database = ( $database[0] == '`' ?
$database : "`{$database}`" );
1494 $table = ( $table[0] == '`' ?
$table : "`{$prefix}{$table}`" );
1496 # Merge our database and table into our final table name.
1497 $tableName = ( isset($database) ?
"{$database}.{$table}" : "{$table}" );
1499 # We're finished, return.
1504 * Fetch a number of table names into an array
1505 * This is handy when you need to construct SQL for joins
1508 * extract($dbr->tableNames('user','watchlist'));
1509 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1510 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1512 public function tableNames() {
1513 $inArray = func_get_args();
1515 foreach ( $inArray as $name ) {
1516 $retVal[$name] = $this->tableName( $name );
1522 * Fetch a number of table names into an zero-indexed numerical array
1523 * This is handy when you need to construct SQL for joins
1526 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1527 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1528 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1530 public function tableNamesN() {
1531 $inArray = func_get_args();
1533 foreach ( $inArray as $name ) {
1534 $retVal[] = $this->tableName( $name );
1542 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1545 $use_index_safe = is_array($use_index) ?
$use_index : array();
1546 $join_conds_safe = is_array($join_conds) ?
$join_conds : array();
1547 foreach ( $tables as $table ) {
1548 // Is there a JOIN and INDEX clause for this table?
1549 if ( isset($join_conds_safe[$table]) && isset($use_index_safe[$table]) ) {
1550 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1551 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1552 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
) . ')';
1553 $retJOIN[] = $tableClause;
1554 // Is there an INDEX clause?
1555 } else if ( isset($use_index_safe[$table]) ) {
1556 $tableClause = $this->tableName( $table );
1557 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1558 $ret[] = $tableClause;
1559 // Is there a JOIN clause?
1560 } else if ( isset($join_conds_safe[$table]) ) {
1561 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1562 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
) . ')';
1563 $retJOIN[] = $tableClause;
1565 $tableClause = $this->tableName( $table );
1566 $ret[] = $tableClause;
1569 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1570 $straightJoins = !empty($ret) ?
implode( ',', $ret ) : "";
1571 $otherJoins = !empty($retJOIN) ?
implode( ' ', $retJOIN ) : "";
1572 // Compile our final table clause
1573 return implode(' ',array($straightJoins,$otherJoins) );
1577 * Wrapper for addslashes()
1578 * @param $s String: to be slashed.
1579 * @return String: slashed string.
1581 function strencode( $s ) {
1582 return mysql_real_escape_string( $s, $this->mConn
);
1586 * If it's a string, adds quotes and backslashes
1587 * Otherwise returns as-is
1589 function addQuotes( $s ) {
1590 if ( is_null( $s ) ) {
1593 # This will also quote numeric values. This should be harmless,
1594 # and protects against weird problems that occur when they really
1595 # _are_ strings such as article titles and string->number->string
1596 # conversion is not 1:1.
1597 return "'" . $this->strencode( $s ) . "'";
1602 * Escape string for safe LIKE usage
1604 function escapeLike( $s ) {
1605 $s=$this->strencode( $s );
1606 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1611 * Returns an appropriately quoted sequence value for inserting a new row.
1612 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1613 * subclass will return an integer, and save the value for insertId()
1615 function nextSequenceValue( $seqName ) {
1621 * PostgreSQL doesn't have them and returns ""
1623 function useIndexClause( $index ) {
1624 return "FORCE INDEX ($index)";
1628 * REPLACE query wrapper
1629 * PostgreSQL simulates this with a DELETE followed by INSERT
1630 * $row is the row to insert, an associative array
1631 * $uniqueIndexes is an array of indexes. Each element may be either a
1632 * field name or an array of field names
1634 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1635 * However if you do this, you run the risk of encountering errors which wouldn't have
1638 * @todo migrate comment to phodocumentor format
1640 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1641 $table = $this->tableName( $table );
1644 if ( !is_array( reset( $rows ) ) ) {
1645 $rows = array( $rows );
1648 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1650 foreach ( $rows as $row ) {
1656 $sql .= '(' . $this->makeList( $row ) . ')';
1658 return $this->query( $sql, $fname );
1662 * DELETE where the condition is a join
1663 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1665 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1666 * join condition matches, set $conds='*'
1668 * DO NOT put the join condition in $conds
1670 * @param $delTable String: The table to delete from.
1671 * @param $joinTable String: The other table.
1672 * @param $delVar String: The variable to join on, in the first table.
1673 * @param $joinVar String: The variable to join on, in the second table.
1674 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
1675 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1677 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1679 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1682 $delTable = $this->tableName( $delTable );
1683 $joinTable = $this->tableName( $joinTable );
1684 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1685 if ( $conds != '*' ) {
1686 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1689 return $this->query( $sql, $fname );
1693 * Returns the size of a text field, or -1 for "unlimited"
1695 function textFieldSize( $table, $field ) {
1696 $table = $this->tableName( $table );
1697 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1698 $res = $this->query( $sql, 'Database::textFieldSize' );
1699 $row = $this->fetchObject( $res );
1700 $this->freeResult( $res );
1703 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1712 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1714 function lowPriorityOption() {
1715 return 'LOW_PRIORITY';
1719 * DELETE query wrapper
1721 * Use $conds == "*" to delete all rows
1723 function delete( $table, $conds, $fname = 'Database::delete' ) {
1725 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1727 $table = $this->tableName( $table );
1728 $sql = "DELETE FROM $table";
1729 if ( $conds != '*' ) {
1730 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1732 return $this->query( $sql, $fname );
1736 * INSERT SELECT wrapper
1737 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1738 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1739 * $conds may be "*" to copy the whole table
1740 * srcTable may be an array of tables.
1742 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1743 $insertOptions = array(), $selectOptions = array() )
1745 $destTable = $this->tableName( $destTable );
1746 if ( is_array( $insertOptions ) ) {
1747 $insertOptions = implode( ' ', $insertOptions );
1749 if( !is_array( $selectOptions ) ) {
1750 $selectOptions = array( $selectOptions );
1752 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1753 if( is_array( $srcTable ) ) {
1754 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1756 $srcTable = $this->tableName( $srcTable );
1758 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1759 " SELECT $startOpts " . implode( ',', $varMap ) .
1760 " FROM $srcTable $useIndex ";
1761 if ( $conds != '*' ) {
1762 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1764 $sql .= " $tailOpts";
1765 return $this->query( $sql, $fname );
1769 * Construct a LIMIT query with optional offset
1770 * This is used for query pages
1771 * @param $sql String: SQL query we will append the limit too
1772 * @param $limit Integer: the SQL limit
1773 * @param $offset Integer the SQL offset (default false)
1775 function limitResult($sql, $limit, $offset=false) {
1776 if( !is_numeric($limit) ) {
1777 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1779 return "$sql LIMIT "
1780 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1783 function limitResultForUpdate($sql, $num) {
1784 return $this->limitResult($sql, $num, 0);
1788 * Returns an SQL expression for a simple conditional.
1791 * @param $cond String: SQL expression which will result in a boolean value
1792 * @param $trueVal String: SQL expression to return if true
1793 * @param $falseVal String: SQL expression to return if false
1794 * @return String: SQL fragment
1796 function conditional( $cond, $trueVal, $falseVal ) {
1797 return " IF($cond, $trueVal, $falseVal) ";
1801 * Returns a comand for str_replace function in SQL query.
1802 * Uses REPLACE() in MySQL
1804 * @param $orig String: column to modify
1805 * @param $old String: column to seek
1806 * @param $new String: column to replace with
1808 function strreplace( $orig, $old, $new ) {
1809 return "REPLACE({$orig}, {$old}, {$new})";
1813 * Determines if the last failure was due to a deadlock
1815 function wasDeadlock() {
1816 return $this->lastErrno() == 1213;
1820 * Perform a deadlock-prone transaction.
1822 * This function invokes a callback function to perform a set of write
1823 * queries. If a deadlock occurs during the processing, the transaction
1824 * will be rolled back and the callback function will be called again.
1827 * $dbw->deadlockLoop( callback, ... );
1829 * Extra arguments are passed through to the specified callback function.
1831 * Returns whatever the callback function returned on its successful,
1832 * iteration, or false on error, for example if the retry limit was
1835 function deadlockLoop() {
1836 $myFname = 'Database::deadlockLoop';
1839 $args = func_get_args();
1840 $function = array_shift( $args );
1841 $oldIgnore = $this->ignoreErrors( true );
1842 $tries = DEADLOCK_TRIES
;
1843 if ( is_array( $function ) ) {
1844 $fname = $function[0];
1849 $retVal = call_user_func_array( $function, $args );
1850 $error = $this->lastError();
1851 $errno = $this->lastErrno();
1852 $sql = $this->lastQuery();
1855 if ( $this->wasDeadlock() ) {
1857 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1859 $this->reportQueryError( $error, $errno, $sql, $fname );
1862 } while( $this->wasDeadlock() && --$tries > 0 );
1863 $this->ignoreErrors( $oldIgnore );
1864 if ( $tries <= 0 ) {
1865 $this->query( 'ROLLBACK', $myFname );
1866 $this->reportQueryError( $error, $errno, $sql, $fname );
1869 $this->query( 'COMMIT', $myFname );
1875 * Do a SELECT MASTER_POS_WAIT()
1877 * @param $pos MySQLMasterPos object
1878 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
1880 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
1881 $fname = 'Database::masterPosWait';
1882 wfProfileIn( $fname );
1884 # Commit any open transactions
1885 if ( $this->mTrxLevel
) {
1886 $this->immediateCommit();
1889 if ( !is_null( $this->mFakeSlaveLag
) ) {
1890 $wait = intval( ( $pos->pos
- microtime(true) +
$this->mFakeSlaveLag
) * 1e6
);
1891 if ( $wait > $timeout * 1e6
) {
1892 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1893 wfProfileOut( $fname );
1895 } elseif ( $wait > 0 ) {
1896 wfDebug( "Fake slave waiting $wait us\n" );
1898 wfProfileOut( $fname );
1901 wfDebug( "Fake slave up to date ($wait us)\n" );
1902 wfProfileOut( $fname );
1907 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1908 $encFile = $this->addQuotes( $pos->file
);
1909 $encPos = intval( $pos->pos
);
1910 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
1911 $res = $this->doQuery( $sql );
1912 if ( $res && $row = $this->fetchRow( $res ) ) {
1913 $this->freeResult( $res );
1914 wfProfileOut( $fname );
1917 wfProfileOut( $fname );
1923 * Get the position of the master from SHOW SLAVE STATUS
1925 function getSlavePos() {
1926 if ( !is_null( $this->mFakeSlaveLag
) ) {
1927 $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag
);
1928 wfDebug( __METHOD__
.": fake slave pos = $pos\n" );
1931 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1932 $row = $this->fetchObject( $res );
1934 $pos = isset($row->Exec_master_log_pos
) ?
$row->Exec_master_log_pos
: $row->Exec_Master_Log_Pos
;
1935 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
1942 * Get the position of the master from SHOW MASTER STATUS
1944 function getMasterPos() {
1945 if ( $this->mFakeMaster
) {
1946 return new MySQLMasterPos( 'fake', microtime( true ) );
1948 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1949 $row = $this->fetchObject( $res );
1951 return new MySQLMasterPos( $row->File
, $row->Position
);
1958 * Begin a transaction, committing any previously open transaction
1960 function begin( $fname = 'Database::begin' ) {
1961 $this->query( 'BEGIN', $fname );
1962 $this->mTrxLevel
= 1;
1968 function commit( $fname = 'Database::commit' ) {
1969 $this->query( 'COMMIT', $fname );
1970 $this->mTrxLevel
= 0;
1974 * Rollback a transaction.
1975 * No-op on non-transactional databases.
1977 function rollback( $fname = 'Database::rollback' ) {
1978 $this->query( 'ROLLBACK', $fname, true );
1979 $this->mTrxLevel
= 0;
1983 * Begin a transaction, committing any previously open transaction
1984 * @deprecated use begin()
1986 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1991 * Commit transaction, if one is open
1992 * @deprecated use commit()
1994 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1999 * Return MW-style timestamp used for MySQL schema
2001 function timestamp( $ts=0 ) {
2002 return wfTimestamp(TS_MW
,$ts);
2006 * Local database timestamp format or null
2008 function timestampOrNull( $ts = null ) {
2009 if( is_null( $ts ) ) {
2012 return $this->timestamp( $ts );
2019 function resultObject( $result ) {
2020 if( empty( $result ) ) {
2022 } elseif ( $result instanceof ResultWrapper
) {
2024 } elseif ( $result === true ) {
2025 // Successful write query
2028 return new ResultWrapper( $this, $result );
2033 * Return aggregated value alias
2035 function aggregateValue ($valuedata,$valuename='value') {
2040 * @return String: wikitext of a link to the server software's web site
2042 function getSoftwareLink() {
2043 return "[http://www.mysql.com/ MySQL]";
2047 * @return String: Version information from the database
2049 function getServerVersion() {
2050 return mysql_get_server_info( $this->mConn
);
2054 * Ping the server and try to reconnect if it there is no connection
2057 if( !function_exists( 'mysql_ping' ) ) {
2058 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
2061 $ping = mysql_ping( $this->mConn
);
2066 // Need to reconnect manually in MySQL client 5.0.13+
2067 if ( version_compare( mysql_get_client_info(), '5.0.13', '>=' ) ) {
2068 mysql_close( $this->mConn
);
2069 $this->mOpened
= false;
2070 $this->mConn
= false;
2071 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
2079 * At the moment, this will only work if the DB user has the PROCESS privilege
2082 if ( !is_null( $this->mFakeSlaveLag
) ) {
2083 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
2084 return $this->mFakeSlaveLag
;
2086 $res = $this->query( 'SHOW PROCESSLIST' );
2087 # Find slave SQL thread
2088 while ( $row = $this->fetchObject( $res ) ) {
2089 /* This should work for most situations - when default db
2090 * for thread is not specified, it had no events executed,
2091 * and therefore it doesn't know yet how lagged it is.
2093 * Relay log I/O thread does not select databases.
2095 if ( $row->User
== 'system user' &&
2096 $row->State
!= 'Waiting for master to send event' &&
2097 $row->State
!= 'Connecting to master' &&
2098 $row->State
!= 'Queueing master event to the relay log' &&
2099 $row->State
!= 'Waiting for master update' &&
2100 $row->State
!= 'Requesting binlog dump'
2102 # This is it, return the time (except -ve)
2103 if ( $row->Time
> 0x7fffffff ) {
2114 * Get status information from SHOW STATUS in an associative array
2116 function getStatus($which="%") {
2117 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2119 while ( $row = $this->fetchObject( $res ) ) {
2120 $status[$row->Variable_name
] = $row->Value
;
2126 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2128 function maxListLen() {
2132 function encodeBlob($b) {
2136 function decodeBlob($b) {
2141 * Override database's default connection timeout.
2142 * May be useful for very long batch queries such as
2143 * full-wiki dumps, where a single query reads out
2144 * over hours or days.
2145 * @param $timeout Integer in seconds
2147 public function setTimeout( $timeout ) {
2148 $this->query( "SET net_read_timeout=$timeout" );
2149 $this->query( "SET net_write_timeout=$timeout" );
2153 * Read and execute SQL commands from a file.
2154 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2155 * @param $filename String: File name to open
2156 * @param $lineCallback Callback: Optional function called before reading each line
2157 * @param $resultCallback Callback: Optional function called for each MySQL result
2159 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2160 $fp = fopen( $filename, 'r' );
2161 if ( false === $fp ) {
2162 throw new MWException( "Could not open \"{$filename}\".\n" );
2164 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2170 * Read and execute commands from an open file handle
2171 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2172 * @param $fp String: File handle
2173 * @param $lineCallback Callback: Optional function called before reading each line
2174 * @param $resultCallback Callback: Optional function called for each MySQL result
2176 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2179 $dollarquote = false;
2181 while ( ! feof( $fp ) ) {
2182 if ( $lineCallback ) {
2183 call_user_func( $lineCallback );
2185 $line = trim( fgets( $fp, 1024 ) );
2186 $sl = strlen( $line ) - 1;
2188 if ( $sl < 0 ) { continue; }
2189 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2191 ## Allow dollar quoting for function declarations
2192 if (substr($line,0,4) == '$mw$') {
2194 $dollarquote = false;
2198 $dollarquote = true;
2201 else if (!$dollarquote) {
2202 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
2204 $line = substr( $line, 0, $sl );
2208 if ( '' != $cmd ) { $cmd .= ' '; }
2212 $cmd = str_replace(';;', ";", $cmd);
2213 $cmd = $this->replaceVars( $cmd );
2214 $res = $this->query( $cmd, __METHOD__
);
2215 if ( $resultCallback ) {
2216 call_user_func( $resultCallback, $res, $this );
2219 if ( false === $res ) {
2220 $err = $this->lastError();
2221 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2233 * Replace variables in sourced SQL
2235 protected function replaceVars( $ins ) {
2237 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2238 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2239 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2242 // Ordinary variables
2243 foreach ( $varnames as $var ) {
2244 if( isset( $GLOBALS[$var] ) ) {
2245 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2246 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2247 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2248 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2253 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-zA-Z_0-9]*)/',
2254 array( &$this, 'tableNameCallback' ), $ins );
2259 * Table name callback
2262 protected function tableNameCallback( $matches ) {
2263 return $this->tableName( $matches[1] );
2267 * Build a concatenation list to feed into a SQL query
2269 function buildConcat( $stringList ) {
2270 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2276 * Abstracted from Filestore::lock() so child classes can implement for
2279 * @param $lockName String: Name of lock to aquire
2280 * @param $method String: Name of method calling us
2283 public function lock( $lockName, $method ) {
2284 $lockName = $this->addQuotes( $lockName );
2285 $result = $this->query( "SELECT GET_LOCK($lockName, 5) AS lockstatus", $method );
2286 $row = $this->fetchObject( $result );
2287 $this->freeResult( $result );
2289 if( $row->lockstatus
== 1 ) {
2292 wfDebug( __METHOD__
." failed to acquire lock\n" );
2299 * @todo fixme - Figure out a way to return a bool
2300 * based on successful lock release.
2302 * @param $lockName String: Name of lock to release
2303 * @param $method String: Name of method calling us
2305 public function unlock( $lockName, $method ) {
2306 $lockName = $this->addQuotes( $lockName );
2307 $result = $this->query( "SELECT RELEASE_LOCK($lockName)", $method );
2308 $this->freeResult( $result );
2312 * Get search engine class. All subclasses of this
2313 * need to implement this if they wish to use searching.
2317 public function getSearchEngine() {
2318 return "SearchMySQL";
2323 * Database abstraction object for mySQL
2324 * Inherit all methods and properties of Database::Database()
2329 class DatabaseMysql
extends Database
{
2333 /******************************************************************************
2335 *****************************************************************************/
2344 function DBObject($data) {
2345 $this->mData
= $data;
2353 return $this->mData
;
2361 * This allows us to distinguish a blob from a normal string and an array of strings
2365 function __construct($data) {
2366 $this->mData
= $data;
2369 return $this->mData
;
2378 private $name, $tablename, $default, $max_length, $nullable,
2379 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2380 function __construct ($info) {
2381 $this->name
= $info->name
;
2382 $this->tablename
= $info->table
;
2383 $this->default = $info->def
;
2384 $this->max_length
= $info->max_length
;
2385 $this->nullable
= !$info->not_null
;
2386 $this->is_pk
= $info->primary_key
;
2387 $this->is_unique
= $info->unique_key
;
2388 $this->is_multiple
= $info->multiple_key
;
2389 $this->is_key
= ($this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
2390 $this->type
= $info->type
;
2397 function tableName() {
2398 return $this->tableName
;
2401 function defaultValue() {
2402 return $this->default;
2405 function maxLength() {
2406 return $this->max_length
;
2409 function nullable() {
2410 return $this->nullable
;
2414 return $this->is_key
;
2417 function isMultipleKey() {
2418 return $this->is_multiple
;
2426 /******************************************************************************
2428 *****************************************************************************/
2431 * Database error base class
2434 class DBError
extends MWException
{
2438 * Construct a database error
2439 * @param $db Database object which threw the error
2440 * @param $error A simple error message to be used for debugging
2442 function __construct( Database
&$db, $error ) {
2444 parent
::__construct( $error );
2451 class DBConnectionError
extends DBError
{
2454 function __construct( Database
&$db, $error = 'unknown error' ) {
2455 $msg = 'DB connection error';
2456 if ( trim( $error ) != '' ) {
2459 $this->error
= $error;
2460 parent
::__construct( $db, $msg );
2463 function useOutputPage() {
2464 // Not likely to work
2468 function useMessageCache() {
2469 // Not likely to work
2473 function getText() {
2474 return $this->getMessage() . "\n";
2477 function getLogMessage() {
2478 # Don't send to the exception log
2482 function getPageTitle() {
2484 return "$wgSitename has a problem";
2487 function getHTML() {
2488 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding;
2489 global $wgSitename, $wgServer, $wgMessageCache;
2491 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
2492 # Hard coding strings instead.
2494 $noconnect = "<p><strong>Sorry! This site is experiencing technical difficulties.</strong></p><p>Try waiting a few minutes and reloading.</p><p><small>(Can't contact the database server: $1)</small></p>";
2495 $mainpage = 'Main Page';
2496 $searchdisabled = <<<EOT
2497 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
2498 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
2502 <!-- SiteSearch Google -->
2503 <FORM method=GET action=\"http://www.google.com/search\">
2504 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
2505 <A HREF=\"http://www.google.com/\">
2506 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
2507 border=\"0\" ALT=\"Google\"></A>
2510 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
2511 <INPUT type=submit name=btnG VALUE=\"Google Search\">
2513 <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 />
2514 <input type='hidden' name='ie' value='$2'>
2515 <input type='hidden' name='oe' value='$2'>
2519 <!-- SiteSearch Google -->";
2520 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
2522 # No database access
2523 if ( is_object( $wgMessageCache ) ) {
2524 $wgMessageCache->disable();
2527 if ( trim( $this->error
) == '' ) {
2528 $this->error
= $this->db
->getProperty('mServer');
2531 $text = str_replace( '$1', $this->error
, $noconnect );
2534 if ( $GLOBALS['wgShowExceptionDetails'] ) {
2535 $text .= '</p><p>Backtrace:</p><p>' .
2536 nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
2540 if($wgUseFileCache) {
2545 $t = Title
::newFromURL( $title );
2546 } elseif (@/**/$_REQUEST['search']) {
2547 $search = $_REQUEST['search'];
2548 return $searchdisabled .
2549 str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
2550 $wgInputEncoding ), $googlesearch );
2552 $t = Title
::newFromText( $mainpage );
2556 $cache = new HTMLFileCache( $t );
2557 if( $cache->isFileCached() ) {
2558 // @todo, FIXME: $msg is not defined on the next line.
2559 $msg = '<p style="color: red"><b>'.$text."<br />\n" .
2560 $cachederror . "</b></p>\n";
2562 $tag = '<div id="article">';
2563 $text = str_replace(
2566 $cache->fetchPageText() );
2577 class DBQueryError
extends DBError
{
2578 public $error, $errno, $sql, $fname;
2580 function __construct( Database
&$db, $error, $errno, $sql, $fname ) {
2581 $message = "A database error has occurred\n" .
2583 "Function: $fname\n" .
2584 "Error: $errno $error\n";
2586 parent
::__construct( $db, $message );
2587 $this->error
= $error;
2588 $this->errno
= $errno;
2590 $this->fname
= $fname;
2593 function getText() {
2594 if ( $this->useMessageCache() ) {
2595 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2596 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
2598 return $this->getMessage();
2603 global $wgShowSQLErrors;
2604 if( !$wgShowSQLErrors ) {
2605 return $this->msg( 'sqlhidden', 'SQL hidden' );
2611 function getLogMessage() {
2612 # Don't send to the exception log
2616 function getPageTitle() {
2617 return $this->msg( 'databaseerror', 'Database error' );
2620 function getHTML() {
2621 if ( $this->useMessageCache() ) {
2622 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2623 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
2625 return nl2br( htmlspecialchars( $this->getMessage() ) );
2633 class DBUnexpectedError
extends DBError
{}
2637 * Result wrapper for grabbing data queried by someone else
2640 class ResultWrapper
implements Iterator
{
2641 var $db, $result, $pos = 0, $currentRow = null;
2644 * Create a new result object from a result resource and a Database object
2646 function ResultWrapper( $database, $result ) {
2647 $this->db
= $database;
2648 if ( $result instanceof ResultWrapper
) {
2649 $this->result
= $result->result
;
2651 $this->result
= $result;
2656 * Get the number of rows in a result object
2658 function numRows() {
2659 return $this->db
->numRows( $this->result
);
2663 * Fetch the next row from the given result object, in object form.
2664 * Fields can be retrieved with $row->fieldname, with fields acting like
2667 * @param $res SQL result object as returned from Database::query(), etc.
2668 * @return MySQL row object
2669 * @throws DBUnexpectedError Thrown if the database returns an error
2671 function fetchObject() {
2672 return $this->db
->fetchObject( $this->result
);
2676 * Fetch the next row from the given result object, in associative array
2677 * form. Fields are retrieved with $row['fieldname'].
2679 * @param $res SQL result object as returned from Database::query(), etc.
2680 * @return MySQL row object
2681 * @throws DBUnexpectedError Thrown if the database returns an error
2683 function fetchRow() {
2684 return $this->db
->fetchRow( $this->result
);
2688 * Free a result object
2691 $this->db
->freeResult( $this->result
);
2692 unset( $this->result
);
2697 * Change the position of the cursor in a result object
2698 * See mysql_data_seek()
2700 function seek( $row ) {
2701 $this->db
->dataSeek( $this->result
, $row );
2704 /*********************
2705 * Iterator functions
2706 * Note that using these in combination with the non-iterator functions
2707 * above may cause rows to be skipped or repeated.
2711 if ($this->numRows()) {
2712 $this->db
->dataSeek($this->result
, 0);
2715 $this->currentRow
= null;
2718 function current() {
2719 if ( is_null( $this->currentRow
) ) {
2722 return $this->currentRow
;
2731 $this->currentRow
= $this->fetchObject();
2732 return $this->currentRow
;
2736 return $this->current() !== false;
2740 class MySQLMasterPos
{
2743 function __construct( $file, $pos ) {
2744 $this->file
= $file;
2748 function __toString() {
2749 return "{$this->file}/{$this->pos}";