3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
8 /** Number of times to re-try an operation in case of deadlock */
9 define( 'DEADLOCK_TRIES', 4 );
10 /** Minimum time to wait before retry, in microseconds */
11 define( 'DEADLOCK_DELAY_MIN', 500000 );
12 /** Maximum time to wait before retry */
13 define( 'DEADLOCK_DELAY_MAX', 1500000 );
15 /******************************************************************************
17 *****************************************************************************/
22 function DBObject($data) {
35 /******************************************************************************
37 *****************************************************************************/
40 * Database error base class
42 class DBError
extends MWException
{
46 * Construct a database error
47 * @param Database $db The database object which threw the error
48 * @param string $error A simple error message to be used for debugging
50 function __construct( Database
&$db, $error ) {
52 parent
::__construct( $error );
56 class DBConnectionError
extends DBError
{
59 function __construct( Database
&$db, $error = 'unknown error' ) {
60 $msg = 'DB connection error';
61 if ( trim( $error ) != '' ) {
64 $this->error
= $error;
65 parent
::__construct( $db, $msg );
68 function useOutputPage() {
73 function useMessageCache() {
79 return $this->getMessage() . "\n";
82 function getLogMessage() {
83 # Don't send to the exception log
87 function getPageTitle() {
89 return "$wgSitename has a problem";
93 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
94 global $wgSitename, $wgServer, $wgMessageCache, $wgLogo;
96 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
97 # Hard coding strings instead.
99 $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>";
100 $mainpage = 'Main Page';
101 $searchdisabled = <<<EOT
102 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
103 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
107 <!-- SiteSearch Google -->
108 <FORM method=GET action=\"http://www.google.com/search\">
109 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
110 <A HREF=\"http://www.google.com/\">
111 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
112 border=\"0\" ALT=\"Google\"></A>
115 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
116 <INPUT type=submit name=btnG VALUE=\"Google Search\">
118 <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 />
119 <input type='hidden' name='ie' value='$2'>
120 <input type='hidden' name='oe' value='$2'>
124 <!-- SiteSearch Google -->";
125 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
128 if ( is_object( $wgMessageCache ) ) {
129 $wgMessageCache->disable();
132 if ( trim( $this->error
) == '' ) {
133 $this->error
= $this->db
->getProperty('mServer');
136 $text = str_replace( '$1', $this->error
, $noconnect );
137 $text .= wfGetSiteNotice();
139 if($wgUseFileCache) {
144 $t = Title
::newFromURL( $title );
145 } elseif (@/**/$_REQUEST['search']) {
146 $search = $_REQUEST['search'];
147 return $searchdisabled .
148 str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
149 $wgInputEncoding ), $googlesearch );
151 $t = Title
::newFromText( $mainpage );
155 $cache = new HTMLFileCache( $t );
156 if( $cache->isFileCached() ) {
157 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
158 $cachederror . "</b></p>\n";
160 $tag = '<div id="article">';
164 $cache->fetchPageText() );
172 class DBQueryError
extends DBError
{
173 public $error, $errno, $sql, $fname;
175 function __construct( Database
&$db, $error, $errno, $sql, $fname ) {
176 $message = "A database error has occurred\n" .
178 "Function: $fname\n" .
179 "Error: $errno $error\n";
181 parent
::__construct( $db, $message );
182 $this->error
= $error;
183 $this->errno
= $errno;
185 $this->fname
= $fname;
189 if ( $this->useMessageCache() ) {
190 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
191 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
193 return $this->getMessage();
198 global $wgShowSQLErrors;
199 if( !$wgShowSQLErrors ) {
200 return $this->msg( 'sqlhidden', 'SQL hidden' );
206 function getLogMessage() {
207 # Don't send to the exception log
211 function getPageTitle() {
212 return $this->msg( 'databaseerror', 'Database error' );
216 if ( $this->useMessageCache() ) {
217 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
218 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
220 return nl2br( htmlspecialchars( $this->getMessage() ) );
225 class DBUnexpectedError
extends DBError
{}
227 /******************************************************************************/
230 * Database abstraction object
235 #------------------------------------------------------------------------------
237 #------------------------------------------------------------------------------
239 protected $mLastQuery = '';
241 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
242 protected $mOut, $mOpened = false;
244 protected $mFailFunction;
245 protected $mTablePrefix;
247 protected $mTrxLevel = 0;
248 protected $mErrorCount = 0;
249 protected $mLBInfo = array();
250 protected $mCascadingDeletes = false;
251 protected $mCleanupTriggers = false;
252 protected $mStrictIPs = false;
254 #------------------------------------------------------------------------------
256 #------------------------------------------------------------------------------
257 # These optionally set a variable and return the previous state
260 * Fail function, takes a Database as a parameter
261 * Set to false for default, 1 for ignore errors
263 function failFunction( $function = NULL ) {
264 return wfSetVar( $this->mFailFunction
, $function );
268 * Output page, used for reporting errors
269 * FALSE means discard output
271 function setOutputPage( $out ) {
276 * Boolean, controls output of large amounts of debug information
278 function debug( $debug = NULL ) {
279 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
283 * Turns buffering of SQL result sets on (true) or off (false).
284 * Default is "on" and it should not be changed without good reasons.
286 function bufferResults( $buffer = NULL ) {
287 if ( is_null( $buffer ) ) {
288 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
290 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
295 * Turns on (false) or off (true) the automatic generation and sending
296 * of a "we're sorry, but there has been a database error" page on
297 * database errors. Default is on (false). When turned off, the
298 * code should use wfLastErrno() and wfLastError() to handle the
299 * situation as appropriate.
301 function ignoreErrors( $ignoreErrors = NULL ) {
302 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
306 * The current depth of nested transactions
307 * @param $level Integer: , default NULL.
309 function trxLevel( $level = NULL ) {
310 return wfSetVar( $this->mTrxLevel
, $level );
314 * Number of errors logged, only useful when errors are ignored
316 function errorCount( $count = NULL ) {
317 return wfSetVar( $this->mErrorCount
, $count );
321 * Properties passed down from the server info array of the load balancer
323 function getLBInfo( $name = NULL ) {
324 if ( is_null( $name ) ) {
325 return $this->mLBInfo
;
327 if ( array_key_exists( $name, $this->mLBInfo
) ) {
328 return $this->mLBInfo
[$name];
335 function setLBInfo( $name, $value = NULL ) {
336 if ( is_null( $value ) ) {
337 $this->mLBInfo
= $name;
339 $this->mLBInfo
[$name] = $value;
344 * Returns true if this database supports (and uses) cascading deletes
346 function cascadingDeletes() {
347 return $this->mCascadingDeletes
;
351 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
353 function cleanupTriggers() {
354 return $this->mCleanupTriggers
;
358 * Returns true if this database is strict about what can be put into an IP field.
359 * Specifically, it uses a NULL value instead of an empty string.
361 function strictIPs() {
362 return $this->mStrictIPs
;
368 function lastQuery() { return $this->mLastQuery
; }
369 function isOpen() { return $this->mOpened
; }
372 function setFlag( $flag ) {
373 $this->mFlags |
= $flag;
376 function clearFlag( $flag ) {
377 $this->mFlags
&= ~
$flag;
380 function getFlag( $flag ) {
381 return !!($this->mFlags
& $flag);
385 * General read-only accessor
387 function getProperty( $name ) {
391 #------------------------------------------------------------------------------
393 #------------------------------------------------------------------------------
396 * @param string $server database server host
397 * @param string $user database user name
398 * @param string $password database user password
399 * @param string $dbname database name
403 * @param failFunction
405 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
407 function __construct( $server = false, $user = false, $password = false, $dbName = false,
408 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
410 global $wgOut, $wgDBprefix, $wgCommandLineMode;
411 # Can't get a reference if it hasn't been set yet
412 if ( !isset( $wgOut ) ) {
415 $this->mOut
=& $wgOut;
417 $this->mFailFunction
= $failFunction;
418 $this->mFlags
= $flags;
420 if ( $this->mFlags
& DBO_DEFAULT
) {
421 if ( $wgCommandLineMode ) {
422 $this->mFlags
&= ~DBO_TRX
;
424 $this->mFlags |
= DBO_TRX
;
429 // Faster read-only access
430 if ( wfReadOnly() ) {
431 $this->mFlags |= DBO_PERSISTENT;
432 $this->mFlags &= ~DBO_TRX;
435 /** Get the default table prefix*/
436 if ( $tablePrefix == 'get from global' ) {
437 $this->mTablePrefix
= $wgDBprefix;
439 $this->mTablePrefix
= $tablePrefix;
443 $this->open( $server, $user, $password, $dbName );
449 * @param failFunction
452 static function newFromParams( $server, $user, $password, $dbName,
453 $failFunction = false, $flags = 0 )
455 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
459 * Usually aborts on failure
460 * If the failFunction is set to a non-zero integer, returns success
462 function open( $server, $user, $password, $dbName ) {
464 wfProfileIn( __METHOD__
);
466 # Test for missing mysql.so
467 # First try to load it
468 if (!@extension_loaded
('mysql')) {
473 # Otherwise we get a suppressed fatal error, which is very hard to track down
474 if ( !function_exists( 'mysql_connect' ) ) {
475 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
479 $this->mServer
= $server;
480 $this->mUser
= $user;
481 $this->mPassword
= $password;
482 $this->mDBname
= $dbName;
486 wfProfileIn("dbconnect-$server");
488 # LIVE PATCH by Tim, ask Domas for why: retry loop
489 $this->mConn
= false;
491 for ( $i = 0; $i < $max && !$this->mConn
; $i++
) {
495 if ( $this->mFlags
& DBO_PERSISTENT
) {
496 @/**/$this->mConn
= mysql_pconnect( $server, $user, $password );
498 # Create a new connection...
499 @/**/$this->mConn
= mysql_connect( $server, $user, $password, true );
501 if ($this->mConn
=== false) {
503 wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
507 wfProfileOut("dbconnect-$server");
509 if ( $dbName != '' ) {
510 if ( $this->mConn
!== false ) {
511 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
513 $error = "Error selecting database $dbName on server {$this->mServer} " .
514 "from client host {$wguname['nodename']}\n";
515 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
519 wfDebug( "DB connection error\n" );
520 wfDebug( "Server: $server, User: $user, Password: " .
521 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
526 $success = (bool)$this->mConn
;
532 // Tell the server we're communicating with it in UTF-8.
533 // This may engage various charset conversions.
534 $this->query( 'SET NAMES utf8' );
537 $this->reportConnectionError();
540 $this->mOpened
= $success;
541 wfProfileOut( __METHOD__
);
547 * Closes a database connection.
548 * if it is open : commits any open transactions
550 * @return bool operation success. true if already closed.
554 $this->mOpened
= false;
555 if ( $this->mConn
) {
556 if ( $this->trxLevel() ) {
557 $this->immediateCommit();
559 return mysql_close( $this->mConn
);
566 * @param string $error fallback error message, used if none is given by MySQL
568 function reportConnectionError( $error = 'Unknown error' ) {
569 $myError = $this->lastError();
574 if ( $this->mFailFunction
) {
575 # Legacy error handling method
576 if ( !is_int( $this->mFailFunction
) ) {
577 $ff = $this->mFailFunction
;
578 $ff( $this, $error );
582 wfLogDBError( "Connection error: $error\n" );
583 throw new DBConnectionError( $this, $error );
588 * Usually aborts on failure
589 * If errors are explicitly ignored, returns success
591 function query( $sql, $fname = '', $tempIgnore = false ) {
594 if ( $wgProfiling ) {
595 # generalizeSQL will probably cut down the query to reasonable
596 # logging size most of the time. The substr is really just a sanity check.
598 # Who's been wasting my precious column space? -- TS
599 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
601 if ( is_null( $this->getLBInfo( 'master' ) ) ) {
602 $queryProf = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
603 $totalProf = 'Database::query';
605 $queryProf = 'query-m: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
606 $totalProf = 'Database::query-master';
608 wfProfileIn( $totalProf );
609 wfProfileIn( $queryProf );
612 $this->mLastQuery
= $sql;
614 # Add a comment for easy SHOW PROCESSLIST interpretation
616 $commentedSql = preg_replace("/\s/", " /* $fname */ ", $sql, 1);
618 $commentedSql = $sql;
621 # If DBO_TRX is set, start a transaction
622 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
623 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK'
628 if ( $this->debug() ) {
629 $sqlx = substr( $commentedSql, 0, 500 );
630 $sqlx = strtr( $sqlx, "\t\n", ' ' );
631 wfDebug( "SQL: $sqlx\n" );
634 # Do the query and handle errors
635 $ret = $this->doQuery( $commentedSql );
637 # Try reconnecting if the connection was lost
638 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
639 # Transaction is gone, like it or not
640 $this->mTrxLevel
= 0;
641 wfDebug( "Connection lost, reconnecting...\n" );
642 if ( $this->ping() ) {
643 wfDebug( "Reconnected\n" );
644 $ret = $this->doQuery( $commentedSql );
646 wfDebug( "Failed\n" );
650 if ( false === $ret ) {
651 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
654 if ( $wgProfiling ) {
655 wfProfileOut( $queryProf );
656 wfProfileOut( $totalProf );
662 * The DBMS-dependent part of query()
663 * @param string $sql SQL query.
665 function doQuery( $sql ) {
666 if( $this->bufferResults() ) {
667 $ret = mysql_query( $sql, $this->mConn
);
669 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
678 * @param string $fname
679 * @param bool $tempIgnore
681 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
682 global $wgCommandLineMode, $wgFullyInitialised, $wgColorErrors;
683 # Ignore errors during error handling to avoid infinite recursion
684 $ignore = $this->ignoreErrors( true );
685 ++
$this->mErrorCount
;
687 if( $ignore ||
$tempIgnore ) {
688 wfDebug("SQL ERROR (ignored): $error\n");
689 $this->ignoreErrors( $ignore );
691 $sql1line = str_replace( "\n", "\\n", $sql );
692 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
693 wfDebug("SQL ERROR: " . $error . "\n");
694 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
700 * Intended to be compatible with the PEAR::DB wrapper functions.
701 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
703 * ? = scalar value, quoted as necessary
704 * ! = raw SQL bit (a function for instance)
705 * & = filename; reads the file and inserts as a blob
706 * (we don't use this though...)
708 function prepare( $sql, $func = 'Database::prepare' ) {
709 /* MySQL doesn't support prepared statements (yet), so just
710 pack up the query for reference. We'll manually replace
712 return array( 'query' => $sql, 'func' => $func );
715 function freePrepared( $prepared ) {
716 /* No-op for MySQL */
720 * Execute a prepared query with the various arguments
721 * @param string $prepared the prepared sql
722 * @param mixed $args Either an array here, or put scalars as varargs
724 function execute( $prepared, $args = null ) {
725 if( !is_array( $args ) ) {
727 $args = func_get_args();
728 array_shift( $args );
730 $sql = $this->fillPrepared( $prepared['query'], $args );
731 return $this->query( $sql, $prepared['func'] );
735 * Prepare & execute an SQL statement, quoting and inserting arguments
736 * in the appropriate places.
737 * @param string $query
738 * @param string $args ...
740 function safeQuery( $query, $args = null ) {
741 $prepared = $this->prepare( $query, 'Database::safeQuery' );
742 if( !is_array( $args ) ) {
744 $args = func_get_args();
745 array_shift( $args );
747 $retval = $this->execute( $prepared, $args );
748 $this->freePrepared( $prepared );
753 * For faking prepared SQL statements on DBs that don't support
755 * @param string $preparedSql - a 'preparable' SQL statement
756 * @param array $args - array of arguments to fill it with
757 * @return string executable SQL
759 function fillPrepared( $preparedQuery, $args ) {
761 $this->preparedArgs
=& $args;
762 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
763 array( &$this, 'fillPreparedArg' ), $preparedQuery );
767 * preg_callback func for fillPrepared()
768 * The arguments should be in $this->preparedArgs and must not be touched
769 * while we're doing this.
771 * @param array $matches
775 function fillPreparedArg( $matches ) {
776 switch( $matches[1] ) {
777 case '\\?': return '?';
778 case '\\!': return '!';
779 case '\\&': return '&';
781 list( $n, $arg ) = each( $this->preparedArgs
);
782 switch( $matches[1] ) {
783 case '?': return $this->addQuotes( $arg );
784 case '!': return $arg;
786 # return $this->addQuotes( file_get_contents( $arg ) );
787 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
789 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
794 * @param mixed $res A SQL result
797 * Free a result object
799 function freeResult( $res ) {
800 if ( !@/**/mysql_free_result( $res ) ) {
801 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
806 * Fetch the next row from the given result object, in object form
808 function fetchObject( $res ) {
809 @/**/$row = mysql_fetch_object( $res );
810 if( $this->lastErrno() ) {
811 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
817 * Fetch the next row from the given result object
820 function fetchRow( $res ) {
821 @/**/$row = mysql_fetch_array( $res );
822 if ( $this->lastErrno() ) {
823 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
829 * Get the number of rows in a result object
831 function numRows( $res ) {
832 @/**/$n = mysql_num_rows( $res );
833 if( $this->lastErrno() ) {
834 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
840 * Get the number of fields in a result object
841 * See documentation for mysql_num_fields()
843 function numFields( $res ) { return mysql_num_fields( $res ); }
846 * Get a field name in a result object
847 * See documentation for mysql_field_name():
848 * http://www.php.net/mysql_field_name
850 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
853 * Get the inserted value of an auto-increment row
855 * The value inserted should be fetched from nextSequenceValue()
858 * $id = $dbw->nextSequenceValue('page_page_id_seq');
859 * $dbw->insert('page',array('page_id' => $id));
860 * $id = $dbw->insertId();
862 function insertId() { return mysql_insert_id( $this->mConn
); }
865 * Change the position of the cursor in a result object
866 * See mysql_data_seek()
868 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
871 * Get the last error number
874 function lastErrno() {
875 if ( $this->mConn
) {
876 return mysql_errno( $this->mConn
);
878 return mysql_errno();
883 * Get a description of the last error
884 * See mysql_error() for more details
886 function lastError() {
887 if ( $this->mConn
) {
888 # Even if it's non-zero, it can still be invalid
889 wfSuppressWarnings();
890 $error = mysql_error( $this->mConn
);
892 $error = mysql_error();
896 $error = mysql_error();
899 $error .= ' (' . $this->mServer
. ')';
904 * Get the number of rows affected by the last write query
905 * See mysql_affected_rows() for more details
907 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
908 /**#@-*/ // end of template : @param $result
911 * Simple UPDATE wrapper
912 * Usually aborts on failure
913 * If errors are explicitly ignored, returns success
915 * This function exists for historical reasons, Database::update() has a more standard
916 * calling convention and feature set
918 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
920 $table = $this->tableName( $table );
921 $sql = "UPDATE $table SET $var = '" .
922 $this->strencode( $value ) . "' WHERE ($cond)";
923 return (bool)$this->query( $sql, $fname );
927 * Simple SELECT wrapper, returns a single field, input must be encoded
928 * Usually aborts on failure
929 * If errors are explicitly ignored, returns FALSE on failure
931 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
932 if ( !is_array( $options ) ) {
933 $options = array( $options );
935 $options['LIMIT'] = 1;
937 $res = $this->select( $table, $var, $cond, $fname, $options );
938 if ( $res === false ||
!$this->numRows( $res ) ) {
941 $row = $this->fetchRow( $res );
942 if ( $row !== false ) {
943 $this->freeResult( $res );
951 * Returns an optional USE INDEX clause to go after the table, and a
952 * string to go at the end of the query
956 * @param array $options an associative array of options to be turned into
957 * an SQL query, valid keys are listed in the function.
960 function makeSelectOptions( $options ) {
964 $noKeyOptions = array();
965 foreach ( $options as $key => $option ) {
966 if ( is_numeric( $key ) ) {
967 $noKeyOptions[$option] = true;
971 if ( isset( $options['GROUP BY'] ) ) $tailOpts .= " GROUP BY {$options['GROUP BY']}";
972 if ( isset( $options['ORDER BY'] ) ) $tailOpts .= " ORDER BY {$options['ORDER BY']}";
974 if (isset($options['LIMIT'])) {
975 $tailOpts .= $this->limitResult('', $options['LIMIT'],
976 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
979 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
980 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
981 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
983 # Various MySQL extensions
984 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
985 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
986 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
987 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
988 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
989 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
990 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
992 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
993 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
998 return array( $startOpts, $useIndex, $tailOpts );
1004 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
1006 if( is_array( $vars ) ) {
1007 $vars = implode( ',', $vars );
1009 if( !is_array( $options ) ) {
1010 $options = array( $options );
1012 if( is_array( $table ) ) {
1013 if ( @is_array
( $options['USE INDEX'] ) )
1014 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
1016 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1017 } elseif ($table!='') {
1018 $from = ' FROM ' . $this->tableName( $table );
1023 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
1025 if( !empty( $conds ) ) {
1026 if ( is_array( $conds ) ) {
1027 $conds = $this->makeList( $conds, LIST_AND
);
1029 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $tailOpts";
1031 $sql = "SELECT $startOpts $vars $from $useIndex $tailOpts";
1034 return $this->query( $sql, $fname );
1038 * Single row SELECT wrapper
1039 * Aborts or returns FALSE on error
1041 * $vars: the selected variables
1042 * $conds: a condition map, terms are ANDed together.
1043 * Items with numeric keys are taken to be literal conditions
1044 * Takes an array of selected variables, and a condition map, which is ANDed
1045 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1046 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1047 * $obj- >page_id is the ID of the Astronomy article
1049 * @todo migrate documentation to phpdocumentor format
1051 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
1052 $options['LIMIT'] = 1;
1053 $res = $this->select( $table, $vars, $conds, $fname, $options );
1054 if ( $res === false )
1056 if ( !$this->numRows($res) ) {
1057 $this->freeResult($res);
1060 $obj = $this->fetchObject( $res );
1061 $this->freeResult( $res );
1067 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1068 * It's only slightly flawed. Don't use for anything important.
1070 * @param string $sql A SQL Query
1073 static function generalizeSQL( $sql ) {
1074 # This does the same as the regexp below would do, but in such a way
1075 # as to avoid crashing php on some large strings.
1076 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1078 $sql = str_replace ( "\\\\", '', $sql);
1079 $sql = str_replace ( "\\'", '', $sql);
1080 $sql = str_replace ( "\\\"", '', $sql);
1081 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1082 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1084 # All newlines, tabs, etc replaced by single space
1085 $sql = preg_replace ( "/\s+/", ' ', $sql);
1088 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1094 * Determines whether a field exists in a table
1095 * Usually aborts on failure
1096 * If errors are explicitly ignored, returns NULL on failure
1098 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1099 $table = $this->tableName( $table );
1100 $res = $this->query( 'DESCRIBE '.$table, $fname );
1107 while ( $row = $this->fetchObject( $res ) ) {
1108 if ( $row->Field
== $field ) {
1117 * Determines whether an index exists
1118 * Usually aborts on failure
1119 * If errors are explicitly ignored, returns NULL on failure
1121 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1122 $info = $this->indexInfo( $table, $index, $fname );
1123 if ( is_null( $info ) ) {
1126 return $info !== false;
1132 * Get information about an index into an object
1133 * Returns false if the index does not exist
1135 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1136 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1137 # SHOW INDEX should work for 3.x and up:
1138 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1139 $table = $this->tableName( $table );
1140 $sql = 'SHOW INDEX FROM '.$table;
1141 $res = $this->query( $sql, $fname );
1146 while ( $row = $this->fetchObject( $res ) ) {
1147 if ( $row->Key_name
== $index ) {
1155 * Query whether a given table exists
1157 function tableExists( $table ) {
1158 $table = $this->tableName( $table );
1159 $old = $this->ignoreErrors( true );
1160 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1161 $this->ignoreErrors( $old );
1163 $this->freeResult( $res );
1171 * mysql_fetch_field() wrapper
1172 * Returns false if the field doesn't exist
1177 function fieldInfo( $table, $field ) {
1178 $table = $this->tableName( $table );
1179 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1180 $n = mysql_num_fields( $res );
1181 for( $i = 0; $i < $n; $i++
) {
1182 $meta = mysql_fetch_field( $res, $i );
1183 if( $field == $meta->name
) {
1191 * mysql_field_type() wrapper
1193 function fieldType( $res, $index ) {
1194 return mysql_field_type( $res, $index );
1198 * Determines if a given index is unique
1200 function indexUnique( $table, $index ) {
1201 $indexInfo = $this->indexInfo( $table, $index );
1202 if ( !$indexInfo ) {
1205 return !$indexInfo->Non_unique
;
1209 * INSERT wrapper, inserts an array into a table
1211 * $a may be a single associative array, or an array of these with numeric keys, for
1214 * Usually aborts on failure
1215 * If errors are explicitly ignored, returns success
1217 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1218 # No rows to insert, easy just return now
1219 if ( !count( $a ) ) {
1223 $table = $this->tableName( $table );
1224 if ( !is_array( $options ) ) {
1225 $options = array( $options );
1227 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1229 $keys = array_keys( $a[0] );
1232 $keys = array_keys( $a );
1235 $sql = 'INSERT ' . implode( ' ', $options ) .
1236 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1240 foreach ( $a as $row ) {
1246 $sql .= '(' . $this->makeList( $row ) . ')';
1249 $sql .= '(' . $this->makeList( $a ) . ')';
1251 return (bool)$this->query( $sql, $fname );
1255 * Make UPDATE options for the Database::update function
1258 * @param array $options The options passed to Database::update
1261 function makeUpdateOptions( $options ) {
1262 if( !is_array( $options ) ) {
1263 $options = array( $options );
1266 if ( in_array( 'LOW_PRIORITY', $options ) )
1267 $opts[] = $this->lowPriorityOption();
1268 if ( in_array( 'IGNORE', $options ) )
1270 return implode(' ', $opts);
1274 * UPDATE wrapper, takes a condition array and a SET array
1276 * @param string $table The table to UPDATE
1277 * @param array $values An array of values to SET
1278 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1279 * @param string $fname The Class::Function calling this function
1281 * @param array $options An array of UPDATE options, can be one or
1282 * more of IGNORE, LOW_PRIORITY
1284 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1285 $table = $this->tableName( $table );
1286 $opts = $this->makeUpdateOptions( $options );
1287 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1288 if ( $conds != '*' ) {
1289 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1291 $this->query( $sql, $fname );
1295 * Makes a wfStrencoded list from an array
1297 * LIST_COMMA - comma separated, no field names
1298 * LIST_AND - ANDed WHERE clause (without the WHERE)
1299 * LIST_OR - ORed WHERE clause (without the WHERE)
1300 * LIST_SET - comma separated with field names, like a SET clause
1301 * LIST_NAMES - comma separated field names
1303 function makeList( $a, $mode = LIST_COMMA
) {
1304 if ( !is_array( $a ) ) {
1305 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1310 foreach ( $a as $field => $value ) {
1312 if ( $mode == LIST_AND
) {
1314 } elseif($mode == LIST_OR
) {
1322 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1323 $list .= "($value)";
1324 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array ($value) ) {
1325 $list .= $field." IN (".$this->makeList($value).") ";
1327 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1328 $list .= "$field = ";
1330 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1337 * Change the current database
1339 function selectDB( $db ) {
1340 $this->mDBname
= $db;
1341 return mysql_select_db( $db, $this->mConn
);
1345 * Format a table name ready for use in constructing an SQL query
1347 * This does two important things: it quotes table names which as necessary,
1348 * and it adds a table prefix if there is one.
1350 * All functions of this object which require a table name call this function
1351 * themselves. Pass the canonical name to such functions. This is only needed
1352 * when calling query() directly.
1354 * @param string $name database table name
1356 function tableName( $name ) {
1358 # Skip quoted literals
1359 if ( $name{0} != '`' ) {
1360 if ( $this->mTablePrefix
!== '' && strpos( '.', $name ) === false ) {
1361 $name = "{$this->mTablePrefix}$name";
1363 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1364 $name = "`$wgSharedDB`.`$name`";
1374 * Fetch a number of table names into an array
1375 * This is handy when you need to construct SQL for joins
1378 * extract($dbr->tableNames('user','watchlist'));
1379 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1380 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1382 function tableNames() {
1383 $inArray = func_get_args();
1385 foreach ( $inArray as $name ) {
1386 $retVal[$name] = $this->tableName( $name );
1394 function tableNamesWithUseIndex( $tables, $use_index ) {
1397 foreach ( $tables as $table )
1398 if ( @$use_index[$table] !== null )
1399 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1401 $ret[] = $this->tableName( $table );
1403 return implode( ',', $ret );
1407 * Wrapper for addslashes()
1408 * @param string $s String to be slashed.
1409 * @return string slashed string.
1411 function strencode( $s ) {
1412 return mysql_real_escape_string( $s, $this->mConn
);
1416 * If it's a string, adds quotes and backslashes
1417 * Otherwise returns as-is
1419 function addQuotes( $s ) {
1420 if ( is_null( $s ) ) {
1423 # This will also quote numeric values. This should be harmless,
1424 # and protects against weird problems that occur when they really
1425 # _are_ strings such as article titles and string->number->string
1426 # conversion is not 1:1.
1427 return "'" . $this->strencode( $s ) . "'";
1432 * Escape string for safe LIKE usage
1434 function escapeLike( $s ) {
1435 $s=$this->strencode( $s );
1436 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1441 * Returns an appropriately quoted sequence value for inserting a new row.
1442 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1443 * subclass will return an integer, and save the value for insertId()
1445 function nextSequenceValue( $seqName ) {
1451 * PostgreSQL doesn't have them and returns ""
1453 function useIndexClause( $index ) {
1454 return "FORCE INDEX ($index)";
1458 * REPLACE query wrapper
1459 * PostgreSQL simulates this with a DELETE followed by INSERT
1460 * $row is the row to insert, an associative array
1461 * $uniqueIndexes is an array of indexes. Each element may be either a
1462 * field name or an array of field names
1464 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1465 * However if you do this, you run the risk of encountering errors which wouldn't have
1468 * @todo migrate comment to phodocumentor format
1470 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1471 $table = $this->tableName( $table );
1474 if ( !is_array( reset( $rows ) ) ) {
1475 $rows = array( $rows );
1478 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1480 foreach ( $rows as $row ) {
1486 $sql .= '(' . $this->makeList( $row ) . ')';
1488 return $this->query( $sql, $fname );
1492 * DELETE where the condition is a join
1493 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1495 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1496 * join condition matches, set $conds='*'
1498 * DO NOT put the join condition in $conds
1500 * @param string $delTable The table to delete from.
1501 * @param string $joinTable The other table.
1502 * @param string $delVar The variable to join on, in the first table.
1503 * @param string $joinVar The variable to join on, in the second table.
1504 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1506 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1508 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1511 $delTable = $this->tableName( $delTable );
1512 $joinTable = $this->tableName( $joinTable );
1513 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1514 if ( $conds != '*' ) {
1515 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1518 return $this->query( $sql, $fname );
1522 * Returns the size of a text field, or -1 for "unlimited"
1524 function textFieldSize( $table, $field ) {
1525 $table = $this->tableName( $table );
1526 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1527 $res = $this->query( $sql, 'Database::textFieldSize' );
1528 $row = $this->fetchObject( $res );
1529 $this->freeResult( $res );
1531 if ( preg_match( "/\((.*)\)/", $row->Type
, $m ) ) {
1540 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1542 function lowPriorityOption() {
1543 return 'LOW_PRIORITY';
1547 * DELETE query wrapper
1549 * Use $conds == "*" to delete all rows
1551 function delete( $table, $conds, $fname = 'Database::delete' ) {
1553 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1555 $table = $this->tableName( $table );
1556 $sql = "DELETE FROM $table";
1557 if ( $conds != '*' ) {
1558 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1560 return $this->query( $sql, $fname );
1564 * INSERT SELECT wrapper
1565 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1566 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1567 * $conds may be "*" to copy the whole table
1568 * srcTable may be an array of tables.
1570 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1571 $insertOptions = array(), $selectOptions = array() )
1573 $destTable = $this->tableName( $destTable );
1574 if ( is_array( $insertOptions ) ) {
1575 $insertOptions = implode( ' ', $insertOptions );
1577 if( !is_array( $selectOptions ) ) {
1578 $selectOptions = array( $selectOptions );
1580 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1581 if( is_array( $srcTable ) ) {
1582 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1584 $srcTable = $this->tableName( $srcTable );
1586 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1587 " SELECT $startOpts " . implode( ',', $varMap ) .
1588 " FROM $srcTable $useIndex ";
1589 if ( $conds != '*' ) {
1590 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1592 $sql .= " $tailOpts";
1593 return $this->query( $sql, $fname );
1597 * Construct a LIMIT query with optional offset
1598 * This is used for query pages
1599 * $sql string SQL query we will append the limit too
1600 * $limit integer the SQL limit
1601 * $offset integer the SQL offset (default false)
1603 function limitResult($sql, $limit, $offset=false) {
1604 if( !is_numeric($limit) ) {
1605 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1607 return " $sql LIMIT "
1608 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1611 function limitResultForUpdate($sql, $num) {
1612 return $this->limitResult($sql, $num, 0);
1616 * Returns an SQL expression for a simple conditional.
1619 * @param string $cond SQL expression which will result in a boolean value
1620 * @param string $trueVal SQL expression to return if true
1621 * @param string $falseVal SQL expression to return if false
1622 * @return string SQL fragment
1624 function conditional( $cond, $trueVal, $falseVal ) {
1625 return " IF($cond, $trueVal, $falseVal) ";
1629 * Determines if the last failure was due to a deadlock
1631 function wasDeadlock() {
1632 return $this->lastErrno() == 1213;
1636 * Perform a deadlock-prone transaction.
1638 * This function invokes a callback function to perform a set of write
1639 * queries. If a deadlock occurs during the processing, the transaction
1640 * will be rolled back and the callback function will be called again.
1643 * $dbw->deadlockLoop( callback, ... );
1645 * Extra arguments are passed through to the specified callback function.
1647 * Returns whatever the callback function returned on its successful,
1648 * iteration, or false on error, for example if the retry limit was
1651 function deadlockLoop() {
1652 $myFname = 'Database::deadlockLoop';
1655 $args = func_get_args();
1656 $function = array_shift( $args );
1657 $oldIgnore = $this->ignoreErrors( true );
1658 $tries = DEADLOCK_TRIES
;
1659 if ( is_array( $function ) ) {
1660 $fname = $function[0];
1665 $retVal = call_user_func_array( $function, $args );
1666 $error = $this->lastError();
1667 $errno = $this->lastErrno();
1668 $sql = $this->lastQuery();
1671 if ( $this->wasDeadlock() ) {
1673 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1675 $this->reportQueryError( $error, $errno, $sql, $fname );
1678 } while( $this->wasDeadlock() && --$tries > 0 );
1679 $this->ignoreErrors( $oldIgnore );
1680 if ( $tries <= 0 ) {
1681 $this->query( 'ROLLBACK', $myFname );
1682 $this->reportQueryError( $error, $errno, $sql, $fname );
1685 $this->query( 'COMMIT', $myFname );
1691 * Do a SELECT MASTER_POS_WAIT()
1693 * @param string $file the binlog file
1694 * @param string $pos the binlog position
1695 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1697 function masterPosWait( $file, $pos, $timeout ) {
1698 $fname = 'Database::masterPosWait';
1699 wfProfileIn( $fname );
1702 # Commit any open transactions
1703 $this->immediateCommit();
1705 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1706 $encFile = $this->strencode( $file );
1707 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1708 $res = $this->doQuery( $sql );
1709 if ( $res && $row = $this->fetchRow( $res ) ) {
1710 $this->freeResult( $res );
1711 wfProfileOut( $fname );
1714 wfProfileOut( $fname );
1720 * Get the position of the master from SHOW SLAVE STATUS
1722 function getSlavePos() {
1723 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1724 $row = $this->fetchObject( $res );
1726 return array( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1728 return array( false, false );
1733 * Get the position of the master from SHOW MASTER STATUS
1735 function getMasterPos() {
1736 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1737 $row = $this->fetchObject( $res );
1739 return array( $row->File
, $row->Position
);
1741 return array( false, false );
1746 * Begin a transaction, committing any previously open transaction
1748 function begin( $fname = 'Database::begin' ) {
1749 $this->query( 'BEGIN', $fname );
1750 $this->mTrxLevel
= 1;
1756 function commit( $fname = 'Database::commit' ) {
1757 $this->query( 'COMMIT', $fname );
1758 $this->mTrxLevel
= 0;
1762 * Rollback a transaction
1764 function rollback( $fname = 'Database::rollback' ) {
1765 $this->query( 'ROLLBACK', $fname );
1766 $this->mTrxLevel
= 0;
1770 * Begin a transaction, committing any previously open transaction
1771 * @deprecated use begin()
1773 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1778 * Commit transaction, if one is open
1779 * @deprecated use commit()
1781 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1786 * Return MW-style timestamp used for MySQL schema
1788 function timestamp( $ts=0 ) {
1789 return wfTimestamp(TS_MW
,$ts);
1793 * Local database timestamp format or null
1795 function timestampOrNull( $ts = null ) {
1796 if( is_null( $ts ) ) {
1799 return $this->timestamp( $ts );
1806 function resultObject( $result ) {
1807 if( empty( $result ) ) {
1810 return new ResultWrapper( $this, $result );
1815 * Return aggregated value alias
1817 function aggregateValue ($valuedata,$valuename='value') {
1822 * @return string wikitext of a link to the server software's web site
1824 function getSoftwareLink() {
1825 return "[http://www.mysql.com/ MySQL]";
1829 * @return string Version information from the database
1831 function getServerVersion() {
1832 return mysql_get_server_info();
1836 * Ping the server and try to reconnect if it there is no connection
1839 if( function_exists( 'mysql_ping' ) ) {
1840 return mysql_ping( $this->mConn
);
1842 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1849 * At the moment, this will only work if the DB user has the PROCESS privilege
1852 $res = $this->query( 'SHOW PROCESSLIST' );
1853 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1854 # dubious, but unfortunately there's no easy rigorous way
1856 while ( $row = $this->fetchObject( $res ) ) {
1857 /* This should work for most situations - when default db
1858 * for thread is not specified, it had no events executed,
1859 * and therefore it doesn't know yet how lagged it is.
1861 * Relay log I/O thread does not select databases.
1863 if ( $row->User
== 'system user' &&
1864 $row->State
!= 'Waiting for master to send event' &&
1865 $row->State
!= 'Connecting to master' &&
1866 $row->State
!= 'Queueing master event to the relay log' &&
1867 $row->State
!= 'Waiting for master update' &&
1868 $row->State
!= 'Requesting binlog dump'
1870 # This is it, return the time (except -ve)
1871 if ( $row->Time
> 0x7fffffff ) {
1882 * Get status information from SHOW STATUS in an associative array
1884 function getStatus($which="%") {
1885 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1887 while ( $row = $this->fetchObject( $res ) ) {
1888 $status[$row->Variable_name
] = $row->Value
;
1894 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1896 function maxListLen() {
1900 function encodeBlob($b) {
1904 function decodeBlob($b) {
1909 * Read and execute SQL commands from a file.
1910 * Returns true on success, error string on failure
1912 function sourceFile( $filename ) {
1913 $fp = fopen( $filename, 'r' );
1914 if ( false === $fp ) {
1915 return "Could not open \"{$filename}\".\n";
1920 $dollarquote = false;
1922 while ( ! feof( $fp ) ) {
1923 $line = trim( fgets( $fp, 1024 ) );
1924 $sl = strlen( $line ) - 1;
1926 if ( $sl < 0 ) { continue; }
1927 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
1929 ## Allow dollar quoting for function declarations
1930 if (substr($line,0,4) == '$mw$') {
1932 $dollarquote = false;
1936 $dollarquote = true;
1939 else if (!$dollarquote) {
1940 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
1942 $line = substr( $line, 0, $sl );
1946 if ( '' != $cmd ) { $cmd .= ' '; }
1950 $cmd = str_replace(';;', ";", $cmd);
1951 $cmd = $this->replaceVars( $cmd );
1952 $res = $this->query( $cmd, 'dbsource', true );
1954 if ( false === $res ) {
1955 $err = $this->lastError();
1956 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1968 * Replace variables in sourced SQL
1970 protected function replaceVars( $ins ) {
1972 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
1973 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
1974 'wgDBadminuser', 'wgDBadminpassword',
1977 // Ordinary variables
1978 foreach ( $varnames as $var ) {
1979 if( isset( $GLOBALS[$var] ) ) {
1980 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
1981 $ins = str_replace( '{$' . $var . '}', $val, $ins );
1982 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
1983 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
1988 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
1989 array( &$this, 'tableNameCallback' ), $ins );
1994 * Table name callback
1997 protected function tableNameCallback( $matches ) {
1998 return $this->tableName( $matches[1] );
2004 * Database abstraction object for mySQL
2005 * Inherit all methods and properties of Database::Database()
2007 * @package MediaWiki
2010 class DatabaseMysql
extends Database
{
2016 * Result wrapper for grabbing data queried by someone else
2018 * @package MediaWiki
2020 class ResultWrapper
{
2026 function ResultWrapper( &$database, $result ) {
2027 $this->db
=& $database;
2028 $this->result
=& $result;
2034 function numRows() {
2035 return $this->db
->numRows( $this->result
);
2041 function fetchObject() {
2042 return $this->db
->fetchObject( $this->result
);
2048 function fetchRow() {
2049 return $this->db
->fetchRow( $this->result
);
2056 $this->db
->freeResult( $this->result
);
2057 unset( $this->result
);
2061 function seek( $row ) {
2062 $this->db
->dataSeek( $this->result
, $row );