f2042c7455f9cdf2456192a8eae5eba91a0246c0
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
43 private $name, $tablename, $default, $max_length, $nullable,
44 $is_pk, $is_unique, $is_key, $type;
45 function __construct ($info) {
46 $this->name
= $info->name
;
47 $this->tablename
= $info->table
;
48 $this->default = $info->def
;
49 $this->max_length
= $info->max_length
;
50 $this->nullable
= !$info->not_null
;
51 $this->is_pk
= $info->primary_key
;
52 $this->is_unique
= $info->unique_key
;
53 $this->is_multiple
= $info->multiple_key
;
54 $this->is_key
= ($this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
55 $this->type
= $info->type
;
62 function tableName() {
63 return $this->tableName
;
66 function defaultValue() {
67 return $this->default;
70 function maxLength() {
71 return $this->max_length
;
75 return $this->nullable
;
82 function isMultipleKey() {
83 return $this->is_multiple
;
91 /******************************************************************************
93 *****************************************************************************/
96 * Database error base class
97 * @addtogroup Database
99 class DBError
extends MWException
{
103 * Construct a database error
104 * @param Database $db The database object which threw the error
105 * @param string $error A simple error message to be used for debugging
107 function __construct( Database
&$db, $error ) {
109 parent
::__construct( $error );
114 * @addtogroup Database
116 class DBConnectionError
extends DBError
{
119 function __construct( Database
&$db, $error = 'unknown error' ) {
120 $msg = 'DB connection error';
121 if ( trim( $error ) != '' ) {
124 $this->error
= $error;
125 parent
::__construct( $db, $msg );
128 function useOutputPage() {
129 // Not likely to work
133 function useMessageCache() {
134 // Not likely to work
139 return $this->getMessage() . "\n";
142 function getLogMessage() {
143 # Don't send to the exception log
147 function getPageTitle() {
149 return "$wgSitename has a problem";
153 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding;
154 global $wgSitename, $wgServer, $wgMessageCache;
156 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
157 # Hard coding strings instead.
159 $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>";
160 $mainpage = 'Main Page';
161 $searchdisabled = <<<EOT
162 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
163 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
167 <!-- SiteSearch Google -->
168 <FORM method=GET action=\"http://www.google.com/search\">
169 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
170 <A HREF=\"http://www.google.com/\">
171 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
172 border=\"0\" ALT=\"Google\"></A>
175 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
176 <INPUT type=submit name=btnG VALUE=\"Google Search\">
178 <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 />
179 <input type='hidden' name='ie' value='$2'>
180 <input type='hidden' name='oe' value='$2'>
184 <!-- SiteSearch Google -->";
185 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
188 if ( is_object( $wgMessageCache ) ) {
189 $wgMessageCache->disable();
192 if ( trim( $this->error
) == '' ) {
193 $this->error
= $this->db
->getProperty('mServer');
196 $text = str_replace( '$1', $this->error
, $noconnect );
197 $text .= wfGetSiteNotice();
199 if($wgUseFileCache) {
204 $t = Title
::newFromURL( $title );
205 } elseif (@/**/$_REQUEST['search']) {
206 $search = $_REQUEST['search'];
207 return $searchdisabled .
208 str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
209 $wgInputEncoding ), $googlesearch );
211 $t = Title
::newFromText( $mainpage );
215 $cache = new HTMLFileCache( $t );
216 if( $cache->isFileCached() ) {
217 // FIXME: $msg is not defined on the next line.
218 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
219 $cachederror . "</b></p>\n";
221 $tag = '<div id="article">';
225 $cache->fetchPageText() );
234 * @addtogroup Database
236 class DBQueryError
extends DBError
{
237 public $error, $errno, $sql, $fname;
239 function __construct( Database
&$db, $error, $errno, $sql, $fname ) {
240 $message = "A database error has occurred\n" .
242 "Function: $fname\n" .
243 "Error: $errno $error\n";
245 parent
::__construct( $db, $message );
246 $this->error
= $error;
247 $this->errno
= $errno;
249 $this->fname
= $fname;
253 if ( $this->useMessageCache() ) {
254 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
255 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
257 return $this->getMessage();
262 global $wgShowSQLErrors;
263 if( !$wgShowSQLErrors ) {
264 return $this->msg( 'sqlhidden', 'SQL hidden' );
270 function getLogMessage() {
271 # Don't send to the exception log
275 function getPageTitle() {
276 return $this->msg( 'databaseerror', 'Database error' );
280 if ( $this->useMessageCache() ) {
281 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
282 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
284 return nl2br( htmlspecialchars( $this->getMessage() ) );
290 * @addtogroup Database
292 class DBUnexpectedError
extends DBError
{}
294 /******************************************************************************/
297 * Database abstraction object
298 * @addtogroup Database
302 #------------------------------------------------------------------------------
304 #------------------------------------------------------------------------------
306 protected $mLastQuery = '';
308 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
309 protected $mOut, $mOpened = false;
311 protected $mFailFunction;
312 protected $mTablePrefix;
314 protected $mTrxLevel = 0;
315 protected $mErrorCount = 0;
316 protected $mLBInfo = array();
318 #------------------------------------------------------------------------------
320 #------------------------------------------------------------------------------
321 # These optionally set a variable and return the previous state
324 * Fail function, takes a Database as a parameter
325 * Set to false for default, 1 for ignore errors
327 function failFunction( $function = NULL ) {
328 return wfSetVar( $this->mFailFunction
, $function );
332 * Output page, used for reporting errors
333 * FALSE means discard output
335 function setOutputPage( $out ) {
340 * Boolean, controls output of large amounts of debug information
342 function debug( $debug = NULL ) {
343 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
347 * Turns buffering of SQL result sets on (true) or off (false).
348 * Default is "on" and it should not be changed without good reasons.
350 function bufferResults( $buffer = NULL ) {
351 if ( is_null( $buffer ) ) {
352 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
354 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
359 * Turns on (false) or off (true) the automatic generation and sending
360 * of a "we're sorry, but there has been a database error" page on
361 * database errors. Default is on (false). When turned off, the
362 * code should use lastErrno() and lastError() to handle the
363 * situation as appropriate.
365 function ignoreErrors( $ignoreErrors = NULL ) {
366 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
370 * The current depth of nested transactions
371 * @param $level Integer: , default NULL.
373 function trxLevel( $level = NULL ) {
374 return wfSetVar( $this->mTrxLevel
, $level );
378 * Number of errors logged, only useful when errors are ignored
380 function errorCount( $count = NULL ) {
381 return wfSetVar( $this->mErrorCount
, $count );
385 * Properties passed down from the server info array of the load balancer
387 function getLBInfo( $name = NULL ) {
388 if ( is_null( $name ) ) {
389 return $this->mLBInfo
;
391 if ( array_key_exists( $name, $this->mLBInfo
) ) {
392 return $this->mLBInfo
[$name];
399 function setLBInfo( $name, $value = NULL ) {
400 if ( is_null( $value ) ) {
401 $this->mLBInfo
= $name;
403 $this->mLBInfo
[$name] = $value;
408 * Returns true if this database supports (and uses) cascading deletes
410 function cascadingDeletes() {
415 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
417 function cleanupTriggers() {
422 * Returns true if this database is strict about what can be put into an IP field.
423 * Specifically, it uses a NULL value instead of an empty string.
425 function strictIPs() {
430 * Returns true if this database uses timestamps rather than integers
432 function realTimestamps() {
437 * Returns true if this database does an implicit sort when doing GROUP BY
439 function implicitGroupby() {
444 * Returns true if this database can do a native search on IP columns
445 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
447 function searchableIPs() {
454 function lastQuery() { return $this->mLastQuery
; }
455 function isOpen() { return $this->mOpened
; }
458 function setFlag( $flag ) {
459 $this->mFlags |
= $flag;
462 function clearFlag( $flag ) {
463 $this->mFlags
&= ~
$flag;
466 function getFlag( $flag ) {
467 return !!($this->mFlags
& $flag);
471 * General read-only accessor
473 function getProperty( $name ) {
477 #------------------------------------------------------------------------------
479 #------------------------------------------------------------------------------
483 * @param string $server database server host
484 * @param string $user database user name
485 * @param string $password database user password
486 * @param string $dbname database name
487 * @param failFunction
489 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
491 function __construct( $server = false, $user = false, $password = false, $dbName = false,
492 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
494 global $wgOut, $wgDBprefix, $wgCommandLineMode;
495 # Can't get a reference if it hasn't been set yet
496 if ( !isset( $wgOut ) ) {
499 $this->mOut
=& $wgOut;
501 $this->mFailFunction
= $failFunction;
502 $this->mFlags
= $flags;
504 if ( $this->mFlags
& DBO_DEFAULT
) {
505 if ( $wgCommandLineMode ) {
506 $this->mFlags
&= ~DBO_TRX
;
508 $this->mFlags |
= DBO_TRX
;
513 // Faster read-only access
514 if ( wfReadOnly() ) {
515 $this->mFlags |= DBO_PERSISTENT;
516 $this->mFlags &= ~DBO_TRX;
519 /** Get the default table prefix*/
520 if ( $tablePrefix == 'get from global' ) {
521 $this->mTablePrefix
= $wgDBprefix;
523 $this->mTablePrefix
= $tablePrefix;
527 $this->open( $server, $user, $password, $dbName );
533 * @param failFunction
536 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
538 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
542 * Usually aborts on failure
543 * If the failFunction is set to a non-zero integer, returns success
545 function open( $server, $user, $password, $dbName ) {
547 wfProfileIn( __METHOD__
);
549 # Test for missing mysql.so
550 # First try to load it
551 if (!@extension_loaded
('mysql')) {
556 # Otherwise we get a suppressed fatal error, which is very hard to track down
557 if ( !function_exists( 'mysql_connect' ) ) {
558 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
562 $this->mServer
= $server;
563 $this->mUser
= $user;
564 $this->mPassword
= $password;
565 $this->mDBname
= $dbName;
569 wfProfileIn("dbconnect-$server");
571 # LIVE PATCH by Tim, ask Domas for why: retry loop
572 $this->mConn
= false;
574 for ( $i = 0; $i < $max && !$this->mConn
; $i++
) {
578 if ( $this->mFlags
& DBO_PERSISTENT
) {
579 @/**/$this->mConn
= mysql_pconnect( $server, $user, $password );
581 # Create a new connection...
582 @/**/$this->mConn
= mysql_connect( $server, $user, $password, true );
584 if ($this->mConn
=== false) {
586 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
590 wfProfileOut("dbconnect-$server");
592 if ( $dbName != '' ) {
593 if ( $this->mConn
!== false ) {
594 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
596 $error = "Error selecting database $dbName on server {$this->mServer} " .
597 "from client host {$wguname['nodename']}\n";
598 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
602 wfDebug( "DB connection error\n" );
603 wfDebug( "Server: $server, User: $user, Password: " .
604 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
609 $success = (bool)$this->mConn
;
615 // Tell the server we're communicating with it in UTF-8.
616 // This may engage various charset conversions.
617 $this->query( 'SET NAMES utf8' );
620 $this->reportConnectionError();
623 $this->mOpened
= $success;
624 wfProfileOut( __METHOD__
);
630 * Closes a database connection.
631 * if it is open : commits any open transactions
633 * @return bool operation success. true if already closed.
637 $this->mOpened
= false;
638 if ( $this->mConn
) {
639 if ( $this->trxLevel() ) {
640 $this->immediateCommit();
642 return mysql_close( $this->mConn
);
649 * @param string $error fallback error message, used if none is given by MySQL
651 function reportConnectionError( $error = 'Unknown error' ) {
652 $myError = $this->lastError();
657 if ( $this->mFailFunction
) {
658 # Legacy error handling method
659 if ( !is_int( $this->mFailFunction
) ) {
660 $ff = $this->mFailFunction
;
661 $ff( $this, $error );
665 wfLogDBError( "Connection error: $error\n" );
666 throw new DBConnectionError( $this, $error );
671 * Usually aborts on failure. If errors are explicitly ignored, returns success.
673 * @param $sql String: SQL query
674 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST comment (you can use __METHOD__ or add some extra info)
675 * @param $tempIgnore Bool: Whether to avoid throwing an exception on errors... maybe best to catch the exception instead?
676 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure if $tempIgnore set
677 * @throws DBQueryError Thrown when the database returns an error of any kind
679 public function query( $sql, $fname = '', $tempIgnore = false ) {
682 if ( $wgProfiling ) {
683 # generalizeSQL will probably cut down the query to reasonable
684 # logging size most of the time. The substr is really just a sanity check.
686 # Who's been wasting my precious column space? -- TS
687 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
689 if ( is_null( $this->getLBInfo( 'master' ) ) ) {
690 $queryProf = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
691 $totalProf = 'Database::query';
693 $queryProf = 'query-m: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
694 $totalProf = 'Database::query-master';
696 wfProfileIn( $totalProf );
697 wfProfileIn( $queryProf );
700 $this->mLastQuery
= $sql;
702 # Add a comment for easy SHOW PROCESSLIST interpretation
704 $commentedSql = preg_replace('/\s/', " /* $fname */ ", $sql, 1);
706 $commentedSql = $sql;
709 # If DBO_TRX is set, start a transaction
710 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
711 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK'
716 if ( $this->debug() ) {
717 $sqlx = substr( $commentedSql, 0, 500 );
718 $sqlx = strtr( $sqlx, "\t\n", ' ' );
719 wfDebug( "SQL: $sqlx\n" );
722 # Do the query and handle errors
723 $ret = $this->doQuery( $commentedSql );
725 # Try reconnecting if the connection was lost
726 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
727 # Transaction is gone, like it or not
728 $this->mTrxLevel
= 0;
729 wfDebug( "Connection lost, reconnecting...\n" );
730 if ( $this->ping() ) {
731 wfDebug( "Reconnected\n" );
732 $sqlx = substr( $commentedSql, 0, 500 );
733 $sqlx = strtr( $sqlx, "\t\n", ' ' );
734 global $wgRequestTime;
735 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
736 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
737 $ret = $this->doQuery( $commentedSql );
739 wfDebug( "Failed\n" );
743 if ( false === $ret ) {
744 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
747 if ( $wgProfiling ) {
748 wfProfileOut( $queryProf );
749 wfProfileOut( $totalProf );
755 * The DBMS-dependent part of query()
756 * @param $sql String: SQL query.
757 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
760 /*private*/ function doQuery( $sql ) {
761 if( $this->bufferResults() ) {
762 $ret = mysql_query( $sql, $this->mConn
);
764 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
773 * @param string $fname
774 * @param bool $tempIgnore
776 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
777 global $wgCommandLineMode;
778 # Ignore errors during error handling to avoid infinite recursion
779 $ignore = $this->ignoreErrors( true );
780 ++
$this->mErrorCount
;
782 if( $ignore ||
$tempIgnore ) {
783 wfDebug("SQL ERROR (ignored): $error\n");
784 $this->ignoreErrors( $ignore );
786 $sql1line = str_replace( "\n", "\\n", $sql );
787 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
788 wfDebug("SQL ERROR: " . $error . "\n");
789 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
795 * Intended to be compatible with the PEAR::DB wrapper functions.
796 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
798 * ? = scalar value, quoted as necessary
799 * ! = raw SQL bit (a function for instance)
800 * & = filename; reads the file and inserts as a blob
801 * (we don't use this though...)
803 function prepare( $sql, $func = 'Database::prepare' ) {
804 /* MySQL doesn't support prepared statements (yet), so just
805 pack up the query for reference. We'll manually replace
807 return array( 'query' => $sql, 'func' => $func );
810 function freePrepared( $prepared ) {
811 /* No-op for MySQL */
815 * Execute a prepared query with the various arguments
816 * @param string $prepared the prepared sql
817 * @param mixed $args Either an array here, or put scalars as varargs
819 function execute( $prepared, $args = null ) {
820 if( !is_array( $args ) ) {
822 $args = func_get_args();
823 array_shift( $args );
825 $sql = $this->fillPrepared( $prepared['query'], $args );
826 return $this->query( $sql, $prepared['func'] );
830 * Prepare & execute an SQL statement, quoting and inserting arguments
831 * in the appropriate places.
832 * @param string $query
833 * @param string $args ...
835 function safeQuery( $query, $args = null ) {
836 $prepared = $this->prepare( $query, 'Database::safeQuery' );
837 if( !is_array( $args ) ) {
839 $args = func_get_args();
840 array_shift( $args );
842 $retval = $this->execute( $prepared, $args );
843 $this->freePrepared( $prepared );
848 * For faking prepared SQL statements on DBs that don't support
850 * @param string $preparedSql - a 'preparable' SQL statement
851 * @param array $args - array of arguments to fill it with
852 * @return string executable SQL
854 function fillPrepared( $preparedQuery, $args ) {
856 $this->preparedArgs
=& $args;
857 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
858 array( &$this, 'fillPreparedArg' ), $preparedQuery );
862 * preg_callback func for fillPrepared()
863 * The arguments should be in $this->preparedArgs and must not be touched
864 * while we're doing this.
866 * @param array $matches
870 function fillPreparedArg( $matches ) {
871 switch( $matches[1] ) {
872 case '\\?': return '?';
873 case '\\!': return '!';
874 case '\\&': return '&';
876 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
877 switch( $matches[1] ) {
878 case '?': return $this->addQuotes( $arg );
879 case '!': return $arg;
881 # return $this->addQuotes( file_get_contents( $arg ) );
882 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
884 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
889 * @param mixed $res A SQL result
892 * Free a result object
894 function freeResult( $res ) {
895 if ( !@/**/mysql_free_result( $res ) ) {
896 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
901 * Fetch the next row from the given result object, in object form.
902 * Fields can be retrieved with $row->fieldname, with fields acting like
905 * @param $res SQL result object as returned from Database::query(), etc.
906 * @return MySQL row object
907 * @throws DBUnexpectedError Thrown if the database returns an error
909 function fetchObject( $res ) {
910 @/**/$row = mysql_fetch_object( $res );
911 if( $this->lastErrno() ) {
912 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
918 * Fetch the next row from the given result object, in associative array
919 * form. Fields are retrieved with $row['fieldname'].
921 * @param $res SQL result object as returned from Database::query(), etc.
922 * @return MySQL row object
923 * @throws DBUnexpectedError Thrown if the database returns an error
925 function fetchRow( $res ) {
926 @/**/$row = mysql_fetch_array( $res );
927 if ( $this->lastErrno() ) {
928 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
934 * Get the number of rows in a result object
936 function numRows( $res ) {
937 @/**/$n = mysql_num_rows( $res );
938 if( $this->lastErrno() ) {
939 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
945 * Get the number of fields in a result object
946 * See documentation for mysql_num_fields()
948 function numFields( $res ) { return mysql_num_fields( $res ); }
951 * Get a field name in a result object
952 * See documentation for mysql_field_name():
953 * http://www.php.net/mysql_field_name
955 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
958 * Get the inserted value of an auto-increment row
960 * The value inserted should be fetched from nextSequenceValue()
963 * $id = $dbw->nextSequenceValue('page_page_id_seq');
964 * $dbw->insert('page',array('page_id' => $id));
965 * $id = $dbw->insertId();
967 function insertId() { return mysql_insert_id( $this->mConn
); }
970 * Change the position of the cursor in a result object
971 * See mysql_data_seek()
973 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
976 * Get the last error number
979 function lastErrno() {
980 if ( $this->mConn
) {
981 return mysql_errno( $this->mConn
);
983 return mysql_errno();
988 * Get a description of the last error
989 * See mysql_error() for more details
991 function lastError() {
992 if ( $this->mConn
) {
993 # Even if it's non-zero, it can still be invalid
994 wfSuppressWarnings();
995 $error = mysql_error( $this->mConn
);
997 $error = mysql_error();
1001 $error = mysql_error();
1004 $error .= ' (' . $this->mServer
. ')';
1009 * Get the number of rows affected by the last write query
1010 * See mysql_affected_rows() for more details
1012 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
1013 /**#@-*/ // end of template : @param $result
1016 * Simple UPDATE wrapper
1017 * Usually aborts on failure
1018 * If errors are explicitly ignored, returns success
1020 * This function exists for historical reasons, Database::update() has a more standard
1021 * calling convention and feature set
1023 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
1025 $table = $this->tableName( $table );
1026 $sql = "UPDATE $table SET $var = '" .
1027 $this->strencode( $value ) . "' WHERE ($cond)";
1028 return (bool)$this->query( $sql, $fname );
1032 * Simple SELECT wrapper, returns a single field, input must be encoded
1033 * Usually aborts on failure
1034 * If errors are explicitly ignored, returns FALSE on failure
1036 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
1037 if ( !is_array( $options ) ) {
1038 $options = array( $options );
1040 $options['LIMIT'] = 1;
1042 $res = $this->select( $table, $var, $cond, $fname, $options );
1043 if ( $res === false ||
!$this->numRows( $res ) ) {
1046 $row = $this->fetchRow( $res );
1047 if ( $row !== false ) {
1048 $this->freeResult( $res );
1056 * Returns an optional USE INDEX clause to go after the table, and a
1057 * string to go at the end of the query
1061 * @param array $options an associative array of options to be turned into
1062 * an SQL query, valid keys are listed in the function.
1065 function makeSelectOptions( $options ) {
1066 $preLimitTail = $postLimitTail = '';
1069 $noKeyOptions = array();
1070 foreach ( $options as $key => $option ) {
1071 if ( is_numeric( $key ) ) {
1072 $noKeyOptions[$option] = true;
1076 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1077 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1079 //if (isset($options['LIMIT'])) {
1080 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1081 // isset($options['OFFSET']) ? $options['OFFSET']
1085 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1086 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1087 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1089 # Various MySQL extensions
1090 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
1091 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
1092 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
1093 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
1094 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
1095 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
1096 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
1097 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
1099 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1100 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1105 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1111 * @param mixed $table Array or string, table name(s) (prefix auto-added)
1112 * @param mixed $vars Array or string, field name(s) to be retrieved
1113 * @param mixed $conds Array or string, condition(s) for WHERE
1114 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1115 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1116 * see Database::makeSelectOptions code for list of supported stuff
1117 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
1119 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
1121 if( is_array( $vars ) ) {
1122 $vars = implode( ',', $vars );
1124 if( !is_array( $options ) ) {
1125 $options = array( $options );
1127 if( is_array( $table ) ) {
1128 if ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1129 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
1131 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1132 } elseif ($table!='') {
1133 if ($table{0}==' ') {
1134 $from = ' FROM ' . $table;
1136 $from = ' FROM ' . $this->tableName( $table );
1142 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1144 if( !empty( $conds ) ) {
1145 if ( is_array( $conds ) ) {
1146 $conds = $this->makeList( $conds, LIST_AND
);
1148 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1150 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1153 if (isset($options['LIMIT']))
1154 $sql = $this->limitResult($sql, $options['LIMIT'],
1155 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
1156 $sql = "$sql $postLimitTail";
1158 if (isset($options['EXPLAIN'])) {
1159 $sql = 'EXPLAIN ' . $sql;
1162 return $this->query( $sql, $fname );
1166 * Single row SELECT wrapper
1167 * Aborts or returns FALSE on error
1169 * $vars: the selected variables
1170 * $conds: a condition map, terms are ANDed together.
1171 * Items with numeric keys are taken to be literal conditions
1172 * Takes an array of selected variables, and a condition map, which is ANDed
1173 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1174 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1175 * $obj- >page_id is the ID of the Astronomy article
1177 * @todo migrate documentation to phpdocumentor format
1179 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
1180 $options['LIMIT'] = 1;
1181 $res = $this->select( $table, $vars, $conds, $fname, $options );
1182 if ( $res === false )
1184 if ( !$this->numRows($res) ) {
1185 $this->freeResult($res);
1188 $obj = $this->fetchObject( $res );
1189 $this->freeResult( $res );
1195 * Estimate rows in dataset
1196 * Returns estimated count, based on EXPLAIN output
1197 * Takes same arguments as Database::select()
1200 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
1201 $options['EXPLAIN']=true;
1202 $res = $this->select ($table, $vars, $conds, $fname, $options );
1203 if ( $res === false )
1205 if (!$this->numRows($res)) {
1206 $this->freeResult($res);
1212 while( $plan = $this->fetchObject( $res ) ) {
1213 $rows *= ($plan->rows
> 0)?
$plan->rows
:1; // avoid resetting to zero
1216 $this->freeResult($res);
1222 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1223 * It's only slightly flawed. Don't use for anything important.
1225 * @param string $sql A SQL Query
1228 static function generalizeSQL( $sql ) {
1229 # This does the same as the regexp below would do, but in such a way
1230 # as to avoid crashing php on some large strings.
1231 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1233 $sql = str_replace ( "\\\\", '', $sql);
1234 $sql = str_replace ( "\\'", '', $sql);
1235 $sql = str_replace ( "\\\"", '', $sql);
1236 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1237 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1239 # All newlines, tabs, etc replaced by single space
1240 $sql = preg_replace ( '/\s+/', ' ', $sql);
1243 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1249 * Determines whether a field exists in a table
1250 * Usually aborts on failure
1251 * If errors are explicitly ignored, returns NULL on failure
1253 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1254 $table = $this->tableName( $table );
1255 $res = $this->query( 'DESCRIBE '.$table, $fname );
1262 while ( $row = $this->fetchObject( $res ) ) {
1263 if ( $row->Field
== $field ) {
1272 * Determines whether an index exists
1273 * Usually aborts on failure
1274 * If errors are explicitly ignored, returns NULL on failure
1276 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1277 $info = $this->indexInfo( $table, $index, $fname );
1278 if ( is_null( $info ) ) {
1281 return $info !== false;
1287 * Get information about an index into an object
1288 * Returns false if the index does not exist
1290 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1291 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1292 # SHOW INDEX should work for 3.x and up:
1293 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1294 $table = $this->tableName( $table );
1295 $sql = 'SHOW INDEX FROM '.$table;
1296 $res = $this->query( $sql, $fname );
1302 while ( $row = $this->fetchObject( $res ) ) {
1303 if ( $row->Key_name
== $index ) {
1307 $this->freeResult($res);
1309 return empty($result) ?
false : $result;
1313 * Query whether a given table exists
1315 function tableExists( $table ) {
1316 $table = $this->tableName( $table );
1317 $old = $this->ignoreErrors( true );
1318 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1319 $this->ignoreErrors( $old );
1321 $this->freeResult( $res );
1329 * mysql_fetch_field() wrapper
1330 * Returns false if the field doesn't exist
1335 function fieldInfo( $table, $field ) {
1336 $table = $this->tableName( $table );
1337 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1338 $n = mysql_num_fields( $res );
1339 for( $i = 0; $i < $n; $i++
) {
1340 $meta = mysql_fetch_field( $res, $i );
1341 if( $field == $meta->name
) {
1342 return new MySQLField($meta);
1349 * mysql_field_type() wrapper
1351 function fieldType( $res, $index ) {
1352 return mysql_field_type( $res, $index );
1356 * Determines if a given index is unique
1358 function indexUnique( $table, $index ) {
1359 $indexInfo = $this->indexInfo( $table, $index );
1360 if ( !$indexInfo ) {
1363 return !$indexInfo[0]->Non_unique
;
1367 * INSERT wrapper, inserts an array into a table
1369 * $a may be a single associative array, or an array of these with numeric keys, for
1372 * Usually aborts on failure
1373 * If errors are explicitly ignored, returns success
1375 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1376 # No rows to insert, easy just return now
1377 if ( !count( $a ) ) {
1381 $table = $this->tableName( $table );
1382 if ( !is_array( $options ) ) {
1383 $options = array( $options );
1385 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1387 $keys = array_keys( $a[0] );
1390 $keys = array_keys( $a );
1393 $sql = 'INSERT ' . implode( ' ', $options ) .
1394 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1398 foreach ( $a as $row ) {
1404 $sql .= '(' . $this->makeList( $row ) . ')';
1407 $sql .= '(' . $this->makeList( $a ) . ')';
1409 return (bool)$this->query( $sql, $fname );
1413 * Make UPDATE options for the Database::update function
1416 * @param array $options The options passed to Database::update
1419 function makeUpdateOptions( $options ) {
1420 if( !is_array( $options ) ) {
1421 $options = array( $options );
1424 if ( in_array( 'LOW_PRIORITY', $options ) )
1425 $opts[] = $this->lowPriorityOption();
1426 if ( in_array( 'IGNORE', $options ) )
1428 return implode(' ', $opts);
1432 * UPDATE wrapper, takes a condition array and a SET array
1434 * @param string $table The table to UPDATE
1435 * @param array $values An array of values to SET
1436 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1437 * @param string $fname The Class::Function calling this function
1439 * @param array $options An array of UPDATE options, can be one or
1440 * more of IGNORE, LOW_PRIORITY
1442 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1443 $table = $this->tableName( $table );
1444 $opts = $this->makeUpdateOptions( $options );
1445 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1446 if ( $conds != '*' ) {
1447 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1449 $this->query( $sql, $fname );
1453 * Makes an encoded list of strings from an array
1455 * LIST_COMMA - comma separated, no field names
1456 * LIST_AND - ANDed WHERE clause (without the WHERE)
1457 * LIST_OR - ORed WHERE clause (without the WHERE)
1458 * LIST_SET - comma separated with field names, like a SET clause
1459 * LIST_NAMES - comma separated field names
1461 function makeList( $a, $mode = LIST_COMMA
) {
1462 if ( !is_array( $a ) ) {
1463 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1468 foreach ( $a as $field => $value ) {
1470 if ( $mode == LIST_AND
) {
1472 } elseif($mode == LIST_OR
) {
1480 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1481 $list .= "($value)";
1482 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
1484 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array ($value) ) {
1485 $list .= $field." IN (".$this->makeList($value).") ";
1487 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1488 $list .= "$field = ";
1490 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1497 * Change the current database
1499 function selectDB( $db ) {
1500 $this->mDBname
= $db;
1501 return mysql_select_db( $db, $this->mConn
);
1505 * Format a table name ready for use in constructing an SQL query
1507 * This does two important things: it quotes table names which as necessary,
1508 * and it adds a table prefix if there is one.
1510 * All functions of this object which require a table name call this function
1511 * themselves. Pass the canonical name to such functions. This is only needed
1512 * when calling query() directly.
1514 * @param string $name database table name
1516 function tableName( $name ) {
1518 # Skip quoted literals
1519 if ( $name{0} != '`' ) {
1520 if ( $this->mTablePrefix
!== '' && strpos( '.', $name ) === false ) {
1521 $name = "{$this->mTablePrefix}$name";
1523 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1524 $name = "`$wgSharedDB`.`$name`";
1534 * Fetch a number of table names into an array
1535 * This is handy when you need to construct SQL for joins
1538 * extract($dbr->tableNames('user','watchlist'));
1539 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1540 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1542 public function tableNames() {
1543 $inArray = func_get_args();
1545 foreach ( $inArray as $name ) {
1546 $retVal[$name] = $this->tableName( $name );
1552 * Fetch a number of table names into an zero-indexed numerical array
1553 * This is handy when you need to construct SQL for joins
1556 * list( $user, $watchlist ) = $dbr->tableNames('user','watchlist');
1557 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1558 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1560 public function tableNamesN() {
1561 $inArray = func_get_args();
1563 foreach ( $inArray as $name ) {
1564 $retVal[] = $this->tableName( $name );
1572 function tableNamesWithUseIndex( $tables, $use_index ) {
1575 foreach ( $tables as $table )
1576 if ( @$use_index[$table] !== null )
1577 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1579 $ret[] = $this->tableName( $table );
1581 return implode( ',', $ret );
1585 * Wrapper for addslashes()
1586 * @param string $s String to be slashed.
1587 * @return string slashed string.
1589 function strencode( $s ) {
1590 return mysql_real_escape_string( $s, $this->mConn
);
1594 * If it's a string, adds quotes and backslashes
1595 * Otherwise returns as-is
1597 function addQuotes( $s ) {
1598 if ( is_null( $s ) ) {
1601 # This will also quote numeric values. This should be harmless,
1602 # and protects against weird problems that occur when they really
1603 # _are_ strings such as article titles and string->number->string
1604 # conversion is not 1:1.
1605 return "'" . $this->strencode( $s ) . "'";
1610 * Escape string for safe LIKE usage
1612 function escapeLike( $s ) {
1613 $s=$this->strencode( $s );
1614 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1619 * Returns an appropriately quoted sequence value for inserting a new row.
1620 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1621 * subclass will return an integer, and save the value for insertId()
1623 function nextSequenceValue( $seqName ) {
1629 * PostgreSQL doesn't have them and returns ""
1631 function useIndexClause( $index ) {
1632 return "FORCE INDEX ($index)";
1636 * REPLACE query wrapper
1637 * PostgreSQL simulates this with a DELETE followed by INSERT
1638 * $row is the row to insert, an associative array
1639 * $uniqueIndexes is an array of indexes. Each element may be either a
1640 * field name or an array of field names
1642 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1643 * However if you do this, you run the risk of encountering errors which wouldn't have
1646 * @todo migrate comment to phodocumentor format
1648 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1649 $table = $this->tableName( $table );
1652 if ( !is_array( reset( $rows ) ) ) {
1653 $rows = array( $rows );
1656 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1658 foreach ( $rows as $row ) {
1664 $sql .= '(' . $this->makeList( $row ) . ')';
1666 return $this->query( $sql, $fname );
1670 * DELETE where the condition is a join
1671 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1673 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1674 * join condition matches, set $conds='*'
1676 * DO NOT put the join condition in $conds
1678 * @param string $delTable The table to delete from.
1679 * @param string $joinTable The other table.
1680 * @param string $delVar The variable to join on, in the first table.
1681 * @param string $joinVar The variable to join on, in the second table.
1682 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1684 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1686 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1689 $delTable = $this->tableName( $delTable );
1690 $joinTable = $this->tableName( $joinTable );
1691 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1692 if ( $conds != '*' ) {
1693 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1696 return $this->query( $sql, $fname );
1700 * Returns the size of a text field, or -1 for "unlimited"
1702 function textFieldSize( $table, $field ) {
1703 $table = $this->tableName( $table );
1704 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1705 $res = $this->query( $sql, 'Database::textFieldSize' );
1706 $row = $this->fetchObject( $res );
1707 $this->freeResult( $res );
1710 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1719 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1721 function lowPriorityOption() {
1722 return 'LOW_PRIORITY';
1726 * DELETE query wrapper
1728 * Use $conds == "*" to delete all rows
1730 function delete( $table, $conds, $fname = 'Database::delete' ) {
1732 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1734 $table = $this->tableName( $table );
1735 $sql = "DELETE FROM $table";
1736 if ( $conds != '*' ) {
1737 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1739 return $this->query( $sql, $fname );
1743 * INSERT SELECT wrapper
1744 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1745 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1746 * $conds may be "*" to copy the whole table
1747 * srcTable may be an array of tables.
1749 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1750 $insertOptions = array(), $selectOptions = array() )
1752 $destTable = $this->tableName( $destTable );
1753 if ( is_array( $insertOptions ) ) {
1754 $insertOptions = implode( ' ', $insertOptions );
1756 if( !is_array( $selectOptions ) ) {
1757 $selectOptions = array( $selectOptions );
1759 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1760 if( is_array( $srcTable ) ) {
1761 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1763 $srcTable = $this->tableName( $srcTable );
1765 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1766 " SELECT $startOpts " . implode( ',', $varMap ) .
1767 " FROM $srcTable $useIndex ";
1768 if ( $conds != '*' ) {
1769 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1771 $sql .= " $tailOpts";
1772 return $this->query( $sql, $fname );
1776 * Construct a LIMIT query with optional offset
1777 * This is used for query pages
1778 * $sql string SQL query we will append the limit too
1779 * $limit integer the SQL limit
1780 * $offset integer the SQL offset (default false)
1782 function limitResult($sql, $limit, $offset=false) {
1783 if( !is_numeric($limit) ) {
1784 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1786 return " $sql LIMIT "
1787 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1790 function limitResultForUpdate($sql, $num) {
1791 return $this->limitResult($sql, $num, 0);
1795 * Returns an SQL expression for a simple conditional.
1798 * @param string $cond SQL expression which will result in a boolean value
1799 * @param string $trueVal SQL expression to return if true
1800 * @param string $falseVal SQL expression to return if false
1801 * @return string SQL fragment
1803 function conditional( $cond, $trueVal, $falseVal ) {
1804 return " IF($cond, $trueVal, $falseVal) ";
1808 * Determines if the last failure was due to a deadlock
1810 function wasDeadlock() {
1811 return $this->lastErrno() == 1213;
1815 * Perform a deadlock-prone transaction.
1817 * This function invokes a callback function to perform a set of write
1818 * queries. If a deadlock occurs during the processing, the transaction
1819 * will be rolled back and the callback function will be called again.
1822 * $dbw->deadlockLoop( callback, ... );
1824 * Extra arguments are passed through to the specified callback function.
1826 * Returns whatever the callback function returned on its successful,
1827 * iteration, or false on error, for example if the retry limit was
1830 function deadlockLoop() {
1831 $myFname = 'Database::deadlockLoop';
1834 $args = func_get_args();
1835 $function = array_shift( $args );
1836 $oldIgnore = $this->ignoreErrors( true );
1837 $tries = DEADLOCK_TRIES
;
1838 if ( is_array( $function ) ) {
1839 $fname = $function[0];
1844 $retVal = call_user_func_array( $function, $args );
1845 $error = $this->lastError();
1846 $errno = $this->lastErrno();
1847 $sql = $this->lastQuery();
1850 if ( $this->wasDeadlock() ) {
1852 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1854 $this->reportQueryError( $error, $errno, $sql, $fname );
1857 } while( $this->wasDeadlock() && --$tries > 0 );
1858 $this->ignoreErrors( $oldIgnore );
1859 if ( $tries <= 0 ) {
1860 $this->query( 'ROLLBACK', $myFname );
1861 $this->reportQueryError( $error, $errno, $sql, $fname );
1864 $this->query( 'COMMIT', $myFname );
1870 * Do a SELECT MASTER_POS_WAIT()
1872 * @param string $file the binlog file
1873 * @param string $pos the binlog position
1874 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1876 function masterPosWait( $file, $pos, $timeout ) {
1877 $fname = 'Database::masterPosWait';
1878 wfProfileIn( $fname );
1881 # Commit any open transactions
1882 $this->immediateCommit();
1884 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1885 $encFile = $this->strencode( $file );
1886 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1887 $res = $this->doQuery( $sql );
1888 if ( $res && $row = $this->fetchRow( $res ) ) {
1889 $this->freeResult( $res );
1890 wfProfileOut( $fname );
1893 wfProfileOut( $fname );
1899 * Get the position of the master from SHOW SLAVE STATUS
1901 function getSlavePos() {
1902 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1903 $row = $this->fetchObject( $res );
1905 return array( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1907 return array( false, false );
1912 * Get the position of the master from SHOW MASTER STATUS
1914 function getMasterPos() {
1915 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1916 $row = $this->fetchObject( $res );
1918 return array( $row->File
, $row->Position
);
1920 return array( false, false );
1925 * Begin a transaction, committing any previously open transaction
1927 function begin( $fname = 'Database::begin' ) {
1928 $this->query( 'BEGIN', $fname );
1929 $this->mTrxLevel
= 1;
1935 function commit( $fname = 'Database::commit' ) {
1936 $this->query( 'COMMIT', $fname );
1937 $this->mTrxLevel
= 0;
1941 * Rollback a transaction
1943 function rollback( $fname = 'Database::rollback' ) {
1944 $this->query( 'ROLLBACK', $fname );
1945 $this->mTrxLevel
= 0;
1949 * Begin a transaction, committing any previously open transaction
1950 * @deprecated use begin()
1952 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1957 * Commit transaction, if one is open
1958 * @deprecated use commit()
1960 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1965 * Return MW-style timestamp used for MySQL schema
1967 function timestamp( $ts=0 ) {
1968 return wfTimestamp(TS_MW
,$ts);
1972 * Local database timestamp format or null
1974 function timestampOrNull( $ts = null ) {
1975 if( is_null( $ts ) ) {
1978 return $this->timestamp( $ts );
1985 function resultObject( $result ) {
1986 if( empty( $result ) ) {
1989 return new ResultWrapper( $this, $result );
1994 * Return aggregated value alias
1996 function aggregateValue ($valuedata,$valuename='value') {
2001 * @return string wikitext of a link to the server software's web site
2003 function getSoftwareLink() {
2004 return "[http://www.mysql.com/ MySQL]";
2008 * @return string Version information from the database
2010 function getServerVersion() {
2011 return mysql_get_server_info( $this->mConn
);
2015 * Ping the server and try to reconnect if it there is no connection
2018 if( function_exists( 'mysql_ping' ) ) {
2019 return mysql_ping( $this->mConn
);
2021 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
2028 * At the moment, this will only work if the DB user has the PROCESS privilege
2031 $res = $this->query( 'SHOW PROCESSLIST' );
2032 # Find slave SQL thread. Assumed to be the second one running, which is a bit
2033 # dubious, but unfortunately there's no easy rigorous way
2034 while ( $row = $this->fetchObject( $res ) ) {
2035 /* This should work for most situations - when default db
2036 * for thread is not specified, it had no events executed,
2037 * and therefore it doesn't know yet how lagged it is.
2039 * Relay log I/O thread does not select databases.
2041 if ( $row->User
== 'system user' &&
2042 $row->State
!= 'Waiting for master to send event' &&
2043 $row->State
!= 'Connecting to master' &&
2044 $row->State
!= 'Queueing master event to the relay log' &&
2045 $row->State
!= 'Waiting for master update' &&
2046 $row->State
!= 'Requesting binlog dump'
2048 # This is it, return the time (except -ve)
2049 if ( $row->Time
> 0x7fffffff ) {
2060 * Get status information from SHOW STATUS in an associative array
2062 function getStatus($which="%") {
2063 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2065 while ( $row = $this->fetchObject( $res ) ) {
2066 $status[$row->Variable_name
] = $row->Value
;
2072 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2074 function maxListLen() {
2078 function encodeBlob($b) {
2082 function decodeBlob($b) {
2087 * Override database's default connection timeout.
2088 * May be useful for very long batch queries such as
2089 * full-wiki dumps, where a single query reads out
2090 * over hours or days.
2091 * @param int $timeout in seconds
2093 public function setTimeout( $timeout ) {
2094 $this->query( "SET net_read_timeout=$timeout" );
2095 $this->query( "SET net_write_timeout=$timeout" );
2099 * Read and execute SQL commands from a file.
2100 * Returns true on success, error string on failure
2102 function sourceFile( $filename ) {
2103 $fp = fopen( $filename, 'r' );
2104 if ( false === $fp ) {
2105 return "Could not open \"{$filename}\".\n";
2110 $dollarquote = false;
2112 while ( ! feof( $fp ) ) {
2113 $line = trim( fgets( $fp, 1024 ) );
2114 $sl = strlen( $line ) - 1;
2116 if ( $sl < 0 ) { continue; }
2117 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2119 ## Allow dollar quoting for function declarations
2120 if (substr($line,0,4) == '$mw$') {
2122 $dollarquote = false;
2126 $dollarquote = true;
2129 else if (!$dollarquote) {
2130 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
2132 $line = substr( $line, 0, $sl );
2136 if ( '' != $cmd ) { $cmd .= ' '; }
2140 $cmd = str_replace(';;', ";", $cmd);
2141 $cmd = $this->replaceVars( $cmd );
2142 $res = $this->query( $cmd, 'dbsource', true );
2144 if ( false === $res ) {
2145 $err = $this->lastError();
2146 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2158 * Replace variables in sourced SQL
2160 protected function replaceVars( $ins ) {
2162 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2163 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2164 'wgDBadminuser', 'wgDBadminpassword',
2167 // Ordinary variables
2168 foreach ( $varnames as $var ) {
2169 if( isset( $GLOBALS[$var] ) ) {
2170 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2171 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2172 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2173 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2178 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
2179 array( &$this, 'tableNameCallback' ), $ins );
2184 * Table name callback
2187 protected function tableNameCallback( $matches ) {
2188 return $this->tableName( $matches[1] );
2194 * Database abstraction object for mySQL
2195 * Inherit all methods and properties of Database::Database()
2197 * @addtogroup Database
2200 class DatabaseMysql
extends Database
{
2206 * Result wrapper for grabbing data queried by someone else
2207 * @addtogroup Database
2209 class ResultWrapper
{
2215 function ResultWrapper( &$database, $result ) {
2216 $this->db
=& $database;
2217 $this->result
=& $result;
2223 function numRows() {
2224 return $this->db
->numRows( $this->result
);
2230 function fetchObject() {
2231 return $this->db
->fetchObject( $this->result
);
2237 function fetchRow() {
2238 return $this->db
->fetchRow( $this->result
);
2245 $this->db
->freeResult( $this->result
);
2246 unset( $this->result
);
2250 function seek( $row ) {
2251 $this->db
->dataSeek( $this->result
, $row );
2255 if ($this->numRows()) {
2256 $this->db
->dataSeek($this->result
, 0);