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 getPageTitle() {
91 return "$wgSitename has a problem";
95 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
96 global $wgSitename, $wgServer, $wgMessageCache, $wgLogo;
98 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
99 # Hard coding strings instead.
101 $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>";
102 $mainpage = 'Main Page';
103 $searchdisabled = <<<EOT
104 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
105 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
109 <!-- SiteSearch Google -->
110 <FORM method=GET action=\"http://www.google.com/search\">
111 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
112 <A HREF=\"http://www.google.com/\">
113 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
114 border=\"0\" ALT=\"Google\"></A>
117 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
118 <INPUT type=submit name=btnG VALUE=\"Google Search\">
120 <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 />
121 <input type='hidden' name='ie' value='$2'>
122 <input type='hidden' name='oe' value='$2'>
126 <!-- SiteSearch Google -->";
127 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
130 if ( is_object( $wgMessageCache ) ) {
131 $wgMessageCache->disable();
134 if ( trim( $this->error
) == '' ) {
135 $this->error
= $this->db
->getProperty('mServer');
138 $text = str_replace( '$1', $this->error
, $noconnect );
139 $text .= wfGetSiteNotice();
141 if($wgUseFileCache) {
146 $t = Title
::newFromURL( $title );
147 } elseif (@/**/$_REQUEST['search']) {
148 $search = $_REQUEST['search'];
149 return $searchdisabled .
150 str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
151 $wgInputEncoding ), $googlesearch );
153 $t = Title
::newFromText( $mainpage );
157 $cache = new CacheManager( $t );
158 if( $cache->isFileCached() ) {
159 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
160 $cachederror . "</b></p>\n";
162 $tag = '<div id="article">';
166 $cache->fetchPageText() );
174 class DBQueryError
extends DBError
{
175 public $error, $errno, $sql, $fname;
177 function __construct( Database
&$db, $error, $errno, $sql, $fname ) {
178 $message = "A database error has occurred\n" .
180 "Function: $fname\n" .
181 "Error: $errno $error\n";
183 parent
::__construct( $db, $message );
184 $this->error
= $error;
185 $this->errno
= $errno;
187 $this->fname
= $fname;
191 if ( $this->useMessageCache() ) {
192 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
193 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
195 return $this->getMessage();
200 global $wgShowSQLErrors;
201 if( !$wgShowSQLErrors ) {
202 return $this->msg( 'sqlhidden', 'SQL hidden' );
208 function getPageTitle() {
209 return $this->msg( 'databaseerror', 'Database error' );
213 if ( $this->useMessageCache() ) {
214 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
215 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
217 return nl2br( htmlspecialchars( $this->getMessage() ) );
222 class DBUnexpectedError
extends DBError
{}
224 /******************************************************************************/
227 * Database abstraction object
232 #------------------------------------------------------------------------------
234 #------------------------------------------------------------------------------
236 protected $mLastQuery = '';
238 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
239 protected $mOut, $mOpened = false;
241 protected $mFailFunction;
242 protected $mTablePrefix;
244 protected $mTrxLevel = 0;
245 protected $mErrorCount = 0;
246 protected $mLBInfo = array();
247 protected $mCascadingDeletes = false;
248 protected $mCleanupTriggers = false;
250 #------------------------------------------------------------------------------
252 #------------------------------------------------------------------------------
253 # These optionally set a variable and return the previous state
256 * Fail function, takes a Database as a parameter
257 * Set to false for default, 1 for ignore errors
259 function failFunction( $function = NULL ) {
260 return wfSetVar( $this->mFailFunction
, $function );
264 * Output page, used for reporting errors
265 * FALSE means discard output
267 function setOutputPage( $out ) {
272 * Boolean, controls output of large amounts of debug information
274 function debug( $debug = NULL ) {
275 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
279 * Turns buffering of SQL result sets on (true) or off (false).
280 * Default is "on" and it should not be changed without good reasons.
282 function bufferResults( $buffer = NULL ) {
283 if ( is_null( $buffer ) ) {
284 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
286 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
291 * Turns on (false) or off (true) the automatic generation and sending
292 * of a "we're sorry, but there has been a database error" page on
293 * database errors. Default is on (false). When turned off, the
294 * code should use wfLastErrno() and wfLastError() to handle the
295 * situation as appropriate.
297 function ignoreErrors( $ignoreErrors = NULL ) {
298 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
302 * The current depth of nested transactions
303 * @param $level Integer: , default NULL.
305 function trxLevel( $level = NULL ) {
306 return wfSetVar( $this->mTrxLevel
, $level );
310 * Number of errors logged, only useful when errors are ignored
312 function errorCount( $count = NULL ) {
313 return wfSetVar( $this->mErrorCount
, $count );
317 * Properties passed down from the server info array of the load balancer
319 function getLBInfo( $name = NULL ) {
320 if ( is_null( $name ) ) {
321 return $this->mLBInfo
;
323 if ( array_key_exists( $name, $this->mLBInfo
) ) {
324 return $this->mLBInfo
[$name];
331 function setLBInfo( $name, $value = NULL ) {
332 if ( is_null( $value ) ) {
333 $this->mLBInfo
= $name;
335 $this->mLBInfo
[$name] = $value;
340 * Returns true if this database supports (and uses) cascading deletes
342 function cascadingDeletes() {
343 return $this->mCascadingDeletes
;
347 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
349 function cleanupTriggers() {
350 return $this->mCleanupTriggers
;
356 function lastQuery() { return $this->mLastQuery
; }
357 function isOpen() { return $this->mOpened
; }
360 function setFlag( $flag ) {
361 $this->mFlags |
= $flag;
364 function clearFlag( $flag ) {
365 $this->mFlags
&= ~
$flag;
368 function getFlag( $flag ) {
369 return !!($this->mFlags
& $flag);
373 * General read-only accessor
375 function getProperty( $name ) {
379 #------------------------------------------------------------------------------
381 #------------------------------------------------------------------------------
384 * @param string $server database server host
385 * @param string $user database user name
386 * @param string $password database user password
387 * @param string $dbname database name
391 * @param failFunction
393 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
395 function __construct( $server = false, $user = false, $password = false, $dbName = false,
396 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
398 global $wgOut, $wgDBprefix, $wgCommandLineMode;
399 # Can't get a reference if it hasn't been set yet
400 if ( !isset( $wgOut ) ) {
403 $this->mOut
=& $wgOut;
405 $this->mFailFunction
= $failFunction;
406 $this->mFlags
= $flags;
408 if ( $this->mFlags
& DBO_DEFAULT
) {
409 if ( $wgCommandLineMode ) {
410 $this->mFlags
&= ~DBO_TRX
;
412 $this->mFlags |
= DBO_TRX
;
417 // Faster read-only access
418 if ( wfReadOnly() ) {
419 $this->mFlags |= DBO_PERSISTENT;
420 $this->mFlags &= ~DBO_TRX;
423 /** Get the default table prefix*/
424 if ( $tablePrefix == 'get from global' ) {
425 $this->mTablePrefix
= $wgDBprefix;
427 $this->mTablePrefix
= $tablePrefix;
431 $this->open( $server, $user, $password, $dbName );
437 * @param failFunction
440 static function newFromParams( $server, $user, $password, $dbName,
441 $failFunction = false, $flags = 0 )
443 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
447 * Usually aborts on failure
448 * If the failFunction is set to a non-zero integer, returns success
450 function open( $server, $user, $password, $dbName ) {
453 # Test for missing mysql.so
454 # First try to load it
455 if (!@extension_loaded
('mysql')) {
460 # Otherwise we get a suppressed fatal error, which is very hard to track down
461 if ( !function_exists( 'mysql_connect' ) ) {
462 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
466 $this->mServer
= $server;
467 $this->mUser
= $user;
468 $this->mPassword
= $password;
469 $this->mDBname
= $dbName;
473 if ( $this->mFlags
& DBO_PERSISTENT
) {
474 @/**/$this->mConn
= mysql_pconnect( $server, $user, $password );
476 # Create a new connection...
477 @/**/$this->mConn
= mysql_connect( $server, $user, $password, true );
480 if ( $dbName != '' ) {
481 if ( $this->mConn
!== false ) {
482 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
484 $error = "Error selecting database $dbName on server {$this->mServer} " .
485 "from client host {$wguname['nodename']}\n";
489 wfDebug( "DB connection error\n" );
490 wfDebug( "Server: $server, User: $user, Password: " .
491 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
496 $success = (bool)$this->mConn
;
500 $this->reportConnectionError();
505 // Tell the server we're communicating with it in UTF-8.
506 // This may engage various charset conversions.
507 $this->query( 'SET NAMES utf8' );
510 $this->mOpened
= $success;
516 * Closes a database connection.
517 * if it is open : commits any open transactions
519 * @return bool operation success. true if already closed.
523 $this->mOpened
= false;
524 if ( $this->mConn
) {
525 if ( $this->trxLevel() ) {
526 $this->immediateCommit();
528 return mysql_close( $this->mConn
);
535 * @param string $error fallback error message, used if none is given by MySQL
537 function reportConnectionError( $error = 'Unknown error' ) {
538 $myError = $this->lastError();
543 if ( $this->mFailFunction
) {
544 # Legacy error handling method
545 if ( !is_int( $this->mFailFunction
) ) {
546 $ff = $this->mFailFunction
;
547 $ff( $this, $error );
551 wfLogDBError( "Connection error: $error\n" );
552 throw new DBConnectionError( $this, $error );
557 * Usually aborts on failure
558 * If errors are explicitly ignored, returns success
560 function query( $sql, $fname = '', $tempIgnore = false ) {
563 if ( $wgProfiling ) {
564 # generalizeSQL will probably cut down the query to reasonable
565 # logging size most of the time. The substr is really just a sanity check.
567 # Who's been wasting my precious column space? -- TS
568 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
570 if ( is_null( $this->getLBInfo( 'master' ) ) ) {
571 $queryProf = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
572 $totalProf = 'Database::query';
574 $queryProf = 'query-m: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
575 $totalProf = 'Database::query-master';
577 wfProfileIn( $totalProf );
578 wfProfileIn( $queryProf );
581 $this->mLastQuery
= $sql;
583 # Add a comment for easy SHOW PROCESSLIST interpretation
585 $commentedSql = preg_replace("/\s/", " /* $fname */ ", $sql, 1);
587 $commentedSql = $sql;
590 # If DBO_TRX is set, start a transaction
591 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
592 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK'
597 if ( $this->debug() ) {
598 $sqlx = substr( $commentedSql, 0, 500 );
599 $sqlx = strtr( $sqlx, "\t\n", ' ' );
600 wfDebug( "SQL: $sqlx\n" );
603 # Do the query and handle errors
604 $ret = $this->doQuery( $commentedSql );
606 # Try reconnecting if the connection was lost
607 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
608 # Transaction is gone, like it or not
609 $this->mTrxLevel
= 0;
610 wfDebug( "Connection lost, reconnecting...\n" );
611 if ( $this->ping() ) {
612 wfDebug( "Reconnected\n" );
613 $ret = $this->doQuery( $commentedSql );
615 wfDebug( "Failed\n" );
619 if ( false === $ret ) {
620 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
623 if ( $wgProfiling ) {
624 wfProfileOut( $queryProf );
625 wfProfileOut( $totalProf );
631 * The DBMS-dependent part of query()
632 * @param string $sql SQL query.
634 function doQuery( $sql ) {
635 if( $this->bufferResults() ) {
636 $ret = mysql_query( $sql, $this->mConn
);
638 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
647 * @param string $fname
648 * @param bool $tempIgnore
650 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
651 global $wgCommandLineMode, $wgFullyInitialised, $wgColorErrors;
652 # Ignore errors during error handling to avoid infinite recursion
653 $ignore = $this->ignoreErrors( true );
654 ++
$this->mErrorCount
;
656 if( $ignore ||
$tempIgnore ) {
657 wfDebug("SQL ERROR (ignored): $error\n");
658 $this->ignoreErrors( $ignore );
660 $sql1line = str_replace( "\n", "\\n", $sql );
661 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
662 wfDebug("SQL ERROR: " . $error . "\n");
663 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
669 * Intended to be compatible with the PEAR::DB wrapper functions.
670 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
672 * ? = scalar value, quoted as necessary
673 * ! = raw SQL bit (a function for instance)
674 * & = filename; reads the file and inserts as a blob
675 * (we don't use this though...)
677 function prepare( $sql, $func = 'Database::prepare' ) {
678 /* MySQL doesn't support prepared statements (yet), so just
679 pack up the query for reference. We'll manually replace
681 return array( 'query' => $sql, 'func' => $func );
684 function freePrepared( $prepared ) {
685 /* No-op for MySQL */
689 * Execute a prepared query with the various arguments
690 * @param string $prepared the prepared sql
691 * @param mixed $args Either an array here, or put scalars as varargs
693 function execute( $prepared, $args = null ) {
694 if( !is_array( $args ) ) {
696 $args = func_get_args();
697 array_shift( $args );
699 $sql = $this->fillPrepared( $prepared['query'], $args );
700 return $this->query( $sql, $prepared['func'] );
704 * Prepare & execute an SQL statement, quoting and inserting arguments
705 * in the appropriate places.
706 * @param string $query
707 * @param string $args ...
709 function safeQuery( $query, $args = null ) {
710 $prepared = $this->prepare( $query, 'Database::safeQuery' );
711 if( !is_array( $args ) ) {
713 $args = func_get_args();
714 array_shift( $args );
716 $retval = $this->execute( $prepared, $args );
717 $this->freePrepared( $prepared );
722 * For faking prepared SQL statements on DBs that don't support
724 * @param string $preparedSql - a 'preparable' SQL statement
725 * @param array $args - array of arguments to fill it with
726 * @return string executable SQL
728 function fillPrepared( $preparedQuery, $args ) {
730 $this->preparedArgs
=& $args;
731 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
732 array( &$this, 'fillPreparedArg' ), $preparedQuery );
736 * preg_callback func for fillPrepared()
737 * The arguments should be in $this->preparedArgs and must not be touched
738 * while we're doing this.
740 * @param array $matches
744 function fillPreparedArg( $matches ) {
745 switch( $matches[1] ) {
746 case '\\?': return '?';
747 case '\\!': return '!';
748 case '\\&': return '&';
750 list( $n, $arg ) = each( $this->preparedArgs
);
751 switch( $matches[1] ) {
752 case '?': return $this->addQuotes( $arg );
753 case '!': return $arg;
755 # return $this->addQuotes( file_get_contents( $arg ) );
756 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
758 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
763 * @param mixed $res A SQL result
766 * Free a result object
768 function freeResult( $res ) {
769 if ( !@/**/mysql_free_result( $res ) ) {
770 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
775 * Fetch the next row from the given result object, in object form
777 function fetchObject( $res ) {
778 @/**/$row = mysql_fetch_object( $res );
779 if( $this->lastErrno() ) {
780 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
786 * Fetch the next row from the given result object
789 function fetchRow( $res ) {
790 @/**/$row = mysql_fetch_array( $res );
791 if ( $this->lastErrno() ) {
792 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
798 * Get the number of rows in a result object
800 function numRows( $res ) {
801 @/**/$n = mysql_num_rows( $res );
802 if( $this->lastErrno() ) {
803 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
809 * Get the number of fields in a result object
810 * See documentation for mysql_num_fields()
812 function numFields( $res ) { return mysql_num_fields( $res ); }
815 * Get a field name in a result object
816 * See documentation for mysql_field_name():
817 * http://www.php.net/mysql_field_name
819 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
822 * Get the inserted value of an auto-increment row
824 * The value inserted should be fetched from nextSequenceValue()
827 * $id = $dbw->nextSequenceValue('page_page_id_seq');
828 * $dbw->insert('page',array('page_id' => $id));
829 * $id = $dbw->insertId();
831 function insertId() { return mysql_insert_id( $this->mConn
); }
834 * Change the position of the cursor in a result object
835 * See mysql_data_seek()
837 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
840 * Get the last error number
843 function lastErrno() {
844 if ( $this->mConn
) {
845 return mysql_errno( $this->mConn
);
847 return mysql_errno();
852 * Get a description of the last error
853 * See mysql_error() for more details
855 function lastError() {
856 if ( $this->mConn
) {
857 # Even if it's non-zero, it can still be invalid
858 wfSuppressWarnings();
859 $error = mysql_error( $this->mConn
);
861 $error = mysql_error();
865 $error = mysql_error();
868 $error .= ' (' . $this->mServer
. ')';
873 * Get the number of rows affected by the last write query
874 * See mysql_affected_rows() for more details
876 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
877 /**#@-*/ // end of template : @param $result
880 * Simple UPDATE wrapper
881 * Usually aborts on failure
882 * If errors are explicitly ignored, returns success
884 * This function exists for historical reasons, Database::update() has a more standard
885 * calling convention and feature set
887 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
889 $table = $this->tableName( $table );
890 $sql = "UPDATE $table SET $var = '" .
891 $this->strencode( $value ) . "' WHERE ($cond)";
892 return (bool)$this->query( $sql, $fname );
896 * Simple SELECT wrapper, returns a single field, input must be encoded
897 * Usually aborts on failure
898 * If errors are explicitly ignored, returns FALSE on failure
900 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
901 if ( !is_array( $options ) ) {
902 $options = array( $options );
904 $options['LIMIT'] = 1;
906 $res = $this->select( $table, $var, $cond, $fname, $options );
907 if ( $res === false ||
!$this->numRows( $res ) ) {
910 $row = $this->fetchRow( $res );
911 if ( $row !== false ) {
912 $this->freeResult( $res );
920 * Returns an optional USE INDEX clause to go after the table, and a
921 * string to go at the end of the query
925 * @param array $options an associative array of options to be turned into
926 * an SQL query, valid keys are listed in the function.
929 function makeSelectOptions( $options ) {
933 $noKeyOptions = array();
934 foreach ( $options as $key => $option ) {
935 if ( is_numeric( $key ) ) {
936 $noKeyOptions[$option] = true;
940 if ( isset( $options['GROUP BY'] ) ) $tailOpts .= " GROUP BY {$options['GROUP BY']}";
941 if ( isset( $options['ORDER BY'] ) ) $tailOpts .= " ORDER BY {$options['ORDER BY']}";
943 if (isset($options['LIMIT'])) {
944 $tailOpts .= $this->limitResult('', $options['LIMIT'],
945 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
948 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
949 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
950 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
952 # Various MySQL extensions
953 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
954 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
955 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
956 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
957 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
958 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
959 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
961 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
962 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
967 return array( $startOpts, $useIndex, $tailOpts );
973 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
975 if( is_array( $vars ) ) {
976 $vars = implode( ',', $vars );
978 if( !is_array( $options ) ) {
979 $options = array( $options );
981 if( is_array( $table ) ) {
982 if ( @is_array
( $options['USE INDEX'] ) )
983 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
985 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
986 } elseif ($table!='') {
987 $from = ' FROM ' . $this->tableName( $table );
992 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
994 if( !empty( $conds ) ) {
995 if ( is_array( $conds ) ) {
996 $conds = $this->makeList( $conds, LIST_AND
);
998 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $tailOpts";
1000 $sql = "SELECT $startOpts $vars $from $useIndex $tailOpts";
1003 return $this->query( $sql, $fname );
1007 * Single row SELECT wrapper
1008 * Aborts or returns FALSE on error
1010 * $vars: the selected variables
1011 * $conds: a condition map, terms are ANDed together.
1012 * Items with numeric keys are taken to be literal conditions
1013 * Takes an array of selected variables, and a condition map, which is ANDed
1014 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1015 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1016 * $obj- >page_id is the ID of the Astronomy article
1018 * @todo migrate documentation to phpdocumentor format
1020 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
1021 $options['LIMIT'] = 1;
1022 $res = $this->select( $table, $vars, $conds, $fname, $options );
1023 if ( $res === false )
1025 if ( !$this->numRows($res) ) {
1026 $this->freeResult($res);
1029 $obj = $this->fetchObject( $res );
1030 $this->freeResult( $res );
1036 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1037 * It's only slightly flawed. Don't use for anything important.
1039 * @param string $sql A SQL Query
1042 static function generalizeSQL( $sql ) {
1043 # This does the same as the regexp below would do, but in such a way
1044 # as to avoid crashing php on some large strings.
1045 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1047 $sql = str_replace ( "\\\\", '', $sql);
1048 $sql = str_replace ( "\\'", '', $sql);
1049 $sql = str_replace ( "\\\"", '', $sql);
1050 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1051 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1053 # All newlines, tabs, etc replaced by single space
1054 $sql = preg_replace ( "/\s+/", ' ', $sql);
1057 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1063 * Determines whether a field exists in a table
1064 * Usually aborts on failure
1065 * If errors are explicitly ignored, returns NULL on failure
1067 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1068 $table = $this->tableName( $table );
1069 $res = $this->query( 'DESCRIBE '.$table, $fname );
1076 while ( $row = $this->fetchObject( $res ) ) {
1077 if ( $row->Field
== $field ) {
1086 * Determines whether an index exists
1087 * Usually aborts on failure
1088 * If errors are explicitly ignored, returns NULL on failure
1090 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1091 $info = $this->indexInfo( $table, $index, $fname );
1092 if ( is_null( $info ) ) {
1095 return $info !== false;
1101 * Get information about an index into an object
1102 * Returns false if the index does not exist
1104 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1105 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1106 # SHOW INDEX should work for 3.x and up:
1107 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1108 $table = $this->tableName( $table );
1109 $sql = 'SHOW INDEX FROM '.$table;
1110 $res = $this->query( $sql, $fname );
1115 while ( $row = $this->fetchObject( $res ) ) {
1116 if ( $row->Key_name
== $index ) {
1124 * Query whether a given table exists
1126 function tableExists( $table ) {
1127 $table = $this->tableName( $table );
1128 $old = $this->ignoreErrors( true );
1129 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1130 $this->ignoreErrors( $old );
1132 $this->freeResult( $res );
1140 * mysql_fetch_field() wrapper
1141 * Returns false if the field doesn't exist
1146 function fieldInfo( $table, $field ) {
1147 $table = $this->tableName( $table );
1148 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1149 $n = mysql_num_fields( $res );
1150 for( $i = 0; $i < $n; $i++
) {
1151 $meta = mysql_fetch_field( $res, $i );
1152 if( $field == $meta->name
) {
1160 * mysql_field_type() wrapper
1162 function fieldType( $res, $index ) {
1163 return mysql_field_type( $res, $index );
1167 * Determines if a given index is unique
1169 function indexUnique( $table, $index ) {
1170 $indexInfo = $this->indexInfo( $table, $index );
1171 if ( !$indexInfo ) {
1174 return !$indexInfo->Non_unique
;
1178 * INSERT wrapper, inserts an array into a table
1180 * $a may be a single associative array, or an array of these with numeric keys, for
1183 * Usually aborts on failure
1184 * If errors are explicitly ignored, returns success
1186 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1187 # No rows to insert, easy just return now
1188 if ( !count( $a ) ) {
1192 $table = $this->tableName( $table );
1193 if ( !is_array( $options ) ) {
1194 $options = array( $options );
1196 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1198 $keys = array_keys( $a[0] );
1201 $keys = array_keys( $a );
1204 $sql = 'INSERT ' . implode( ' ', $options ) .
1205 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1209 foreach ( $a as $row ) {
1215 $sql .= '(' . $this->makeList( $row ) . ')';
1218 $sql .= '(' . $this->makeList( $a ) . ')';
1220 return (bool)$this->query( $sql, $fname );
1224 * Make UPDATE options for the Database::update function
1227 * @param array $options The options passed to Database::update
1230 function makeUpdateOptions( $options ) {
1231 if( !is_array( $options ) ) {
1232 $options = array( $options );
1235 if ( in_array( 'LOW_PRIORITY', $options ) )
1236 $opts[] = $this->lowPriorityOption();
1237 if ( in_array( 'IGNORE', $options ) )
1239 return implode(' ', $opts);
1243 * UPDATE wrapper, takes a condition array and a SET array
1245 * @param string $table The table to UPDATE
1246 * @param array $values An array of values to SET
1247 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1248 * @param string $fname The Class::Function calling this function
1250 * @param array $options An array of UPDATE options, can be one or
1251 * more of IGNORE, LOW_PRIORITY
1253 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1254 $table = $this->tableName( $table );
1255 $opts = $this->makeUpdateOptions( $options );
1256 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1257 if ( $conds != '*' ) {
1258 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1260 $this->query( $sql, $fname );
1264 * Makes a wfStrencoded list from an array
1266 * LIST_COMMA - comma separated, no field names
1267 * LIST_AND - ANDed WHERE clause (without the WHERE)
1268 * LIST_OR - ORed WHERE clause (without the WHERE)
1269 * LIST_SET - comma separated with field names, like a SET clause
1270 * LIST_NAMES - comma separated field names
1272 function makeList( $a, $mode = LIST_COMMA
) {
1273 if ( !is_array( $a ) ) {
1274 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1279 foreach ( $a as $field => $value ) {
1281 if ( $mode == LIST_AND
) {
1283 } elseif($mode == LIST_OR
) {
1291 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1292 $list .= "($value)";
1293 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array ($value) ) {
1294 $list .= $field." IN (".$this->makeList($value).") ";
1296 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1297 $list .= "$field = ";
1299 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1306 * Change the current database
1308 function selectDB( $db ) {
1309 $this->mDBname
= $db;
1310 return mysql_select_db( $db, $this->mConn
);
1314 * Format a table name ready for use in constructing an SQL query
1316 * This does two important things: it quotes table names which as necessary,
1317 * and it adds a table prefix if there is one.
1319 * All functions of this object which require a table name call this function
1320 * themselves. Pass the canonical name to such functions. This is only needed
1321 * when calling query() directly.
1323 * @param string $name database table name
1325 function tableName( $name ) {
1327 # Skip quoted literals
1328 if ( $name{0} != '`' ) {
1329 if ( $this->mTablePrefix
!== '' && strpos( '.', $name ) === false ) {
1330 $name = "{$this->mTablePrefix}$name";
1332 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1333 $name = "`$wgSharedDB`.`$name`";
1343 * Fetch a number of table names into an array
1344 * This is handy when you need to construct SQL for joins
1347 * extract($dbr->tableNames('user','watchlist'));
1348 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1349 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1351 function tableNames() {
1352 $inArray = func_get_args();
1354 foreach ( $inArray as $name ) {
1355 $retVal[$name] = $this->tableName( $name );
1363 function tableNamesWithUseIndex( $tables, $use_index ) {
1366 foreach ( $tables as $table )
1367 if ( @$use_index[$table] !== null )
1368 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1370 $ret[] = $this->tableName( $table );
1372 return implode( ',', $ret );
1376 * Wrapper for addslashes()
1377 * @param string $s String to be slashed.
1378 * @return string slashed string.
1380 function strencode( $s ) {
1381 return mysql_real_escape_string( $s, $this->mConn
);
1385 * If it's a string, adds quotes and backslashes
1386 * Otherwise returns as-is
1388 function addQuotes( $s ) {
1389 if ( is_null( $s ) ) {
1392 # This will also quote numeric values. This should be harmless,
1393 # and protects against weird problems that occur when they really
1394 # _are_ strings such as article titles and string->number->string
1395 # conversion is not 1:1.
1396 return "'" . $this->strencode( $s ) . "'";
1401 * Escape string for safe LIKE usage
1403 function escapeLike( $s ) {
1404 $s=$this->strencode( $s );
1405 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1410 * Returns an appropriately quoted sequence value for inserting a new row.
1411 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1412 * subclass will return an integer, and save the value for insertId()
1414 function nextSequenceValue( $seqName ) {
1420 * PostgreSQL doesn't have them and returns ""
1422 function useIndexClause( $index ) {
1423 return "FORCE INDEX ($index)";
1427 * REPLACE query wrapper
1428 * PostgreSQL simulates this with a DELETE followed by INSERT
1429 * $row is the row to insert, an associative array
1430 * $uniqueIndexes is an array of indexes. Each element may be either a
1431 * field name or an array of field names
1433 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1434 * However if you do this, you run the risk of encountering errors which wouldn't have
1437 * @todo migrate comment to phodocumentor format
1439 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1440 $table = $this->tableName( $table );
1443 if ( !is_array( reset( $rows ) ) ) {
1444 $rows = array( $rows );
1447 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1449 foreach ( $rows as $row ) {
1455 $sql .= '(' . $this->makeList( $row ) . ')';
1457 return $this->query( $sql, $fname );
1461 * DELETE where the condition is a join
1462 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1464 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1465 * join condition matches, set $conds='*'
1467 * DO NOT put the join condition in $conds
1469 * @param string $delTable The table to delete from.
1470 * @param string $joinTable The other table.
1471 * @param string $delVar The variable to join on, in the first table.
1472 * @param string $joinVar The variable to join on, in the second table.
1473 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1475 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1477 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1480 $delTable = $this->tableName( $delTable );
1481 $joinTable = $this->tableName( $joinTable );
1482 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1483 if ( $conds != '*' ) {
1484 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1487 return $this->query( $sql, $fname );
1491 * Returns the size of a text field, or -1 for "unlimited"
1493 function textFieldSize( $table, $field ) {
1494 $table = $this->tableName( $table );
1495 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1496 $res = $this->query( $sql, 'Database::textFieldSize' );
1497 $row = $this->fetchObject( $res );
1498 $this->freeResult( $res );
1500 if ( preg_match( "/\((.*)\)/", $row->Type
, $m ) ) {
1509 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1511 function lowPriorityOption() {
1512 return 'LOW_PRIORITY';
1516 * DELETE query wrapper
1518 * Use $conds == "*" to delete all rows
1520 function delete( $table, $conds, $fname = 'Database::delete' ) {
1522 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1524 $table = $this->tableName( $table );
1525 $sql = "DELETE FROM $table";
1526 if ( $conds != '*' ) {
1527 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1529 return $this->query( $sql, $fname );
1533 * INSERT SELECT wrapper
1534 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1535 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1536 * $conds may be "*" to copy the whole table
1537 * srcTable may be an array of tables.
1539 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1540 $insertOptions = array(), $selectOptions = array() )
1542 $destTable = $this->tableName( $destTable );
1543 if ( is_array( $insertOptions ) ) {
1544 $insertOptions = implode( ' ', $insertOptions );
1546 if( !is_array( $selectOptions ) ) {
1547 $selectOptions = array( $selectOptions );
1549 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1550 if( is_array( $srcTable ) ) {
1551 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1553 $srcTable = $this->tableName( $srcTable );
1555 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1556 " SELECT $startOpts " . implode( ',', $varMap ) .
1557 " FROM $srcTable $useIndex ";
1558 if ( $conds != '*' ) {
1559 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1561 $sql .= " $tailOpts";
1562 return $this->query( $sql, $fname );
1566 * Construct a LIMIT query with optional offset
1567 * This is used for query pages
1568 * $sql string SQL query we will append the limit too
1569 * $limit integer the SQL limit
1570 * $offset integer the SQL offset (default false)
1572 function limitResult($sql, $limit, $offset=false) {
1573 if( !is_numeric($limit) ) {
1574 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1576 return " $sql LIMIT "
1577 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1580 function limitResultForUpdate($sql, $num) {
1581 return $this->limitResult($sql, $num, 0);
1585 * Returns an SQL expression for a simple conditional.
1588 * @param string $cond SQL expression which will result in a boolean value
1589 * @param string $trueVal SQL expression to return if true
1590 * @param string $falseVal SQL expression to return if false
1591 * @return string SQL fragment
1593 function conditional( $cond, $trueVal, $falseVal ) {
1594 return " IF($cond, $trueVal, $falseVal) ";
1598 * Determines if the last failure was due to a deadlock
1600 function wasDeadlock() {
1601 return $this->lastErrno() == 1213;
1605 * Perform a deadlock-prone transaction.
1607 * This function invokes a callback function to perform a set of write
1608 * queries. If a deadlock occurs during the processing, the transaction
1609 * will be rolled back and the callback function will be called again.
1612 * $dbw->deadlockLoop( callback, ... );
1614 * Extra arguments are passed through to the specified callback function.
1616 * Returns whatever the callback function returned on its successful,
1617 * iteration, or false on error, for example if the retry limit was
1620 function deadlockLoop() {
1621 $myFname = 'Database::deadlockLoop';
1624 $args = func_get_args();
1625 $function = array_shift( $args );
1626 $oldIgnore = $this->ignoreErrors( true );
1627 $tries = DEADLOCK_TRIES
;
1628 if ( is_array( $function ) ) {
1629 $fname = $function[0];
1634 $retVal = call_user_func_array( $function, $args );
1635 $error = $this->lastError();
1636 $errno = $this->lastErrno();
1637 $sql = $this->lastQuery();
1640 if ( $this->wasDeadlock() ) {
1642 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1644 $this->reportQueryError( $error, $errno, $sql, $fname );
1647 } while( $this->wasDeadlock() && --$tries > 0 );
1648 $this->ignoreErrors( $oldIgnore );
1649 if ( $tries <= 0 ) {
1650 $this->query( 'ROLLBACK', $myFname );
1651 $this->reportQueryError( $error, $errno, $sql, $fname );
1654 $this->query( 'COMMIT', $myFname );
1660 * Do a SELECT MASTER_POS_WAIT()
1662 * @param string $file the binlog file
1663 * @param string $pos the binlog position
1664 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1666 function masterPosWait( $file, $pos, $timeout ) {
1667 $fname = 'Database::masterPosWait';
1668 wfProfileIn( $fname );
1671 # Commit any open transactions
1672 $this->immediateCommit();
1674 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1675 $encFile = $this->strencode( $file );
1676 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1677 $res = $this->doQuery( $sql );
1678 if ( $res && $row = $this->fetchRow( $res ) ) {
1679 $this->freeResult( $res );
1680 wfProfileOut( $fname );
1683 wfProfileOut( $fname );
1689 * Get the position of the master from SHOW SLAVE STATUS
1691 function getSlavePos() {
1692 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1693 $row = $this->fetchObject( $res );
1695 return array( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1697 return array( false, false );
1702 * Get the position of the master from SHOW MASTER STATUS
1704 function getMasterPos() {
1705 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1706 $row = $this->fetchObject( $res );
1708 return array( $row->File
, $row->Position
);
1710 return array( false, false );
1715 * Begin a transaction, committing any previously open transaction
1717 function begin( $fname = 'Database::begin' ) {
1718 $this->query( 'BEGIN', $fname );
1719 $this->mTrxLevel
= 1;
1725 function commit( $fname = 'Database::commit' ) {
1726 $this->query( 'COMMIT', $fname );
1727 $this->mTrxLevel
= 0;
1731 * Rollback a transaction
1733 function rollback( $fname = 'Database::rollback' ) {
1734 $this->query( 'ROLLBACK', $fname );
1735 $this->mTrxLevel
= 0;
1739 * Begin a transaction, committing any previously open transaction
1740 * @deprecated use begin()
1742 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1747 * Commit transaction, if one is open
1748 * @deprecated use commit()
1750 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1755 * Return MW-style timestamp used for MySQL schema
1757 function timestamp( $ts=0 ) {
1758 return wfTimestamp(TS_MW
,$ts);
1762 * Local database timestamp format or null
1764 function timestampOrNull( $ts = null ) {
1765 if( is_null( $ts ) ) {
1768 return $this->timestamp( $ts );
1775 function resultObject( $result ) {
1776 if( empty( $result ) ) {
1779 return new ResultWrapper( $this, $result );
1784 * Return aggregated value alias
1786 function aggregateValue ($valuedata,$valuename='value') {
1791 * @return string wikitext of a link to the server software's web site
1793 function getSoftwareLink() {
1794 return "[http://www.mysql.com/ MySQL]";
1798 * @return string Version information from the database
1800 function getServerVersion() {
1801 return mysql_get_server_info();
1805 * Ping the server and try to reconnect if it there is no connection
1808 if( function_exists( 'mysql_ping' ) ) {
1809 return mysql_ping( $this->mConn
);
1811 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1818 * At the moment, this will only work if the DB user has the PROCESS privilege
1821 $res = $this->query( 'SHOW PROCESSLIST' );
1822 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1823 # dubious, but unfortunately there's no easy rigorous way
1825 while ( $row = $this->fetchObject( $res ) ) {
1826 /* This should work for most situations - when default db
1827 * for thread is not specified, it had no events executed,
1828 * and therefore it doesn't know yet how lagged it is.
1830 * Relay log I/O thread does not select databases.
1832 if ( $row->User
== 'system user' &&
1833 $row->State
!= 'Waiting for master to send event' &&
1834 $row->State
!= 'Connecting to master' &&
1835 $row->State
!= 'Queueing master event to the relay log' &&
1836 $row->State
!= 'Waiting for master update' &&
1837 $row->State
!= 'Requesting binlog dump'
1839 # This is it, return the time (except -ve)
1840 if ( $row->Time
> 0x7fffffff ) {
1851 * Get status information from SHOW STATUS in an associative array
1853 function getStatus($which="%") {
1854 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1856 while ( $row = $this->fetchObject( $res ) ) {
1857 $status[$row->Variable_name
] = $row->Value
;
1863 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1865 function maxListLen() {
1869 function encodeBlob($b) {
1873 function decodeBlob($b) {
1878 * Read and execute SQL commands from a file.
1879 * Returns true on success, error string on failure
1881 function sourceFile( $filename ) {
1882 $fp = fopen( $filename, 'r' );
1883 if ( false === $fp ) {
1884 return "Could not open \"{$fname}\".\n";
1889 $dollarquote = false;
1891 while ( ! feof( $fp ) ) {
1892 $line = trim( fgets( $fp, 1024 ) );
1893 $sl = strlen( $line ) - 1;
1895 if ( $sl < 0 ) { continue; }
1896 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
1898 ## Allow dollar quoting for function declarations
1899 if (substr($line,0,4) == '$mw$') {
1901 $dollarquote = false;
1905 $dollarquote = true;
1908 else if (!$dollarquote) {
1909 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
1911 $line = substr( $line, 0, $sl );
1915 if ( '' != $cmd ) { $cmd .= ' '; }
1919 $cmd = str_replace(';;', ";", $cmd);
1920 $cmd = $this->replaceVars( $cmd );
1921 $res = $this->query( $cmd, 'dbsource', true );
1923 if ( false === $res ) {
1924 $err = $this->lastError();
1925 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1937 * Replace variables in sourced SQL
1939 protected function replaceVars( $ins ) {
1941 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
1942 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
1943 'wgDBadminuser', 'wgDBadminpassword',
1946 // Ordinary variables
1947 foreach ( $varnames as $var ) {
1948 if( isset( $GLOBALS[$var] ) ) {
1949 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
1950 $ins = str_replace( '{$' . $var . '}', $val, $ins );
1951 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
1952 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
1957 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
1958 array( &$this, 'tableNameCallback' ), $ins );
1963 * Table name callback
1966 protected function tableNameCallback( $matches ) {
1967 return $this->tableName( $matches[1] );
1973 * Database abstraction object for mySQL
1974 * Inherit all methods and properties of Database::Database()
1976 * @package MediaWiki
1979 class DatabaseMysql
extends Database
{
1985 * Result wrapper for grabbing data queried by someone else
1987 * @package MediaWiki
1989 class ResultWrapper
{
1995 function ResultWrapper( &$database, $result ) {
1996 $this->db
=& $database;
1997 $this->result
=& $result;
2003 function numRows() {
2004 return $this->db
->numRows( $this->result
);
2010 function fetchObject() {
2011 return $this->db
->fetchObject( $this->result
);
2017 function fetchRow() {
2018 return $this->db
->fetchRow( $this->result
);
2025 $this->db
->freeResult( $this->result
);
2026 unset( $this->result
);
2030 function seek( $row ) {
2031 $this->db
->dataSeek( $this->result
, $row );