d51553f8d24d6da37ffbf253a3494bceb8dbcbad
3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
7 /** Number of times to re-try an operation in case of deadlock */
8 define( 'DEADLOCK_TRIES', 4 );
9 /** Minimum time to wait before retry, in microseconds */
10 define( 'DEADLOCK_DELAY_MIN', 500000 );
11 /** Maximum time to wait before retry */
12 define( 'DEADLOCK_DELAY_MAX', 1500000 );
14 /******************************************************************************
16 *****************************************************************************/
21 function DBObject($data) {
34 /******************************************************************************
36 *****************************************************************************/
39 * Database error base class
41 class DBError
extends MWException
{
45 * Construct a database error
46 * @param Database $db The database object which threw the error
47 * @param string $error A simple error message to be used for debugging
49 function __construct( Database
&$db, $error ) {
51 parent
::__construct( $error );
55 class DBConnectionError
extends DBError
{
58 function __construct( Database
&$db, $error = 'unknown error' ) {
59 $msg = 'DB connection error';
60 if ( trim( $error ) != '' ) {
63 $this->error
= $error;
64 parent
::__construct( $db, $msg );
67 function useOutputPage() {
72 function useMessageCache() {
78 return $this->getMessage() . "\n";
81 function getLogMessage() {
82 # Don't send to the exception log
86 function getPageTitle() {
88 return "$wgSitename has a problem";
92 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding;
93 global $wgSitename, $wgServer, $wgMessageCache;
95 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
96 # Hard coding strings instead.
98 $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>";
99 $mainpage = 'Main Page';
100 $searchdisabled = <<<EOT
101 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
102 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
106 <!-- SiteSearch Google -->
107 <FORM method=GET action=\"http://www.google.com/search\">
108 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
109 <A HREF=\"http://www.google.com/\">
110 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
111 border=\"0\" ALT=\"Google\"></A>
114 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
115 <INPUT type=submit name=btnG VALUE=\"Google Search\">
117 <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 />
118 <input type='hidden' name='ie' value='$2'>
119 <input type='hidden' name='oe' value='$2'>
123 <!-- SiteSearch Google -->";
124 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
127 if ( is_object( $wgMessageCache ) ) {
128 $wgMessageCache->disable();
131 if ( trim( $this->error
) == '' ) {
132 $this->error
= $this->db
->getProperty('mServer');
135 $text = str_replace( '$1', $this->error
, $noconnect );
136 $text .= wfGetSiteNotice();
138 if($wgUseFileCache) {
143 $t = Title
::newFromURL( $title );
144 } elseif (@/**/$_REQUEST['search']) {
145 $search = $_REQUEST['search'];
146 return $searchdisabled .
147 str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
148 $wgInputEncoding ), $googlesearch );
150 $t = Title
::newFromText( $mainpage );
154 $cache = new HTMLFileCache( $t );
155 if( $cache->isFileCached() ) {
156 // FIXME: $msg is not defined on the next line.
157 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
158 $cachederror . "</b></p>\n";
160 $tag = '<div id="article">';
164 $cache->fetchPageText() );
172 class DBQueryError
extends DBError
{
173 public $error, $errno, $sql, $fname;
175 function __construct( Database
&$db, $error, $errno, $sql, $fname ) {
176 $message = "A database error has occurred\n" .
178 "Function: $fname\n" .
179 "Error: $errno $error\n";
181 parent
::__construct( $db, $message );
182 $this->error
= $error;
183 $this->errno
= $errno;
185 $this->fname
= $fname;
189 if ( $this->useMessageCache() ) {
190 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
191 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
193 return $this->getMessage();
198 global $wgShowSQLErrors;
199 if( !$wgShowSQLErrors ) {
200 return $this->msg( 'sqlhidden', 'SQL hidden' );
206 function getLogMessage() {
207 # Don't send to the exception log
211 function getPageTitle() {
212 return $this->msg( 'databaseerror', 'Database error' );
216 if ( $this->useMessageCache() ) {
217 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
218 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
220 return nl2br( htmlspecialchars( $this->getMessage() ) );
225 class DBUnexpectedError
extends DBError
{}
227 /******************************************************************************/
230 * Database abstraction object
234 #------------------------------------------------------------------------------
236 #------------------------------------------------------------------------------
238 protected $mLastQuery = '';
240 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
241 protected $mOut, $mOpened = false;
243 protected $mFailFunction;
244 protected $mTablePrefix;
246 protected $mTrxLevel = 0;
247 protected $mErrorCount = 0;
248 protected $mLBInfo = array();
249 protected $mCascadingDeletes = false;
250 protected $mCleanupTriggers = false;
251 protected $mStrictIPs = false;
253 #------------------------------------------------------------------------------
255 #------------------------------------------------------------------------------
256 # These optionally set a variable and return the previous state
259 * Fail function, takes a Database as a parameter
260 * Set to false for default, 1 for ignore errors
262 function failFunction( $function = NULL ) {
263 return wfSetVar( $this->mFailFunction
, $function );
267 * Output page, used for reporting errors
268 * FALSE means discard output
270 function setOutputPage( $out ) {
275 * Boolean, controls output of large amounts of debug information
277 function debug( $debug = NULL ) {
278 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
282 * Turns buffering of SQL result sets on (true) or off (false).
283 * Default is "on" and it should not be changed without good reasons.
285 function bufferResults( $buffer = NULL ) {
286 if ( is_null( $buffer ) ) {
287 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
289 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
294 * Turns on (false) or off (true) the automatic generation and sending
295 * of a "we're sorry, but there has been a database error" page on
296 * database errors. Default is on (false). When turned off, the
297 * code should use lastErrno() and lastError() to handle the
298 * situation as appropriate.
300 function ignoreErrors( $ignoreErrors = NULL ) {
301 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
305 * The current depth of nested transactions
306 * @param $level Integer: , default NULL.
308 function trxLevel( $level = NULL ) {
309 return wfSetVar( $this->mTrxLevel
, $level );
313 * Number of errors logged, only useful when errors are ignored
315 function errorCount( $count = NULL ) {
316 return wfSetVar( $this->mErrorCount
, $count );
320 * Properties passed down from the server info array of the load balancer
322 function getLBInfo( $name = NULL ) {
323 if ( is_null( $name ) ) {
324 return $this->mLBInfo
;
326 if ( array_key_exists( $name, $this->mLBInfo
) ) {
327 return $this->mLBInfo
[$name];
334 function setLBInfo( $name, $value = NULL ) {
335 if ( is_null( $value ) ) {
336 $this->mLBInfo
= $name;
338 $this->mLBInfo
[$name] = $value;
343 * Returns true if this database supports (and uses) cascading deletes
345 function cascadingDeletes() {
346 return $this->mCascadingDeletes
;
350 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
352 function cleanupTriggers() {
353 return $this->mCleanupTriggers
;
357 * Returns true if this database is strict about what can be put into an IP field.
358 * Specifically, it uses a NULL value instead of an empty string.
360 function strictIPs() {
361 return $this->mStrictIPs
;
365 * Returns true if this database uses timestamps rather than integers
367 function realTimestamps() {
372 * Returns true if this database does an implicit sort when doing GROUP BY
374 function implicitGroupby() {
379 * Returns true if this database can do a native search on IP columns
380 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
382 function searchableIPs() {
389 function lastQuery() { return $this->mLastQuery
; }
390 function isOpen() { return $this->mOpened
; }
393 function setFlag( $flag ) {
394 $this->mFlags |
= $flag;
397 function clearFlag( $flag ) {
398 $this->mFlags
&= ~
$flag;
401 function getFlag( $flag ) {
402 return !!($this->mFlags
& $flag);
406 * General read-only accessor
408 function getProperty( $name ) {
412 #------------------------------------------------------------------------------
414 #------------------------------------------------------------------------------
417 * @param string $server database server host
418 * @param string $user database user name
419 * @param string $password database user password
420 * @param string $dbname database name
424 * @param failFunction
426 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
428 function __construct( $server = false, $user = false, $password = false, $dbName = false,
429 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
431 global $wgOut, $wgDBprefix, $wgCommandLineMode;
432 # Can't get a reference if it hasn't been set yet
433 if ( !isset( $wgOut ) ) {
436 $this->mOut
=& $wgOut;
438 $this->mFailFunction
= $failFunction;
439 $this->mFlags
= $flags;
441 if ( $this->mFlags
& DBO_DEFAULT
) {
442 if ( $wgCommandLineMode ) {
443 $this->mFlags
&= ~DBO_TRX
;
445 $this->mFlags |
= DBO_TRX
;
450 // Faster read-only access
451 if ( wfReadOnly() ) {
452 $this->mFlags |= DBO_PERSISTENT;
453 $this->mFlags &= ~DBO_TRX;
456 /** Get the default table prefix*/
457 if ( $tablePrefix == 'get from global' ) {
458 $this->mTablePrefix
= $wgDBprefix;
460 $this->mTablePrefix
= $tablePrefix;
464 $this->open( $server, $user, $password, $dbName );
470 * @param failFunction
473 static function newFromParams( $server, $user, $password, $dbName,
474 $failFunction = false, $flags = 0 )
476 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
480 * Usually aborts on failure
481 * If the failFunction is set to a non-zero integer, returns success
483 function open( $server, $user, $password, $dbName ) {
485 wfProfileIn( __METHOD__
);
487 # Test for missing mysql.so
488 # First try to load it
489 if (!@extension_loaded
('mysql')) {
494 # Otherwise we get a suppressed fatal error, which is very hard to track down
495 if ( !function_exists( 'mysql_connect' ) ) {
496 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
500 $this->mServer
= $server;
501 $this->mUser
= $user;
502 $this->mPassword
= $password;
503 $this->mDBname
= $dbName;
507 wfProfileIn("dbconnect-$server");
509 # LIVE PATCH by Tim, ask Domas for why: retry loop
510 $this->mConn
= false;
512 for ( $i = 0; $i < $max && !$this->mConn
; $i++
) {
516 if ( $this->mFlags
& DBO_PERSISTENT
) {
517 @/**/$this->mConn
= mysql_pconnect( $server, $user, $password );
519 # Create a new connection...
520 @/**/$this->mConn
= mysql_connect( $server, $user, $password, true );
522 if ($this->mConn
=== false) {
524 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
528 wfProfileOut("dbconnect-$server");
530 if ( $dbName != '' ) {
531 if ( $this->mConn
!== false ) {
532 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
534 $error = "Error selecting database $dbName on server {$this->mServer} " .
535 "from client host {$wguname['nodename']}\n";
536 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
540 wfDebug( "DB connection error\n" );
541 wfDebug( "Server: $server, User: $user, Password: " .
542 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
547 $success = (bool)$this->mConn
;
553 // Tell the server we're communicating with it in UTF-8.
554 // This may engage various charset conversions.
555 $this->query( 'SET NAMES utf8' );
558 $this->reportConnectionError();
561 $this->mOpened
= $success;
562 wfProfileOut( __METHOD__
);
568 * Closes a database connection.
569 * if it is open : commits any open transactions
571 * @return bool operation success. true if already closed.
575 $this->mOpened
= false;
576 if ( $this->mConn
) {
577 if ( $this->trxLevel() ) {
578 $this->immediateCommit();
580 return mysql_close( $this->mConn
);
587 * @param string $error fallback error message, used if none is given by MySQL
589 function reportConnectionError( $error = 'Unknown error' ) {
590 $myError = $this->lastError();
595 if ( $this->mFailFunction
) {
596 # Legacy error handling method
597 if ( !is_int( $this->mFailFunction
) ) {
598 $ff = $this->mFailFunction
;
599 $ff( $this, $error );
603 wfLogDBError( "Connection error: $error\n" );
604 throw new DBConnectionError( $this, $error );
609 * Usually aborts on failure
610 * If errors are explicitly ignored, returns success
612 function query( $sql, $fname = '', $tempIgnore = false ) {
615 if ( $wgProfiling ) {
616 # generalizeSQL will probably cut down the query to reasonable
617 # logging size most of the time. The substr is really just a sanity check.
619 # Who's been wasting my precious column space? -- TS
620 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
622 if ( is_null( $this->getLBInfo( 'master' ) ) ) {
623 $queryProf = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
624 $totalProf = 'Database::query';
626 $queryProf = 'query-m: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
627 $totalProf = 'Database::query-master';
629 wfProfileIn( $totalProf );
630 wfProfileIn( $queryProf );
633 $this->mLastQuery
= $sql;
635 # Add a comment for easy SHOW PROCESSLIST interpretation
637 $commentedSql = preg_replace('/\s/', " /* $fname */ ", $sql, 1);
639 $commentedSql = $sql;
642 # If DBO_TRX is set, start a transaction
643 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
644 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK'
649 if ( $this->debug() ) {
650 $sqlx = substr( $commentedSql, 0, 500 );
651 $sqlx = strtr( $sqlx, "\t\n", ' ' );
652 wfDebug( "SQL: $sqlx\n" );
655 # Do the query and handle errors
656 $ret = $this->doQuery( $commentedSql );
658 # Try reconnecting if the connection was lost
659 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
660 # Transaction is gone, like it or not
661 $this->mTrxLevel
= 0;
662 wfDebug( "Connection lost, reconnecting...\n" );
663 if ( $this->ping() ) {
664 wfDebug( "Reconnected\n" );
665 $sqlx = substr( $commentedSql, 0, 500 );
666 $sqlx = strtr( $sqlx, "\t\n", ' ' );
667 global $wgRequestTime;
668 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
669 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
670 $ret = $this->doQuery( $commentedSql );
672 wfDebug( "Failed\n" );
676 if ( false === $ret ) {
677 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
680 if ( $wgProfiling ) {
681 wfProfileOut( $queryProf );
682 wfProfileOut( $totalProf );
688 * The DBMS-dependent part of query()
689 * @param string $sql SQL query.
691 function doQuery( $sql ) {
692 if( $this->bufferResults() ) {
693 $ret = mysql_query( $sql, $this->mConn
);
695 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
704 * @param string $fname
705 * @param bool $tempIgnore
707 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
708 global $wgCommandLineMode;
709 # Ignore errors during error handling to avoid infinite recursion
710 $ignore = $this->ignoreErrors( true );
711 ++
$this->mErrorCount
;
713 if( $ignore ||
$tempIgnore ) {
714 wfDebug("SQL ERROR (ignored): $error\n");
715 $this->ignoreErrors( $ignore );
717 $sql1line = str_replace( "\n", "\\n", $sql );
718 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
719 wfDebug("SQL ERROR: " . $error . "\n");
720 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
726 * Intended to be compatible with the PEAR::DB wrapper functions.
727 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
729 * ? = scalar value, quoted as necessary
730 * ! = raw SQL bit (a function for instance)
731 * & = filename; reads the file and inserts as a blob
732 * (we don't use this though...)
734 function prepare( $sql, $func = 'Database::prepare' ) {
735 /* MySQL doesn't support prepared statements (yet), so just
736 pack up the query for reference. We'll manually replace
738 return array( 'query' => $sql, 'func' => $func );
741 function freePrepared( $prepared ) {
742 /* No-op for MySQL */
746 * Execute a prepared query with the various arguments
747 * @param string $prepared the prepared sql
748 * @param mixed $args Either an array here, or put scalars as varargs
750 function execute( $prepared, $args = null ) {
751 if( !is_array( $args ) ) {
753 $args = func_get_args();
754 array_shift( $args );
756 $sql = $this->fillPrepared( $prepared['query'], $args );
757 return $this->query( $sql, $prepared['func'] );
761 * Prepare & execute an SQL statement, quoting and inserting arguments
762 * in the appropriate places.
763 * @param string $query
764 * @param string $args ...
766 function safeQuery( $query, $args = null ) {
767 $prepared = $this->prepare( $query, 'Database::safeQuery' );
768 if( !is_array( $args ) ) {
770 $args = func_get_args();
771 array_shift( $args );
773 $retval = $this->execute( $prepared, $args );
774 $this->freePrepared( $prepared );
779 * For faking prepared SQL statements on DBs that don't support
781 * @param string $preparedSql - a 'preparable' SQL statement
782 * @param array $args - array of arguments to fill it with
783 * @return string executable SQL
785 function fillPrepared( $preparedQuery, $args ) {
787 $this->preparedArgs
=& $args;
788 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
789 array( &$this, 'fillPreparedArg' ), $preparedQuery );
793 * preg_callback func for fillPrepared()
794 * The arguments should be in $this->preparedArgs and must not be touched
795 * while we're doing this.
797 * @param array $matches
801 function fillPreparedArg( $matches ) {
802 switch( $matches[1] ) {
803 case '\\?': return '?';
804 case '\\!': return '!';
805 case '\\&': return '&';
807 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
808 switch( $matches[1] ) {
809 case '?': return $this->addQuotes( $arg );
810 case '!': return $arg;
812 # return $this->addQuotes( file_get_contents( $arg ) );
813 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
815 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
820 * @param mixed $res A SQL result
823 * Free a result object
825 function freeResult( $res ) {
826 if ( !@/**/mysql_free_result( $res ) ) {
827 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
832 * Fetch the next row from the given result object, in object form
834 function fetchObject( $res ) {
835 @/**/$row = mysql_fetch_object( $res );
836 if( $this->lastErrno() ) {
837 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
843 * Fetch the next row from the given result object
846 function fetchRow( $res ) {
847 @/**/$row = mysql_fetch_array( $res );
848 if ( $this->lastErrno() ) {
849 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
855 * Get the number of rows in a result object
857 function numRows( $res ) {
858 @/**/$n = mysql_num_rows( $res );
859 if( $this->lastErrno() ) {
860 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
866 * Get the number of fields in a result object
867 * See documentation for mysql_num_fields()
869 function numFields( $res ) { return mysql_num_fields( $res ); }
872 * Get a field name in a result object
873 * See documentation for mysql_field_name():
874 * http://www.php.net/mysql_field_name
876 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
879 * Get the inserted value of an auto-increment row
881 * The value inserted should be fetched from nextSequenceValue()
884 * $id = $dbw->nextSequenceValue('page_page_id_seq');
885 * $dbw->insert('page',array('page_id' => $id));
886 * $id = $dbw->insertId();
888 function insertId() { return mysql_insert_id( $this->mConn
); }
891 * Change the position of the cursor in a result object
892 * See mysql_data_seek()
894 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
897 * Get the last error number
900 function lastErrno() {
901 if ( $this->mConn
) {
902 return mysql_errno( $this->mConn
);
904 return mysql_errno();
909 * Get a description of the last error
910 * See mysql_error() for more details
912 function lastError() {
913 if ( $this->mConn
) {
914 # Even if it's non-zero, it can still be invalid
915 wfSuppressWarnings();
916 $error = mysql_error( $this->mConn
);
918 $error = mysql_error();
922 $error = mysql_error();
925 $error .= ' (' . $this->mServer
. ')';
930 * Get the number of rows affected by the last write query
931 * See mysql_affected_rows() for more details
933 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
934 /**#@-*/ // end of template : @param $result
937 * Simple UPDATE wrapper
938 * Usually aborts on failure
939 * If errors are explicitly ignored, returns success
941 * This function exists for historical reasons, Database::update() has a more standard
942 * calling convention and feature set
944 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
946 $table = $this->tableName( $table );
947 $sql = "UPDATE $table SET $var = '" .
948 $this->strencode( $value ) . "' WHERE ($cond)";
949 return (bool)$this->query( $sql, $fname );
953 * Simple SELECT wrapper, returns a single field, input must be encoded
954 * Usually aborts on failure
955 * If errors are explicitly ignored, returns FALSE on failure
957 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
958 if ( !is_array( $options ) ) {
959 $options = array( $options );
961 $options['LIMIT'] = 1;
963 $res = $this->select( $table, $var, $cond, $fname, $options );
964 if ( $res === false ||
!$this->numRows( $res ) ) {
967 $row = $this->fetchRow( $res );
968 if ( $row !== false ) {
969 $this->freeResult( $res );
977 * Returns an optional USE INDEX clause to go after the table, and a
978 * string to go at the end of the query
982 * @param array $options an associative array of options to be turned into
983 * an SQL query, valid keys are listed in the function.
986 function makeSelectOptions( $options ) {
990 $noKeyOptions = array();
991 foreach ( $options as $key => $option ) {
992 if ( is_numeric( $key ) ) {
993 $noKeyOptions[$option] = true;
997 if ( isset( $options['GROUP BY'] ) ) $tailOpts .= " GROUP BY {$options['GROUP BY']}";
998 if ( isset( $options['ORDER BY'] ) ) $tailOpts .= " ORDER BY {$options['ORDER BY']}";
1000 if (isset($options['LIMIT'])) {
1001 $tailOpts .= $this->limitResult('', $options['LIMIT'],
1002 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
1005 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1006 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1007 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1009 # Various MySQL extensions
1010 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
1011 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
1012 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
1013 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
1014 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
1015 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
1016 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
1017 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
1019 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1020 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1025 return array( $startOpts, $useIndex, $tailOpts );
1031 * @param mixed $table Array or string, table name(s) (prefix auto-added)
1032 * @param mixed $vars Array or string, field name(s) to be retrieved
1033 * @param mixed $conds Array or string, condition(s) for WHERE
1034 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1035 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1036 * see Database::makeSelectOptions code for list of supported stuff
1037 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
1039 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
1041 if( is_array( $vars ) ) {
1042 $vars = implode( ',', $vars );
1044 if( !is_array( $options ) ) {
1045 $options = array( $options );
1047 if( is_array( $table ) ) {
1048 if ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1049 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
1051 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1052 } elseif ($table!='') {
1053 if ($table{0}==' ') {
1054 $from = ' FROM ' . $table;
1056 $from = ' FROM ' . $this->tableName( $table );
1062 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
1064 if( !empty( $conds ) ) {
1065 if ( is_array( $conds ) ) {
1066 $conds = $this->makeList( $conds, LIST_AND
);
1068 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $tailOpts";
1070 $sql = "SELECT $startOpts $vars $from $useIndex $tailOpts";
1073 return $this->query( $sql, $fname );
1077 * Single row SELECT wrapper
1078 * Aborts or returns FALSE on error
1080 * $vars: the selected variables
1081 * $conds: a condition map, terms are ANDed together.
1082 * Items with numeric keys are taken to be literal conditions
1083 * Takes an array of selected variables, and a condition map, which is ANDed
1084 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1085 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1086 * $obj- >page_id is the ID of the Astronomy article
1088 * @todo migrate documentation to phpdocumentor format
1090 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
1091 $options['LIMIT'] = 1;
1092 $res = $this->select( $table, $vars, $conds, $fname, $options );
1093 if ( $res === false )
1095 if ( !$this->numRows($res) ) {
1096 $this->freeResult($res);
1099 $obj = $this->fetchObject( $res );
1100 $this->freeResult( $res );
1106 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1107 * It's only slightly flawed. Don't use for anything important.
1109 * @param string $sql A SQL Query
1112 static function generalizeSQL( $sql ) {
1113 # This does the same as the regexp below would do, but in such a way
1114 # as to avoid crashing php on some large strings.
1115 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1117 $sql = str_replace ( "\\\\", '', $sql);
1118 $sql = str_replace ( "\\'", '', $sql);
1119 $sql = str_replace ( "\\\"", '', $sql);
1120 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1121 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1123 # All newlines, tabs, etc replaced by single space
1124 $sql = preg_replace ( '/\s+/', ' ', $sql);
1127 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1133 * Determines whether a field exists in a table
1134 * Usually aborts on failure
1135 * If errors are explicitly ignored, returns NULL on failure
1137 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1138 $table = $this->tableName( $table );
1139 $res = $this->query( 'DESCRIBE '.$table, $fname );
1146 while ( $row = $this->fetchObject( $res ) ) {
1147 if ( $row->Field
== $field ) {
1156 * Determines whether an index exists
1157 * Usually aborts on failure
1158 * If errors are explicitly ignored, returns NULL on failure
1160 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1161 $info = $this->indexInfo( $table, $index, $fname );
1162 if ( is_null( $info ) ) {
1165 return $info !== false;
1171 * Get information about an index into an object
1172 * Returns false if the index does not exist
1174 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1175 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1176 # SHOW INDEX should work for 3.x and up:
1177 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1178 $table = $this->tableName( $table );
1179 $sql = 'SHOW INDEX FROM '.$table;
1180 $res = $this->query( $sql, $fname );
1186 while ( $row = $this->fetchObject( $res ) ) {
1187 if ( $row->Key_name
== $index ) {
1191 $this->freeResult($res);
1193 return empty($result) ?
false : $result;
1197 * Query whether a given table exists
1199 function tableExists( $table ) {
1200 $table = $this->tableName( $table );
1201 $old = $this->ignoreErrors( true );
1202 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1203 $this->ignoreErrors( $old );
1205 $this->freeResult( $res );
1213 * mysql_fetch_field() wrapper
1214 * Returns false if the field doesn't exist
1219 function fieldInfo( $table, $field ) {
1220 $table = $this->tableName( $table );
1221 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1222 $n = mysql_num_fields( $res );
1223 for( $i = 0; $i < $n; $i++
) {
1224 $meta = mysql_fetch_field( $res, $i );
1225 if( $field == $meta->name
) {
1233 * mysql_field_type() wrapper
1235 function fieldType( $res, $index ) {
1236 return mysql_field_type( $res, $index );
1240 * Determines if a given index is unique
1242 function indexUnique( $table, $index ) {
1243 $indexInfo = $this->indexInfo( $table, $index );
1244 if ( !$indexInfo ) {
1247 return !$indexInfo[0]->Non_unique
;
1251 * INSERT wrapper, inserts an array into a table
1253 * $a may be a single associative array, or an array of these with numeric keys, for
1256 * Usually aborts on failure
1257 * If errors are explicitly ignored, returns success
1259 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1260 # No rows to insert, easy just return now
1261 if ( !count( $a ) ) {
1265 $table = $this->tableName( $table );
1266 if ( !is_array( $options ) ) {
1267 $options = array( $options );
1269 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1271 $keys = array_keys( $a[0] );
1274 $keys = array_keys( $a );
1277 $sql = 'INSERT ' . implode( ' ', $options ) .
1278 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1282 foreach ( $a as $row ) {
1288 $sql .= '(' . $this->makeList( $row ) . ')';
1291 $sql .= '(' . $this->makeList( $a ) . ')';
1293 return (bool)$this->query( $sql, $fname );
1297 * Make UPDATE options for the Database::update function
1300 * @param array $options The options passed to Database::update
1303 function makeUpdateOptions( $options ) {
1304 if( !is_array( $options ) ) {
1305 $options = array( $options );
1308 if ( in_array( 'LOW_PRIORITY', $options ) )
1309 $opts[] = $this->lowPriorityOption();
1310 if ( in_array( 'IGNORE', $options ) )
1312 return implode(' ', $opts);
1316 * UPDATE wrapper, takes a condition array and a SET array
1318 * @param string $table The table to UPDATE
1319 * @param array $values An array of values to SET
1320 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1321 * @param string $fname The Class::Function calling this function
1323 * @param array $options An array of UPDATE options, can be one or
1324 * more of IGNORE, LOW_PRIORITY
1326 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1327 $table = $this->tableName( $table );
1328 $opts = $this->makeUpdateOptions( $options );
1329 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1330 if ( $conds != '*' ) {
1331 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1333 $this->query( $sql, $fname );
1337 * Makes an encoded list of strings from an array
1339 * LIST_COMMA - comma separated, no field names
1340 * LIST_AND - ANDed WHERE clause (without the WHERE)
1341 * LIST_OR - ORed WHERE clause (without the WHERE)
1342 * LIST_SET - comma separated with field names, like a SET clause
1343 * LIST_NAMES - comma separated field names
1345 function makeList( $a, $mode = LIST_COMMA
) {
1346 if ( !is_array( $a ) ) {
1347 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1352 foreach ( $a as $field => $value ) {
1354 if ( $mode == LIST_AND
) {
1356 } elseif($mode == LIST_OR
) {
1364 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1365 $list .= "($value)";
1366 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
1368 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array ($value) ) {
1369 $list .= $field." IN (".$this->makeList($value).") ";
1371 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1372 $list .= "$field = ";
1374 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1381 * Change the current database
1383 function selectDB( $db ) {
1384 $this->mDBname
= $db;
1385 return mysql_select_db( $db, $this->mConn
);
1389 * Format a table name ready for use in constructing an SQL query
1391 * This does two important things: it quotes table names which as necessary,
1392 * and it adds a table prefix if there is one.
1394 * All functions of this object which require a table name call this function
1395 * themselves. Pass the canonical name to such functions. This is only needed
1396 * when calling query() directly.
1398 * @param string $name database table name
1400 function tableName( $name ) {
1402 # Skip quoted literals
1403 if ( $name{0} != '`' ) {
1404 if ( $this->mTablePrefix
!== '' && strpos( '.', $name ) === false ) {
1405 $name = "{$this->mTablePrefix}$name";
1407 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1408 $name = "`$wgSharedDB`.`$name`";
1418 * Fetch a number of table names into an array
1419 * This is handy when you need to construct SQL for joins
1422 * extract($dbr->tableNames('user','watchlist'));
1423 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1424 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1426 public function tableNames() {
1427 $inArray = func_get_args();
1429 foreach ( $inArray as $name ) {
1430 $retVal[$name] = $this->tableName( $name );
1436 * @desc: Fetch a number of table names into an zero-indexed numerical array
1437 * This is handy when you need to construct SQL for joins
1440 * list( $user, $watchlist ) = $dbr->tableNames('user','watchlist');
1441 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1442 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1444 public function tableNamesN() {
1445 $inArray = func_get_args();
1447 foreach ( $inArray as $name ) {
1448 $retVal[] = $this->tableName( $name );
1456 function tableNamesWithUseIndex( $tables, $use_index ) {
1459 foreach ( $tables as $table )
1460 if ( @$use_index[$table] !== null )
1461 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1463 $ret[] = $this->tableName( $table );
1465 return implode( ',', $ret );
1469 * Wrapper for addslashes()
1470 * @param string $s String to be slashed.
1471 * @return string slashed string.
1473 function strencode( $s ) {
1474 return mysql_real_escape_string( $s, $this->mConn
);
1478 * If it's a string, adds quotes and backslashes
1479 * Otherwise returns as-is
1481 function addQuotes( $s ) {
1482 if ( is_null( $s ) ) {
1485 # This will also quote numeric values. This should be harmless,
1486 # and protects against weird problems that occur when they really
1487 # _are_ strings such as article titles and string->number->string
1488 # conversion is not 1:1.
1489 return "'" . $this->strencode( $s ) . "'";
1494 * Escape string for safe LIKE usage
1496 function escapeLike( $s ) {
1497 $s=$this->strencode( $s );
1498 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1503 * Returns an appropriately quoted sequence value for inserting a new row.
1504 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1505 * subclass will return an integer, and save the value for insertId()
1507 function nextSequenceValue( $seqName ) {
1513 * PostgreSQL doesn't have them and returns ""
1515 function useIndexClause( $index ) {
1516 return "FORCE INDEX ($index)";
1520 * REPLACE query wrapper
1521 * PostgreSQL simulates this with a DELETE followed by INSERT
1522 * $row is the row to insert, an associative array
1523 * $uniqueIndexes is an array of indexes. Each element may be either a
1524 * field name or an array of field names
1526 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1527 * However if you do this, you run the risk of encountering errors which wouldn't have
1530 * @todo migrate comment to phodocumentor format
1532 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1533 $table = $this->tableName( $table );
1536 if ( !is_array( reset( $rows ) ) ) {
1537 $rows = array( $rows );
1540 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1542 foreach ( $rows as $row ) {
1548 $sql .= '(' . $this->makeList( $row ) . ')';
1550 return $this->query( $sql, $fname );
1554 * DELETE where the condition is a join
1555 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1557 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1558 * join condition matches, set $conds='*'
1560 * DO NOT put the join condition in $conds
1562 * @param string $delTable The table to delete from.
1563 * @param string $joinTable The other table.
1564 * @param string $delVar The variable to join on, in the first table.
1565 * @param string $joinVar The variable to join on, in the second table.
1566 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1568 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1570 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1573 $delTable = $this->tableName( $delTable );
1574 $joinTable = $this->tableName( $joinTable );
1575 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1576 if ( $conds != '*' ) {
1577 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1580 return $this->query( $sql, $fname );
1584 * Returns the size of a text field, or -1 for "unlimited"
1586 function textFieldSize( $table, $field ) {
1587 $table = $this->tableName( $table );
1588 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1589 $res = $this->query( $sql, 'Database::textFieldSize' );
1590 $row = $this->fetchObject( $res );
1591 $this->freeResult( $res );
1594 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1603 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1605 function lowPriorityOption() {
1606 return 'LOW_PRIORITY';
1610 * DELETE query wrapper
1612 * Use $conds == "*" to delete all rows
1614 function delete( $table, $conds, $fname = 'Database::delete' ) {
1616 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1618 $table = $this->tableName( $table );
1619 $sql = "DELETE FROM $table";
1620 if ( $conds != '*' ) {
1621 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1623 return $this->query( $sql, $fname );
1627 * INSERT SELECT wrapper
1628 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1629 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1630 * $conds may be "*" to copy the whole table
1631 * srcTable may be an array of tables.
1633 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1634 $insertOptions = array(), $selectOptions = array() )
1636 $destTable = $this->tableName( $destTable );
1637 if ( is_array( $insertOptions ) ) {
1638 $insertOptions = implode( ' ', $insertOptions );
1640 if( !is_array( $selectOptions ) ) {
1641 $selectOptions = array( $selectOptions );
1643 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1644 if( is_array( $srcTable ) ) {
1645 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1647 $srcTable = $this->tableName( $srcTable );
1649 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1650 " SELECT $startOpts " . implode( ',', $varMap ) .
1651 " FROM $srcTable $useIndex ";
1652 if ( $conds != '*' ) {
1653 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1655 $sql .= " $tailOpts";
1656 return $this->query( $sql, $fname );
1660 * Construct a LIMIT query with optional offset
1661 * This is used for query pages
1662 * $sql string SQL query we will append the limit too
1663 * $limit integer the SQL limit
1664 * $offset integer the SQL offset (default false)
1666 function limitResult($sql, $limit, $offset=false) {
1667 if( !is_numeric($limit) ) {
1668 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1670 return " $sql LIMIT "
1671 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1674 function limitResultForUpdate($sql, $num) {
1675 return $this->limitResult($sql, $num, 0);
1679 * Returns an SQL expression for a simple conditional.
1682 * @param string $cond SQL expression which will result in a boolean value
1683 * @param string $trueVal SQL expression to return if true
1684 * @param string $falseVal SQL expression to return if false
1685 * @return string SQL fragment
1687 function conditional( $cond, $trueVal, $falseVal ) {
1688 return " IF($cond, $trueVal, $falseVal) ";
1692 * Determines if the last failure was due to a deadlock
1694 function wasDeadlock() {
1695 return $this->lastErrno() == 1213;
1699 * Perform a deadlock-prone transaction.
1701 * This function invokes a callback function to perform a set of write
1702 * queries. If a deadlock occurs during the processing, the transaction
1703 * will be rolled back and the callback function will be called again.
1706 * $dbw->deadlockLoop( callback, ... );
1708 * Extra arguments are passed through to the specified callback function.
1710 * Returns whatever the callback function returned on its successful,
1711 * iteration, or false on error, for example if the retry limit was
1714 function deadlockLoop() {
1715 $myFname = 'Database::deadlockLoop';
1718 $args = func_get_args();
1719 $function = array_shift( $args );
1720 $oldIgnore = $this->ignoreErrors( true );
1721 $tries = DEADLOCK_TRIES
;
1722 if ( is_array( $function ) ) {
1723 $fname = $function[0];
1728 $retVal = call_user_func_array( $function, $args );
1729 $error = $this->lastError();
1730 $errno = $this->lastErrno();
1731 $sql = $this->lastQuery();
1734 if ( $this->wasDeadlock() ) {
1736 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1738 $this->reportQueryError( $error, $errno, $sql, $fname );
1741 } while( $this->wasDeadlock() && --$tries > 0 );
1742 $this->ignoreErrors( $oldIgnore );
1743 if ( $tries <= 0 ) {
1744 $this->query( 'ROLLBACK', $myFname );
1745 $this->reportQueryError( $error, $errno, $sql, $fname );
1748 $this->query( 'COMMIT', $myFname );
1754 * Do a SELECT MASTER_POS_WAIT()
1756 * @param string $file the binlog file
1757 * @param string $pos the binlog position
1758 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1760 function masterPosWait( $file, $pos, $timeout ) {
1761 $fname = 'Database::masterPosWait';
1762 wfProfileIn( $fname );
1765 # Commit any open transactions
1766 $this->immediateCommit();
1768 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1769 $encFile = $this->strencode( $file );
1770 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1771 $res = $this->doQuery( $sql );
1772 if ( $res && $row = $this->fetchRow( $res ) ) {
1773 $this->freeResult( $res );
1774 wfProfileOut( $fname );
1777 wfProfileOut( $fname );
1783 * Get the position of the master from SHOW SLAVE STATUS
1785 function getSlavePos() {
1786 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1787 $row = $this->fetchObject( $res );
1789 return array( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1791 return array( false, false );
1796 * Get the position of the master from SHOW MASTER STATUS
1798 function getMasterPos() {
1799 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1800 $row = $this->fetchObject( $res );
1802 return array( $row->File
, $row->Position
);
1804 return array( false, false );
1809 * Begin a transaction, committing any previously open transaction
1811 function begin( $fname = 'Database::begin' ) {
1812 $this->query( 'BEGIN', $fname );
1813 $this->mTrxLevel
= 1;
1819 function commit( $fname = 'Database::commit' ) {
1820 $this->query( 'COMMIT', $fname );
1821 $this->mTrxLevel
= 0;
1825 * Rollback a transaction
1827 function rollback( $fname = 'Database::rollback' ) {
1828 $this->query( 'ROLLBACK', $fname );
1829 $this->mTrxLevel
= 0;
1833 * Begin a transaction, committing any previously open transaction
1834 * @deprecated use begin()
1836 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1841 * Commit transaction, if one is open
1842 * @deprecated use commit()
1844 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1849 * Return MW-style timestamp used for MySQL schema
1851 function timestamp( $ts=0 ) {
1852 return wfTimestamp(TS_MW
,$ts);
1856 * Local database timestamp format or null
1858 function timestampOrNull( $ts = null ) {
1859 if( is_null( $ts ) ) {
1862 return $this->timestamp( $ts );
1869 function resultObject( $result ) {
1870 if( empty( $result ) ) {
1873 return new ResultWrapper( $this, $result );
1878 * Return aggregated value alias
1880 function aggregateValue ($valuedata,$valuename='value') {
1885 * @return string wikitext of a link to the server software's web site
1887 function getSoftwareLink() {
1888 return "[http://www.mysql.com/ MySQL]";
1892 * @return string Version information from the database
1894 function getServerVersion() {
1895 return mysql_get_server_info( $this->mConn
);
1899 * Ping the server and try to reconnect if it there is no connection
1902 if( function_exists( 'mysql_ping' ) ) {
1903 return mysql_ping( $this->mConn
);
1905 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1912 * At the moment, this will only work if the DB user has the PROCESS privilege
1915 $res = $this->query( 'SHOW PROCESSLIST' );
1916 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1917 # dubious, but unfortunately there's no easy rigorous way
1918 while ( $row = $this->fetchObject( $res ) ) {
1919 /* This should work for most situations - when default db
1920 * for thread is not specified, it had no events executed,
1921 * and therefore it doesn't know yet how lagged it is.
1923 * Relay log I/O thread does not select databases.
1925 if ( $row->User
== 'system user' &&
1926 $row->State
!= 'Waiting for master to send event' &&
1927 $row->State
!= 'Connecting to master' &&
1928 $row->State
!= 'Queueing master event to the relay log' &&
1929 $row->State
!= 'Waiting for master update' &&
1930 $row->State
!= 'Requesting binlog dump'
1932 # This is it, return the time (except -ve)
1933 if ( $row->Time
> 0x7fffffff ) {
1944 * Get status information from SHOW STATUS in an associative array
1946 function getStatus($which="%") {
1947 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1949 while ( $row = $this->fetchObject( $res ) ) {
1950 $status[$row->Variable_name
] = $row->Value
;
1956 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1958 function maxListLen() {
1962 function encodeBlob($b) {
1966 function decodeBlob($b) {
1971 * Read and execute SQL commands from a file.
1972 * Returns true on success, error string on failure
1974 function sourceFile( $filename ) {
1975 $fp = fopen( $filename, 'r' );
1976 if ( false === $fp ) {
1977 return "Could not open \"{$filename}\".\n";
1982 $dollarquote = false;
1984 while ( ! feof( $fp ) ) {
1985 $line = trim( fgets( $fp, 1024 ) );
1986 $sl = strlen( $line ) - 1;
1988 if ( $sl < 0 ) { continue; }
1989 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
1991 ## Allow dollar quoting for function declarations
1992 if (substr($line,0,4) == '$mw$') {
1994 $dollarquote = false;
1998 $dollarquote = true;
2001 else if (!$dollarquote) {
2002 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
2004 $line = substr( $line, 0, $sl );
2008 if ( '' != $cmd ) { $cmd .= ' '; }
2012 $cmd = str_replace(';;', ";", $cmd);
2013 $cmd = $this->replaceVars( $cmd );
2014 $res = $this->query( $cmd, 'dbsource', true );
2016 if ( false === $res ) {
2017 $err = $this->lastError();
2018 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2030 * Replace variables in sourced SQL
2032 protected function replaceVars( $ins ) {
2034 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2035 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2036 'wgDBadminuser', 'wgDBadminpassword',
2039 // Ordinary variables
2040 foreach ( $varnames as $var ) {
2041 if( isset( $GLOBALS[$var] ) ) {
2042 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2043 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2044 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2045 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2050 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
2051 array( &$this, 'tableNameCallback' ), $ins );
2056 * Table name callback
2059 protected function tableNameCallback( $matches ) {
2060 return $this->tableName( $matches[1] );
2066 * Database abstraction object for mySQL
2067 * Inherit all methods and properties of Database::Database()
2071 class DatabaseMysql
extends Database
{
2077 * Result wrapper for grabbing data queried by someone else
2080 class ResultWrapper
{
2086 function ResultWrapper( &$database, $result ) {
2087 $this->db
=& $database;
2088 $this->result
=& $result;
2094 function numRows() {
2095 return $this->db
->numRows( $this->result
);
2101 function fetchObject() {
2102 return $this->db
->fetchObject( $this->result
);
2108 function fetchRow() {
2109 return $this->db
->fetchRow( $this->result
);
2116 $this->db
->freeResult( $this->result
);
2117 unset( $this->result
);
2121 function seek( $row ) {
2122 $this->db
->dataSeek( $this->result
, $row );
2126 if ($this->numRows()) {
2127 $this->db
->dataSeek($this->result
, 0);