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 *****************************************************************************/
20 * @addtogroup Database
25 function DBObject($data) {
40 * @addtogroup Database
42 * This allows us to distinguish a blob from a normal string and an array of strings
46 function __construct($data) {
56 * @addtogroup Database
59 private $name, $tablename, $default, $max_length, $nullable,
60 $is_pk, $is_unique, $is_key, $type;
61 function __construct ($info) {
62 $this->name
= $info->name
;
63 $this->tablename
= $info->table
;
64 $this->default = $info->def
;
65 $this->max_length
= $info->max_length
;
66 $this->nullable
= !$info->not_null
;
67 $this->is_pk
= $info->primary_key
;
68 $this->is_unique
= $info->unique_key
;
69 $this->is_multiple
= $info->multiple_key
;
70 $this->is_key
= ($this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
71 $this->type
= $info->type
;
78 function tableName() {
79 return $this->tableName
;
82 function defaultValue() {
83 return $this->default;
86 function maxLength() {
87 return $this->max_length
;
91 return $this->nullable
;
98 function isMultipleKey() {
99 return $this->is_multiple
;
107 /******************************************************************************
109 *****************************************************************************/
112 * Database error base class
113 * @addtogroup Database
115 class DBError
extends MWException
{
119 * Construct a database error
120 * @param Database $db The database object which threw the error
121 * @param string $error A simple error message to be used for debugging
123 function __construct( Database
&$db, $error ) {
125 parent
::__construct( $error );
130 * @addtogroup Database
132 class DBConnectionError
extends DBError
{
135 function __construct( Database
&$db, $error = 'unknown error' ) {
136 $msg = 'DB connection error';
137 if ( trim( $error ) != '' ) {
140 $this->error
= $error;
141 parent
::__construct( $db, $msg );
144 function useOutputPage() {
145 // Not likely to work
149 function useMessageCache() {
150 // Not likely to work
155 return $this->getMessage() . "\n";
158 function getLogMessage() {
159 # Don't send to the exception log
163 function getPageTitle() {
165 return "$wgSitename has a problem";
169 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding;
170 global $wgSitename, $wgServer, $wgMessageCache;
172 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
173 # Hard coding strings instead.
175 $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>";
176 $mainpage = 'Main Page';
177 $searchdisabled = <<<EOT
178 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
179 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
183 <!-- SiteSearch Google -->
184 <FORM method=GET action=\"http://www.google.com/search\">
185 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
186 <A HREF=\"http://www.google.com/\">
187 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
188 border=\"0\" ALT=\"Google\"></A>
191 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
192 <INPUT type=submit name=btnG VALUE=\"Google Search\">
194 <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 />
195 <input type='hidden' name='ie' value='$2'>
196 <input type='hidden' name='oe' value='$2'>
200 <!-- SiteSearch Google -->";
201 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
204 if ( is_object( $wgMessageCache ) ) {
205 $wgMessageCache->disable();
208 if ( trim( $this->error
) == '' ) {
209 $this->error
= $this->db
->getProperty('mServer');
212 $text = str_replace( '$1', $this->error
, $noconnect );
213 $text .= wfGetSiteNotice();
215 if($wgUseFileCache) {
220 $t = Title
::newFromURL( $title );
221 } elseif (@/**/$_REQUEST['search']) {
222 $search = $_REQUEST['search'];
223 return $searchdisabled .
224 str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
225 $wgInputEncoding ), $googlesearch );
227 $t = Title
::newFromText( $mainpage );
231 $cache = new HTMLFileCache( $t );
232 if( $cache->isFileCached() ) {
233 // @todo, FIXME: $msg is not defined on the next line.
234 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
235 $cachederror . "</b></p>\n";
237 $tag = '<div id="article">';
241 $cache->fetchPageText() );
250 * @addtogroup Database
252 class DBQueryError
extends DBError
{
253 public $error, $errno, $sql, $fname;
255 function __construct( Database
&$db, $error, $errno, $sql, $fname ) {
256 $message = "A database error has occurred\n" .
258 "Function: $fname\n" .
259 "Error: $errno $error\n";
261 parent
::__construct( $db, $message );
262 $this->error
= $error;
263 $this->errno
= $errno;
265 $this->fname
= $fname;
269 if ( $this->useMessageCache() ) {
270 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
271 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
273 return $this->getMessage();
278 global $wgShowSQLErrors;
279 if( !$wgShowSQLErrors ) {
280 return $this->msg( 'sqlhidden', 'SQL hidden' );
286 function getLogMessage() {
287 # Don't send to the exception log
291 function getPageTitle() {
292 return $this->msg( 'databaseerror', 'Database error' );
296 if ( $this->useMessageCache() ) {
297 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
298 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
300 return nl2br( htmlspecialchars( $this->getMessage() ) );
306 * @addtogroup Database
308 class DBUnexpectedError
extends DBError
{}
310 /******************************************************************************/
313 * Database abstraction object
314 * @addtogroup Database
318 #------------------------------------------------------------------------------
320 #------------------------------------------------------------------------------
322 protected $mLastQuery = '';
324 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
325 protected $mOut, $mOpened = false;
327 protected $mFailFunction;
328 protected $mTablePrefix;
330 protected $mTrxLevel = 0;
331 protected $mErrorCount = 0;
332 protected $mLBInfo = array();
334 #------------------------------------------------------------------------------
336 #------------------------------------------------------------------------------
337 # These optionally set a variable and return the previous state
340 * Fail function, takes a Database as a parameter
341 * Set to false for default, 1 for ignore errors
343 function failFunction( $function = NULL ) {
344 return wfSetVar( $this->mFailFunction
, $function );
348 * Output page, used for reporting errors
349 * FALSE means discard output
351 function setOutputPage( $out ) {
356 * Boolean, controls output of large amounts of debug information
358 function debug( $debug = NULL ) {
359 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
363 * Turns buffering of SQL result sets on (true) or off (false).
364 * Default is "on" and it should not be changed without good reasons.
366 function bufferResults( $buffer = NULL ) {
367 if ( is_null( $buffer ) ) {
368 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
370 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
375 * Turns on (false) or off (true) the automatic generation and sending
376 * of a "we're sorry, but there has been a database error" page on
377 * database errors. Default is on (false). When turned off, the
378 * code should use lastErrno() and lastError() to handle the
379 * situation as appropriate.
381 function ignoreErrors( $ignoreErrors = NULL ) {
382 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
386 * The current depth of nested transactions
387 * @param $level Integer: , default NULL.
389 function trxLevel( $level = NULL ) {
390 return wfSetVar( $this->mTrxLevel
, $level );
394 * Number of errors logged, only useful when errors are ignored
396 function errorCount( $count = NULL ) {
397 return wfSetVar( $this->mErrorCount
, $count );
401 * Properties passed down from the server info array of the load balancer
403 function getLBInfo( $name = NULL ) {
404 if ( is_null( $name ) ) {
405 return $this->mLBInfo
;
407 if ( array_key_exists( $name, $this->mLBInfo
) ) {
408 return $this->mLBInfo
[$name];
415 function setLBInfo( $name, $value = NULL ) {
416 if ( is_null( $value ) ) {
417 $this->mLBInfo
= $name;
419 $this->mLBInfo
[$name] = $value;
424 * Returns true if this database supports (and uses) cascading deletes
426 function cascadingDeletes() {
431 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
433 function cleanupTriggers() {
438 * Returns true if this database is strict about what can be put into an IP field.
439 * Specifically, it uses a NULL value instead of an empty string.
441 function strictIPs() {
446 * Returns true if this database uses timestamps rather than integers
448 function realTimestamps() {
453 * Returns true if this database does an implicit sort when doing GROUP BY
455 function implicitGroupby() {
460 * Returns true if this database does an implicit order by when the column has an index
461 * For example: SELECT page_title FROM page LIMIT 1
463 function implicitOrderby() {
468 * Returns true if this database can do a native search on IP columns
469 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
471 function searchableIPs() {
476 * Returns true if this database can use functional indexes
478 function functionalIndexes() {
485 function lastQuery() { return $this->mLastQuery
; }
486 function isOpen() { return $this->mOpened
; }
489 function setFlag( $flag ) {
490 $this->mFlags |
= $flag;
493 function clearFlag( $flag ) {
494 $this->mFlags
&= ~
$flag;
497 function getFlag( $flag ) {
498 return !!($this->mFlags
& $flag);
502 * General read-only accessor
504 function getProperty( $name ) {
508 #------------------------------------------------------------------------------
510 #------------------------------------------------------------------------------
514 * @param string $server database server host
515 * @param string $user database user name
516 * @param string $password database user password
517 * @param string $dbname database name
518 * @param failFunction
520 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
522 function __construct( $server = false, $user = false, $password = false, $dbName = false,
523 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
525 global $wgOut, $wgDBprefix, $wgCommandLineMode;
526 # Can't get a reference if it hasn't been set yet
527 if ( !isset( $wgOut ) ) {
530 $this->mOut
=& $wgOut;
532 $this->mFailFunction
= $failFunction;
533 $this->mFlags
= $flags;
535 if ( $this->mFlags
& DBO_DEFAULT
) {
536 if ( $wgCommandLineMode ) {
537 $this->mFlags
&= ~DBO_TRX
;
539 $this->mFlags |
= DBO_TRX
;
544 // Faster read-only access
545 if ( wfReadOnly() ) {
546 $this->mFlags |= DBO_PERSISTENT;
547 $this->mFlags &= ~DBO_TRX;
550 /** Get the default table prefix*/
551 if ( $tablePrefix == 'get from global' ) {
552 $this->mTablePrefix
= $wgDBprefix;
554 $this->mTablePrefix
= $tablePrefix;
558 $this->open( $server, $user, $password, $dbName );
564 * @param failFunction
567 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
569 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
573 * Usually aborts on failure
574 * If the failFunction is set to a non-zero integer, returns success
576 function open( $server, $user, $password, $dbName ) {
578 wfProfileIn( __METHOD__
);
580 # Test for missing mysql.so
581 # First try to load it
582 if (!@extension_loaded
('mysql')) {
587 # Otherwise we get a suppressed fatal error, which is very hard to track down
588 if ( !function_exists( 'mysql_connect' ) ) {
589 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
593 $this->mServer
= $server;
594 $this->mUser
= $user;
595 $this->mPassword
= $password;
596 $this->mDBname
= $dbName;
600 wfProfileIn("dbconnect-$server");
602 # LIVE PATCH by Tim, ask Domas for why: retry loop
603 $this->mConn
= false;
605 for ( $i = 0; $i < $max && !$this->mConn
; $i++
) {
609 if ( $this->mFlags
& DBO_PERSISTENT
) {
610 @/**/$this->mConn
= mysql_pconnect( $server, $user, $password );
612 # Create a new connection...
613 @/**/$this->mConn
= mysql_connect( $server, $user, $password, true );
615 if ($this->mConn
=== false) {
617 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
621 wfProfileOut("dbconnect-$server");
623 if ( $dbName != '' ) {
624 if ( $this->mConn
!== false ) {
625 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
627 $error = "Error selecting database $dbName on server {$this->mServer} " .
628 "from client host {$wguname['nodename']}\n";
629 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
633 wfDebug( "DB connection error\n" );
634 wfDebug( "Server: $server, User: $user, Password: " .
635 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
640 $success = (bool)$this->mConn
;
644 $version = $this->getServerVersion();
645 if ( version_compare( $version, '4.1' ) >= 0 ) {
646 // Tell the server we're communicating with it in UTF-8.
647 // This may engage various charset conversions.
650 $this->query( 'SET NAMES utf8', __METHOD__
);
652 // Turn off strict mode
653 $this->query( "SET sql_mode = ''", __METHOD__
);
656 // Turn off strict mode if it is on
658 $this->reportConnectionError();
661 $this->mOpened
= $success;
662 wfProfileOut( __METHOD__
);
668 * Closes a database connection.
669 * if it is open : commits any open transactions
671 * @return bool operation success. true if already closed.
675 $this->mOpened
= false;
676 if ( $this->mConn
) {
677 if ( $this->trxLevel() ) {
678 $this->immediateCommit();
680 return mysql_close( $this->mConn
);
687 * @param string $error fallback error message, used if none is given by MySQL
689 function reportConnectionError( $error = 'Unknown error' ) {
690 $myError = $this->lastError();
695 if ( $this->mFailFunction
) {
696 # Legacy error handling method
697 if ( !is_int( $this->mFailFunction
) ) {
698 $ff = $this->mFailFunction
;
699 $ff( $this, $error );
703 wfLogDBError( "Connection error: $error\n" );
704 throw new DBConnectionError( $this, $error );
709 * Usually aborts on failure. If errors are explicitly ignored, returns success.
711 * @param $sql String: SQL query
712 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
713 * comment (you can use __METHOD__ or add some extra info)
714 * @param $tempIgnore Bool: Whether to avoid throwing an exception on errors...
715 * maybe best to catch the exception instead?
716 * @return true for a successful write query, ResultWrapper object for a successful read query,
717 * or false on failure if $tempIgnore set
718 * @throws DBQueryError Thrown when the database returns an error of any kind
720 public function query( $sql, $fname = '', $tempIgnore = false ) {
723 if ( $wgProfiling ) {
724 # generalizeSQL will probably cut down the query to reasonable
725 # logging size most of the time. The substr is really just a sanity check.
727 # Who's been wasting my precious column space? -- TS
728 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
730 if ( is_null( $this->getLBInfo( 'master' ) ) ) {
731 $queryProf = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
732 $totalProf = 'Database::query';
734 $queryProf = 'query-m: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
735 $totalProf = 'Database::query-master';
737 wfProfileIn( $totalProf );
738 wfProfileIn( $queryProf );
741 $this->mLastQuery
= $sql;
743 # Add a comment for easy SHOW PROCESSLIST interpretation
746 if ( is_object( $wgUser ) && !($wgUser instanceof StubObject
) ) {
747 $userName = $wgUser->getName();
748 if ( mb_strlen( $userName ) > 15 ) {
749 $userName = mb_substr( $userName, 0, 15 ) . '...';
751 $userName = str_replace( '/', '', $userName );
755 $commentedSql = preg_replace('/\s/', " /* $fname $userName */ ", $sql, 1);
757 # $commentedSql = $sql;
760 # If DBO_TRX is set, start a transaction
761 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
762 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK') {
763 // avoid establishing transactions for SHOW and SET statements too -
764 // that would delay transaction initializations to once connection
765 // is really used by application
766 $sqlstart = substr($sql,0,10); // very much worth it, benchmark certified(tm)
767 if (strpos($sqlstart,"SHOW ")!==0 and strpos($sqlstart,"SET ")!==0)
771 if ( $this->debug() ) {
772 $sqlx = substr( $commentedSql, 0, 500 );
773 $sqlx = strtr( $sqlx, "\t\n", ' ' );
774 wfDebug( "SQL: $sqlx\n" );
777 # Do the query and handle errors
778 $ret = $this->doQuery( $commentedSql );
780 # Try reconnecting if the connection was lost
781 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
782 # Transaction is gone, like it or not
783 $this->mTrxLevel
= 0;
784 wfDebug( "Connection lost, reconnecting...\n" );
785 if ( $this->ping() ) {
786 wfDebug( "Reconnected\n" );
787 $sqlx = substr( $commentedSql, 0, 500 );
788 $sqlx = strtr( $sqlx, "\t\n", ' ' );
789 global $wgRequestTime;
790 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
791 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
792 $ret = $this->doQuery( $commentedSql );
794 wfDebug( "Failed\n" );
798 if ( false === $ret ) {
799 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
802 if ( $wgProfiling ) {
803 wfProfileOut( $queryProf );
804 wfProfileOut( $totalProf );
806 return $this->resultObject( $ret );
810 * The DBMS-dependent part of query()
811 * @param $sql String: SQL query.
812 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
815 /*private*/ function doQuery( $sql ) {
816 if( $this->bufferResults() ) {
817 $ret = mysql_query( $sql, $this->mConn
);
819 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
828 * @param string $fname
829 * @param bool $tempIgnore
831 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
832 global $wgCommandLineMode;
833 # Ignore errors during error handling to avoid infinite recursion
834 $ignore = $this->ignoreErrors( true );
835 ++
$this->mErrorCount
;
837 if( $ignore ||
$tempIgnore ) {
838 wfDebug("SQL ERROR (ignored): $error\n");
839 $this->ignoreErrors( $ignore );
841 $sql1line = str_replace( "\n", "\\n", $sql );
842 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
843 wfDebug("SQL ERROR: " . $error . "\n");
844 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
850 * Intended to be compatible with the PEAR::DB wrapper functions.
851 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
853 * ? = scalar value, quoted as necessary
854 * ! = raw SQL bit (a function for instance)
855 * & = filename; reads the file and inserts as a blob
856 * (we don't use this though...)
858 function prepare( $sql, $func = 'Database::prepare' ) {
859 /* MySQL doesn't support prepared statements (yet), so just
860 pack up the query for reference. We'll manually replace
862 return array( 'query' => $sql, 'func' => $func );
865 function freePrepared( $prepared ) {
866 /* No-op for MySQL */
870 * Execute a prepared query with the various arguments
871 * @param string $prepared the prepared sql
872 * @param mixed $args Either an array here, or put scalars as varargs
874 function execute( $prepared, $args = null ) {
875 if( !is_array( $args ) ) {
877 $args = func_get_args();
878 array_shift( $args );
880 $sql = $this->fillPrepared( $prepared['query'], $args );
881 return $this->query( $sql, $prepared['func'] );
885 * Prepare & execute an SQL statement, quoting and inserting arguments
886 * in the appropriate places.
887 * @param string $query
888 * @param string $args ...
890 function safeQuery( $query, $args = null ) {
891 $prepared = $this->prepare( $query, 'Database::safeQuery' );
892 if( !is_array( $args ) ) {
894 $args = func_get_args();
895 array_shift( $args );
897 $retval = $this->execute( $prepared, $args );
898 $this->freePrepared( $prepared );
903 * For faking prepared SQL statements on DBs that don't support
905 * @param string $preparedSql - a 'preparable' SQL statement
906 * @param array $args - array of arguments to fill it with
907 * @return string executable SQL
909 function fillPrepared( $preparedQuery, $args ) {
911 $this->preparedArgs
=& $args;
912 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
913 array( &$this, 'fillPreparedArg' ), $preparedQuery );
917 * preg_callback func for fillPrepared()
918 * The arguments should be in $this->preparedArgs and must not be touched
919 * while we're doing this.
921 * @param array $matches
925 function fillPreparedArg( $matches ) {
926 switch( $matches[1] ) {
927 case '\\?': return '?';
928 case '\\!': return '!';
929 case '\\&': return '&';
931 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
932 switch( $matches[1] ) {
933 case '?': return $this->addQuotes( $arg );
934 case '!': return $arg;
936 # return $this->addQuotes( file_get_contents( $arg ) );
937 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
939 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
944 * @param mixed $res A SQL result
947 * Free a result object
949 function freeResult( $res ) {
950 if ( $res instanceof ResultWrapper
) {
953 if ( !@/**/mysql_free_result( $res ) ) {
954 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
959 * Fetch the next row from the given result object, in object form.
960 * Fields can be retrieved with $row->fieldname, with fields acting like
963 * @param $res SQL result object as returned from Database::query(), etc.
964 * @return MySQL row object
965 * @throws DBUnexpectedError Thrown if the database returns an error
967 function fetchObject( $res ) {
968 if ( $res instanceof ResultWrapper
) {
971 @/**/$row = mysql_fetch_object( $res );
972 if( $this->lastErrno() ) {
973 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
979 * Fetch the next row from the given result object, in associative array
980 * form. Fields are retrieved with $row['fieldname'].
982 * @param $res SQL result object as returned from Database::query(), etc.
983 * @return MySQL row object
984 * @throws DBUnexpectedError Thrown if the database returns an error
986 function fetchRow( $res ) {
987 if ( $res instanceof ResultWrapper
) {
990 @/**/$row = mysql_fetch_array( $res );
991 if ( $this->lastErrno() ) {
992 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
998 * Get the number of rows in a result object
1000 function numRows( $res ) {
1001 if ( $res instanceof ResultWrapper
) {
1002 $res = $res->result
;
1004 @/**/$n = mysql_num_rows( $res );
1005 if( $this->lastErrno() ) {
1006 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
1012 * Get the number of fields in a result object
1013 * See documentation for mysql_num_fields()
1015 function numFields( $res ) {
1016 if ( $res instanceof ResultWrapper
) {
1017 $res = $res->result
;
1019 return mysql_num_fields( $res );
1023 * Get a field name in a result object
1024 * See documentation for mysql_field_name():
1025 * http://www.php.net/mysql_field_name
1027 function fieldName( $res, $n ) {
1028 if ( $res instanceof ResultWrapper
) {
1029 $res = $res->result
;
1031 return mysql_field_name( $res, $n );
1035 * Get the inserted value of an auto-increment row
1037 * The value inserted should be fetched from nextSequenceValue()
1040 * $id = $dbw->nextSequenceValue('page_page_id_seq');
1041 * $dbw->insert('page',array('page_id' => $id));
1042 * $id = $dbw->insertId();
1044 function insertId() { return mysql_insert_id( $this->mConn
); }
1047 * Change the position of the cursor in a result object
1048 * See mysql_data_seek()
1050 function dataSeek( $res, $row ) {
1051 if ( $res instanceof ResultWrapper
) {
1052 $res = $res->result
;
1054 return mysql_data_seek( $res, $row );
1058 * Get the last error number
1061 function lastErrno() {
1062 if ( $this->mConn
) {
1063 return mysql_errno( $this->mConn
);
1065 return mysql_errno();
1070 * Get a description of the last error
1071 * See mysql_error() for more details
1073 function lastError() {
1074 if ( $this->mConn
) {
1075 # Even if it's non-zero, it can still be invalid
1076 wfSuppressWarnings();
1077 $error = mysql_error( $this->mConn
);
1079 $error = mysql_error();
1081 wfRestoreWarnings();
1083 $error = mysql_error();
1086 $error .= ' (' . $this->mServer
. ')';
1091 * Get the number of rows affected by the last write query
1092 * See mysql_affected_rows() for more details
1094 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
1095 /**#@-*/ // end of template : @param $result
1098 * Simple UPDATE wrapper
1099 * Usually aborts on failure
1100 * If errors are explicitly ignored, returns success
1102 * This function exists for historical reasons, Database::update() has a more standard
1103 * calling convention and feature set
1105 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
1107 $table = $this->tableName( $table );
1108 $sql = "UPDATE $table SET $var = '" .
1109 $this->strencode( $value ) . "' WHERE ($cond)";
1110 return (bool)$this->query( $sql, $fname );
1114 * Simple SELECT wrapper, returns a single field, input must be encoded
1115 * Usually aborts on failure
1116 * If errors are explicitly ignored, returns FALSE on failure
1118 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
1119 if ( !is_array( $options ) ) {
1120 $options = array( $options );
1122 $options['LIMIT'] = 1;
1124 $res = $this->select( $table, $var, $cond, $fname, $options );
1125 if ( $res === false ||
!$this->numRows( $res ) ) {
1128 $row = $this->fetchRow( $res );
1129 if ( $row !== false ) {
1130 $this->freeResult( $res );
1138 * Returns an optional USE INDEX clause to go after the table, and a
1139 * string to go at the end of the query
1143 * @param array $options an associative array of options to be turned into
1144 * an SQL query, valid keys are listed in the function.
1147 function makeSelectOptions( $options ) {
1148 $preLimitTail = $postLimitTail = '';
1151 $noKeyOptions = array();
1152 foreach ( $options as $key => $option ) {
1153 if ( is_numeric( $key ) ) {
1154 $noKeyOptions[$option] = true;
1158 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1159 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1160 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1162 //if (isset($options['LIMIT'])) {
1163 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1164 // isset($options['OFFSET']) ? $options['OFFSET']
1168 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1169 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1170 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1172 # Various MySQL extensions
1173 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
1174 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
1175 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
1176 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
1177 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
1178 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
1179 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
1180 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
1182 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1183 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1188 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1194 * @param mixed $table Array or string, table name(s) (prefix auto-added)
1195 * @param mixed $vars Array or string, field name(s) to be retrieved
1196 * @param mixed $conds Array or string, condition(s) for WHERE
1197 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1198 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1199 * see Database::makeSelectOptions code for list of supported stuff
1200 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
1202 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
1204 if( is_array( $vars ) ) {
1205 $vars = implode( ',', $vars );
1207 if( !is_array( $options ) ) {
1208 $options = array( $options );
1210 if( is_array( $table ) ) {
1211 if ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1212 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
1214 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1215 } elseif ($table!='') {
1216 if ($table{0}==' ') {
1217 $from = ' FROM ' . $table;
1219 $from = ' FROM ' . $this->tableName( $table );
1225 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1227 if( !empty( $conds ) ) {
1228 if ( is_array( $conds ) ) {
1229 $conds = $this->makeList( $conds, LIST_AND
);
1231 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1233 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1236 if (isset($options['LIMIT']))
1237 $sql = $this->limitResult($sql, $options['LIMIT'],
1238 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
1239 $sql = "$sql $postLimitTail";
1241 if (isset($options['EXPLAIN'])) {
1242 $sql = 'EXPLAIN ' . $sql;
1244 return $this->query( $sql, $fname );
1248 * Single row SELECT wrapper
1249 * Aborts or returns FALSE on error
1251 * $vars: the selected variables
1252 * $conds: a condition map, terms are ANDed together.
1253 * Items with numeric keys are taken to be literal conditions
1254 * Takes an array of selected variables, and a condition map, which is ANDed
1255 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1256 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1257 * $obj- >page_id is the ID of the Astronomy article
1259 * @todo migrate documentation to phpdocumentor format
1261 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
1262 $options['LIMIT'] = 1;
1263 $res = $this->select( $table, $vars, $conds, $fname, $options );
1264 if ( $res === false )
1266 if ( !$this->numRows($res) ) {
1267 $this->freeResult($res);
1270 $obj = $this->fetchObject( $res );
1271 $this->freeResult( $res );
1277 * Estimate rows in dataset
1278 * Returns estimated count, based on EXPLAIN output
1279 * Takes same arguments as Database::select()
1282 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
1283 $options['EXPLAIN']=true;
1284 $res = $this->select ($table, $vars, $conds, $fname, $options );
1285 if ( $res === false )
1287 if (!$this->numRows($res)) {
1288 $this->freeResult($res);
1294 while( $plan = $this->fetchObject( $res ) ) {
1295 $rows *= ($plan->rows
> 0)?
$plan->rows
:1; // avoid resetting to zero
1298 $this->freeResult($res);
1304 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1305 * It's only slightly flawed. Don't use for anything important.
1307 * @param string $sql A SQL Query
1310 static function generalizeSQL( $sql ) {
1311 # This does the same as the regexp below would do, but in such a way
1312 # as to avoid crashing php on some large strings.
1313 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1315 $sql = str_replace ( "\\\\", '', $sql);
1316 $sql = str_replace ( "\\'", '', $sql);
1317 $sql = str_replace ( "\\\"", '', $sql);
1318 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1319 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1321 # All newlines, tabs, etc replaced by single space
1322 $sql = preg_replace ( '/\s+/', ' ', $sql);
1325 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1331 * Determines whether a field exists in a table
1332 * Usually aborts on failure
1333 * If errors are explicitly ignored, returns NULL on failure
1335 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1336 $table = $this->tableName( $table );
1337 $res = $this->query( 'DESCRIBE '.$table, $fname );
1344 while ( $row = $this->fetchObject( $res ) ) {
1345 if ( $row->Field
== $field ) {
1354 * Determines whether an index exists
1355 * Usually aborts on failure
1356 * If errors are explicitly ignored, returns NULL on failure
1358 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1359 $info = $this->indexInfo( $table, $index, $fname );
1360 if ( is_null( $info ) ) {
1363 return $info !== false;
1369 * Get information about an index into an object
1370 * Returns false if the index does not exist
1372 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1373 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1374 # SHOW INDEX should work for 3.x and up:
1375 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1376 $table = $this->tableName( $table );
1377 $sql = 'SHOW INDEX FROM '.$table;
1378 $res = $this->query( $sql, $fname );
1384 while ( $row = $this->fetchObject( $res ) ) {
1385 if ( $row->Key_name
== $index ) {
1389 $this->freeResult($res);
1391 return empty($result) ?
false : $result;
1395 * Query whether a given table exists
1397 function tableExists( $table ) {
1398 $table = $this->tableName( $table );
1399 $old = $this->ignoreErrors( true );
1400 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1401 $this->ignoreErrors( $old );
1403 $this->freeResult( $res );
1411 * mysql_fetch_field() wrapper
1412 * Returns false if the field doesn't exist
1417 function fieldInfo( $table, $field ) {
1418 $table = $this->tableName( $table );
1419 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1420 $n = mysql_num_fields( $res->result
);
1421 for( $i = 0; $i < $n; $i++
) {
1422 $meta = mysql_fetch_field( $res->result
, $i );
1423 if( $field == $meta->name
) {
1424 return new MySQLField($meta);
1431 * mysql_field_type() wrapper
1433 function fieldType( $res, $index ) {
1434 if ( $res instanceof ResultWrapper
) {
1435 $res = $res->result
;
1437 return mysql_field_type( $res, $index );
1441 * Determines if a given index is unique
1443 function indexUnique( $table, $index ) {
1444 $indexInfo = $this->indexInfo( $table, $index );
1445 if ( !$indexInfo ) {
1448 return !$indexInfo[0]->Non_unique
;
1452 * INSERT wrapper, inserts an array into a table
1454 * $a may be a single associative array, or an array of these with numeric keys, for
1457 * Usually aborts on failure
1458 * If errors are explicitly ignored, returns success
1460 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1461 # No rows to insert, easy just return now
1462 if ( !count( $a ) ) {
1466 $table = $this->tableName( $table );
1467 if ( !is_array( $options ) ) {
1468 $options = array( $options );
1470 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1472 $keys = array_keys( $a[0] );
1475 $keys = array_keys( $a );
1478 $sql = 'INSERT ' . implode( ' ', $options ) .
1479 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1483 foreach ( $a as $row ) {
1489 $sql .= '(' . $this->makeList( $row ) . ')';
1492 $sql .= '(' . $this->makeList( $a ) . ')';
1494 return (bool)$this->query( $sql, $fname );
1498 * Make UPDATE options for the Database::update function
1501 * @param array $options The options passed to Database::update
1504 function makeUpdateOptions( $options ) {
1505 if( !is_array( $options ) ) {
1506 $options = array( $options );
1509 if ( in_array( 'LOW_PRIORITY', $options ) )
1510 $opts[] = $this->lowPriorityOption();
1511 if ( in_array( 'IGNORE', $options ) )
1513 return implode(' ', $opts);
1517 * UPDATE wrapper, takes a condition array and a SET array
1519 * @param string $table The table to UPDATE
1520 * @param array $values An array of values to SET
1521 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1522 * @param string $fname The Class::Function calling this function
1524 * @param array $options An array of UPDATE options, can be one or
1525 * more of IGNORE, LOW_PRIORITY
1528 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1529 $table = $this->tableName( $table );
1530 $opts = $this->makeUpdateOptions( $options );
1531 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1532 if ( $conds != '*' ) {
1533 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1535 return $this->query( $sql, $fname );
1539 * Makes an encoded list of strings from an array
1541 * LIST_COMMA - comma separated, no field names
1542 * LIST_AND - ANDed WHERE clause (without the WHERE)
1543 * LIST_OR - ORed WHERE clause (without the WHERE)
1544 * LIST_SET - comma separated with field names, like a SET clause
1545 * LIST_NAMES - comma separated field names
1547 function makeList( $a, $mode = LIST_COMMA
) {
1548 if ( !is_array( $a ) ) {
1549 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1554 foreach ( $a as $field => $value ) {
1556 if ( $mode == LIST_AND
) {
1558 } elseif($mode == LIST_OR
) {
1566 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1567 $list .= "($value)";
1568 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
1570 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array($value) ) {
1571 if( count( $value ) == 0 ) {
1572 throw new MWException( __METHOD__
.': empty input' );
1573 } elseif( count( $value ) == 1 ) {
1574 // Special-case single values, as IN isn't terribly efficient
1575 $list .= $field." = ".$this->addQuotes( $value[0] );
1577 $list .= $field." IN (".$this->makeList($value).") ";
1579 } elseif( is_null($value) ) {
1580 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1581 $list .= "$field IS ";
1582 } elseif ( $mode == LIST_SET
) {
1583 $list .= "$field = ";
1587 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1588 $list .= "$field = ";
1590 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1597 * Change the current database
1599 function selectDB( $db ) {
1600 $this->mDBname
= $db;
1601 return mysql_select_db( $db, $this->mConn
);
1605 * Format a table name ready for use in constructing an SQL query
1607 * This does two important things: it quotes table names which as necessary,
1608 * and it adds a table prefix if there is one.
1610 * All functions of this object which require a table name call this function
1611 * themselves. Pass the canonical name to such functions. This is only needed
1612 * when calling query() directly.
1614 * @param string $name database table name
1616 function tableName( $name ) {
1618 # Skip quoted literals
1619 if ( $name{0} != '`' ) {
1620 if ( $this->mTablePrefix
!== '' && strpos( $name, '.' ) === false ) {
1621 $name = "{$this->mTablePrefix}$name";
1623 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1624 $name = "`$wgSharedDB`.`$name`";
1634 * Fetch a number of table names into an array
1635 * This is handy when you need to construct SQL for joins
1638 * extract($dbr->tableNames('user','watchlist'));
1639 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1640 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1642 public function tableNames() {
1643 $inArray = func_get_args();
1645 foreach ( $inArray as $name ) {
1646 $retVal[$name] = $this->tableName( $name );
1652 * Fetch a number of table names into an zero-indexed numerical array
1653 * This is handy when you need to construct SQL for joins
1656 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1657 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1658 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1660 public function tableNamesN() {
1661 $inArray = func_get_args();
1663 foreach ( $inArray as $name ) {
1664 $retVal[] = $this->tableName( $name );
1672 function tableNamesWithUseIndex( $tables, $use_index ) {
1675 foreach ( $tables as $table )
1676 if ( @$use_index[$table] !== null )
1677 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1679 $ret[] = $this->tableName( $table );
1681 return implode( ',', $ret );
1685 * Wrapper for addslashes()
1686 * @param string $s String to be slashed.
1687 * @return string slashed string.
1689 function strencode( $s ) {
1690 return mysql_real_escape_string( $s, $this->mConn
);
1694 * If it's a string, adds quotes and backslashes
1695 * Otherwise returns as-is
1697 function addQuotes( $s ) {
1698 if ( is_null( $s ) ) {
1701 # This will also quote numeric values. This should be harmless,
1702 # and protects against weird problems that occur when they really
1703 # _are_ strings such as article titles and string->number->string
1704 # conversion is not 1:1.
1705 return "'" . $this->strencode( $s ) . "'";
1710 * Escape string for safe LIKE usage
1712 function escapeLike( $s ) {
1713 $s=$this->strencode( $s );
1714 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1719 * Returns an appropriately quoted sequence value for inserting a new row.
1720 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1721 * subclass will return an integer, and save the value for insertId()
1723 function nextSequenceValue( $seqName ) {
1729 * PostgreSQL doesn't have them and returns ""
1731 function useIndexClause( $index ) {
1732 return "FORCE INDEX ($index)";
1736 * REPLACE query wrapper
1737 * PostgreSQL simulates this with a DELETE followed by INSERT
1738 * $row is the row to insert, an associative array
1739 * $uniqueIndexes is an array of indexes. Each element may be either a
1740 * field name or an array of field names
1742 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1743 * However if you do this, you run the risk of encountering errors which wouldn't have
1746 * @todo migrate comment to phodocumentor format
1748 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1749 $table = $this->tableName( $table );
1752 if ( !is_array( reset( $rows ) ) ) {
1753 $rows = array( $rows );
1756 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1758 foreach ( $rows as $row ) {
1764 $sql .= '(' . $this->makeList( $row ) . ')';
1766 return $this->query( $sql, $fname );
1770 * DELETE where the condition is a join
1771 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1773 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1774 * join condition matches, set $conds='*'
1776 * DO NOT put the join condition in $conds
1778 * @param string $delTable The table to delete from.
1779 * @param string $joinTable The other table.
1780 * @param string $delVar The variable to join on, in the first table.
1781 * @param string $joinVar The variable to join on, in the second table.
1782 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1784 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1786 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1789 $delTable = $this->tableName( $delTable );
1790 $joinTable = $this->tableName( $joinTable );
1791 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1792 if ( $conds != '*' ) {
1793 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1796 return $this->query( $sql, $fname );
1800 * Returns the size of a text field, or -1 for "unlimited"
1802 function textFieldSize( $table, $field ) {
1803 $table = $this->tableName( $table );
1804 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1805 $res = $this->query( $sql, 'Database::textFieldSize' );
1806 $row = $this->fetchObject( $res );
1807 $this->freeResult( $res );
1810 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1819 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1821 function lowPriorityOption() {
1822 return 'LOW_PRIORITY';
1826 * DELETE query wrapper
1828 * Use $conds == "*" to delete all rows
1830 function delete( $table, $conds, $fname = 'Database::delete' ) {
1832 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1834 $table = $this->tableName( $table );
1835 $sql = "DELETE FROM $table";
1836 if ( $conds != '*' ) {
1837 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1839 return $this->query( $sql, $fname );
1843 * INSERT SELECT wrapper
1844 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1845 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1846 * $conds may be "*" to copy the whole table
1847 * srcTable may be an array of tables.
1849 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1850 $insertOptions = array(), $selectOptions = array() )
1852 $destTable = $this->tableName( $destTable );
1853 if ( is_array( $insertOptions ) ) {
1854 $insertOptions = implode( ' ', $insertOptions );
1856 if( !is_array( $selectOptions ) ) {
1857 $selectOptions = array( $selectOptions );
1859 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1860 if( is_array( $srcTable ) ) {
1861 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1863 $srcTable = $this->tableName( $srcTable );
1865 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1866 " SELECT $startOpts " . implode( ',', $varMap ) .
1867 " FROM $srcTable $useIndex ";
1868 if ( $conds != '*' ) {
1869 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1871 $sql .= " $tailOpts";
1872 return $this->query( $sql, $fname );
1876 * Construct a LIMIT query with optional offset
1877 * This is used for query pages
1878 * $sql string SQL query we will append the limit too
1879 * $limit integer the SQL limit
1880 * $offset integer the SQL offset (default false)
1882 function limitResult($sql, $limit, $offset=false) {
1883 if( !is_numeric($limit) ) {
1884 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1886 return " $sql LIMIT "
1887 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1890 function limitResultForUpdate($sql, $num) {
1891 return $this->limitResult($sql, $num, 0);
1895 * Returns an SQL expression for a simple conditional.
1898 * @param string $cond SQL expression which will result in a boolean value
1899 * @param string $trueVal SQL expression to return if true
1900 * @param string $falseVal SQL expression to return if false
1901 * @return string SQL fragment
1903 function conditional( $cond, $trueVal, $falseVal ) {
1904 return " IF($cond, $trueVal, $falseVal) ";
1908 * Determines if the last failure was due to a deadlock
1910 function wasDeadlock() {
1911 return $this->lastErrno() == 1213;
1915 * Perform a deadlock-prone transaction.
1917 * This function invokes a callback function to perform a set of write
1918 * queries. If a deadlock occurs during the processing, the transaction
1919 * will be rolled back and the callback function will be called again.
1922 * $dbw->deadlockLoop( callback, ... );
1924 * Extra arguments are passed through to the specified callback function.
1926 * Returns whatever the callback function returned on its successful,
1927 * iteration, or false on error, for example if the retry limit was
1930 function deadlockLoop() {
1931 $myFname = 'Database::deadlockLoop';
1934 $args = func_get_args();
1935 $function = array_shift( $args );
1936 $oldIgnore = $this->ignoreErrors( true );
1937 $tries = DEADLOCK_TRIES
;
1938 if ( is_array( $function ) ) {
1939 $fname = $function[0];
1944 $retVal = call_user_func_array( $function, $args );
1945 $error = $this->lastError();
1946 $errno = $this->lastErrno();
1947 $sql = $this->lastQuery();
1950 if ( $this->wasDeadlock() ) {
1952 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1954 $this->reportQueryError( $error, $errno, $sql, $fname );
1957 } while( $this->wasDeadlock() && --$tries > 0 );
1958 $this->ignoreErrors( $oldIgnore );
1959 if ( $tries <= 0 ) {
1960 $this->query( 'ROLLBACK', $myFname );
1961 $this->reportQueryError( $error, $errno, $sql, $fname );
1964 $this->query( 'COMMIT', $myFname );
1970 * Do a SELECT MASTER_POS_WAIT()
1972 * @param string $file the binlog file
1973 * @param string $pos the binlog position
1974 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1976 function masterPosWait( $file, $pos, $timeout ) {
1977 $fname = 'Database::masterPosWait';
1978 wfProfileIn( $fname );
1981 # Commit any open transactions
1982 $this->immediateCommit();
1984 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1985 $encFile = $this->strencode( $file );
1986 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1987 $res = $this->doQuery( $sql );
1988 if ( $res && $row = $this->fetchRow( $res ) ) {
1989 $this->freeResult( $res );
1990 wfProfileOut( $fname );
1993 wfProfileOut( $fname );
1999 * Get the position of the master from SHOW SLAVE STATUS
2001 function getSlavePos() {
2002 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
2003 $row = $this->fetchObject( $res );
2005 return array( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
2007 return array( false, false );
2012 * Get the position of the master from SHOW MASTER STATUS
2014 function getMasterPos() {
2015 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
2016 $row = $this->fetchObject( $res );
2018 return array( $row->File
, $row->Position
);
2020 return array( false, false );
2025 * Begin a transaction, committing any previously open transaction
2027 function begin( $fname = 'Database::begin' ) {
2028 $this->query( 'BEGIN', $fname );
2029 $this->mTrxLevel
= 1;
2035 function commit( $fname = 'Database::commit' ) {
2036 $this->query( 'COMMIT', $fname );
2037 $this->mTrxLevel
= 0;
2041 * Rollback a transaction.
2042 * No-op on non-transactional databases.
2044 function rollback( $fname = 'Database::rollback' ) {
2045 $this->query( 'ROLLBACK', $fname, true );
2046 $this->mTrxLevel
= 0;
2050 * Begin a transaction, committing any previously open transaction
2051 * @deprecated use begin()
2053 function immediateBegin( $fname = 'Database::immediateBegin' ) {
2058 * Commit transaction, if one is open
2059 * @deprecated use commit()
2061 function immediateCommit( $fname = 'Database::immediateCommit' ) {
2066 * Return MW-style timestamp used for MySQL schema
2068 function timestamp( $ts=0 ) {
2069 return wfTimestamp(TS_MW
,$ts);
2073 * Local database timestamp format or null
2075 function timestampOrNull( $ts = null ) {
2076 if( is_null( $ts ) ) {
2079 return $this->timestamp( $ts );
2086 function resultObject( $result ) {
2087 if( empty( $result ) ) {
2089 } elseif ( $result instanceof ResultWrapper
) {
2091 } elseif ( $result === true ) {
2092 // Successful write query
2095 return new ResultWrapper( $this, $result );
2100 * Return aggregated value alias
2102 function aggregateValue ($valuedata,$valuename='value') {
2107 * @return string wikitext of a link to the server software's web site
2109 function getSoftwareLink() {
2110 return "[http://www.mysql.com/ MySQL]";
2114 * @return string Version information from the database
2116 function getServerVersion() {
2117 return mysql_get_server_info( $this->mConn
);
2121 * Ping the server and try to reconnect if it there is no connection
2124 if( !function_exists( 'mysql_ping' ) ) {
2125 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
2128 $ping = mysql_ping( $this->mConn
);
2133 // Need to reconnect manually in MySQL client 5.0.13+
2134 if ( version_compare( mysql_get_client_info(), '5.0.13', '>=' ) ) {
2135 mysql_close( $this->mConn
);
2136 $this->mOpened
= false;
2137 $this->mConn
= false;
2138 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
2146 * At the moment, this will only work if the DB user has the PROCESS privilege
2149 $res = $this->query( 'SHOW PROCESSLIST' );
2150 # Find slave SQL thread
2151 while ( $row = $this->fetchObject( $res ) ) {
2152 /* This should work for most situations - when default db
2153 * for thread is not specified, it had no events executed,
2154 * and therefore it doesn't know yet how lagged it is.
2156 * Relay log I/O thread does not select databases.
2158 if ( $row->User
== 'system user' &&
2159 $row->State
!= 'Waiting for master to send event' &&
2160 $row->State
!= 'Connecting to master' &&
2161 $row->State
!= 'Queueing master event to the relay log' &&
2162 $row->State
!= 'Waiting for master update' &&
2163 $row->State
!= 'Requesting binlog dump'
2165 # This is it, return the time (except -ve)
2166 if ( $row->Time
> 0x7fffffff ) {
2177 * Get status information from SHOW STATUS in an associative array
2179 function getStatus($which="%") {
2180 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2182 while ( $row = $this->fetchObject( $res ) ) {
2183 $status[$row->Variable_name
] = $row->Value
;
2189 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2191 function maxListLen() {
2195 function encodeBlob($b) {
2199 function decodeBlob($b) {
2204 * Override database's default connection timeout.
2205 * May be useful for very long batch queries such as
2206 * full-wiki dumps, where a single query reads out
2207 * over hours or days.
2208 * @param int $timeout in seconds
2210 public function setTimeout( $timeout ) {
2211 $this->query( "SET net_read_timeout=$timeout" );
2212 $this->query( "SET net_write_timeout=$timeout" );
2216 * Read and execute SQL commands from a file.
2217 * Returns true on success, error string on failure
2218 * @param string $filename File name to open
2219 * @param callback $lineCallback Optional function called before reading each line
2220 * @param callback $resultCallback Optional function called for each MySQL result
2222 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2223 $fp = fopen( $filename, 'r' );
2224 if ( false === $fp ) {
2225 return "Could not open \"{$filename}\".\n";
2227 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2233 * Read and execute commands from an open file handle
2234 * Returns true on success, error string on failure
2235 * @param string $fp File handle
2236 * @param callback $lineCallback Optional function called before reading each line
2237 * @param callback $resultCallback Optional function called for each MySQL result
2239 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2242 $dollarquote = false;
2244 while ( ! feof( $fp ) ) {
2245 if ( $lineCallback ) {
2246 call_user_func( $lineCallback );
2248 $line = trim( fgets( $fp, 1024 ) );
2249 $sl = strlen( $line ) - 1;
2251 if ( $sl < 0 ) { continue; }
2252 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2254 ## Allow dollar quoting for function declarations
2255 if (substr($line,0,4) == '$mw$') {
2257 $dollarquote = false;
2261 $dollarquote = true;
2264 else if (!$dollarquote) {
2265 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
2267 $line = substr( $line, 0, $sl );
2271 if ( '' != $cmd ) { $cmd .= ' '; }
2275 $cmd = str_replace(';;', ";", $cmd);
2276 $cmd = $this->replaceVars( $cmd );
2277 $res = $this->query( $cmd, __METHOD__
, true );
2278 if ( $resultCallback ) {
2279 call_user_func( $resultCallback, $res );
2282 if ( false === $res ) {
2283 $err = $this->lastError();
2284 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2296 * Replace variables in sourced SQL
2298 protected function replaceVars( $ins ) {
2300 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2301 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2302 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2305 // Ordinary variables
2306 foreach ( $varnames as $var ) {
2307 if( isset( $GLOBALS[$var] ) ) {
2308 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2309 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2310 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2311 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2316 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
2317 array( &$this, 'tableNameCallback' ), $ins );
2322 * Table name callback
2325 protected function tableNameCallback( $matches ) {
2326 return $this->tableName( $matches[1] );
2330 * Build a concatenation list to feed into a SQL query
2332 function buildConcat( $stringList ) {
2333 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2339 * Database abstraction object for mySQL
2340 * Inherit all methods and properties of Database::Database()
2342 * @addtogroup Database
2345 class DatabaseMysql
extends Database
{
2351 * Result wrapper for grabbing data queried by someone else
2352 * @addtogroup Database
2354 class ResultWrapper
implements Iterator
{
2355 var $db, $result, $pos = 0, $currentRow = null;
2358 * Create a new result object from a result resource and a Database object
2360 function ResultWrapper( $database, $result ) {
2361 $this->db
= $database;
2362 if ( $result instanceof ResultWrapper
) {
2363 $this->result
= $result->result
;
2365 $this->result
= $result;
2370 * Get the number of rows in a result object
2372 function numRows() {
2373 return $this->db
->numRows( $this->result
);
2377 * Fetch the next row from the given result object, in object form.
2378 * Fields can be retrieved with $row->fieldname, with fields acting like
2381 * @param $res SQL result object as returned from Database::query(), etc.
2382 * @return MySQL row object
2383 * @throws DBUnexpectedError Thrown if the database returns an error
2385 function fetchObject() {
2386 return $this->db
->fetchObject( $this->result
);
2390 * Fetch the next row from the given result object, in associative array
2391 * form. Fields are retrieved with $row['fieldname'].
2393 * @param $res SQL result object as returned from Database::query(), etc.
2394 * @return MySQL row object
2395 * @throws DBUnexpectedError Thrown if the database returns an error
2397 function fetchRow() {
2398 return $this->db
->fetchRow( $this->result
);
2402 * Free a result object
2405 $this->db
->freeResult( $this->result
);
2406 unset( $this->result
);
2411 * Change the position of the cursor in a result object
2412 * See mysql_data_seek()
2414 function seek( $row ) {
2415 $this->db
->dataSeek( $this->result
, $row );
2418 /*********************
2419 * Iterator functions
2420 * Note that using these in combination with the non-iterator functions
2421 * above may cause rows to be skipped or repeated.
2425 if ($this->numRows()) {
2426 $this->db
->dataSeek($this->result
, 0);
2429 $this->currentRow
= null;
2432 function current() {
2433 if ( is_null( $this->currentRow
) ) {
2436 return $this->currentRow
;
2445 $this->currentRow
= $this->fetchObject();
2446 return $this->currentRow
;
2450 return $this->current() !== false;