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();
248 #------------------------------------------------------------------------------
250 #------------------------------------------------------------------------------
251 # These optionally set a variable and return the previous state
254 * Fail function, takes a Database as a parameter
255 * Set to false for default, 1 for ignore errors
257 function failFunction( $function = NULL ) {
258 return wfSetVar( $this->mFailFunction
, $function );
262 * Output page, used for reporting errors
263 * FALSE means discard output
265 function setOutputPage( $out ) {
270 * Boolean, controls output of large amounts of debug information
272 function debug( $debug = NULL ) {
273 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
277 * Turns buffering of SQL result sets on (true) or off (false).
278 * Default is "on" and it should not be changed without good reasons.
280 function bufferResults( $buffer = NULL ) {
281 if ( is_null( $buffer ) ) {
282 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
284 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
289 * Turns on (false) or off (true) the automatic generation and sending
290 * of a "we're sorry, but there has been a database error" page on
291 * database errors. Default is on (false). When turned off, the
292 * code should use wfLastErrno() and wfLastError() to handle the
293 * situation as appropriate.
295 function ignoreErrors( $ignoreErrors = NULL ) {
296 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
300 * The current depth of nested transactions
301 * @param $level Integer: , default NULL.
303 function trxLevel( $level = NULL ) {
304 return wfSetVar( $this->mTrxLevel
, $level );
308 * Number of errors logged, only useful when errors are ignored
310 function errorCount( $count = NULL ) {
311 return wfSetVar( $this->mErrorCount
, $count );
315 * Properties passed down from the server info array of the load balancer
317 function getLBInfo( $name = NULL ) {
318 if ( is_null( $name ) ) {
319 return $this->mLBInfo
;
321 if ( array_key_exists( $name, $this->mLBInfo
) ) {
322 return $this->mLBInfo
[$name];
329 function setLBInfo( $name, $value = NULL ) {
330 if ( is_null( $value ) ) {
331 $this->mLBInfo
= $name;
333 $this->mLBInfo
[$name] = $value;
340 function lastQuery() { return $this->mLastQuery
; }
341 function isOpen() { return $this->mOpened
; }
344 function setFlag( $flag ) {
345 $this->mFlags |
= $flag;
348 function clearFlag( $flag ) {
349 $this->mFlags
&= ~
$flag;
352 function getFlag( $flag ) {
353 return !!($this->mFlags
& $flag);
357 * General read-only accessor
359 function getProperty( $name ) {
363 #------------------------------------------------------------------------------
365 #------------------------------------------------------------------------------
368 * @param string $server database server host
369 * @param string $user database user name
370 * @param string $password database user password
371 * @param string $dbname database name
375 * @param failFunction
377 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
379 function __construct( $server = false, $user = false, $password = false, $dbName = false,
380 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
382 global $wgOut, $wgDBprefix, $wgCommandLineMode;
383 # Can't get a reference if it hasn't been set yet
384 if ( !isset( $wgOut ) ) {
387 $this->mOut
=& $wgOut;
389 $this->mFailFunction
= $failFunction;
390 $this->mFlags
= $flags;
392 if ( $this->mFlags
& DBO_DEFAULT
) {
393 if ( $wgCommandLineMode ) {
394 $this->mFlags
&= ~DBO_TRX
;
396 $this->mFlags |
= DBO_TRX
;
401 // Faster read-only access
402 if ( wfReadOnly() ) {
403 $this->mFlags |= DBO_PERSISTENT;
404 $this->mFlags &= ~DBO_TRX;
407 /** Get the default table prefix*/
408 if ( $tablePrefix == 'get from global' ) {
409 $this->mTablePrefix
= $wgDBprefix;
411 $this->mTablePrefix
= $tablePrefix;
415 $this->open( $server, $user, $password, $dbName );
421 * @param failFunction
424 static function newFromParams( $server, $user, $password, $dbName,
425 $failFunction = false, $flags = 0 )
427 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
431 * Usually aborts on failure
432 * If the failFunction is set to a non-zero integer, returns success
434 function open( $server, $user, $password, $dbName ) {
437 # Test for missing mysql.so
438 # First try to load it
439 if (!@extension_loaded
('mysql')) {
444 # Otherwise we get a suppressed fatal error, which is very hard to track down
445 if ( !function_exists( 'mysql_connect' ) ) {
446 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
450 $this->mServer
= $server;
451 $this->mUser
= $user;
452 $this->mPassword
= $password;
453 $this->mDBname
= $dbName;
457 if ( $this->mFlags
& DBO_PERSISTENT
) {
458 @/**/$this->mConn
= mysql_pconnect( $server, $user, $password );
460 # Create a new connection...
461 @/**/$this->mConn
= mysql_connect( $server, $user, $password, true );
464 if ( $dbName != '' ) {
465 if ( $this->mConn
!== false ) {
466 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
468 $error = "Error selecting database $dbName on server {$this->mServer} " .
469 "from client host {$wguname['nodename']}\n";
473 wfDebug( "DB connection error\n" );
474 wfDebug( "Server: $server, User: $user, Password: " .
475 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
480 $success = (bool)$this->mConn
;
484 $this->reportConnectionError();
489 // Tell the server we're communicating with it in UTF-8.
490 // This may engage various charset conversions.
491 $this->query( 'SET NAMES utf8' );
494 $this->mOpened
= $success;
500 * Closes a database connection.
501 * if it is open : commits any open transactions
503 * @return bool operation success. true if already closed.
507 $this->mOpened
= false;
508 if ( $this->mConn
) {
509 if ( $this->trxLevel() ) {
510 $this->immediateCommit();
512 return mysql_close( $this->mConn
);
519 * @param string $error fallback error message, used if none is given by MySQL
521 function reportConnectionError( $error = 'Unknown error' ) {
522 $myError = $this->lastError();
527 if ( $this->mFailFunction
) {
528 # Legacy error handling method
529 if ( !is_int( $this->mFailFunction
) ) {
530 $ff = $this->mFailFunction
;
531 $ff( $this, $error );
535 wfLogDBError( "Connection error: $error\n" );
536 throw new DBConnectionError( $this, $error );
541 * Usually aborts on failure
542 * If errors are explicitly ignored, returns success
544 function query( $sql, $fname = '', $tempIgnore = false ) {
547 if ( $wgProfiling ) {
548 # generalizeSQL will probably cut down the query to reasonable
549 # logging size most of the time. The substr is really just a sanity check.
551 # Who's been wasting my precious column space? -- TS
552 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
554 if ( is_null( $this->getLBInfo( 'master' ) ) ) {
555 $queryProf = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
556 $totalProf = 'Database::query';
558 $queryProf = 'query-m: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
559 $totalProf = 'Database::query-master';
561 wfProfileIn( $totalProf );
562 wfProfileIn( $queryProf );
565 $this->mLastQuery
= $sql;
567 # Add a comment for easy SHOW PROCESSLIST interpretation
569 $commentedSql = preg_replace("/\s/", " /* $fname */ ", $sql, 1);
571 $commentedSql = $sql;
574 # If DBO_TRX is set, start a transaction
575 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
576 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK'
581 if ( $this->debug() ) {
582 $sqlx = substr( $commentedSql, 0, 500 );
583 $sqlx = strtr( $sqlx, "\t\n", ' ' );
584 wfDebug( "SQL: $sqlx\n" );
587 # Do the query and handle errors
588 $ret = $this->doQuery( $commentedSql );
590 # Try reconnecting if the connection was lost
591 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
592 # Transaction is gone, like it or not
593 $this->mTrxLevel
= 0;
594 wfDebug( "Connection lost, reconnecting...\n" );
595 if ( $this->ping() ) {
596 wfDebug( "Reconnected\n" );
597 $ret = $this->doQuery( $commentedSql );
599 wfDebug( "Failed\n" );
603 if ( false === $ret ) {
604 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
607 if ( $wgProfiling ) {
608 wfProfileOut( $queryProf );
609 wfProfileOut( $totalProf );
615 * The DBMS-dependent part of query()
616 * @param string $sql SQL query.
618 function doQuery( $sql ) {
619 if( $this->bufferResults() ) {
620 $ret = mysql_query( $sql, $this->mConn
);
622 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
631 * @param string $fname
632 * @param bool $tempIgnore
634 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
635 global $wgCommandLineMode, $wgFullyInitialised, $wgColorErrors;
636 # Ignore errors during error handling to avoid infinite recursion
637 $ignore = $this->ignoreErrors( true );
638 ++
$this->mErrorCount
;
640 if( $ignore ||
$tempIgnore ) {
641 wfDebug("SQL ERROR (ignored): $error\n");
642 $this->ignoreErrors( $ignore );
644 $sql1line = str_replace( "\n", "\\n", $sql );
645 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
646 wfDebug("SQL ERROR: " . $error . "\n");
647 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
653 * Intended to be compatible with the PEAR::DB wrapper functions.
654 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
656 * ? = scalar value, quoted as necessary
657 * ! = raw SQL bit (a function for instance)
658 * & = filename; reads the file and inserts as a blob
659 * (we don't use this though...)
661 function prepare( $sql, $func = 'Database::prepare' ) {
662 /* MySQL doesn't support prepared statements (yet), so just
663 pack up the query for reference. We'll manually replace
665 return array( 'query' => $sql, 'func' => $func );
668 function freePrepared( $prepared ) {
669 /* No-op for MySQL */
673 * Execute a prepared query with the various arguments
674 * @param string $prepared the prepared sql
675 * @param mixed $args Either an array here, or put scalars as varargs
677 function execute( $prepared, $args = null ) {
678 if( !is_array( $args ) ) {
680 $args = func_get_args();
681 array_shift( $args );
683 $sql = $this->fillPrepared( $prepared['query'], $args );
684 return $this->query( $sql, $prepared['func'] );
688 * Prepare & execute an SQL statement, quoting and inserting arguments
689 * in the appropriate places.
690 * @param string $query
691 * @param string $args ...
693 function safeQuery( $query, $args = null ) {
694 $prepared = $this->prepare( $query, 'Database::safeQuery' );
695 if( !is_array( $args ) ) {
697 $args = func_get_args();
698 array_shift( $args );
700 $retval = $this->execute( $prepared, $args );
701 $this->freePrepared( $prepared );
706 * For faking prepared SQL statements on DBs that don't support
708 * @param string $preparedSql - a 'preparable' SQL statement
709 * @param array $args - array of arguments to fill it with
710 * @return string executable SQL
712 function fillPrepared( $preparedQuery, $args ) {
714 $this->preparedArgs
=& $args;
715 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
716 array( &$this, 'fillPreparedArg' ), $preparedQuery );
720 * preg_callback func for fillPrepared()
721 * The arguments should be in $this->preparedArgs and must not be touched
722 * while we're doing this.
724 * @param array $matches
728 function fillPreparedArg( $matches ) {
729 switch( $matches[1] ) {
730 case '\\?': return '?';
731 case '\\!': return '!';
732 case '\\&': return '&';
734 list( $n, $arg ) = each( $this->preparedArgs
);
735 switch( $matches[1] ) {
736 case '?': return $this->addQuotes( $arg );
737 case '!': return $arg;
739 # return $this->addQuotes( file_get_contents( $arg ) );
740 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
742 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
747 * @param mixed $res A SQL result
750 * Free a result object
752 function freeResult( $res ) {
753 if ( !@/**/mysql_free_result( $res ) ) {
754 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
759 * Fetch the next row from the given result object, in object form
761 function fetchObject( $res ) {
762 @/**/$row = mysql_fetch_object( $res );
763 if( $this->lastErrno() ) {
764 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
770 * Fetch the next row from the given result object
773 function fetchRow( $res ) {
774 @/**/$row = mysql_fetch_array( $res );
775 if ( $this->lastErrno() ) {
776 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
782 * Get the number of rows in a result object
784 function numRows( $res ) {
785 @/**/$n = mysql_num_rows( $res );
786 if( $this->lastErrno() ) {
787 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
793 * Get the number of fields in a result object
794 * See documentation for mysql_num_fields()
796 function numFields( $res ) { return mysql_num_fields( $res ); }
799 * Get a field name in a result object
800 * See documentation for mysql_field_name():
801 * http://www.php.net/mysql_field_name
803 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
806 * Get the inserted value of an auto-increment row
808 * The value inserted should be fetched from nextSequenceValue()
811 * $id = $dbw->nextSequenceValue('page_page_id_seq');
812 * $dbw->insert('page',array('page_id' => $id));
813 * $id = $dbw->insertId();
815 function insertId() { return mysql_insert_id( $this->mConn
); }
818 * Change the position of the cursor in a result object
819 * See mysql_data_seek()
821 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
824 * Get the last error number
827 function lastErrno() {
828 if ( $this->mConn
) {
829 return mysql_errno( $this->mConn
);
831 return mysql_errno();
836 * Get a description of the last error
837 * See mysql_error() for more details
839 function lastError() {
840 if ( $this->mConn
) {
841 # Even if it's non-zero, it can still be invalid
842 wfSuppressWarnings();
843 $error = mysql_error( $this->mConn
);
845 $error = mysql_error();
849 $error = mysql_error();
852 $error .= ' (' . $this->mServer
. ')';
857 * Get the number of rows affected by the last write query
858 * See mysql_affected_rows() for more details
860 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
861 /**#@-*/ // end of template : @param $result
864 * Simple UPDATE wrapper
865 * Usually aborts on failure
866 * If errors are explicitly ignored, returns success
868 * This function exists for historical reasons, Database::update() has a more standard
869 * calling convention and feature set
871 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
873 $table = $this->tableName( $table );
874 $sql = "UPDATE $table SET $var = '" .
875 $this->strencode( $value ) . "' WHERE ($cond)";
876 return (bool)$this->query( $sql, $fname );
880 * Simple SELECT wrapper, returns a single field, input must be encoded
881 * Usually aborts on failure
882 * If errors are explicitly ignored, returns FALSE on failure
884 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
885 if ( !is_array( $options ) ) {
886 $options = array( $options );
888 $options['LIMIT'] = 1;
890 $res = $this->select( $table, $var, $cond, $fname, $options );
891 if ( $res === false ||
!$this->numRows( $res ) ) {
894 $row = $this->fetchRow( $res );
895 if ( $row !== false ) {
896 $this->freeResult( $res );
904 * Returns an optional USE INDEX clause to go after the table, and a
905 * string to go at the end of the query
909 * @param array $options an associative array of options to be turned into
910 * an SQL query, valid keys are listed in the function.
913 function makeSelectOptions( $options ) {
917 $noKeyOptions = array();
918 foreach ( $options as $key => $option ) {
919 if ( is_numeric( $key ) ) {
920 $noKeyOptions[$option] = true;
924 if ( isset( $options['GROUP BY'] ) ) $tailOpts .= " GROUP BY {$options['GROUP BY']}";
925 if ( isset( $options['ORDER BY'] ) ) $tailOpts .= " ORDER BY {$options['ORDER BY']}";
927 if (isset($options['LIMIT'])) {
928 $tailOpts .= $this->limitResult('', $options['LIMIT'],
929 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
932 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
933 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
934 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
936 # Various MySQL extensions
937 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
938 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
939 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
940 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
941 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
942 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
943 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
945 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
946 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
951 return array( $startOpts, $useIndex, $tailOpts );
957 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
959 if( is_array( $vars ) ) {
960 $vars = implode( ',', $vars );
962 if( !is_array( $options ) ) {
963 $options = array( $options );
965 if( is_array( $table ) ) {
966 if ( @is_array
( $options['USE INDEX'] ) )
967 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
969 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
970 } elseif ($table!='') {
971 $from = ' FROM ' . $this->tableName( $table );
976 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
978 if( !empty( $conds ) ) {
979 if ( is_array( $conds ) ) {
980 $conds = $this->makeList( $conds, LIST_AND
);
982 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $tailOpts";
984 $sql = "SELECT $startOpts $vars $from $useIndex $tailOpts";
987 return $this->query( $sql, $fname );
991 * Single row SELECT wrapper
992 * Aborts or returns FALSE on error
994 * $vars: the selected variables
995 * $conds: a condition map, terms are ANDed together.
996 * Items with numeric keys are taken to be literal conditions
997 * Takes an array of selected variables, and a condition map, which is ANDed
998 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
999 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1000 * $obj- >page_id is the ID of the Astronomy article
1002 * @todo migrate documentation to phpdocumentor format
1004 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
1005 $options['LIMIT'] = 1;
1006 $res = $this->select( $table, $vars, $conds, $fname, $options );
1007 if ( $res === false )
1009 if ( !$this->numRows($res) ) {
1010 $this->freeResult($res);
1013 $obj = $this->fetchObject( $res );
1014 $this->freeResult( $res );
1020 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1021 * It's only slightly flawed. Don't use for anything important.
1023 * @param string $sql A SQL Query
1026 static function generalizeSQL( $sql ) {
1027 # This does the same as the regexp below would do, but in such a way
1028 # as to avoid crashing php on some large strings.
1029 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1031 $sql = str_replace ( "\\\\", '', $sql);
1032 $sql = str_replace ( "\\'", '', $sql);
1033 $sql = str_replace ( "\\\"", '', $sql);
1034 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1035 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1037 # All newlines, tabs, etc replaced by single space
1038 $sql = preg_replace ( "/\s+/", ' ', $sql);
1041 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1047 * Determines whether a field exists in a table
1048 * Usually aborts on failure
1049 * If errors are explicitly ignored, returns NULL on failure
1051 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1052 $table = $this->tableName( $table );
1053 $res = $this->query( 'DESCRIBE '.$table, $fname );
1060 while ( $row = $this->fetchObject( $res ) ) {
1061 if ( $row->Field
== $field ) {
1070 * Determines whether an index exists
1071 * Usually aborts on failure
1072 * If errors are explicitly ignored, returns NULL on failure
1074 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1075 $info = $this->indexInfo( $table, $index, $fname );
1076 if ( is_null( $info ) ) {
1079 return $info !== false;
1085 * Get information about an index into an object
1086 * Returns false if the index does not exist
1088 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1089 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1090 # SHOW INDEX should work for 3.x and up:
1091 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1092 $table = $this->tableName( $table );
1093 $sql = 'SHOW INDEX FROM '.$table;
1094 $res = $this->query( $sql, $fname );
1099 while ( $row = $this->fetchObject( $res ) ) {
1100 if ( $row->Key_name
== $index ) {
1108 * Query whether a given table exists
1110 function tableExists( $table ) {
1111 $table = $this->tableName( $table );
1112 $old = $this->ignoreErrors( true );
1113 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1114 $this->ignoreErrors( $old );
1116 $this->freeResult( $res );
1124 * mysql_fetch_field() wrapper
1125 * Returns false if the field doesn't exist
1130 function fieldInfo( $table, $field ) {
1131 $table = $this->tableName( $table );
1132 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1133 $n = mysql_num_fields( $res );
1134 for( $i = 0; $i < $n; $i++
) {
1135 $meta = mysql_fetch_field( $res, $i );
1136 if( $field == $meta->name
) {
1144 * mysql_field_type() wrapper
1146 function fieldType( $res, $index ) {
1147 return mysql_field_type( $res, $index );
1151 * Determines if a given index is unique
1153 function indexUnique( $table, $index ) {
1154 $indexInfo = $this->indexInfo( $table, $index );
1155 if ( !$indexInfo ) {
1158 return !$indexInfo->Non_unique
;
1162 * INSERT wrapper, inserts an array into a table
1164 * $a may be a single associative array, or an array of these with numeric keys, for
1167 * Usually aborts on failure
1168 * If errors are explicitly ignored, returns success
1170 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1171 # No rows to insert, easy just return now
1172 if ( !count( $a ) ) {
1176 $table = $this->tableName( $table );
1177 if ( !is_array( $options ) ) {
1178 $options = array( $options );
1180 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1182 $keys = array_keys( $a[0] );
1185 $keys = array_keys( $a );
1188 $sql = 'INSERT ' . implode( ' ', $options ) .
1189 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1193 foreach ( $a as $row ) {
1199 $sql .= '(' . $this->makeList( $row ) . ')';
1202 $sql .= '(' . $this->makeList( $a ) . ')';
1204 return (bool)$this->query( $sql, $fname );
1208 * Make UPDATE options for the Database::update function
1211 * @param array $options The options passed to Database::update
1214 function makeUpdateOptions( $options ) {
1215 if( !is_array( $options ) ) {
1216 $options = array( $options );
1219 if ( in_array( 'LOW_PRIORITY', $options ) )
1220 $opts[] = $this->lowPriorityOption();
1221 if ( in_array( 'IGNORE', $options ) )
1223 return implode(' ', $opts);
1227 * UPDATE wrapper, takes a condition array and a SET array
1229 * @param string $table The table to UPDATE
1230 * @param array $values An array of values to SET
1231 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1232 * @param string $fname The Class::Function calling this function
1234 * @param array $options An array of UPDATE options, can be one or
1235 * more of IGNORE, LOW_PRIORITY
1237 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1238 $table = $this->tableName( $table );
1239 $opts = $this->makeUpdateOptions( $options );
1240 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1241 if ( $conds != '*' ) {
1242 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1244 $this->query( $sql, $fname );
1248 * Makes a wfStrencoded list from an array
1250 * LIST_COMMA - comma separated, no field names
1251 * LIST_AND - ANDed WHERE clause (without the WHERE)
1252 * LIST_OR - ORed WHERE clause (without the WHERE)
1253 * LIST_SET - comma separated with field names, like a SET clause
1254 * LIST_NAMES - comma separated field names
1256 function makeList( $a, $mode = LIST_COMMA
) {
1257 if ( !is_array( $a ) ) {
1258 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1263 foreach ( $a as $field => $value ) {
1265 if ( $mode == LIST_AND
) {
1267 } elseif($mode == LIST_OR
) {
1275 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1276 $list .= "($value)";
1277 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array ($value) ) {
1278 $list .= $field." IN (".$this->makeList($value).") ";
1280 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1281 $list .= "$field = ";
1283 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1290 * Change the current database
1292 function selectDB( $db ) {
1293 $this->mDBname
= $db;
1294 return mysql_select_db( $db, $this->mConn
);
1298 * Format a table name ready for use in constructing an SQL query
1300 * This does two important things: it quotes table names which as necessary,
1301 * and it adds a table prefix if there is one.
1303 * All functions of this object which require a table name call this function
1304 * themselves. Pass the canonical name to such functions. This is only needed
1305 * when calling query() directly.
1307 * @param string $name database table name
1309 function tableName( $name ) {
1311 # Skip quoted literals
1312 if ( $name{0} != '`' ) {
1313 if ( $this->mTablePrefix
!== '' && strpos( '.', $name ) === false ) {
1314 $name = "{$this->mTablePrefix}$name";
1316 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1317 $name = "`$wgSharedDB`.`$name`";
1327 * Fetch a number of table names into an array
1328 * This is handy when you need to construct SQL for joins
1331 * extract($dbr->tableNames('user','watchlist'));
1332 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1333 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1335 function tableNames() {
1336 $inArray = func_get_args();
1338 foreach ( $inArray as $name ) {
1339 $retVal[$name] = $this->tableName( $name );
1347 function tableNamesWithUseIndex( $tables, $use_index ) {
1350 foreach ( $tables as $table )
1351 if ( @$use_index[$table] !== null )
1352 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1354 $ret[] = $this->tableName( $table );
1356 return implode( ',', $ret );
1360 * Wrapper for addslashes()
1361 * @param string $s String to be slashed.
1362 * @return string slashed string.
1364 function strencode( $s ) {
1365 return mysql_real_escape_string( $s, $this->mConn
);
1369 * If it's a string, adds quotes and backslashes
1370 * Otherwise returns as-is
1372 function addQuotes( $s ) {
1373 if ( is_null( $s ) ) {
1376 # This will also quote numeric values. This should be harmless,
1377 # and protects against weird problems that occur when they really
1378 # _are_ strings such as article titles and string->number->string
1379 # conversion is not 1:1.
1380 return "'" . $this->strencode( $s ) . "'";
1385 * Escape string for safe LIKE usage
1387 function escapeLike( $s ) {
1388 $s=$this->strencode( $s );
1389 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1394 * Returns an appropriately quoted sequence value for inserting a new row.
1395 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1396 * subclass will return an integer, and save the value for insertId()
1398 function nextSequenceValue( $seqName ) {
1404 * PostgreSQL doesn't have them and returns ""
1406 function useIndexClause( $index ) {
1407 return "FORCE INDEX ($index)";
1411 * REPLACE query wrapper
1412 * PostgreSQL simulates this with a DELETE followed by INSERT
1413 * $row is the row to insert, an associative array
1414 * $uniqueIndexes is an array of indexes. Each element may be either a
1415 * field name or an array of field names
1417 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1418 * However if you do this, you run the risk of encountering errors which wouldn't have
1421 * @todo migrate comment to phodocumentor format
1423 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1424 $table = $this->tableName( $table );
1427 if ( !is_array( reset( $rows ) ) ) {
1428 $rows = array( $rows );
1431 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1433 foreach ( $rows as $row ) {
1439 $sql .= '(' . $this->makeList( $row ) . ')';
1441 return $this->query( $sql, $fname );
1445 * DELETE where the condition is a join
1446 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1448 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1449 * join condition matches, set $conds='*'
1451 * DO NOT put the join condition in $conds
1453 * @param string $delTable The table to delete from.
1454 * @param string $joinTable The other table.
1455 * @param string $delVar The variable to join on, in the first table.
1456 * @param string $joinVar The variable to join on, in the second table.
1457 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1459 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1461 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1464 $delTable = $this->tableName( $delTable );
1465 $joinTable = $this->tableName( $joinTable );
1466 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1467 if ( $conds != '*' ) {
1468 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1471 return $this->query( $sql, $fname );
1475 * Returns the size of a text field, or -1 for "unlimited"
1477 function textFieldSize( $table, $field ) {
1478 $table = $this->tableName( $table );
1479 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1480 $res = $this->query( $sql, 'Database::textFieldSize' );
1481 $row = $this->fetchObject( $res );
1482 $this->freeResult( $res );
1484 if ( preg_match( "/\((.*)\)/", $row->Type
, $m ) ) {
1493 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1495 function lowPriorityOption() {
1496 return 'LOW_PRIORITY';
1500 * DELETE query wrapper
1502 * Use $conds == "*" to delete all rows
1504 function delete( $table, $conds, $fname = 'Database::delete' ) {
1506 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1508 $table = $this->tableName( $table );
1509 $sql = "DELETE FROM $table";
1510 if ( $conds != '*' ) {
1511 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1513 return $this->query( $sql, $fname );
1517 * INSERT SELECT wrapper
1518 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1519 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1520 * $conds may be "*" to copy the whole table
1521 * srcTable may be an array of tables.
1523 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1524 $insertOptions = array(), $selectOptions = array() )
1526 $destTable = $this->tableName( $destTable );
1527 if ( is_array( $insertOptions ) ) {
1528 $insertOptions = implode( ' ', $insertOptions );
1530 if( !is_array( $selectOptions ) ) {
1531 $selectOptions = array( $selectOptions );
1533 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1534 if( is_array( $srcTable ) ) {
1535 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1537 $srcTable = $this->tableName( $srcTable );
1539 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1540 " SELECT $startOpts " . implode( ',', $varMap ) .
1541 " FROM $srcTable $useIndex ";
1542 if ( $conds != '*' ) {
1543 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1545 $sql .= " $tailOpts";
1546 return $this->query( $sql, $fname );
1550 * Construct a LIMIT query with optional offset
1551 * This is used for query pages
1552 * $sql string SQL query we will append the limit too
1553 * $limit integer the SQL limit
1554 * $offset integer the SQL offset (default false)
1556 function limitResult($sql, $limit, $offset=false) {
1557 if( !is_numeric($limit) ) {
1558 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1560 return " $sql LIMIT "
1561 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1564 function limitResultForUpdate($sql, $num) {
1565 return $this->limitResult($sql, $num, 0);
1569 * Returns an SQL expression for a simple conditional.
1572 * @param string $cond SQL expression which will result in a boolean value
1573 * @param string $trueVal SQL expression to return if true
1574 * @param string $falseVal SQL expression to return if false
1575 * @return string SQL fragment
1577 function conditional( $cond, $trueVal, $falseVal ) {
1578 return " IF($cond, $trueVal, $falseVal) ";
1582 * Determines if the last failure was due to a deadlock
1584 function wasDeadlock() {
1585 return $this->lastErrno() == 1213;
1589 * Perform a deadlock-prone transaction.
1591 * This function invokes a callback function to perform a set of write
1592 * queries. If a deadlock occurs during the processing, the transaction
1593 * will be rolled back and the callback function will be called again.
1596 * $dbw->deadlockLoop( callback, ... );
1598 * Extra arguments are passed through to the specified callback function.
1600 * Returns whatever the callback function returned on its successful,
1601 * iteration, or false on error, for example if the retry limit was
1604 function deadlockLoop() {
1605 $myFname = 'Database::deadlockLoop';
1608 $args = func_get_args();
1609 $function = array_shift( $args );
1610 $oldIgnore = $this->ignoreErrors( true );
1611 $tries = DEADLOCK_TRIES
;
1612 if ( is_array( $function ) ) {
1613 $fname = $function[0];
1618 $retVal = call_user_func_array( $function, $args );
1619 $error = $this->lastError();
1620 $errno = $this->lastErrno();
1621 $sql = $this->lastQuery();
1624 if ( $this->wasDeadlock() ) {
1626 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1628 $this->reportQueryError( $error, $errno, $sql, $fname );
1631 } while( $this->wasDeadlock() && --$tries > 0 );
1632 $this->ignoreErrors( $oldIgnore );
1633 if ( $tries <= 0 ) {
1634 $this->query( 'ROLLBACK', $myFname );
1635 $this->reportQueryError( $error, $errno, $sql, $fname );
1638 $this->query( 'COMMIT', $myFname );
1644 * Do a SELECT MASTER_POS_WAIT()
1646 * @param string $file the binlog file
1647 * @param string $pos the binlog position
1648 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1650 function masterPosWait( $file, $pos, $timeout ) {
1651 $fname = 'Database::masterPosWait';
1652 wfProfileIn( $fname );
1655 # Commit any open transactions
1656 $this->immediateCommit();
1658 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1659 $encFile = $this->strencode( $file );
1660 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1661 $res = $this->doQuery( $sql );
1662 if ( $res && $row = $this->fetchRow( $res ) ) {
1663 $this->freeResult( $res );
1664 wfProfileOut( $fname );
1667 wfProfileOut( $fname );
1673 * Get the position of the master from SHOW SLAVE STATUS
1675 function getSlavePos() {
1676 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1677 $row = $this->fetchObject( $res );
1679 return array( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1681 return array( false, false );
1686 * Get the position of the master from SHOW MASTER STATUS
1688 function getMasterPos() {
1689 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1690 $row = $this->fetchObject( $res );
1692 return array( $row->File
, $row->Position
);
1694 return array( false, false );
1699 * Begin a transaction, committing any previously open transaction
1701 function begin( $fname = 'Database::begin' ) {
1702 $this->query( 'BEGIN', $fname );
1703 $this->mTrxLevel
= 1;
1709 function commit( $fname = 'Database::commit' ) {
1710 $this->query( 'COMMIT', $fname );
1711 $this->mTrxLevel
= 0;
1715 * Rollback a transaction
1717 function rollback( $fname = 'Database::rollback' ) {
1718 $this->query( 'ROLLBACK', $fname );
1719 $this->mTrxLevel
= 0;
1723 * Begin a transaction, committing any previously open transaction
1724 * @deprecated use begin()
1726 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1731 * Commit transaction, if one is open
1732 * @deprecated use commit()
1734 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1739 * Return MW-style timestamp used for MySQL schema
1741 function timestamp( $ts=0 ) {
1742 return wfTimestamp(TS_MW
,$ts);
1746 * Local database timestamp format or null
1748 function timestampOrNull( $ts = null ) {
1749 if( is_null( $ts ) ) {
1752 return $this->timestamp( $ts );
1759 function resultObject( $result ) {
1760 if( empty( $result ) ) {
1763 return new ResultWrapper( $this, $result );
1768 * Return aggregated value alias
1770 function aggregateValue ($valuedata,$valuename='value') {
1775 * @return string wikitext of a link to the server software's web site
1777 function getSoftwareLink() {
1778 return "[http://www.mysql.com/ MySQL]";
1782 * @return string Version information from the database
1784 function getServerVersion() {
1785 return mysql_get_server_info();
1789 * Ping the server and try to reconnect if it there is no connection
1792 if( function_exists( 'mysql_ping' ) ) {
1793 return mysql_ping( $this->mConn
);
1795 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1802 * At the moment, this will only work if the DB user has the PROCESS privilege
1805 $res = $this->query( 'SHOW PROCESSLIST' );
1806 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1807 # dubious, but unfortunately there's no easy rigorous way
1809 while ( $row = $this->fetchObject( $res ) ) {
1810 /* This should work for most situations - when default db
1811 * for thread is not specified, it had no events executed,
1812 * and therefore it doesn't know yet how lagged it is.
1814 * Relay log I/O thread does not select databases.
1816 if ( $row->User
== 'system user' &&
1817 $row->State
!= 'Waiting for master to send event' &&
1818 $row->State
!= 'Connecting to master' &&
1819 $row->State
!= 'Queueing master event to the relay log' &&
1820 $row->State
!= 'Waiting for master update' &&
1821 $row->State
!= 'Requesting binlog dump'
1823 # This is it, return the time (except -ve)
1824 if ( $row->Time
> 0x7fffffff ) {
1835 * Get status information from SHOW STATUS in an associative array
1837 function getStatus($which="%") {
1838 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1840 while ( $row = $this->fetchObject( $res ) ) {
1841 $status[$row->Variable_name
] = $row->Value
;
1847 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1849 function maxListLen() {
1853 function encodeBlob($b) {
1857 function decodeBlob($b) {
1862 * Read and execute SQL commands from a file.
1863 * Returns true on success, error string on failure
1865 function sourceFile( $filename ) {
1866 $fp = fopen( $filename, 'r' );
1867 if ( false === $fp ) {
1868 return "Could not open \"{$fname}\".\n";
1873 $dollarquote = false;
1875 while ( ! feof( $fp ) ) {
1876 $line = trim( fgets( $fp, 1024 ) );
1877 $sl = strlen( $line ) - 1;
1879 if ( $sl < 0 ) { continue; }
1880 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
1882 ## Allow dollar quoting for function declarations
1883 if (substr($line,0,4) == '$mw$') {
1885 $dollarquote = false;
1889 $dollarquote = true;
1892 else if (!$dollarquote) {
1893 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
1895 $line = substr( $line, 0, $sl );
1899 if ( '' != $cmd ) { $cmd .= ' '; }
1903 $cmd = str_replace(';;', ";", $cmd);
1904 $cmd = $this->replaceVars( $cmd );
1905 $res = $this->query( $cmd, 'dbsource', true );
1907 if ( false === $res ) {
1908 $err = $this->lastError();
1909 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1921 * Replace variables in sourced SQL
1923 protected function replaceVars( $ins ) {
1925 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
1926 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
1927 'wgDBadminuser', 'wgDBadminpassword',
1930 // Ordinary variables
1931 foreach ( $varnames as $var ) {
1932 if( isset( $GLOBALS[$var] ) ) {
1933 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
1934 $ins = str_replace( '{$' . $var . '}', $val, $ins );
1935 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
1936 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
1941 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
1942 array( &$this, 'tableNameCallback' ), $ins );
1947 * Table name callback
1950 protected function tableNameCallback( $matches ) {
1951 return $this->tableName( $matches[1] );
1957 * Database abstraction object for mySQL
1958 * Inherit all methods and properties of Database::Database()
1960 * @package MediaWiki
1963 class DatabaseMysql
extends Database
{
1969 * Result wrapper for grabbing data queried by someone else
1971 * @package MediaWiki
1973 class ResultWrapper
{
1979 function ResultWrapper( &$database, $result ) {
1980 $this->db
=& $database;
1981 $this->result
=& $result;
1987 function numRows() {
1988 return $this->db
->numRows( $this->result
);
1994 function fetchObject() {
1995 return $this->db
->fetchObject( $this->result
);
2001 function fetchRow() {
2002 return $this->db
->fetchRow( $this->result
);
2009 $this->db
->freeResult( $this->result
);
2010 unset( $this->result
);
2014 function seek( $row ) {
2015 $this->db
->dataSeek( $this->result
, $row );