1812cd1ec3d20d155144aa3d36d368e5fdf34885
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 ) {
452 wfProfileIn( __METHOD__
);
454 # Test for missing mysql.so
455 # First try to load it
456 if (!@extension_loaded
('mysql')) {
461 # Otherwise we get a suppressed fatal error, which is very hard to track down
462 if ( !function_exists( 'mysql_connect' ) ) {
463 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
467 $this->mServer
= $server;
468 $this->mUser
= $user;
469 $this->mPassword
= $password;
470 $this->mDBname
= $dbName;
474 if ( $this->mFlags
& DBO_PERSISTENT
) {
475 @/**/$this->mConn
= mysql_pconnect( $server, $user, $password );
477 # Create a new connection...
478 @/**/$this->mConn
= mysql_connect( $server, $user, $password, true );
481 if ( $dbName != '' ) {
482 if ( $this->mConn
!== false ) {
483 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
485 $error = "Error selecting database $dbName on server {$this->mServer} " .
486 "from client host {$wguname['nodename']}\n";
490 wfDebug( "DB connection error\n" );
491 wfDebug( "Server: $server, User: $user, Password: " .
492 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
497 $success = (bool)$this->mConn
;
501 $this->reportConnectionError();
506 // Tell the server we're communicating with it in UTF-8.
507 // This may engage various charset conversions.
508 $this->query( 'SET NAMES utf8' );
511 $this->mOpened
= $success;
512 wfProfileOut( __METHOD__
);
518 * Closes a database connection.
519 * if it is open : commits any open transactions
521 * @return bool operation success. true if already closed.
525 $this->mOpened
= false;
526 if ( $this->mConn
) {
527 if ( $this->trxLevel() ) {
528 $this->immediateCommit();
530 return mysql_close( $this->mConn
);
537 * @param string $error fallback error message, used if none is given by MySQL
539 function reportConnectionError( $error = 'Unknown error' ) {
540 $myError = $this->lastError();
545 if ( $this->mFailFunction
) {
546 # Legacy error handling method
547 if ( !is_int( $this->mFailFunction
) ) {
548 $ff = $this->mFailFunction
;
549 $ff( $this, $error );
553 wfLogDBError( "Connection error: $error\n" );
554 throw new DBConnectionError( $this, $error );
559 * Usually aborts on failure
560 * If errors are explicitly ignored, returns success
562 function query( $sql, $fname = '', $tempIgnore = false ) {
565 if ( $wgProfiling ) {
566 # generalizeSQL will probably cut down the query to reasonable
567 # logging size most of the time. The substr is really just a sanity check.
569 # Who's been wasting my precious column space? -- TS
570 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
572 if ( is_null( $this->getLBInfo( 'master' ) ) ) {
573 $queryProf = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
574 $totalProf = 'Database::query';
576 $queryProf = 'query-m: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
577 $totalProf = 'Database::query-master';
579 wfProfileIn( $totalProf );
580 wfProfileIn( $queryProf );
583 $this->mLastQuery
= $sql;
585 # Add a comment for easy SHOW PROCESSLIST interpretation
587 $commentedSql = preg_replace("/\s/", " /* $fname */ ", $sql, 1);
589 $commentedSql = $sql;
592 # If DBO_TRX is set, start a transaction
593 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
594 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK'
599 if ( $this->debug() ) {
600 $sqlx = substr( $commentedSql, 0, 500 );
601 $sqlx = strtr( $sqlx, "\t\n", ' ' );
602 wfDebug( "SQL: $sqlx\n" );
605 # Do the query and handle errors
606 $ret = $this->doQuery( $commentedSql );
608 # Try reconnecting if the connection was lost
609 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
610 # Transaction is gone, like it or not
611 $this->mTrxLevel
= 0;
612 wfDebug( "Connection lost, reconnecting...\n" );
613 if ( $this->ping() ) {
614 wfDebug( "Reconnected\n" );
615 $ret = $this->doQuery( $commentedSql );
617 wfDebug( "Failed\n" );
621 if ( false === $ret ) {
622 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
625 if ( $wgProfiling ) {
626 wfProfileOut( $queryProf );
627 wfProfileOut( $totalProf );
633 * The DBMS-dependent part of query()
634 * @param string $sql SQL query.
636 function doQuery( $sql ) {
637 if( $this->bufferResults() ) {
638 $ret = mysql_query( $sql, $this->mConn
);
640 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
649 * @param string $fname
650 * @param bool $tempIgnore
652 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
653 global $wgCommandLineMode, $wgFullyInitialised, $wgColorErrors;
654 # Ignore errors during error handling to avoid infinite recursion
655 $ignore = $this->ignoreErrors( true );
656 ++
$this->mErrorCount
;
658 if( $ignore ||
$tempIgnore ) {
659 wfDebug("SQL ERROR (ignored): $error\n");
660 $this->ignoreErrors( $ignore );
662 $sql1line = str_replace( "\n", "\\n", $sql );
663 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
664 wfDebug("SQL ERROR: " . $error . "\n");
665 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
671 * Intended to be compatible with the PEAR::DB wrapper functions.
672 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
674 * ? = scalar value, quoted as necessary
675 * ! = raw SQL bit (a function for instance)
676 * & = filename; reads the file and inserts as a blob
677 * (we don't use this though...)
679 function prepare( $sql, $func = 'Database::prepare' ) {
680 /* MySQL doesn't support prepared statements (yet), so just
681 pack up the query for reference. We'll manually replace
683 return array( 'query' => $sql, 'func' => $func );
686 function freePrepared( $prepared ) {
687 /* No-op for MySQL */
691 * Execute a prepared query with the various arguments
692 * @param string $prepared the prepared sql
693 * @param mixed $args Either an array here, or put scalars as varargs
695 function execute( $prepared, $args = null ) {
696 if( !is_array( $args ) ) {
698 $args = func_get_args();
699 array_shift( $args );
701 $sql = $this->fillPrepared( $prepared['query'], $args );
702 return $this->query( $sql, $prepared['func'] );
706 * Prepare & execute an SQL statement, quoting and inserting arguments
707 * in the appropriate places.
708 * @param string $query
709 * @param string $args ...
711 function safeQuery( $query, $args = null ) {
712 $prepared = $this->prepare( $query, 'Database::safeQuery' );
713 if( !is_array( $args ) ) {
715 $args = func_get_args();
716 array_shift( $args );
718 $retval = $this->execute( $prepared, $args );
719 $this->freePrepared( $prepared );
724 * For faking prepared SQL statements on DBs that don't support
726 * @param string $preparedSql - a 'preparable' SQL statement
727 * @param array $args - array of arguments to fill it with
728 * @return string executable SQL
730 function fillPrepared( $preparedQuery, $args ) {
732 $this->preparedArgs
=& $args;
733 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
734 array( &$this, 'fillPreparedArg' ), $preparedQuery );
738 * preg_callback func for fillPrepared()
739 * The arguments should be in $this->preparedArgs and must not be touched
740 * while we're doing this.
742 * @param array $matches
746 function fillPreparedArg( $matches ) {
747 switch( $matches[1] ) {
748 case '\\?': return '?';
749 case '\\!': return '!';
750 case '\\&': return '&';
752 list( $n, $arg ) = each( $this->preparedArgs
);
753 switch( $matches[1] ) {
754 case '?': return $this->addQuotes( $arg );
755 case '!': return $arg;
757 # return $this->addQuotes( file_get_contents( $arg ) );
758 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
760 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
765 * @param mixed $res A SQL result
768 * Free a result object
770 function freeResult( $res ) {
771 if ( !@/**/mysql_free_result( $res ) ) {
772 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
777 * Fetch the next row from the given result object, in object form
779 function fetchObject( $res ) {
780 @/**/$row = mysql_fetch_object( $res );
781 if( $this->lastErrno() ) {
782 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
788 * Fetch the next row from the given result object
791 function fetchRow( $res ) {
792 @/**/$row = mysql_fetch_array( $res );
793 if ( $this->lastErrno() ) {
794 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
800 * Get the number of rows in a result object
802 function numRows( $res ) {
803 @/**/$n = mysql_num_rows( $res );
804 if( $this->lastErrno() ) {
805 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
811 * Get the number of fields in a result object
812 * See documentation for mysql_num_fields()
814 function numFields( $res ) { return mysql_num_fields( $res ); }
817 * Get a field name in a result object
818 * See documentation for mysql_field_name():
819 * http://www.php.net/mysql_field_name
821 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
824 * Get the inserted value of an auto-increment row
826 * The value inserted should be fetched from nextSequenceValue()
829 * $id = $dbw->nextSequenceValue('page_page_id_seq');
830 * $dbw->insert('page',array('page_id' => $id));
831 * $id = $dbw->insertId();
833 function insertId() { return mysql_insert_id( $this->mConn
); }
836 * Change the position of the cursor in a result object
837 * See mysql_data_seek()
839 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
842 * Get the last error number
845 function lastErrno() {
846 if ( $this->mConn
) {
847 return mysql_errno( $this->mConn
);
849 return mysql_errno();
854 * Get a description of the last error
855 * See mysql_error() for more details
857 function lastError() {
858 if ( $this->mConn
) {
859 # Even if it's non-zero, it can still be invalid
860 wfSuppressWarnings();
861 $error = mysql_error( $this->mConn
);
863 $error = mysql_error();
867 $error = mysql_error();
870 $error .= ' (' . $this->mServer
. ')';
875 * Get the number of rows affected by the last write query
876 * See mysql_affected_rows() for more details
878 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
879 /**#@-*/ // end of template : @param $result
882 * Simple UPDATE wrapper
883 * Usually aborts on failure
884 * If errors are explicitly ignored, returns success
886 * This function exists for historical reasons, Database::update() has a more standard
887 * calling convention and feature set
889 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
891 $table = $this->tableName( $table );
892 $sql = "UPDATE $table SET $var = '" .
893 $this->strencode( $value ) . "' WHERE ($cond)";
894 return (bool)$this->query( $sql, $fname );
898 * Simple SELECT wrapper, returns a single field, input must be encoded
899 * Usually aborts on failure
900 * If errors are explicitly ignored, returns FALSE on failure
902 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
903 if ( !is_array( $options ) ) {
904 $options = array( $options );
906 $options['LIMIT'] = 1;
908 $res = $this->select( $table, $var, $cond, $fname, $options );
909 if ( $res === false ||
!$this->numRows( $res ) ) {
912 $row = $this->fetchRow( $res );
913 if ( $row !== false ) {
914 $this->freeResult( $res );
922 * Returns an optional USE INDEX clause to go after the table, and a
923 * string to go at the end of the query
927 * @param array $options an associative array of options to be turned into
928 * an SQL query, valid keys are listed in the function.
931 function makeSelectOptions( $options ) {
935 $noKeyOptions = array();
936 foreach ( $options as $key => $option ) {
937 if ( is_numeric( $key ) ) {
938 $noKeyOptions[$option] = true;
942 if ( isset( $options['GROUP BY'] ) ) $tailOpts .= " GROUP BY {$options['GROUP BY']}";
943 if ( isset( $options['ORDER BY'] ) ) $tailOpts .= " ORDER BY {$options['ORDER BY']}";
945 if (isset($options['LIMIT'])) {
946 $tailOpts .= $this->limitResult('', $options['LIMIT'],
947 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
950 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
951 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
952 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
954 # Various MySQL extensions
955 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
956 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
957 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
958 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
959 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
960 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
961 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
963 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
964 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
969 return array( $startOpts, $useIndex, $tailOpts );
975 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
977 if( is_array( $vars ) ) {
978 $vars = implode( ',', $vars );
980 if( !is_array( $options ) ) {
981 $options = array( $options );
983 if( is_array( $table ) ) {
984 if ( @is_array
( $options['USE INDEX'] ) )
985 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
987 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
988 } elseif ($table!='') {
989 $from = ' FROM ' . $this->tableName( $table );
994 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
996 if( !empty( $conds ) ) {
997 if ( is_array( $conds ) ) {
998 $conds = $this->makeList( $conds, LIST_AND
);
1000 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $tailOpts";
1002 $sql = "SELECT $startOpts $vars $from $useIndex $tailOpts";
1005 return $this->query( $sql, $fname );
1009 * Single row SELECT wrapper
1010 * Aborts or returns FALSE on error
1012 * $vars: the selected variables
1013 * $conds: a condition map, terms are ANDed together.
1014 * Items with numeric keys are taken to be literal conditions
1015 * Takes an array of selected variables, and a condition map, which is ANDed
1016 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1017 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1018 * $obj- >page_id is the ID of the Astronomy article
1020 * @todo migrate documentation to phpdocumentor format
1022 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
1023 $options['LIMIT'] = 1;
1024 $res = $this->select( $table, $vars, $conds, $fname, $options );
1025 if ( $res === false )
1027 if ( !$this->numRows($res) ) {
1028 $this->freeResult($res);
1031 $obj = $this->fetchObject( $res );
1032 $this->freeResult( $res );
1038 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1039 * It's only slightly flawed. Don't use for anything important.
1041 * @param string $sql A SQL Query
1044 static function generalizeSQL( $sql ) {
1045 # This does the same as the regexp below would do, but in such a way
1046 # as to avoid crashing php on some large strings.
1047 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1049 $sql = str_replace ( "\\\\", '', $sql);
1050 $sql = str_replace ( "\\'", '', $sql);
1051 $sql = str_replace ( "\\\"", '', $sql);
1052 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1053 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1055 # All newlines, tabs, etc replaced by single space
1056 $sql = preg_replace ( "/\s+/", ' ', $sql);
1059 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1065 * Determines whether a field exists in a table
1066 * Usually aborts on failure
1067 * If errors are explicitly ignored, returns NULL on failure
1069 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1070 $table = $this->tableName( $table );
1071 $res = $this->query( 'DESCRIBE '.$table, $fname );
1078 while ( $row = $this->fetchObject( $res ) ) {
1079 if ( $row->Field
== $field ) {
1088 * Determines whether an index exists
1089 * Usually aborts on failure
1090 * If errors are explicitly ignored, returns NULL on failure
1092 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1093 $info = $this->indexInfo( $table, $index, $fname );
1094 if ( is_null( $info ) ) {
1097 return $info !== false;
1103 * Get information about an index into an object
1104 * Returns false if the index does not exist
1106 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1107 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1108 # SHOW INDEX should work for 3.x and up:
1109 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1110 $table = $this->tableName( $table );
1111 $sql = 'SHOW INDEX FROM '.$table;
1112 $res = $this->query( $sql, $fname );
1117 while ( $row = $this->fetchObject( $res ) ) {
1118 if ( $row->Key_name
== $index ) {
1126 * Query whether a given table exists
1128 function tableExists( $table ) {
1129 $table = $this->tableName( $table );
1130 $old = $this->ignoreErrors( true );
1131 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1132 $this->ignoreErrors( $old );
1134 $this->freeResult( $res );
1142 * mysql_fetch_field() wrapper
1143 * Returns false if the field doesn't exist
1148 function fieldInfo( $table, $field ) {
1149 $table = $this->tableName( $table );
1150 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1151 $n = mysql_num_fields( $res );
1152 for( $i = 0; $i < $n; $i++
) {
1153 $meta = mysql_fetch_field( $res, $i );
1154 if( $field == $meta->name
) {
1162 * mysql_field_type() wrapper
1164 function fieldType( $res, $index ) {
1165 return mysql_field_type( $res, $index );
1169 * Determines if a given index is unique
1171 function indexUnique( $table, $index ) {
1172 $indexInfo = $this->indexInfo( $table, $index );
1173 if ( !$indexInfo ) {
1176 return !$indexInfo->Non_unique
;
1180 * INSERT wrapper, inserts an array into a table
1182 * $a may be a single associative array, or an array of these with numeric keys, for
1185 * Usually aborts on failure
1186 * If errors are explicitly ignored, returns success
1188 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1189 # No rows to insert, easy just return now
1190 if ( !count( $a ) ) {
1194 $table = $this->tableName( $table );
1195 if ( !is_array( $options ) ) {
1196 $options = array( $options );
1198 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1200 $keys = array_keys( $a[0] );
1203 $keys = array_keys( $a );
1206 $sql = 'INSERT ' . implode( ' ', $options ) .
1207 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1211 foreach ( $a as $row ) {
1217 $sql .= '(' . $this->makeList( $row ) . ')';
1220 $sql .= '(' . $this->makeList( $a ) . ')';
1222 return (bool)$this->query( $sql, $fname );
1226 * Make UPDATE options for the Database::update function
1229 * @param array $options The options passed to Database::update
1232 function makeUpdateOptions( $options ) {
1233 if( !is_array( $options ) ) {
1234 $options = array( $options );
1237 if ( in_array( 'LOW_PRIORITY', $options ) )
1238 $opts[] = $this->lowPriorityOption();
1239 if ( in_array( 'IGNORE', $options ) )
1241 return implode(' ', $opts);
1245 * UPDATE wrapper, takes a condition array and a SET array
1247 * @param string $table The table to UPDATE
1248 * @param array $values An array of values to SET
1249 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1250 * @param string $fname The Class::Function calling this function
1252 * @param array $options An array of UPDATE options, can be one or
1253 * more of IGNORE, LOW_PRIORITY
1255 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1256 $table = $this->tableName( $table );
1257 $opts = $this->makeUpdateOptions( $options );
1258 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1259 if ( $conds != '*' ) {
1260 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1262 $this->query( $sql, $fname );
1266 * Makes a wfStrencoded list from an array
1268 * LIST_COMMA - comma separated, no field names
1269 * LIST_AND - ANDed WHERE clause (without the WHERE)
1270 * LIST_OR - ORed WHERE clause (without the WHERE)
1271 * LIST_SET - comma separated with field names, like a SET clause
1272 * LIST_NAMES - comma separated field names
1274 function makeList( $a, $mode = LIST_COMMA
) {
1275 if ( !is_array( $a ) ) {
1276 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1281 foreach ( $a as $field => $value ) {
1283 if ( $mode == LIST_AND
) {
1285 } elseif($mode == LIST_OR
) {
1293 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1294 $list .= "($value)";
1295 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array ($value) ) {
1296 $list .= $field." IN (".$this->makeList($value).") ";
1298 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1299 $list .= "$field = ";
1301 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1308 * Change the current database
1310 function selectDB( $db ) {
1311 $this->mDBname
= $db;
1312 return mysql_select_db( $db, $this->mConn
);
1316 * Format a table name ready for use in constructing an SQL query
1318 * This does two important things: it quotes table names which as necessary,
1319 * and it adds a table prefix if there is one.
1321 * All functions of this object which require a table name call this function
1322 * themselves. Pass the canonical name to such functions. This is only needed
1323 * when calling query() directly.
1325 * @param string $name database table name
1327 function tableName( $name ) {
1329 # Skip quoted literals
1330 if ( $name{0} != '`' ) {
1331 if ( $this->mTablePrefix
!== '' && strpos( '.', $name ) === false ) {
1332 $name = "{$this->mTablePrefix}$name";
1334 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1335 $name = "`$wgSharedDB`.`$name`";
1345 * Fetch a number of table names into an array
1346 * This is handy when you need to construct SQL for joins
1349 * extract($dbr->tableNames('user','watchlist'));
1350 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1351 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1353 function tableNames() {
1354 $inArray = func_get_args();
1356 foreach ( $inArray as $name ) {
1357 $retVal[$name] = $this->tableName( $name );
1365 function tableNamesWithUseIndex( $tables, $use_index ) {
1368 foreach ( $tables as $table )
1369 if ( @$use_index[$table] !== null )
1370 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1372 $ret[] = $this->tableName( $table );
1374 return implode( ',', $ret );
1378 * Wrapper for addslashes()
1379 * @param string $s String to be slashed.
1380 * @return string slashed string.
1382 function strencode( $s ) {
1383 return mysql_real_escape_string( $s, $this->mConn
);
1387 * If it's a string, adds quotes and backslashes
1388 * Otherwise returns as-is
1390 function addQuotes( $s ) {
1391 if ( is_null( $s ) ) {
1394 # This will also quote numeric values. This should be harmless,
1395 # and protects against weird problems that occur when they really
1396 # _are_ strings such as article titles and string->number->string
1397 # conversion is not 1:1.
1398 return "'" . $this->strencode( $s ) . "'";
1403 * Escape string for safe LIKE usage
1405 function escapeLike( $s ) {
1406 $s=$this->strencode( $s );
1407 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1412 * Returns an appropriately quoted sequence value for inserting a new row.
1413 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1414 * subclass will return an integer, and save the value for insertId()
1416 function nextSequenceValue( $seqName ) {
1422 * PostgreSQL doesn't have them and returns ""
1424 function useIndexClause( $index ) {
1425 return "FORCE INDEX ($index)";
1429 * REPLACE query wrapper
1430 * PostgreSQL simulates this with a DELETE followed by INSERT
1431 * $row is the row to insert, an associative array
1432 * $uniqueIndexes is an array of indexes. Each element may be either a
1433 * field name or an array of field names
1435 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1436 * However if you do this, you run the risk of encountering errors which wouldn't have
1439 * @todo migrate comment to phodocumentor format
1441 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1442 $table = $this->tableName( $table );
1445 if ( !is_array( reset( $rows ) ) ) {
1446 $rows = array( $rows );
1449 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1451 foreach ( $rows as $row ) {
1457 $sql .= '(' . $this->makeList( $row ) . ')';
1459 return $this->query( $sql, $fname );
1463 * DELETE where the condition is a join
1464 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1466 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1467 * join condition matches, set $conds='*'
1469 * DO NOT put the join condition in $conds
1471 * @param string $delTable The table to delete from.
1472 * @param string $joinTable The other table.
1473 * @param string $delVar The variable to join on, in the first table.
1474 * @param string $joinVar The variable to join on, in the second table.
1475 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1477 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1479 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1482 $delTable = $this->tableName( $delTable );
1483 $joinTable = $this->tableName( $joinTable );
1484 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1485 if ( $conds != '*' ) {
1486 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1489 return $this->query( $sql, $fname );
1493 * Returns the size of a text field, or -1 for "unlimited"
1495 function textFieldSize( $table, $field ) {
1496 $table = $this->tableName( $table );
1497 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1498 $res = $this->query( $sql, 'Database::textFieldSize' );
1499 $row = $this->fetchObject( $res );
1500 $this->freeResult( $res );
1502 if ( preg_match( "/\((.*)\)/", $row->Type
, $m ) ) {
1511 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1513 function lowPriorityOption() {
1514 return 'LOW_PRIORITY';
1518 * DELETE query wrapper
1520 * Use $conds == "*" to delete all rows
1522 function delete( $table, $conds, $fname = 'Database::delete' ) {
1524 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1526 $table = $this->tableName( $table );
1527 $sql = "DELETE FROM $table";
1528 if ( $conds != '*' ) {
1529 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1531 return $this->query( $sql, $fname );
1535 * INSERT SELECT wrapper
1536 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1537 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1538 * $conds may be "*" to copy the whole table
1539 * srcTable may be an array of tables.
1541 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1542 $insertOptions = array(), $selectOptions = array() )
1544 $destTable = $this->tableName( $destTable );
1545 if ( is_array( $insertOptions ) ) {
1546 $insertOptions = implode( ' ', $insertOptions );
1548 if( !is_array( $selectOptions ) ) {
1549 $selectOptions = array( $selectOptions );
1551 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1552 if( is_array( $srcTable ) ) {
1553 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1555 $srcTable = $this->tableName( $srcTable );
1557 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1558 " SELECT $startOpts " . implode( ',', $varMap ) .
1559 " FROM $srcTable $useIndex ";
1560 if ( $conds != '*' ) {
1561 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1563 $sql .= " $tailOpts";
1564 return $this->query( $sql, $fname );
1568 * Construct a LIMIT query with optional offset
1569 * This is used for query pages
1570 * $sql string SQL query we will append the limit too
1571 * $limit integer the SQL limit
1572 * $offset integer the SQL offset (default false)
1574 function limitResult($sql, $limit, $offset=false) {
1575 if( !is_numeric($limit) ) {
1576 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1578 return " $sql LIMIT "
1579 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1582 function limitResultForUpdate($sql, $num) {
1583 return $this->limitResult($sql, $num, 0);
1587 * Returns an SQL expression for a simple conditional.
1590 * @param string $cond SQL expression which will result in a boolean value
1591 * @param string $trueVal SQL expression to return if true
1592 * @param string $falseVal SQL expression to return if false
1593 * @return string SQL fragment
1595 function conditional( $cond, $trueVal, $falseVal ) {
1596 return " IF($cond, $trueVal, $falseVal) ";
1600 * Determines if the last failure was due to a deadlock
1602 function wasDeadlock() {
1603 return $this->lastErrno() == 1213;
1607 * Perform a deadlock-prone transaction.
1609 * This function invokes a callback function to perform a set of write
1610 * queries. If a deadlock occurs during the processing, the transaction
1611 * will be rolled back and the callback function will be called again.
1614 * $dbw->deadlockLoop( callback, ... );
1616 * Extra arguments are passed through to the specified callback function.
1618 * Returns whatever the callback function returned on its successful,
1619 * iteration, or false on error, for example if the retry limit was
1622 function deadlockLoop() {
1623 $myFname = 'Database::deadlockLoop';
1626 $args = func_get_args();
1627 $function = array_shift( $args );
1628 $oldIgnore = $this->ignoreErrors( true );
1629 $tries = DEADLOCK_TRIES
;
1630 if ( is_array( $function ) ) {
1631 $fname = $function[0];
1636 $retVal = call_user_func_array( $function, $args );
1637 $error = $this->lastError();
1638 $errno = $this->lastErrno();
1639 $sql = $this->lastQuery();
1642 if ( $this->wasDeadlock() ) {
1644 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1646 $this->reportQueryError( $error, $errno, $sql, $fname );
1649 } while( $this->wasDeadlock() && --$tries > 0 );
1650 $this->ignoreErrors( $oldIgnore );
1651 if ( $tries <= 0 ) {
1652 $this->query( 'ROLLBACK', $myFname );
1653 $this->reportQueryError( $error, $errno, $sql, $fname );
1656 $this->query( 'COMMIT', $myFname );
1662 * Do a SELECT MASTER_POS_WAIT()
1664 * @param string $file the binlog file
1665 * @param string $pos the binlog position
1666 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1668 function masterPosWait( $file, $pos, $timeout ) {
1669 $fname = 'Database::masterPosWait';
1670 wfProfileIn( $fname );
1673 # Commit any open transactions
1674 $this->immediateCommit();
1676 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1677 $encFile = $this->strencode( $file );
1678 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1679 $res = $this->doQuery( $sql );
1680 if ( $res && $row = $this->fetchRow( $res ) ) {
1681 $this->freeResult( $res );
1682 wfProfileOut( $fname );
1685 wfProfileOut( $fname );
1691 * Get the position of the master from SHOW SLAVE STATUS
1693 function getSlavePos() {
1694 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1695 $row = $this->fetchObject( $res );
1697 return array( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1699 return array( false, false );
1704 * Get the position of the master from SHOW MASTER STATUS
1706 function getMasterPos() {
1707 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1708 $row = $this->fetchObject( $res );
1710 return array( $row->File
, $row->Position
);
1712 return array( false, false );
1717 * Begin a transaction, committing any previously open transaction
1719 function begin( $fname = 'Database::begin' ) {
1720 $this->query( 'BEGIN', $fname );
1721 $this->mTrxLevel
= 1;
1727 function commit( $fname = 'Database::commit' ) {
1728 $this->query( 'COMMIT', $fname );
1729 $this->mTrxLevel
= 0;
1733 * Rollback a transaction
1735 function rollback( $fname = 'Database::rollback' ) {
1736 $this->query( 'ROLLBACK', $fname );
1737 $this->mTrxLevel
= 0;
1741 * Begin a transaction, committing any previously open transaction
1742 * @deprecated use begin()
1744 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1749 * Commit transaction, if one is open
1750 * @deprecated use commit()
1752 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1757 * Return MW-style timestamp used for MySQL schema
1759 function timestamp( $ts=0 ) {
1760 return wfTimestamp(TS_MW
,$ts);
1764 * Local database timestamp format or null
1766 function timestampOrNull( $ts = null ) {
1767 if( is_null( $ts ) ) {
1770 return $this->timestamp( $ts );
1777 function resultObject( $result ) {
1778 if( empty( $result ) ) {
1781 return new ResultWrapper( $this, $result );
1786 * Return aggregated value alias
1788 function aggregateValue ($valuedata,$valuename='value') {
1793 * @return string wikitext of a link to the server software's web site
1795 function getSoftwareLink() {
1796 return "[http://www.mysql.com/ MySQL]";
1800 * @return string Version information from the database
1802 function getServerVersion() {
1803 return mysql_get_server_info();
1807 * Ping the server and try to reconnect if it there is no connection
1810 if( function_exists( 'mysql_ping' ) ) {
1811 return mysql_ping( $this->mConn
);
1813 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1820 * At the moment, this will only work if the DB user has the PROCESS privilege
1823 $res = $this->query( 'SHOW PROCESSLIST' );
1824 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1825 # dubious, but unfortunately there's no easy rigorous way
1827 while ( $row = $this->fetchObject( $res ) ) {
1828 /* This should work for most situations - when default db
1829 * for thread is not specified, it had no events executed,
1830 * and therefore it doesn't know yet how lagged it is.
1832 * Relay log I/O thread does not select databases.
1834 if ( $row->User
== 'system user' &&
1835 $row->State
!= 'Waiting for master to send event' &&
1836 $row->State
!= 'Connecting to master' &&
1837 $row->State
!= 'Queueing master event to the relay log' &&
1838 $row->State
!= 'Waiting for master update' &&
1839 $row->State
!= 'Requesting binlog dump'
1841 # This is it, return the time (except -ve)
1842 if ( $row->Time
> 0x7fffffff ) {
1853 * Get status information from SHOW STATUS in an associative array
1855 function getStatus($which="%") {
1856 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1858 while ( $row = $this->fetchObject( $res ) ) {
1859 $status[$row->Variable_name
] = $row->Value
;
1865 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1867 function maxListLen() {
1871 function encodeBlob($b) {
1875 function decodeBlob($b) {
1880 * Read and execute SQL commands from a file.
1881 * Returns true on success, error string on failure
1883 function sourceFile( $filename ) {
1884 $fp = fopen( $filename, 'r' );
1885 if ( false === $fp ) {
1886 return "Could not open \"{$fname}\".\n";
1891 $dollarquote = false;
1893 while ( ! feof( $fp ) ) {
1894 $line = trim( fgets( $fp, 1024 ) );
1895 $sl = strlen( $line ) - 1;
1897 if ( $sl < 0 ) { continue; }
1898 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
1900 ## Allow dollar quoting for function declarations
1901 if (substr($line,0,4) == '$mw$') {
1903 $dollarquote = false;
1907 $dollarquote = true;
1910 else if (!$dollarquote) {
1911 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
1913 $line = substr( $line, 0, $sl );
1917 if ( '' != $cmd ) { $cmd .= ' '; }
1921 $cmd = str_replace(';;', ";", $cmd);
1922 $cmd = $this->replaceVars( $cmd );
1923 $res = $this->query( $cmd, 'dbsource', true );
1925 if ( false === $res ) {
1926 $err = $this->lastError();
1927 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1939 * Replace variables in sourced SQL
1941 protected function replaceVars( $ins ) {
1943 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
1944 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
1945 'wgDBadminuser', 'wgDBadminpassword',
1948 // Ordinary variables
1949 foreach ( $varnames as $var ) {
1950 if( isset( $GLOBALS[$var] ) ) {
1951 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
1952 $ins = str_replace( '{$' . $var . '}', $val, $ins );
1953 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
1954 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
1959 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
1960 array( &$this, 'tableNameCallback' ), $ins );
1965 * Table name callback
1968 protected function tableNameCallback( $matches ) {
1969 return $this->tableName( $matches[1] );
1975 * Database abstraction object for mySQL
1976 * Inherit all methods and properties of Database::Database()
1978 * @package MediaWiki
1981 class DatabaseMysql
extends Database
{
1987 * Result wrapper for grabbing data queried by someone else
1989 * @package MediaWiki
1991 class ResultWrapper
{
1997 function ResultWrapper( &$database, $result ) {
1998 $this->db
=& $database;
1999 $this->result
=& $result;
2005 function numRows() {
2006 return $this->db
->numRows( $this->result
);
2012 function fetchObject() {
2013 return $this->db
->fetchObject( $this->result
);
2019 function fetchRow() {
2020 return $this->db
->fetchRow( $this->result
);
2027 $this->db
->freeResult( $this->result
);
2028 unset( $this->result
);
2032 function seek( $row ) {
2033 $this->db
->dataSeek( $this->result
, $row );