3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
8 /** See Database::makeList() */
9 define( 'LIST_COMMA', 0 );
10 define( 'LIST_AND', 1 );
11 define( 'LIST_SET', 2 );
12 define( 'LIST_NAMES', 3);
13 define( 'LIST_OR', 4);
15 /** Number of times to re-try an operation in case of deadlock */
16 define( 'DEADLOCK_TRIES', 4 );
17 /** Minimum time to wait before retry, in microseconds */
18 define( 'DEADLOCK_DELAY_MIN', 500000 );
19 /** Maximum time to wait before retry */
20 define( 'DEADLOCK_DELAY_MAX', 1500000 );
22 /******************************************************************************
24 *****************************************************************************/
29 function DBObject($data) {
42 /******************************************************************************
44 *****************************************************************************/
47 * Database error base class
49 class DBError
extends MWException
{
53 * Construct a database error
54 * @param Database $db The database object which threw the error
55 * @param string $error A simple error message to be used for debugging
57 function __construct( Database
&$db, $error ) {
59 parent
::__construct( $error );
63 class DBConnectionError
extends DBError
{
66 function __construct( Database
&$db, $error = 'unknown error' ) {
67 $msg = 'DB connection error';
68 if ( trim( $error ) != '' ) {
71 $this->error
= $error;
72 parent
::__construct( $db, $msg );
75 function useOutputPage() {
80 function useMessageCache() {
86 return $this->getMessage() . "\n";
89 function getLogMessage() {
90 # Don't send to the exception log
94 function getPageTitle() {
96 return "$wgSitename has a problem";
100 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
101 global $wgSitename, $wgServer, $wgMessageCache, $wgLogo;
103 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
104 # Hard coding strings instead.
106 $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>";
107 $mainpage = 'Main Page';
108 $searchdisabled = <<<EOT
109 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
110 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
114 <!-- SiteSearch Google -->
115 <FORM method=GET action=\"http://www.google.com/search\">
116 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
117 <A HREF=\"http://www.google.com/\">
118 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
119 border=\"0\" ALT=\"Google\"></A>
122 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
123 <INPUT type=submit name=btnG VALUE=\"Google Search\">
125 <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 />
126 <input type='hidden' name='ie' value='$2'>
127 <input type='hidden' name='oe' value='$2'>
131 <!-- SiteSearch Google -->";
132 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
135 if ( is_object( $wgMessageCache ) ) {
136 $wgMessageCache->disable();
139 if ( trim( $this->error
) == '' ) {
140 $this->error
= $this->db
->getProperty('mServer');
143 $text = str_replace( '$1', $this->error
, $noconnect );
144 $text .= wfGetSiteNotice();
146 if($wgUseFileCache) {
151 $t = Title
::newFromURL( $title );
152 } elseif (@/**/$_REQUEST['search']) {
153 $search = $_REQUEST['search'];
154 return $searchdisabled .
155 str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
156 $wgInputEncoding ), $googlesearch );
158 $t = Title
::newFromText( $mainpage );
162 $cache = new CacheManager( $t );
163 if( $cache->isFileCached() ) {
164 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
165 $cachederror . "</b></p>\n";
167 $tag = '<div id="article">';
171 $cache->fetchPageText() );
179 class DBQueryError
extends DBError
{
180 public $error, $errno, $sql, $fname;
182 function __construct( Database
&$db, $error, $errno, $sql, $fname ) {
183 $message = "A database error has occurred\n" .
185 "Function: $fname\n" .
186 "Error: $errno $error\n";
188 parent
::__construct( $db, $message );
189 $this->error
= $error;
190 $this->errno
= $errno;
192 $this->fname
= $fname;
196 if ( $this->useMessageCache() ) {
197 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
198 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
200 return $this->getMessage();
205 global $wgShowSQLErrors;
206 if( !$wgShowSQLErrors ) {
207 return $this->msg( 'sqlhidden', 'SQL hidden' );
213 function getLogMessage() {
214 # Don't send to the exception log
218 function getPageTitle() {
219 return $this->msg( 'databaseerror', 'Database error' );
223 if ( $this->useMessageCache() ) {
224 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
225 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
227 return nl2br( htmlspecialchars( $this->getMessage() ) );
232 class DBUnexpectedError
extends DBError
{}
234 /******************************************************************************/
237 * Database abstraction object
242 #------------------------------------------------------------------------------
244 #------------------------------------------------------------------------------
246 protected $mLastQuery = '';
248 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
249 protected $mOut, $mOpened = false;
251 protected $mFailFunction;
252 protected $mTablePrefix;
254 protected $mTrxLevel = 0;
255 protected $mErrorCount = 0;
256 protected $mLBInfo = array();
257 protected $mCascadingDeletes = false;
258 protected $mCleanupTriggers = false;
259 protected $mStrictIPs = false;
261 #------------------------------------------------------------------------------
263 #------------------------------------------------------------------------------
264 # These optionally set a variable and return the previous state
267 * Fail function, takes a Database as a parameter
268 * Set to false for default, 1 for ignore errors
270 function failFunction( $function = NULL ) {
271 return wfSetVar( $this->mFailFunction
, $function );
275 * Output page, used for reporting errors
276 * FALSE means discard output
278 function setOutputPage( $out ) {
283 * Boolean, controls output of large amounts of debug information
285 function debug( $debug = NULL ) {
286 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
290 * Turns buffering of SQL result sets on (true) or off (false).
291 * Default is "on" and it should not be changed without good reasons.
293 function bufferResults( $buffer = NULL ) {
294 if ( is_null( $buffer ) ) {
295 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
297 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
302 * Turns on (false) or off (true) the automatic generation and sending
303 * of a "we're sorry, but there has been a database error" page on
304 * database errors. Default is on (false). When turned off, the
305 * code should use wfLastErrno() and wfLastError() to handle the
306 * situation as appropriate.
308 function ignoreErrors( $ignoreErrors = NULL ) {
309 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
313 * The current depth of nested transactions
314 * @param $level Integer: , default NULL.
316 function trxLevel( $level = NULL ) {
317 return wfSetVar( $this->mTrxLevel
, $level );
321 * Number of errors logged, only useful when errors are ignored
323 function errorCount( $count = NULL ) {
324 return wfSetVar( $this->mErrorCount
, $count );
328 * Properties passed down from the server info array of the load balancer
330 function getLBInfo( $name = NULL ) {
331 if ( is_null( $name ) ) {
332 return $this->mLBInfo
;
334 if ( array_key_exists( $name, $this->mLBInfo
) ) {
335 return $this->mLBInfo
[$name];
342 function setLBInfo( $name, $value = NULL ) {
343 if ( is_null( $value ) ) {
344 $this->mLBInfo
= $name;
346 $this->mLBInfo
[$name] = $value;
351 * Returns true if this database supports (and uses) cascading deletes
353 function cascadingDeletes() {
354 return $this->mCascadingDeletes
;
358 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
360 function cleanupTriggers() {
361 return $this->mCleanupTriggers
;
365 * Returns true if this database is strict about what can be put into an IP field.
366 * Specifically, it uses a NULL value instead of an empty string.
368 function strictIPs() {
369 return $this->mStrictIPs
;
375 function lastQuery() { return $this->mLastQuery
; }
376 function isOpen() { return $this->mOpened
; }
379 function setFlag( $flag ) {
380 $this->mFlags |
= $flag;
383 function clearFlag( $flag ) {
384 $this->mFlags
&= ~
$flag;
387 function getFlag( $flag ) {
388 return !!($this->mFlags
& $flag);
392 * General read-only accessor
394 function getProperty( $name ) {
398 #------------------------------------------------------------------------------
400 #------------------------------------------------------------------------------
403 * @param string $server database server host
404 * @param string $user database user name
405 * @param string $password database user password
406 * @param string $dbname database name
410 * @param failFunction
412 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
414 function __construct( $server = false, $user = false, $password = false, $dbName = false,
415 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
417 global $wgOut, $wgDBprefix, $wgCommandLineMode;
418 # Can't get a reference if it hasn't been set yet
419 if ( !isset( $wgOut ) ) {
422 $this->mOut
=& $wgOut;
424 $this->mFailFunction
= $failFunction;
425 $this->mFlags
= $flags;
427 if ( $this->mFlags
& DBO_DEFAULT
) {
428 if ( $wgCommandLineMode ) {
429 $this->mFlags
&= ~DBO_TRX
;
431 $this->mFlags |
= DBO_TRX
;
436 // Faster read-only access
437 if ( wfReadOnly() ) {
438 $this->mFlags |= DBO_PERSISTENT;
439 $this->mFlags &= ~DBO_TRX;
442 /** Get the default table prefix*/
443 if ( $tablePrefix == 'get from global' ) {
444 $this->mTablePrefix
= $wgDBprefix;
446 $this->mTablePrefix
= $tablePrefix;
450 $this->open( $server, $user, $password, $dbName );
456 * @param failFunction
459 static function newFromParams( $server, $user, $password, $dbName,
460 $failFunction = false, $flags = 0 )
462 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
466 * Usually aborts on failure
467 * If the failFunction is set to a non-zero integer, returns success
469 function open( $server, $user, $password, $dbName ) {
471 wfProfileIn( __METHOD__
);
473 # Test for missing mysql.so
474 # First try to load it
475 if (!@extension_loaded
('mysql')) {
480 # Otherwise we get a suppressed fatal error, which is very hard to track down
481 if ( !function_exists( 'mysql_connect' ) ) {
482 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
486 $this->mServer
= $server;
487 $this->mUser
= $user;
488 $this->mPassword
= $password;
489 $this->mDBname
= $dbName;
493 if ( $this->mFlags
& DBO_PERSISTENT
) {
494 @/**/$this->mConn
= mysql_pconnect( $server, $user, $password );
496 # Create a new connection...
497 @/**/$this->mConn
= mysql_connect( $server, $user, $password, true );
500 if ( $dbName != '' ) {
501 if ( $this->mConn
!== false ) {
502 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
504 $error = "Error selecting database $dbName on server {$this->mServer} " .
505 "from client host {$wguname['nodename']}\n";
509 wfDebug( "DB connection error\n" );
510 wfDebug( "Server: $server, User: $user, Password: " .
511 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
516 $success = (bool)$this->mConn
;
520 $this->reportConnectionError();
525 // Tell the server we're communicating with it in UTF-8.
526 // This may engage various charset conversions.
527 $this->query( 'SET NAMES utf8' );
530 $this->mOpened
= $success;
531 wfProfileOut( __METHOD__
);
537 * Closes a database connection.
538 * if it is open : commits any open transactions
540 * @return bool operation success. true if already closed.
544 $this->mOpened
= false;
545 if ( $this->mConn
) {
546 if ( $this->trxLevel() ) {
547 $this->immediateCommit();
549 return mysql_close( $this->mConn
);
556 * @param string $error fallback error message, used if none is given by MySQL
558 function reportConnectionError( $error = 'Unknown error' ) {
559 $myError = $this->lastError();
564 if ( $this->mFailFunction
) {
565 # Legacy error handling method
566 if ( !is_int( $this->mFailFunction
) ) {
567 $ff = $this->mFailFunction
;
568 $ff( $this, $error );
572 wfLogDBError( "Connection error: $error\n" );
573 throw new DBConnectionError( $this, $error );
578 * Usually aborts on failure
579 * If errors are explicitly ignored, returns success
581 function query( $sql, $fname = '', $tempIgnore = false ) {
584 if ( $wgProfiling ) {
585 # generalizeSQL will probably cut down the query to reasonable
586 # logging size most of the time. The substr is really just a sanity check.
588 # Who's been wasting my precious column space? -- TS
589 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
591 if ( is_null( $this->getLBInfo( 'master' ) ) ) {
592 $queryProf = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
593 $totalProf = 'Database::query';
595 $queryProf = 'query-m: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
596 $totalProf = 'Database::query-master';
598 wfProfileIn( $totalProf );
599 wfProfileIn( $queryProf );
602 $this->mLastQuery
= $sql;
604 # Add a comment for easy SHOW PROCESSLIST interpretation
606 $commentedSql = preg_replace("/\s/", " /* $fname */ ", $sql, 1);
608 $commentedSql = $sql;
611 # If DBO_TRX is set, start a transaction
612 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
613 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK'
618 if ( $this->debug() ) {
619 $sqlx = substr( $commentedSql, 0, 500 );
620 $sqlx = strtr( $sqlx, "\t\n", ' ' );
621 wfDebug( "SQL: $sqlx\n" );
624 # Do the query and handle errors
625 $ret = $this->doQuery( $commentedSql );
627 # Try reconnecting if the connection was lost
628 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
629 # Transaction is gone, like it or not
630 $this->mTrxLevel
= 0;
631 wfDebug( "Connection lost, reconnecting...\n" );
632 if ( $this->ping() ) {
633 wfDebug( "Reconnected\n" );
634 $ret = $this->doQuery( $commentedSql );
636 wfDebug( "Failed\n" );
640 if ( false === $ret ) {
641 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
644 if ( $wgProfiling ) {
645 wfProfileOut( $queryProf );
646 wfProfileOut( $totalProf );
652 * The DBMS-dependent part of query()
653 * @param string $sql SQL query.
655 function doQuery( $sql ) {
656 if( $this->bufferResults() ) {
657 $ret = mysql_query( $sql, $this->mConn
);
659 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
668 * @param string $fname
669 * @param bool $tempIgnore
671 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
672 global $wgCommandLineMode, $wgFullyInitialised, $wgColorErrors;
673 # Ignore errors during error handling to avoid infinite recursion
674 $ignore = $this->ignoreErrors( true );
675 ++
$this->mErrorCount
;
677 if( $ignore ||
$tempIgnore ) {
678 wfDebug("SQL ERROR (ignored): $error\n");
679 $this->ignoreErrors( $ignore );
681 $sql1line = str_replace( "\n", "\\n", $sql );
682 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
683 wfDebug("SQL ERROR: " . $error . "\n");
684 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
690 * Intended to be compatible with the PEAR::DB wrapper functions.
691 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
693 * ? = scalar value, quoted as necessary
694 * ! = raw SQL bit (a function for instance)
695 * & = filename; reads the file and inserts as a blob
696 * (we don't use this though...)
698 function prepare( $sql, $func = 'Database::prepare' ) {
699 /* MySQL doesn't support prepared statements (yet), so just
700 pack up the query for reference. We'll manually replace
702 return array( 'query' => $sql, 'func' => $func );
705 function freePrepared( $prepared ) {
706 /* No-op for MySQL */
710 * Execute a prepared query with the various arguments
711 * @param string $prepared the prepared sql
712 * @param mixed $args Either an array here, or put scalars as varargs
714 function execute( $prepared, $args = null ) {
715 if( !is_array( $args ) ) {
717 $args = func_get_args();
718 array_shift( $args );
720 $sql = $this->fillPrepared( $prepared['query'], $args );
721 return $this->query( $sql, $prepared['func'] );
725 * Prepare & execute an SQL statement, quoting and inserting arguments
726 * in the appropriate places.
727 * @param string $query
728 * @param string $args ...
730 function safeQuery( $query, $args = null ) {
731 $prepared = $this->prepare( $query, 'Database::safeQuery' );
732 if( !is_array( $args ) ) {
734 $args = func_get_args();
735 array_shift( $args );
737 $retval = $this->execute( $prepared, $args );
738 $this->freePrepared( $prepared );
743 * For faking prepared SQL statements on DBs that don't support
745 * @param string $preparedSql - a 'preparable' SQL statement
746 * @param array $args - array of arguments to fill it with
747 * @return string executable SQL
749 function fillPrepared( $preparedQuery, $args ) {
751 $this->preparedArgs
=& $args;
752 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
753 array( &$this, 'fillPreparedArg' ), $preparedQuery );
757 * preg_callback func for fillPrepared()
758 * The arguments should be in $this->preparedArgs and must not be touched
759 * while we're doing this.
761 * @param array $matches
765 function fillPreparedArg( $matches ) {
766 switch( $matches[1] ) {
767 case '\\?': return '?';
768 case '\\!': return '!';
769 case '\\&': return '&';
771 list( $n, $arg ) = each( $this->preparedArgs
);
772 switch( $matches[1] ) {
773 case '?': return $this->addQuotes( $arg );
774 case '!': return $arg;
776 # return $this->addQuotes( file_get_contents( $arg ) );
777 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
779 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
784 * @param mixed $res A SQL result
787 * Free a result object
789 function freeResult( $res ) {
790 if ( !@/**/mysql_free_result( $res ) ) {
791 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
796 * Fetch the next row from the given result object, in object form
798 function fetchObject( $res ) {
799 @/**/$row = mysql_fetch_object( $res );
800 if( $this->lastErrno() ) {
801 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
807 * Fetch the next row from the given result object
810 function fetchRow( $res ) {
811 @/**/$row = mysql_fetch_array( $res );
812 if ( $this->lastErrno() ) {
813 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
819 * Get the number of rows in a result object
821 function numRows( $res ) {
822 @/**/$n = mysql_num_rows( $res );
823 if( $this->lastErrno() ) {
824 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
830 * Get the number of fields in a result object
831 * See documentation for mysql_num_fields()
833 function numFields( $res ) { return mysql_num_fields( $res ); }
836 * Get a field name in a result object
837 * See documentation for mysql_field_name():
838 * http://www.php.net/mysql_field_name
840 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
843 * Get the inserted value of an auto-increment row
845 * The value inserted should be fetched from nextSequenceValue()
848 * $id = $dbw->nextSequenceValue('page_page_id_seq');
849 * $dbw->insert('page',array('page_id' => $id));
850 * $id = $dbw->insertId();
852 function insertId() { return mysql_insert_id( $this->mConn
); }
855 * Change the position of the cursor in a result object
856 * See mysql_data_seek()
858 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
861 * Get the last error number
864 function lastErrno() {
865 if ( $this->mConn
) {
866 return mysql_errno( $this->mConn
);
868 return mysql_errno();
873 * Get a description of the last error
874 * See mysql_error() for more details
876 function lastError() {
877 if ( $this->mConn
) {
878 # Even if it's non-zero, it can still be invalid
879 wfSuppressWarnings();
880 $error = mysql_error( $this->mConn
);
882 $error = mysql_error();
886 $error = mysql_error();
889 $error .= ' (' . $this->mServer
. ')';
894 * Get the number of rows affected by the last write query
895 * See mysql_affected_rows() for more details
897 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
898 /**#@-*/ // end of template : @param $result
901 * Simple UPDATE wrapper
902 * Usually aborts on failure
903 * If errors are explicitly ignored, returns success
905 * This function exists for historical reasons, Database::update() has a more standard
906 * calling convention and feature set
908 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
910 $table = $this->tableName( $table );
911 $sql = "UPDATE $table SET $var = '" .
912 $this->strencode( $value ) . "' WHERE ($cond)";
913 return (bool)$this->query( $sql, $fname );
917 * Simple SELECT wrapper, returns a single field, input must be encoded
918 * Usually aborts on failure
919 * If errors are explicitly ignored, returns FALSE on failure
921 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
922 if ( !is_array( $options ) ) {
923 $options = array( $options );
925 $options['LIMIT'] = 1;
927 $res = $this->select( $table, $var, $cond, $fname, $options );
928 if ( $res === false ||
!$this->numRows( $res ) ) {
931 $row = $this->fetchRow( $res );
932 if ( $row !== false ) {
933 $this->freeResult( $res );
941 * Returns an optional USE INDEX clause to go after the table, and a
942 * string to go at the end of the query
946 * @param array $options an associative array of options to be turned into
947 * an SQL query, valid keys are listed in the function.
950 function makeSelectOptions( $options ) {
954 $noKeyOptions = array();
955 foreach ( $options as $key => $option ) {
956 if ( is_numeric( $key ) ) {
957 $noKeyOptions[$option] = true;
961 if ( isset( $options['GROUP BY'] ) ) $tailOpts .= " GROUP BY {$options['GROUP BY']}";
962 if ( isset( $options['ORDER BY'] ) ) $tailOpts .= " ORDER BY {$options['ORDER BY']}";
964 if (isset($options['LIMIT'])) {
965 $tailOpts .= $this->limitResult('', $options['LIMIT'],
966 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
969 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
970 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
971 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
973 # Various MySQL extensions
974 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
975 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
976 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
977 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
978 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
979 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
980 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
982 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
983 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
988 return array( $startOpts, $useIndex, $tailOpts );
994 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
996 if( is_array( $vars ) ) {
997 $vars = implode( ',', $vars );
999 if( !is_array( $options ) ) {
1000 $options = array( $options );
1002 if( is_array( $table ) ) {
1003 if ( @is_array
( $options['USE INDEX'] ) )
1004 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
1006 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1007 } elseif ($table!='') {
1008 $from = ' FROM ' . $this->tableName( $table );
1013 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
1015 if( !empty( $conds ) ) {
1016 if ( is_array( $conds ) ) {
1017 $conds = $this->makeList( $conds, LIST_AND
);
1019 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $tailOpts";
1021 $sql = "SELECT $startOpts $vars $from $useIndex $tailOpts";
1024 return $this->query( $sql, $fname );
1028 * Single row SELECT wrapper
1029 * Aborts or returns FALSE on error
1031 * $vars: the selected variables
1032 * $conds: a condition map, terms are ANDed together.
1033 * Items with numeric keys are taken to be literal conditions
1034 * Takes an array of selected variables, and a condition map, which is ANDed
1035 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1036 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1037 * $obj- >page_id is the ID of the Astronomy article
1039 * @todo migrate documentation to phpdocumentor format
1041 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
1042 $options['LIMIT'] = 1;
1043 $res = $this->select( $table, $vars, $conds, $fname, $options );
1044 if ( $res === false )
1046 if ( !$this->numRows($res) ) {
1047 $this->freeResult($res);
1050 $obj = $this->fetchObject( $res );
1051 $this->freeResult( $res );
1057 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1058 * It's only slightly flawed. Don't use for anything important.
1060 * @param string $sql A SQL Query
1063 static function generalizeSQL( $sql ) {
1064 # This does the same as the regexp below would do, but in such a way
1065 # as to avoid crashing php on some large strings.
1066 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1068 $sql = str_replace ( "\\\\", '', $sql);
1069 $sql = str_replace ( "\\'", '', $sql);
1070 $sql = str_replace ( "\\\"", '', $sql);
1071 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1072 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1074 # All newlines, tabs, etc replaced by single space
1075 $sql = preg_replace ( "/\s+/", ' ', $sql);
1078 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1084 * Determines whether a field exists in a table
1085 * Usually aborts on failure
1086 * If errors are explicitly ignored, returns NULL on failure
1088 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1089 $table = $this->tableName( $table );
1090 $res = $this->query( 'DESCRIBE '.$table, $fname );
1097 while ( $row = $this->fetchObject( $res ) ) {
1098 if ( $row->Field
== $field ) {
1107 * Determines whether an index exists
1108 * Usually aborts on failure
1109 * If errors are explicitly ignored, returns NULL on failure
1111 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1112 $info = $this->indexInfo( $table, $index, $fname );
1113 if ( is_null( $info ) ) {
1116 return $info !== false;
1122 * Get information about an index into an object
1123 * Returns false if the index does not exist
1125 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1126 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1127 # SHOW INDEX should work for 3.x and up:
1128 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1129 $table = $this->tableName( $table );
1130 $sql = 'SHOW INDEX FROM '.$table;
1131 $res = $this->query( $sql, $fname );
1136 while ( $row = $this->fetchObject( $res ) ) {
1137 if ( $row->Key_name
== $index ) {
1145 * Query whether a given table exists
1147 function tableExists( $table ) {
1148 $table = $this->tableName( $table );
1149 $old = $this->ignoreErrors( true );
1150 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1151 $this->ignoreErrors( $old );
1153 $this->freeResult( $res );
1161 * mysql_fetch_field() wrapper
1162 * Returns false if the field doesn't exist
1167 function fieldInfo( $table, $field ) {
1168 $table = $this->tableName( $table );
1169 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1170 $n = mysql_num_fields( $res );
1171 for( $i = 0; $i < $n; $i++
) {
1172 $meta = mysql_fetch_field( $res, $i );
1173 if( $field == $meta->name
) {
1181 * mysql_field_type() wrapper
1183 function fieldType( $res, $index ) {
1184 return mysql_field_type( $res, $index );
1188 * Determines if a given index is unique
1190 function indexUnique( $table, $index ) {
1191 $indexInfo = $this->indexInfo( $table, $index );
1192 if ( !$indexInfo ) {
1195 return !$indexInfo->Non_unique
;
1199 * INSERT wrapper, inserts an array into a table
1201 * $a may be a single associative array, or an array of these with numeric keys, for
1204 * Usually aborts on failure
1205 * If errors are explicitly ignored, returns success
1207 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1208 # No rows to insert, easy just return now
1209 if ( !count( $a ) ) {
1213 $table = $this->tableName( $table );
1214 if ( !is_array( $options ) ) {
1215 $options = array( $options );
1217 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1219 $keys = array_keys( $a[0] );
1222 $keys = array_keys( $a );
1225 $sql = 'INSERT ' . implode( ' ', $options ) .
1226 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1230 foreach ( $a as $row ) {
1236 $sql .= '(' . $this->makeList( $row ) . ')';
1239 $sql .= '(' . $this->makeList( $a ) . ')';
1241 return (bool)$this->query( $sql, $fname );
1245 * Make UPDATE options for the Database::update function
1248 * @param array $options The options passed to Database::update
1251 function makeUpdateOptions( $options ) {
1252 if( !is_array( $options ) ) {
1253 $options = array( $options );
1256 if ( in_array( 'LOW_PRIORITY', $options ) )
1257 $opts[] = $this->lowPriorityOption();
1258 if ( in_array( 'IGNORE', $options ) )
1260 return implode(' ', $opts);
1264 * UPDATE wrapper, takes a condition array and a SET array
1266 * @param string $table The table to UPDATE
1267 * @param array $values An array of values to SET
1268 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1269 * @param string $fname The Class::Function calling this function
1271 * @param array $options An array of UPDATE options, can be one or
1272 * more of IGNORE, LOW_PRIORITY
1274 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1275 $table = $this->tableName( $table );
1276 $opts = $this->makeUpdateOptions( $options );
1277 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1278 if ( $conds != '*' ) {
1279 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1281 $this->query( $sql, $fname );
1285 * Makes a wfStrencoded list from an array
1287 * LIST_COMMA - comma separated, no field names
1288 * LIST_AND - ANDed WHERE clause (without the WHERE)
1289 * LIST_OR - ORed WHERE clause (without the WHERE)
1290 * LIST_SET - comma separated with field names, like a SET clause
1291 * LIST_NAMES - comma separated field names
1293 function makeList( $a, $mode = LIST_COMMA
) {
1294 if ( !is_array( $a ) ) {
1295 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1300 foreach ( $a as $field => $value ) {
1302 if ( $mode == LIST_AND
) {
1304 } elseif($mode == LIST_OR
) {
1312 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1313 $list .= "($value)";
1314 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array ($value) ) {
1315 $list .= $field." IN (".$this->makeList($value).") ";
1317 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1318 $list .= "$field = ";
1320 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1327 * Change the current database
1329 function selectDB( $db ) {
1330 $this->mDBname
= $db;
1331 return mysql_select_db( $db, $this->mConn
);
1335 * Format a table name ready for use in constructing an SQL query
1337 * This does two important things: it quotes table names which as necessary,
1338 * and it adds a table prefix if there is one.
1340 * All functions of this object which require a table name call this function
1341 * themselves. Pass the canonical name to such functions. This is only needed
1342 * when calling query() directly.
1344 * @param string $name database table name
1346 function tableName( $name ) {
1348 # Skip quoted literals
1349 if ( $name{0} != '`' ) {
1350 if ( $this->mTablePrefix
!== '' && strpos( '.', $name ) === false ) {
1351 $name = "{$this->mTablePrefix}$name";
1353 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1354 $name = "`$wgSharedDB`.`$name`";
1364 * Fetch a number of table names into an array
1365 * This is handy when you need to construct SQL for joins
1368 * extract($dbr->tableNames('user','watchlist'));
1369 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1370 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1372 function tableNames() {
1373 $inArray = func_get_args();
1375 foreach ( $inArray as $name ) {
1376 $retVal[$name] = $this->tableName( $name );
1384 function tableNamesWithUseIndex( $tables, $use_index ) {
1387 foreach ( $tables as $table )
1388 if ( @$use_index[$table] !== null )
1389 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1391 $ret[] = $this->tableName( $table );
1393 return implode( ',', $ret );
1397 * Wrapper for addslashes()
1398 * @param string $s String to be slashed.
1399 * @return string slashed string.
1401 function strencode( $s ) {
1402 return mysql_real_escape_string( $s, $this->mConn
);
1406 * If it's a string, adds quotes and backslashes
1407 * Otherwise returns as-is
1409 function addQuotes( $s ) {
1410 if ( is_null( $s ) ) {
1413 # This will also quote numeric values. This should be harmless,
1414 # and protects against weird problems that occur when they really
1415 # _are_ strings such as article titles and string->number->string
1416 # conversion is not 1:1.
1417 return "'" . $this->strencode( $s ) . "'";
1422 * Escape string for safe LIKE usage
1424 function escapeLike( $s ) {
1425 $s=$this->strencode( $s );
1426 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1431 * Returns an appropriately quoted sequence value for inserting a new row.
1432 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1433 * subclass will return an integer, and save the value for insertId()
1435 function nextSequenceValue( $seqName ) {
1441 * PostgreSQL doesn't have them and returns ""
1443 function useIndexClause( $index ) {
1444 return "FORCE INDEX ($index)";
1448 * REPLACE query wrapper
1449 * PostgreSQL simulates this with a DELETE followed by INSERT
1450 * $row is the row to insert, an associative array
1451 * $uniqueIndexes is an array of indexes. Each element may be either a
1452 * field name or an array of field names
1454 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1455 * However if you do this, you run the risk of encountering errors which wouldn't have
1458 * @todo migrate comment to phodocumentor format
1460 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1461 $table = $this->tableName( $table );
1464 if ( !is_array( reset( $rows ) ) ) {
1465 $rows = array( $rows );
1468 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1470 foreach ( $rows as $row ) {
1476 $sql .= '(' . $this->makeList( $row ) . ')';
1478 return $this->query( $sql, $fname );
1482 * DELETE where the condition is a join
1483 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1485 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1486 * join condition matches, set $conds='*'
1488 * DO NOT put the join condition in $conds
1490 * @param string $delTable The table to delete from.
1491 * @param string $joinTable The other table.
1492 * @param string $delVar The variable to join on, in the first table.
1493 * @param string $joinVar The variable to join on, in the second table.
1494 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1496 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1498 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1501 $delTable = $this->tableName( $delTable );
1502 $joinTable = $this->tableName( $joinTable );
1503 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1504 if ( $conds != '*' ) {
1505 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1508 return $this->query( $sql, $fname );
1512 * Returns the size of a text field, or -1 for "unlimited"
1514 function textFieldSize( $table, $field ) {
1515 $table = $this->tableName( $table );
1516 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1517 $res = $this->query( $sql, 'Database::textFieldSize' );
1518 $row = $this->fetchObject( $res );
1519 $this->freeResult( $res );
1521 if ( preg_match( "/\((.*)\)/", $row->Type
, $m ) ) {
1530 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1532 function lowPriorityOption() {
1533 return 'LOW_PRIORITY';
1537 * DELETE query wrapper
1539 * Use $conds == "*" to delete all rows
1541 function delete( $table, $conds, $fname = 'Database::delete' ) {
1543 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1545 $table = $this->tableName( $table );
1546 $sql = "DELETE FROM $table";
1547 if ( $conds != '*' ) {
1548 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1550 return $this->query( $sql, $fname );
1554 * INSERT SELECT wrapper
1555 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1556 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1557 * $conds may be "*" to copy the whole table
1558 * srcTable may be an array of tables.
1560 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1561 $insertOptions = array(), $selectOptions = array() )
1563 $destTable = $this->tableName( $destTable );
1564 if ( is_array( $insertOptions ) ) {
1565 $insertOptions = implode( ' ', $insertOptions );
1567 if( !is_array( $selectOptions ) ) {
1568 $selectOptions = array( $selectOptions );
1570 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1571 if( is_array( $srcTable ) ) {
1572 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1574 $srcTable = $this->tableName( $srcTable );
1576 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1577 " SELECT $startOpts " . implode( ',', $varMap ) .
1578 " FROM $srcTable $useIndex ";
1579 if ( $conds != '*' ) {
1580 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1582 $sql .= " $tailOpts";
1583 return $this->query( $sql, $fname );
1587 * Construct a LIMIT query with optional offset
1588 * This is used for query pages
1589 * $sql string SQL query we will append the limit too
1590 * $limit integer the SQL limit
1591 * $offset integer the SQL offset (default false)
1593 function limitResult($sql, $limit, $offset=false) {
1594 if( !is_numeric($limit) ) {
1595 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1597 return " $sql LIMIT "
1598 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1601 function limitResultForUpdate($sql, $num) {
1602 return $this->limitResult($sql, $num, 0);
1606 * Returns an SQL expression for a simple conditional.
1609 * @param string $cond SQL expression which will result in a boolean value
1610 * @param string $trueVal SQL expression to return if true
1611 * @param string $falseVal SQL expression to return if false
1612 * @return string SQL fragment
1614 function conditional( $cond, $trueVal, $falseVal ) {
1615 return " IF($cond, $trueVal, $falseVal) ";
1619 * Determines if the last failure was due to a deadlock
1621 function wasDeadlock() {
1622 return $this->lastErrno() == 1213;
1626 * Perform a deadlock-prone transaction.
1628 * This function invokes a callback function to perform a set of write
1629 * queries. If a deadlock occurs during the processing, the transaction
1630 * will be rolled back and the callback function will be called again.
1633 * $dbw->deadlockLoop( callback, ... );
1635 * Extra arguments are passed through to the specified callback function.
1637 * Returns whatever the callback function returned on its successful,
1638 * iteration, or false on error, for example if the retry limit was
1641 function deadlockLoop() {
1642 $myFname = 'Database::deadlockLoop';
1645 $args = func_get_args();
1646 $function = array_shift( $args );
1647 $oldIgnore = $this->ignoreErrors( true );
1648 $tries = DEADLOCK_TRIES
;
1649 if ( is_array( $function ) ) {
1650 $fname = $function[0];
1655 $retVal = call_user_func_array( $function, $args );
1656 $error = $this->lastError();
1657 $errno = $this->lastErrno();
1658 $sql = $this->lastQuery();
1661 if ( $this->wasDeadlock() ) {
1663 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1665 $this->reportQueryError( $error, $errno, $sql, $fname );
1668 } while( $this->wasDeadlock() && --$tries > 0 );
1669 $this->ignoreErrors( $oldIgnore );
1670 if ( $tries <= 0 ) {
1671 $this->query( 'ROLLBACK', $myFname );
1672 $this->reportQueryError( $error, $errno, $sql, $fname );
1675 $this->query( 'COMMIT', $myFname );
1681 * Do a SELECT MASTER_POS_WAIT()
1683 * @param string $file the binlog file
1684 * @param string $pos the binlog position
1685 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1687 function masterPosWait( $file, $pos, $timeout ) {
1688 $fname = 'Database::masterPosWait';
1689 wfProfileIn( $fname );
1692 # Commit any open transactions
1693 $this->immediateCommit();
1695 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1696 $encFile = $this->strencode( $file );
1697 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1698 $res = $this->doQuery( $sql );
1699 if ( $res && $row = $this->fetchRow( $res ) ) {
1700 $this->freeResult( $res );
1701 wfProfileOut( $fname );
1704 wfProfileOut( $fname );
1710 * Get the position of the master from SHOW SLAVE STATUS
1712 function getSlavePos() {
1713 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1714 $row = $this->fetchObject( $res );
1716 return array( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1718 return array( false, false );
1723 * Get the position of the master from SHOW MASTER STATUS
1725 function getMasterPos() {
1726 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1727 $row = $this->fetchObject( $res );
1729 return array( $row->File
, $row->Position
);
1731 return array( false, false );
1736 * Begin a transaction, committing any previously open transaction
1738 function begin( $fname = 'Database::begin' ) {
1739 $this->query( 'BEGIN', $fname );
1740 $this->mTrxLevel
= 1;
1746 function commit( $fname = 'Database::commit' ) {
1747 $this->query( 'COMMIT', $fname );
1748 $this->mTrxLevel
= 0;
1752 * Rollback a transaction
1754 function rollback( $fname = 'Database::rollback' ) {
1755 $this->query( 'ROLLBACK', $fname );
1756 $this->mTrxLevel
= 0;
1760 * Begin a transaction, committing any previously open transaction
1761 * @deprecated use begin()
1763 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1768 * Commit transaction, if one is open
1769 * @deprecated use commit()
1771 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1776 * Return MW-style timestamp used for MySQL schema
1778 function timestamp( $ts=0 ) {
1779 return wfTimestamp(TS_MW
,$ts);
1783 * Local database timestamp format or null
1785 function timestampOrNull( $ts = null ) {
1786 if( is_null( $ts ) ) {
1789 return $this->timestamp( $ts );
1796 function resultObject( $result ) {
1797 if( empty( $result ) ) {
1800 return new ResultWrapper( $this, $result );
1805 * Return aggregated value alias
1807 function aggregateValue ($valuedata,$valuename='value') {
1812 * @return string wikitext of a link to the server software's web site
1814 function getSoftwareLink() {
1815 return "[http://www.mysql.com/ MySQL]";
1819 * @return string Version information from the database
1821 function getServerVersion() {
1822 return mysql_get_server_info();
1826 * Ping the server and try to reconnect if it there is no connection
1829 if( function_exists( 'mysql_ping' ) ) {
1830 return mysql_ping( $this->mConn
);
1832 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1839 * At the moment, this will only work if the DB user has the PROCESS privilege
1842 $res = $this->query( 'SHOW PROCESSLIST' );
1843 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1844 # dubious, but unfortunately there's no easy rigorous way
1846 while ( $row = $this->fetchObject( $res ) ) {
1847 /* This should work for most situations - when default db
1848 * for thread is not specified, it had no events executed,
1849 * and therefore it doesn't know yet how lagged it is.
1851 * Relay log I/O thread does not select databases.
1853 if ( $row->User
== 'system user' &&
1854 $row->State
!= 'Waiting for master to send event' &&
1855 $row->State
!= 'Connecting to master' &&
1856 $row->State
!= 'Queueing master event to the relay log' &&
1857 $row->State
!= 'Waiting for master update' &&
1858 $row->State
!= 'Requesting binlog dump'
1860 # This is it, return the time (except -ve)
1861 if ( $row->Time
> 0x7fffffff ) {
1872 * Get status information from SHOW STATUS in an associative array
1874 function getStatus($which="%") {
1875 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1877 while ( $row = $this->fetchObject( $res ) ) {
1878 $status[$row->Variable_name
] = $row->Value
;
1884 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1886 function maxListLen() {
1890 function encodeBlob($b) {
1894 function decodeBlob($b) {
1899 * Read and execute SQL commands from a file.
1900 * Returns true on success, error string on failure
1902 function sourceFile( $filename ) {
1903 $fp = fopen( $filename, 'r' );
1904 if ( false === $fp ) {
1905 return "Could not open \"{$fname}\".\n";
1910 $dollarquote = false;
1912 while ( ! feof( $fp ) ) {
1913 $line = trim( fgets( $fp, 1024 ) );
1914 $sl = strlen( $line ) - 1;
1916 if ( $sl < 0 ) { continue; }
1917 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
1919 ## Allow dollar quoting for function declarations
1920 if (substr($line,0,4) == '$mw$') {
1922 $dollarquote = false;
1926 $dollarquote = true;
1929 else if (!$dollarquote) {
1930 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
1932 $line = substr( $line, 0, $sl );
1936 if ( '' != $cmd ) { $cmd .= ' '; }
1940 $cmd = str_replace(';;', ";", $cmd);
1941 $cmd = $this->replaceVars( $cmd );
1942 $res = $this->query( $cmd, 'dbsource', true );
1944 if ( false === $res ) {
1945 $err = $this->lastError();
1946 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1958 * Replace variables in sourced SQL
1960 protected function replaceVars( $ins ) {
1962 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
1963 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
1964 'wgDBadminuser', 'wgDBadminpassword',
1967 // Ordinary variables
1968 foreach ( $varnames as $var ) {
1969 if( isset( $GLOBALS[$var] ) ) {
1970 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
1971 $ins = str_replace( '{$' . $var . '}', $val, $ins );
1972 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
1973 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
1978 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
1979 array( &$this, 'tableNameCallback' ), $ins );
1984 * Table name callback
1987 protected function tableNameCallback( $matches ) {
1988 return $this->tableName( $matches[1] );
1994 * Database abstraction object for mySQL
1995 * Inherit all methods and properties of Database::Database()
1997 * @package MediaWiki
2000 class DatabaseMysql
extends Database
{
2006 * Result wrapper for grabbing data queried by someone else
2008 * @package MediaWiki
2010 class ResultWrapper
{
2016 function ResultWrapper( &$database, $result ) {
2017 $this->db
=& $database;
2018 $this->result
=& $result;
2024 function numRows() {
2025 return $this->db
->numRows( $this->result
);
2031 function fetchObject() {
2032 return $this->db
->fetchObject( $this->result
);
2038 function fetchRow() {
2039 return $this->db
->fetchRow( $this->result
);
2046 $this->db
->freeResult( $this->result
);
2047 unset( $this->result
);
2051 function seek( $row ) {
2052 $this->db
->dataSeek( $this->result
, $row );