3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
8 /** See Database::makeList() */
9 define( 'LIST_COMMA', 0 );
10 define( 'LIST_AND', 1 );
11 define( 'LIST_SET', 2 );
12 define( 'LIST_NAMES', 3);
13 define( 'LIST_OR', 4);
15 /** Number of times to re-try an operation in case of deadlock */
16 define( 'DEADLOCK_TRIES', 4 );
17 /** Minimum time to wait before retry, in microseconds */
18 define( 'DEADLOCK_DELAY_MIN', 500000 );
19 /** Maximum time to wait before retry */
20 define( 'DEADLOCK_DELAY_MAX', 1500000 );
22 /******************************************************************************
24 *****************************************************************************/
29 function DBObject($data) {
42 /******************************************************************************
44 *****************************************************************************/
47 * Database error base class
49 class DBError
extends MWException
{
53 * Construct a database error
54 * @param Database $db The database object which threw the error
55 * @param string $error A simple error message to be used for debugging
57 function __construct( Database
&$db, $error ) {
59 parent
::__construct( $error );
63 class DBConnectionError
extends DBError
{
66 function __construct( Database
&$db, $error = 'unknown error' ) {
67 $msg = 'DB connection error';
68 if ( trim( $error ) != '' ) {
71 $this->error
= $error;
72 parent
::__construct( $db, $msg );
75 function useOutputPage() {
80 function useMessageCache() {
86 return $this->getMessage() . "\n";
89 function getLogMessage() {
90 # Don't send to the exception log
94 function getPageTitle() {
96 return "$wgSitename has a problem";
100 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
101 global $wgSitename, $wgServer, $wgMessageCache, $wgLogo;
103 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
104 # Hard coding strings instead.
106 $noconnect = "<p><strong>Sorry! This site is experiencing technical difficulties.</strong></p><p>Try waiting a few minutes and reloading.</p><p><small>(Can't contact the database server: $1)</small></p>";
107 $mainpage = 'Main Page';
108 $searchdisabled = <<<EOT
109 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
110 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
114 <!-- SiteSearch Google -->
115 <FORM method=GET action=\"http://www.google.com/search\">
116 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
117 <A HREF=\"http://www.google.com/\">
118 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
119 border=\"0\" ALT=\"Google\"></A>
122 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
123 <INPUT type=submit name=btnG VALUE=\"Google Search\">
125 <input type=hidden name=domains value=\"$wgServer\"><br /><input type=radio name=sitesearch value=\"\"> WWW <input type=radio name=sitesearch value=\"$wgServer\" checked> $wgServer <br />
126 <input type='hidden' name='ie' value='$2'>
127 <input type='hidden' name='oe' value='$2'>
131 <!-- SiteSearch Google -->";
132 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
135 if ( is_object( $wgMessageCache ) ) {
136 $wgMessageCache->disable();
139 if ( trim( $this->error
) == '' ) {
140 $this->error
= $this->db
->getProperty('mServer');
143 $text = str_replace( '$1', $this->error
, $noconnect );
144 $text .= wfGetSiteNotice();
146 if($wgUseFileCache) {
151 $t = Title
::newFromURL( $title );
152 } elseif (@/**/$_REQUEST['search']) {
153 $search = $_REQUEST['search'];
154 return $searchdisabled .
155 str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
156 $wgInputEncoding ), $googlesearch );
158 $t = Title
::newFromText( $mainpage );
162 $cache = new CacheManager( $t );
163 if( $cache->isFileCached() ) {
164 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
165 $cachederror . "</b></p>\n";
167 $tag = '<div id="article">';
171 $cache->fetchPageText() );
179 class DBQueryError
extends DBError
{
180 public $error, $errno, $sql, $fname;
182 function __construct( Database
&$db, $error, $errno, $sql, $fname ) {
183 $message = "A database error has occurred\n" .
185 "Function: $fname\n" .
186 "Error: $errno $error\n";
188 parent
::__construct( $db, $message );
189 $this->error
= $error;
190 $this->errno
= $errno;
192 $this->fname
= $fname;
196 if ( $this->useMessageCache() ) {
197 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
198 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
200 return $this->getMessage();
205 global $wgShowSQLErrors;
206 if( !$wgShowSQLErrors ) {
207 return $this->msg( 'sqlhidden', 'SQL hidden' );
213 function getLogMessage() {
214 # Don't send to the exception log
218 function getPageTitle() {
219 return $this->msg( 'databaseerror', 'Database error' );
223 if ( $this->useMessageCache() ) {
224 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
225 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
227 return nl2br( htmlspecialchars( $this->getMessage() ) );
232 class DBUnexpectedError
extends DBError
{}
234 /******************************************************************************/
237 * Database abstraction object
242 #------------------------------------------------------------------------------
244 #------------------------------------------------------------------------------
246 protected $mLastQuery = '';
248 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
249 protected $mOut, $mOpened = false;
251 protected $mFailFunction;
252 protected $mTablePrefix;
254 protected $mTrxLevel = 0;
255 protected $mErrorCount = 0;
256 protected $mLBInfo = array();
257 protected $mCascadingDeletes = false;
258 protected $mCleanupTriggers = false;
259 protected $mStrictIPs = false;
261 #------------------------------------------------------------------------------
263 #------------------------------------------------------------------------------
264 # These optionally set a variable and return the previous state
267 * Fail function, takes a Database as a parameter
268 * Set to false for default, 1 for ignore errors
270 function failFunction( $function = NULL ) {
271 return wfSetVar( $this->mFailFunction
, $function );
275 * Output page, used for reporting errors
276 * FALSE means discard output
278 function setOutputPage( $out ) {
283 * Boolean, controls output of large amounts of debug information
285 function debug( $debug = NULL ) {
286 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
290 * Turns buffering of SQL result sets on (true) or off (false).
291 * Default is "on" and it should not be changed without good reasons.
293 function bufferResults( $buffer = NULL ) {
294 if ( is_null( $buffer ) ) {
295 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
297 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
302 * Turns on (false) or off (true) the automatic generation and sending
303 * of a "we're sorry, but there has been a database error" page on
304 * database errors. Default is on (false). When turned off, the
305 * code should use wfLastErrno() and wfLastError() to handle the
306 * situation as appropriate.
308 function ignoreErrors( $ignoreErrors = NULL ) {
309 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
313 * The current depth of nested transactions
314 * @param $level Integer: , default NULL.
316 function trxLevel( $level = NULL ) {
317 return wfSetVar( $this->mTrxLevel
, $level );
321 * Number of errors logged, only useful when errors are ignored
323 function errorCount( $count = NULL ) {
324 return wfSetVar( $this->mErrorCount
, $count );
328 * Properties passed down from the server info array of the load balancer
330 function getLBInfo( $name = NULL ) {
331 if ( is_null( $name ) ) {
332 return $this->mLBInfo
;
334 if ( array_key_exists( $name, $this->mLBInfo
) ) {
335 return $this->mLBInfo
[$name];
342 function setLBInfo( $name, $value = NULL ) {
343 if ( is_null( $value ) ) {
344 $this->mLBInfo
= $name;
346 $this->mLBInfo
[$name] = $value;
351 * Returns true if this database supports (and uses) cascading deletes
353 function cascadingDeletes() {
354 return $this->mCascadingDeletes
;
358 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
360 function cleanupTriggers() {
361 return $this->mCleanupTriggers
;
365 * Returns true if this database is strict about what can be put into an IP field.
366 * Specifically, it uses a NULL value instead of an empty string.
368 function strictIPs() {
369 return $this->mStrictIPs
;
375 function lastQuery() { return $this->mLastQuery
; }
376 function isOpen() { return $this->mOpened
; }
379 function setFlag( $flag ) {
380 $this->mFlags |
= $flag;
383 function clearFlag( $flag ) {
384 $this->mFlags
&= ~
$flag;
387 function getFlag( $flag ) {
388 return !!($this->mFlags
& $flag);
392 * General read-only accessor
394 function getProperty( $name ) {
398 #------------------------------------------------------------------------------
400 #------------------------------------------------------------------------------
403 * @param string $server database server host
404 * @param string $user database user name
405 * @param string $password database user password
406 * @param string $dbname database name
410 * @param failFunction
412 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
414 function __construct( $server = false, $user = false, $password = false, $dbName = false,
415 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
417 global $wgOut, $wgDBprefix, $wgCommandLineMode;
418 # Can't get a reference if it hasn't been set yet
419 if ( !isset( $wgOut ) ) {
422 $this->mOut
=& $wgOut;
424 $this->mFailFunction
= $failFunction;
425 $this->mFlags
= $flags;
427 if ( $this->mFlags
& DBO_DEFAULT
) {
428 if ( $wgCommandLineMode ) {
429 $this->mFlags
&= ~DBO_TRX
;
431 $this->mFlags |
= DBO_TRX
;
436 // Faster read-only access
437 if ( wfReadOnly() ) {
438 $this->mFlags |= DBO_PERSISTENT;
439 $this->mFlags &= ~DBO_TRX;
442 /** Get the default table prefix*/
443 if ( $tablePrefix == 'get from global' ) {
444 $this->mTablePrefix
= $wgDBprefix;
446 $this->mTablePrefix
= $tablePrefix;
450 $this->open( $server, $user, $password, $dbName );
456 * @param failFunction
459 static function newFromParams( $server, $user, $password, $dbName,
460 $failFunction = false, $flags = 0 )
462 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
466 * Usually aborts on failure
467 * If the failFunction is set to a non-zero integer, returns success
469 function open( $server, $user, $password, $dbName ) {
471 wfProfileIn( __METHOD__
);
473 # Test for missing mysql.so
474 # First try to load it
475 if (!@extension_loaded
('mysql')) {
480 # Otherwise we get a suppressed fatal error, which is very hard to track down
481 if ( !function_exists( 'mysql_connect' ) ) {
482 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
486 $this->mServer
= $server;
487 $this->mUser
= $user;
488 $this->mPassword
= $password;
489 $this->mDBname
= $dbName;
493 wfProfileIn("dbconnect-$server");
495 # LIVE PATCH by Tim, ask Domas for why: retry loop
496 $this->mConn
= false;
497 for ( $i = 0; $i < 3 && !$this->mConn
; $i++
) {
501 if ( $this->mFlags
& DBO_PERSISTENT
) {
502 @/**/$this->mConn
= mysql_pconnect( $server, $user, $password );
504 # Create a new connection...
505 @/**/$this->mConn
= mysql_connect( $server, $user, $password, true );
507 if ($this->mConn
=== false) {
508 wfLogDBError("Connect loop error ($server): " . mysql_errno() . " - " . mysql_error()."\n");
512 wfProfileOut("dbconnect-$server");
514 if ( $dbName != '' ) {
515 if ( $this->mConn
!== false ) {
516 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
518 $error = "Error selecting database $dbName on server {$this->mServer} " .
519 "from client host {$wguname['nodename']}\n";
520 wfLogDBError(" Error selecting database $dbname on server {$this->mServer} \n");
524 wfDebug( "DB connection error\n" );
525 wfDebug( "Server: $server, User: $user, Password: " .
526 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
531 $success = (bool)$this->mConn
;
537 // Tell the server we're communicating with it in UTF-8.
538 // This may engage various charset conversions.
539 $this->query( 'SET NAMES utf8' );
542 $this->reportConnectionError();
545 $this->mOpened
= $success;
546 wfProfileOut( __METHOD__
);
552 * Closes a database connection.
553 * if it is open : commits any open transactions
555 * @return bool operation success. true if already closed.
559 $this->mOpened
= false;
560 if ( $this->mConn
) {
561 if ( $this->trxLevel() ) {
562 $this->immediateCommit();
564 return mysql_close( $this->mConn
);
571 * @param string $error fallback error message, used if none is given by MySQL
573 function reportConnectionError( $error = 'Unknown error' ) {
574 $myError = $this->lastError();
579 if ( $this->mFailFunction
) {
580 # Legacy error handling method
581 if ( !is_int( $this->mFailFunction
) ) {
582 $ff = $this->mFailFunction
;
583 $ff( $this, $error );
587 wfLogDBError( "Connection error: $error\n" );
588 throw new DBConnectionError( $this, $error );
593 * Usually aborts on failure
594 * If errors are explicitly ignored, returns success
596 function query( $sql, $fname = '', $tempIgnore = false ) {
599 if ( $wgProfiling ) {
600 # generalizeSQL will probably cut down the query to reasonable
601 # logging size most of the time. The substr is really just a sanity check.
603 # Who's been wasting my precious column space? -- TS
604 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
606 if ( is_null( $this->getLBInfo( 'master' ) ) ) {
607 $queryProf = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
608 $totalProf = 'Database::query';
610 $queryProf = 'query-m: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
611 $totalProf = 'Database::query-master';
613 wfProfileIn( $totalProf );
614 wfProfileIn( $queryProf );
617 $this->mLastQuery
= $sql;
619 # Add a comment for easy SHOW PROCESSLIST interpretation
621 $commentedSql = preg_replace("/\s/", " /* $fname */ ", $sql, 1);
623 $commentedSql = $sql;
626 # If DBO_TRX is set, start a transaction
627 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
628 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK'
633 if ( $this->debug() ) {
634 $sqlx = substr( $commentedSql, 0, 500 );
635 $sqlx = strtr( $sqlx, "\t\n", ' ' );
636 wfDebug( "SQL: $sqlx\n" );
639 # Do the query and handle errors
640 $ret = $this->doQuery( $commentedSql );
642 # Try reconnecting if the connection was lost
643 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
644 # Transaction is gone, like it or not
645 $this->mTrxLevel
= 0;
646 wfDebug( "Connection lost, reconnecting...\n" );
647 if ( $this->ping() ) {
648 wfDebug( "Reconnected\n" );
649 $ret = $this->doQuery( $commentedSql );
651 wfDebug( "Failed\n" );
655 if ( false === $ret ) {
656 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
659 if ( $wgProfiling ) {
660 wfProfileOut( $queryProf );
661 wfProfileOut( $totalProf );
667 * The DBMS-dependent part of query()
668 * @param string $sql SQL query.
670 function doQuery( $sql ) {
671 if( $this->bufferResults() ) {
672 $ret = mysql_query( $sql, $this->mConn
);
674 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
683 * @param string $fname
684 * @param bool $tempIgnore
686 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
687 global $wgCommandLineMode, $wgFullyInitialised, $wgColorErrors;
688 # Ignore errors during error handling to avoid infinite recursion
689 $ignore = $this->ignoreErrors( true );
690 ++
$this->mErrorCount
;
692 if( $ignore ||
$tempIgnore ) {
693 wfDebug("SQL ERROR (ignored): $error\n");
694 $this->ignoreErrors( $ignore );
696 $sql1line = str_replace( "\n", "\\n", $sql );
697 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
698 wfDebug("SQL ERROR: " . $error . "\n");
699 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
705 * Intended to be compatible with the PEAR::DB wrapper functions.
706 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
708 * ? = scalar value, quoted as necessary
709 * ! = raw SQL bit (a function for instance)
710 * & = filename; reads the file and inserts as a blob
711 * (we don't use this though...)
713 function prepare( $sql, $func = 'Database::prepare' ) {
714 /* MySQL doesn't support prepared statements (yet), so just
715 pack up the query for reference. We'll manually replace
717 return array( 'query' => $sql, 'func' => $func );
720 function freePrepared( $prepared ) {
721 /* No-op for MySQL */
725 * Execute a prepared query with the various arguments
726 * @param string $prepared the prepared sql
727 * @param mixed $args Either an array here, or put scalars as varargs
729 function execute( $prepared, $args = null ) {
730 if( !is_array( $args ) ) {
732 $args = func_get_args();
733 array_shift( $args );
735 $sql = $this->fillPrepared( $prepared['query'], $args );
736 return $this->query( $sql, $prepared['func'] );
740 * Prepare & execute an SQL statement, quoting and inserting arguments
741 * in the appropriate places.
742 * @param string $query
743 * @param string $args ...
745 function safeQuery( $query, $args = null ) {
746 $prepared = $this->prepare( $query, 'Database::safeQuery' );
747 if( !is_array( $args ) ) {
749 $args = func_get_args();
750 array_shift( $args );
752 $retval = $this->execute( $prepared, $args );
753 $this->freePrepared( $prepared );
758 * For faking prepared SQL statements on DBs that don't support
760 * @param string $preparedSql - a 'preparable' SQL statement
761 * @param array $args - array of arguments to fill it with
762 * @return string executable SQL
764 function fillPrepared( $preparedQuery, $args ) {
766 $this->preparedArgs
=& $args;
767 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
768 array( &$this, 'fillPreparedArg' ), $preparedQuery );
772 * preg_callback func for fillPrepared()
773 * The arguments should be in $this->preparedArgs and must not be touched
774 * while we're doing this.
776 * @param array $matches
780 function fillPreparedArg( $matches ) {
781 switch( $matches[1] ) {
782 case '\\?': return '?';
783 case '\\!': return '!';
784 case '\\&': return '&';
786 list( $n, $arg ) = each( $this->preparedArgs
);
787 switch( $matches[1] ) {
788 case '?': return $this->addQuotes( $arg );
789 case '!': return $arg;
791 # return $this->addQuotes( file_get_contents( $arg ) );
792 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
794 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
799 * @param mixed $res A SQL result
802 * Free a result object
804 function freeResult( $res ) {
805 if ( !@/**/mysql_free_result( $res ) ) {
806 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
811 * Fetch the next row from the given result object, in object form
813 function fetchObject( $res ) {
814 @/**/$row = mysql_fetch_object( $res );
815 if( $this->lastErrno() ) {
816 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
822 * Fetch the next row from the given result object
825 function fetchRow( $res ) {
826 @/**/$row = mysql_fetch_array( $res );
827 if ( $this->lastErrno() ) {
828 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
834 * Get the number of rows in a result object
836 function numRows( $res ) {
837 @/**/$n = mysql_num_rows( $res );
838 if( $this->lastErrno() ) {
839 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
845 * Get the number of fields in a result object
846 * See documentation for mysql_num_fields()
848 function numFields( $res ) { return mysql_num_fields( $res ); }
851 * Get a field name in a result object
852 * See documentation for mysql_field_name():
853 * http://www.php.net/mysql_field_name
855 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
858 * Get the inserted value of an auto-increment row
860 * The value inserted should be fetched from nextSequenceValue()
863 * $id = $dbw->nextSequenceValue('page_page_id_seq');
864 * $dbw->insert('page',array('page_id' => $id));
865 * $id = $dbw->insertId();
867 function insertId() { return mysql_insert_id( $this->mConn
); }
870 * Change the position of the cursor in a result object
871 * See mysql_data_seek()
873 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
876 * Get the last error number
879 function lastErrno() {
880 if ( $this->mConn
) {
881 return mysql_errno( $this->mConn
);
883 return mysql_errno();
888 * Get a description of the last error
889 * See mysql_error() for more details
891 function lastError() {
892 if ( $this->mConn
) {
893 # Even if it's non-zero, it can still be invalid
894 wfSuppressWarnings();
895 $error = mysql_error( $this->mConn
);
897 $error = mysql_error();
901 $error = mysql_error();
904 $error .= ' (' . $this->mServer
. ')';
909 * Get the number of rows affected by the last write query
910 * See mysql_affected_rows() for more details
912 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
913 /**#@-*/ // end of template : @param $result
916 * Simple UPDATE wrapper
917 * Usually aborts on failure
918 * If errors are explicitly ignored, returns success
920 * This function exists for historical reasons, Database::update() has a more standard
921 * calling convention and feature set
923 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
925 $table = $this->tableName( $table );
926 $sql = "UPDATE $table SET $var = '" .
927 $this->strencode( $value ) . "' WHERE ($cond)";
928 return (bool)$this->query( $sql, $fname );
932 * Simple SELECT wrapper, returns a single field, input must be encoded
933 * Usually aborts on failure
934 * If errors are explicitly ignored, returns FALSE on failure
936 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
937 if ( !is_array( $options ) ) {
938 $options = array( $options );
940 $options['LIMIT'] = 1;
942 $res = $this->select( $table, $var, $cond, $fname, $options );
943 if ( $res === false ||
!$this->numRows( $res ) ) {
946 $row = $this->fetchRow( $res );
947 if ( $row !== false ) {
948 $this->freeResult( $res );
956 * Returns an optional USE INDEX clause to go after the table, and a
957 * string to go at the end of the query
961 * @param array $options an associative array of options to be turned into
962 * an SQL query, valid keys are listed in the function.
965 function makeSelectOptions( $options ) {
969 $noKeyOptions = array();
970 foreach ( $options as $key => $option ) {
971 if ( is_numeric( $key ) ) {
972 $noKeyOptions[$option] = true;
976 if ( isset( $options['GROUP BY'] ) ) $tailOpts .= " GROUP BY {$options['GROUP BY']}";
977 if ( isset( $options['ORDER BY'] ) ) $tailOpts .= " ORDER BY {$options['ORDER BY']}";
979 if (isset($options['LIMIT'])) {
980 $tailOpts .= $this->limitResult('', $options['LIMIT'],
981 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
984 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
985 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
986 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
988 # Various MySQL extensions
989 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
990 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
991 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
992 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
993 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
994 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
995 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
997 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
998 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1003 return array( $startOpts, $useIndex, $tailOpts );
1009 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
1011 if( is_array( $vars ) ) {
1012 $vars = implode( ',', $vars );
1014 if( !is_array( $options ) ) {
1015 $options = array( $options );
1017 if( is_array( $table ) ) {
1018 if ( @is_array
( $options['USE INDEX'] ) )
1019 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
1021 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1022 } elseif ($table!='') {
1023 $from = ' FROM ' . $this->tableName( $table );
1028 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
1030 if( !empty( $conds ) ) {
1031 if ( is_array( $conds ) ) {
1032 $conds = $this->makeList( $conds, LIST_AND
);
1034 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $tailOpts";
1036 $sql = "SELECT $startOpts $vars $from $useIndex $tailOpts";
1039 return $this->query( $sql, $fname );
1043 * Single row SELECT wrapper
1044 * Aborts or returns FALSE on error
1046 * $vars: the selected variables
1047 * $conds: a condition map, terms are ANDed together.
1048 * Items with numeric keys are taken to be literal conditions
1049 * Takes an array of selected variables, and a condition map, which is ANDed
1050 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1051 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1052 * $obj- >page_id is the ID of the Astronomy article
1054 * @todo migrate documentation to phpdocumentor format
1056 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
1057 $options['LIMIT'] = 1;
1058 $res = $this->select( $table, $vars, $conds, $fname, $options );
1059 if ( $res === false )
1061 if ( !$this->numRows($res) ) {
1062 $this->freeResult($res);
1065 $obj = $this->fetchObject( $res );
1066 $this->freeResult( $res );
1072 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1073 * It's only slightly flawed. Don't use for anything important.
1075 * @param string $sql A SQL Query
1078 static function generalizeSQL( $sql ) {
1079 # This does the same as the regexp below would do, but in such a way
1080 # as to avoid crashing php on some large strings.
1081 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1083 $sql = str_replace ( "\\\\", '', $sql);
1084 $sql = str_replace ( "\\'", '', $sql);
1085 $sql = str_replace ( "\\\"", '', $sql);
1086 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1087 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1089 # All newlines, tabs, etc replaced by single space
1090 $sql = preg_replace ( "/\s+/", ' ', $sql);
1093 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1099 * Determines whether a field exists in a table
1100 * Usually aborts on failure
1101 * If errors are explicitly ignored, returns NULL on failure
1103 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1104 $table = $this->tableName( $table );
1105 $res = $this->query( 'DESCRIBE '.$table, $fname );
1112 while ( $row = $this->fetchObject( $res ) ) {
1113 if ( $row->Field
== $field ) {
1122 * Determines whether an index exists
1123 * Usually aborts on failure
1124 * If errors are explicitly ignored, returns NULL on failure
1126 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1127 $info = $this->indexInfo( $table, $index, $fname );
1128 if ( is_null( $info ) ) {
1131 return $info !== false;
1137 * Get information about an index into an object
1138 * Returns false if the index does not exist
1140 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1141 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1142 # SHOW INDEX should work for 3.x and up:
1143 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1144 $table = $this->tableName( $table );
1145 $sql = 'SHOW INDEX FROM '.$table;
1146 $res = $this->query( $sql, $fname );
1151 while ( $row = $this->fetchObject( $res ) ) {
1152 if ( $row->Key_name
== $index ) {
1160 * Query whether a given table exists
1162 function tableExists( $table ) {
1163 $table = $this->tableName( $table );
1164 $old = $this->ignoreErrors( true );
1165 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1166 $this->ignoreErrors( $old );
1168 $this->freeResult( $res );
1176 * mysql_fetch_field() wrapper
1177 * Returns false if the field doesn't exist
1182 function fieldInfo( $table, $field ) {
1183 $table = $this->tableName( $table );
1184 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1185 $n = mysql_num_fields( $res );
1186 for( $i = 0; $i < $n; $i++
) {
1187 $meta = mysql_fetch_field( $res, $i );
1188 if( $field == $meta->name
) {
1196 * mysql_field_type() wrapper
1198 function fieldType( $res, $index ) {
1199 return mysql_field_type( $res, $index );
1203 * Determines if a given index is unique
1205 function indexUnique( $table, $index ) {
1206 $indexInfo = $this->indexInfo( $table, $index );
1207 if ( !$indexInfo ) {
1210 return !$indexInfo->Non_unique
;
1214 * INSERT wrapper, inserts an array into a table
1216 * $a may be a single associative array, or an array of these with numeric keys, for
1219 * Usually aborts on failure
1220 * If errors are explicitly ignored, returns success
1222 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1223 # No rows to insert, easy just return now
1224 if ( !count( $a ) ) {
1228 $table = $this->tableName( $table );
1229 if ( !is_array( $options ) ) {
1230 $options = array( $options );
1232 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1234 $keys = array_keys( $a[0] );
1237 $keys = array_keys( $a );
1240 $sql = 'INSERT ' . implode( ' ', $options ) .
1241 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1245 foreach ( $a as $row ) {
1251 $sql .= '(' . $this->makeList( $row ) . ')';
1254 $sql .= '(' . $this->makeList( $a ) . ')';
1256 return (bool)$this->query( $sql, $fname );
1260 * Make UPDATE options for the Database::update function
1263 * @param array $options The options passed to Database::update
1266 function makeUpdateOptions( $options ) {
1267 if( !is_array( $options ) ) {
1268 $options = array( $options );
1271 if ( in_array( 'LOW_PRIORITY', $options ) )
1272 $opts[] = $this->lowPriorityOption();
1273 if ( in_array( 'IGNORE', $options ) )
1275 return implode(' ', $opts);
1279 * UPDATE wrapper, takes a condition array and a SET array
1281 * @param string $table The table to UPDATE
1282 * @param array $values An array of values to SET
1283 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1284 * @param string $fname The Class::Function calling this function
1286 * @param array $options An array of UPDATE options, can be one or
1287 * more of IGNORE, LOW_PRIORITY
1289 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1290 $table = $this->tableName( $table );
1291 $opts = $this->makeUpdateOptions( $options );
1292 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1293 if ( $conds != '*' ) {
1294 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1296 $this->query( $sql, $fname );
1300 * Makes a wfStrencoded list from an array
1302 * LIST_COMMA - comma separated, no field names
1303 * LIST_AND - ANDed WHERE clause (without the WHERE)
1304 * LIST_OR - ORed WHERE clause (without the WHERE)
1305 * LIST_SET - comma separated with field names, like a SET clause
1306 * LIST_NAMES - comma separated field names
1308 function makeList( $a, $mode = LIST_COMMA
) {
1309 if ( !is_array( $a ) ) {
1310 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1315 foreach ( $a as $field => $value ) {
1317 if ( $mode == LIST_AND
) {
1319 } elseif($mode == LIST_OR
) {
1327 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1328 $list .= "($value)";
1329 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array ($value) ) {
1330 $list .= $field." IN (".$this->makeList($value).") ";
1332 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1333 $list .= "$field = ";
1335 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1342 * Change the current database
1344 function selectDB( $db ) {
1345 $this->mDBname
= $db;
1346 return mysql_select_db( $db, $this->mConn
);
1350 * Format a table name ready for use in constructing an SQL query
1352 * This does two important things: it quotes table names which as necessary,
1353 * and it adds a table prefix if there is one.
1355 * All functions of this object which require a table name call this function
1356 * themselves. Pass the canonical name to such functions. This is only needed
1357 * when calling query() directly.
1359 * @param string $name database table name
1361 function tableName( $name ) {
1363 # Skip quoted literals
1364 if ( $name{0} != '`' ) {
1365 if ( $this->mTablePrefix
!== '' && strpos( '.', $name ) === false ) {
1366 $name = "{$this->mTablePrefix}$name";
1368 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1369 $name = "`$wgSharedDB`.`$name`";
1379 * Fetch a number of table names into an array
1380 * This is handy when you need to construct SQL for joins
1383 * extract($dbr->tableNames('user','watchlist'));
1384 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1385 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1387 function tableNames() {
1388 $inArray = func_get_args();
1390 foreach ( $inArray as $name ) {
1391 $retVal[$name] = $this->tableName( $name );
1399 function tableNamesWithUseIndex( $tables, $use_index ) {
1402 foreach ( $tables as $table )
1403 if ( @$use_index[$table] !== null )
1404 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1406 $ret[] = $this->tableName( $table );
1408 return implode( ',', $ret );
1412 * Wrapper for addslashes()
1413 * @param string $s String to be slashed.
1414 * @return string slashed string.
1416 function strencode( $s ) {
1417 return mysql_real_escape_string( $s, $this->mConn
);
1421 * If it's a string, adds quotes and backslashes
1422 * Otherwise returns as-is
1424 function addQuotes( $s ) {
1425 if ( is_null( $s ) ) {
1428 # This will also quote numeric values. This should be harmless,
1429 # and protects against weird problems that occur when they really
1430 # _are_ strings such as article titles and string->number->string
1431 # conversion is not 1:1.
1432 return "'" . $this->strencode( $s ) . "'";
1437 * Escape string for safe LIKE usage
1439 function escapeLike( $s ) {
1440 $s=$this->strencode( $s );
1441 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1446 * Returns an appropriately quoted sequence value for inserting a new row.
1447 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1448 * subclass will return an integer, and save the value for insertId()
1450 function nextSequenceValue( $seqName ) {
1456 * PostgreSQL doesn't have them and returns ""
1458 function useIndexClause( $index ) {
1459 return "FORCE INDEX ($index)";
1463 * REPLACE query wrapper
1464 * PostgreSQL simulates this with a DELETE followed by INSERT
1465 * $row is the row to insert, an associative array
1466 * $uniqueIndexes is an array of indexes. Each element may be either a
1467 * field name or an array of field names
1469 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1470 * However if you do this, you run the risk of encountering errors which wouldn't have
1473 * @todo migrate comment to phodocumentor format
1475 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1476 $table = $this->tableName( $table );
1479 if ( !is_array( reset( $rows ) ) ) {
1480 $rows = array( $rows );
1483 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1485 foreach ( $rows as $row ) {
1491 $sql .= '(' . $this->makeList( $row ) . ')';
1493 return $this->query( $sql, $fname );
1497 * DELETE where the condition is a join
1498 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1500 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1501 * join condition matches, set $conds='*'
1503 * DO NOT put the join condition in $conds
1505 * @param string $delTable The table to delete from.
1506 * @param string $joinTable The other table.
1507 * @param string $delVar The variable to join on, in the first table.
1508 * @param string $joinVar The variable to join on, in the second table.
1509 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1511 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1513 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1516 $delTable = $this->tableName( $delTable );
1517 $joinTable = $this->tableName( $joinTable );
1518 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1519 if ( $conds != '*' ) {
1520 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1523 return $this->query( $sql, $fname );
1527 * Returns the size of a text field, or -1 for "unlimited"
1529 function textFieldSize( $table, $field ) {
1530 $table = $this->tableName( $table );
1531 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1532 $res = $this->query( $sql, 'Database::textFieldSize' );
1533 $row = $this->fetchObject( $res );
1534 $this->freeResult( $res );
1536 if ( preg_match( "/\((.*)\)/", $row->Type
, $m ) ) {
1545 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1547 function lowPriorityOption() {
1548 return 'LOW_PRIORITY';
1552 * DELETE query wrapper
1554 * Use $conds == "*" to delete all rows
1556 function delete( $table, $conds, $fname = 'Database::delete' ) {
1558 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1560 $table = $this->tableName( $table );
1561 $sql = "DELETE FROM $table";
1562 if ( $conds != '*' ) {
1563 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1565 return $this->query( $sql, $fname );
1569 * INSERT SELECT wrapper
1570 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1571 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1572 * $conds may be "*" to copy the whole table
1573 * srcTable may be an array of tables.
1575 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1576 $insertOptions = array(), $selectOptions = array() )
1578 $destTable = $this->tableName( $destTable );
1579 if ( is_array( $insertOptions ) ) {
1580 $insertOptions = implode( ' ', $insertOptions );
1582 if( !is_array( $selectOptions ) ) {
1583 $selectOptions = array( $selectOptions );
1585 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1586 if( is_array( $srcTable ) ) {
1587 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1589 $srcTable = $this->tableName( $srcTable );
1591 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1592 " SELECT $startOpts " . implode( ',', $varMap ) .
1593 " FROM $srcTable $useIndex ";
1594 if ( $conds != '*' ) {
1595 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1597 $sql .= " $tailOpts";
1598 return $this->query( $sql, $fname );
1602 * Construct a LIMIT query with optional offset
1603 * This is used for query pages
1604 * $sql string SQL query we will append the limit too
1605 * $limit integer the SQL limit
1606 * $offset integer the SQL offset (default false)
1608 function limitResult($sql, $limit, $offset=false) {
1609 if( !is_numeric($limit) ) {
1610 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1612 return " $sql LIMIT "
1613 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1616 function limitResultForUpdate($sql, $num) {
1617 return $this->limitResult($sql, $num, 0);
1621 * Returns an SQL expression for a simple conditional.
1624 * @param string $cond SQL expression which will result in a boolean value
1625 * @param string $trueVal SQL expression to return if true
1626 * @param string $falseVal SQL expression to return if false
1627 * @return string SQL fragment
1629 function conditional( $cond, $trueVal, $falseVal ) {
1630 return " IF($cond, $trueVal, $falseVal) ";
1634 * Determines if the last failure was due to a deadlock
1636 function wasDeadlock() {
1637 return $this->lastErrno() == 1213;
1641 * Perform a deadlock-prone transaction.
1643 * This function invokes a callback function to perform a set of write
1644 * queries. If a deadlock occurs during the processing, the transaction
1645 * will be rolled back and the callback function will be called again.
1648 * $dbw->deadlockLoop( callback, ... );
1650 * Extra arguments are passed through to the specified callback function.
1652 * Returns whatever the callback function returned on its successful,
1653 * iteration, or false on error, for example if the retry limit was
1656 function deadlockLoop() {
1657 $myFname = 'Database::deadlockLoop';
1660 $args = func_get_args();
1661 $function = array_shift( $args );
1662 $oldIgnore = $this->ignoreErrors( true );
1663 $tries = DEADLOCK_TRIES
;
1664 if ( is_array( $function ) ) {
1665 $fname = $function[0];
1670 $retVal = call_user_func_array( $function, $args );
1671 $error = $this->lastError();
1672 $errno = $this->lastErrno();
1673 $sql = $this->lastQuery();
1676 if ( $this->wasDeadlock() ) {
1678 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1680 $this->reportQueryError( $error, $errno, $sql, $fname );
1683 } while( $this->wasDeadlock() && --$tries > 0 );
1684 $this->ignoreErrors( $oldIgnore );
1685 if ( $tries <= 0 ) {
1686 $this->query( 'ROLLBACK', $myFname );
1687 $this->reportQueryError( $error, $errno, $sql, $fname );
1690 $this->query( 'COMMIT', $myFname );
1696 * Do a SELECT MASTER_POS_WAIT()
1698 * @param string $file the binlog file
1699 * @param string $pos the binlog position
1700 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1702 function masterPosWait( $file, $pos, $timeout ) {
1703 $fname = 'Database::masterPosWait';
1704 wfProfileIn( $fname );
1707 # Commit any open transactions
1708 $this->immediateCommit();
1710 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1711 $encFile = $this->strencode( $file );
1712 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1713 $res = $this->doQuery( $sql );
1714 if ( $res && $row = $this->fetchRow( $res ) ) {
1715 $this->freeResult( $res );
1716 wfProfileOut( $fname );
1719 wfProfileOut( $fname );
1725 * Get the position of the master from SHOW SLAVE STATUS
1727 function getSlavePos() {
1728 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1729 $row = $this->fetchObject( $res );
1731 return array( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1733 return array( false, false );
1738 * Get the position of the master from SHOW MASTER STATUS
1740 function getMasterPos() {
1741 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1742 $row = $this->fetchObject( $res );
1744 return array( $row->File
, $row->Position
);
1746 return array( false, false );
1751 * Begin a transaction, committing any previously open transaction
1753 function begin( $fname = 'Database::begin' ) {
1754 $this->query( 'BEGIN', $fname );
1755 $this->mTrxLevel
= 1;
1761 function commit( $fname = 'Database::commit' ) {
1762 $this->query( 'COMMIT', $fname );
1763 $this->mTrxLevel
= 0;
1767 * Rollback a transaction
1769 function rollback( $fname = 'Database::rollback' ) {
1770 $this->query( 'ROLLBACK', $fname );
1771 $this->mTrxLevel
= 0;
1775 * Begin a transaction, committing any previously open transaction
1776 * @deprecated use begin()
1778 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1783 * Commit transaction, if one is open
1784 * @deprecated use commit()
1786 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1791 * Return MW-style timestamp used for MySQL schema
1793 function timestamp( $ts=0 ) {
1794 return wfTimestamp(TS_MW
,$ts);
1798 * Local database timestamp format or null
1800 function timestampOrNull( $ts = null ) {
1801 if( is_null( $ts ) ) {
1804 return $this->timestamp( $ts );
1811 function resultObject( $result ) {
1812 if( empty( $result ) ) {
1815 return new ResultWrapper( $this, $result );
1820 * Return aggregated value alias
1822 function aggregateValue ($valuedata,$valuename='value') {
1827 * @return string wikitext of a link to the server software's web site
1829 function getSoftwareLink() {
1830 return "[http://www.mysql.com/ MySQL]";
1834 * @return string Version information from the database
1836 function getServerVersion() {
1837 return mysql_get_server_info();
1841 * Ping the server and try to reconnect if it there is no connection
1844 if( function_exists( 'mysql_ping' ) ) {
1845 return mysql_ping( $this->mConn
);
1847 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1854 * At the moment, this will only work if the DB user has the PROCESS privilege
1857 $res = $this->query( 'SHOW PROCESSLIST' );
1858 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1859 # dubious, but unfortunately there's no easy rigorous way
1861 while ( $row = $this->fetchObject( $res ) ) {
1862 /* This should work for most situations - when default db
1863 * for thread is not specified, it had no events executed,
1864 * and therefore it doesn't know yet how lagged it is.
1866 * Relay log I/O thread does not select databases.
1868 if ( $row->User
== 'system user' &&
1869 $row->State
!= 'Waiting for master to send event' &&
1870 $row->State
!= 'Connecting to master' &&
1871 $row->State
!= 'Queueing master event to the relay log' &&
1872 $row->State
!= 'Waiting for master update' &&
1873 $row->State
!= 'Requesting binlog dump'
1875 # This is it, return the time (except -ve)
1876 if ( $row->Time
> 0x7fffffff ) {
1887 * Get status information from SHOW STATUS in an associative array
1889 function getStatus($which="%") {
1890 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1892 while ( $row = $this->fetchObject( $res ) ) {
1893 $status[$row->Variable_name
] = $row->Value
;
1899 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1901 function maxListLen() {
1905 function encodeBlob($b) {
1909 function decodeBlob($b) {
1914 * Read and execute SQL commands from a file.
1915 * Returns true on success, error string on failure
1917 function sourceFile( $filename ) {
1918 $fp = fopen( $filename, 'r' );
1919 if ( false === $fp ) {
1920 return "Could not open \"{$filename}\".\n";
1925 $dollarquote = false;
1927 while ( ! feof( $fp ) ) {
1928 $line = trim( fgets( $fp, 1024 ) );
1929 $sl = strlen( $line ) - 1;
1931 if ( $sl < 0 ) { continue; }
1932 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
1934 ## Allow dollar quoting for function declarations
1935 if (substr($line,0,4) == '$mw$') {
1937 $dollarquote = false;
1941 $dollarquote = true;
1944 else if (!$dollarquote) {
1945 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
1947 $line = substr( $line, 0, $sl );
1951 if ( '' != $cmd ) { $cmd .= ' '; }
1955 $cmd = str_replace(';;', ";", $cmd);
1956 $cmd = $this->replaceVars( $cmd );
1957 $res = $this->query( $cmd, 'dbsource', true );
1959 if ( false === $res ) {
1960 $err = $this->lastError();
1961 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1973 * Replace variables in sourced SQL
1975 protected function replaceVars( $ins ) {
1977 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
1978 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
1979 'wgDBadminuser', 'wgDBadminpassword',
1982 // Ordinary variables
1983 foreach ( $varnames as $var ) {
1984 if( isset( $GLOBALS[$var] ) ) {
1985 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
1986 $ins = str_replace( '{$' . $var . '}', $val, $ins );
1987 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
1988 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
1993 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
1994 array( &$this, 'tableNameCallback' ), $ins );
1999 * Table name callback
2002 protected function tableNameCallback( $matches ) {
2003 return $this->tableName( $matches[1] );
2009 * Database abstraction object for mySQL
2010 * Inherit all methods and properties of Database::Database()
2012 * @package MediaWiki
2015 class DatabaseMysql
extends Database
{
2021 * Result wrapper for grabbing data queried by someone else
2023 * @package MediaWiki
2025 class ResultWrapper
{
2031 function ResultWrapper( &$database, $result ) {
2032 $this->db
=& $database;
2033 $this->result
=& $result;
2039 function numRows() {
2040 return $this->db
->numRows( $this->result
);
2046 function fetchObject() {
2047 return $this->db
->fetchObject( $this->result
);
2053 function fetchRow() {
2054 return $this->db
->fetchRow( $this->result
);
2061 $this->db
->freeResult( $this->result
);
2062 unset( $this->result
);
2066 function seek( $row ) {
2067 $this->db
->dataSeek( $this->result
, $row );