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 *****************************************************************************/
24 function DBObject($data) {
41 private $name, $tablename, $default, $max_length, $nullable,
42 $is_pk, $is_unique, $is_key, $type;
43 function __construct ($info) {
44 $this->name
= $info->name
;
45 $this->tablename
= $info->table
;
46 $this->default = $info->def
;
47 $this->max_length
= $info->max_length
;
48 $this->nullable
= !$info->not_null
;
49 $this->is_pk
= $info->primary_key
;
50 $this->is_unique
= $info->unique_key
;
51 $this->is_multiple
= $info->multiple_key
;
52 $this->is_key
= ($this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
53 $this->type
= $info->type
;
60 function tableName() {
61 return $this->tableName
;
64 function defaultValue() {
65 return $this->default;
68 function maxLength() {
69 return $this->max_length
;
73 return $this->nullable
;
80 function isMultipleKey() {
81 return $this->is_multiple
;
89 /******************************************************************************
91 *****************************************************************************/
94 * Database error base class
96 class DBError
extends MWException
{
100 * Construct a database error
101 * @param Database $db The database object which threw the error
102 * @param string $error A simple error message to be used for debugging
104 function __construct( Database
&$db, $error ) {
106 parent
::__construct( $error );
110 class DBConnectionError
extends DBError
{
113 function __construct( Database
&$db, $error = 'unknown error' ) {
114 $msg = 'DB connection error';
115 if ( trim( $error ) != '' ) {
118 $this->error
= $error;
119 parent
::__construct( $db, $msg );
122 function useOutputPage() {
123 // Not likely to work
127 function useMessageCache() {
128 // Not likely to work
133 return $this->getMessage() . "\n";
136 function getLogMessage() {
137 # Don't send to the exception log
141 function getPageTitle() {
143 return "$wgSitename has a problem";
147 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding;
148 global $wgSitename, $wgServer, $wgMessageCache;
150 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
151 # Hard coding strings instead.
153 $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>";
154 $mainpage = 'Main Page';
155 $searchdisabled = <<<EOT
156 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
157 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
161 <!-- SiteSearch Google -->
162 <FORM method=GET action=\"http://www.google.com/search\">
163 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
164 <A HREF=\"http://www.google.com/\">
165 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
166 border=\"0\" ALT=\"Google\"></A>
169 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
170 <INPUT type=submit name=btnG VALUE=\"Google Search\">
172 <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 />
173 <input type='hidden' name='ie' value='$2'>
174 <input type='hidden' name='oe' value='$2'>
178 <!-- SiteSearch Google -->";
179 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
182 if ( is_object( $wgMessageCache ) ) {
183 $wgMessageCache->disable();
186 if ( trim( $this->error
) == '' ) {
187 $this->error
= $this->db
->getProperty('mServer');
190 $text = str_replace( '$1', $this->error
, $noconnect );
191 $text .= wfGetSiteNotice();
193 if($wgUseFileCache) {
198 $t = Title
::newFromURL( $title );
199 } elseif (@/**/$_REQUEST['search']) {
200 $search = $_REQUEST['search'];
201 return $searchdisabled .
202 str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
203 $wgInputEncoding ), $googlesearch );
205 $t = Title
::newFromText( $mainpage );
209 $cache = new HTMLFileCache( $t );
210 if( $cache->isFileCached() ) {
211 // FIXME: $msg is not defined on the next line.
212 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
213 $cachederror . "</b></p>\n";
215 $tag = '<div id="article">';
219 $cache->fetchPageText() );
227 class DBQueryError
extends DBError
{
228 public $error, $errno, $sql, $fname;
230 function __construct( Database
&$db, $error, $errno, $sql, $fname ) {
231 $message = "A database error has occurred\n" .
233 "Function: $fname\n" .
234 "Error: $errno $error\n";
236 parent
::__construct( $db, $message );
237 $this->error
= $error;
238 $this->errno
= $errno;
240 $this->fname
= $fname;
244 if ( $this->useMessageCache() ) {
245 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
246 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
248 return $this->getMessage();
253 global $wgShowSQLErrors;
254 if( !$wgShowSQLErrors ) {
255 return $this->msg( 'sqlhidden', 'SQL hidden' );
261 function getLogMessage() {
262 # Don't send to the exception log
266 function getPageTitle() {
267 return $this->msg( 'databaseerror', 'Database error' );
271 if ( $this->useMessageCache() ) {
272 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
273 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
275 return nl2br( htmlspecialchars( $this->getMessage() ) );
280 class DBUnexpectedError
extends DBError
{}
282 /******************************************************************************/
285 * Database abstraction object
289 #------------------------------------------------------------------------------
291 #------------------------------------------------------------------------------
293 protected $mLastQuery = '';
295 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
296 protected $mOut, $mOpened = false;
298 protected $mFailFunction;
299 protected $mTablePrefix;
301 protected $mTrxLevel = 0;
302 protected $mErrorCount = 0;
303 protected $mLBInfo = array();
305 #------------------------------------------------------------------------------
307 #------------------------------------------------------------------------------
308 # These optionally set a variable and return the previous state
311 * Fail function, takes a Database as a parameter
312 * Set to false for default, 1 for ignore errors
314 function failFunction( $function = NULL ) {
315 return wfSetVar( $this->mFailFunction
, $function );
319 * Output page, used for reporting errors
320 * FALSE means discard output
322 function setOutputPage( $out ) {
327 * Boolean, controls output of large amounts of debug information
329 function debug( $debug = NULL ) {
330 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
334 * Turns buffering of SQL result sets on (true) or off (false).
335 * Default is "on" and it should not be changed without good reasons.
337 function bufferResults( $buffer = NULL ) {
338 if ( is_null( $buffer ) ) {
339 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
341 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
346 * Turns on (false) or off (true) the automatic generation and sending
347 * of a "we're sorry, but there has been a database error" page on
348 * database errors. Default is on (false). When turned off, the
349 * code should use lastErrno() and lastError() to handle the
350 * situation as appropriate.
352 function ignoreErrors( $ignoreErrors = NULL ) {
353 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
357 * The current depth of nested transactions
358 * @param $level Integer: , default NULL.
360 function trxLevel( $level = NULL ) {
361 return wfSetVar( $this->mTrxLevel
, $level );
365 * Number of errors logged, only useful when errors are ignored
367 function errorCount( $count = NULL ) {
368 return wfSetVar( $this->mErrorCount
, $count );
372 * Properties passed down from the server info array of the load balancer
374 function getLBInfo( $name = NULL ) {
375 if ( is_null( $name ) ) {
376 return $this->mLBInfo
;
378 if ( array_key_exists( $name, $this->mLBInfo
) ) {
379 return $this->mLBInfo
[$name];
386 function setLBInfo( $name, $value = NULL ) {
387 if ( is_null( $value ) ) {
388 $this->mLBInfo
= $name;
390 $this->mLBInfo
[$name] = $value;
395 * Returns true if this database supports (and uses) cascading deletes
397 function cascadingDeletes() {
402 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
404 function cleanupTriggers() {
409 * Returns true if this database is strict about what can be put into an IP field.
410 * Specifically, it uses a NULL value instead of an empty string.
412 function strictIPs() {
417 * Returns true if this database uses timestamps rather than integers
419 function realTimestamps() {
424 * Returns true if this database does an implicit sort when doing GROUP BY
426 function implicitGroupby() {
431 * Returns true if this database can do a native search on IP columns
432 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
434 function searchableIPs() {
441 function lastQuery() { return $this->mLastQuery
; }
442 function isOpen() { return $this->mOpened
; }
445 function setFlag( $flag ) {
446 $this->mFlags |
= $flag;
449 function clearFlag( $flag ) {
450 $this->mFlags
&= ~
$flag;
453 function getFlag( $flag ) {
454 return !!($this->mFlags
& $flag);
458 * General read-only accessor
460 function getProperty( $name ) {
464 #------------------------------------------------------------------------------
466 #------------------------------------------------------------------------------
470 * @param string $server database server host
471 * @param string $user database user name
472 * @param string $password database user password
473 * @param string $dbname database name
474 * @param failFunction
476 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
478 function __construct( $server = false, $user = false, $password = false, $dbName = false,
479 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
481 global $wgOut, $wgDBprefix, $wgCommandLineMode;
482 # Can't get a reference if it hasn't been set yet
483 if ( !isset( $wgOut ) ) {
486 $this->mOut
=& $wgOut;
488 $this->mFailFunction
= $failFunction;
489 $this->mFlags
= $flags;
491 if ( $this->mFlags
& DBO_DEFAULT
) {
492 if ( $wgCommandLineMode ) {
493 $this->mFlags
&= ~DBO_TRX
;
495 $this->mFlags |
= DBO_TRX
;
500 // Faster read-only access
501 if ( wfReadOnly() ) {
502 $this->mFlags |= DBO_PERSISTENT;
503 $this->mFlags &= ~DBO_TRX;
506 /** Get the default table prefix*/
507 if ( $tablePrefix == 'get from global' ) {
508 $this->mTablePrefix
= $wgDBprefix;
510 $this->mTablePrefix
= $tablePrefix;
514 $this->open( $server, $user, $password, $dbName );
520 * @param failFunction
523 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
525 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
529 * Usually aborts on failure
530 * If the failFunction is set to a non-zero integer, returns success
532 function open( $server, $user, $password, $dbName ) {
534 wfProfileIn( __METHOD__
);
536 # Test for missing mysql.so
537 # First try to load it
538 if (!@extension_loaded
('mysql')) {
543 # Otherwise we get a suppressed fatal error, which is very hard to track down
544 if ( !function_exists( 'mysql_connect' ) ) {
545 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
549 $this->mServer
= $server;
550 $this->mUser
= $user;
551 $this->mPassword
= $password;
552 $this->mDBname
= $dbName;
556 wfProfileIn("dbconnect-$server");
558 # LIVE PATCH by Tim, ask Domas for why: retry loop
559 $this->mConn
= false;
561 for ( $i = 0; $i < $max && !$this->mConn
; $i++
) {
565 if ( $this->mFlags
& DBO_PERSISTENT
) {
566 @/**/$this->mConn
= mysql_pconnect( $server, $user, $password );
568 # Create a new connection...
569 @/**/$this->mConn
= mysql_connect( $server, $user, $password, true );
571 if ($this->mConn
=== false) {
573 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
577 wfProfileOut("dbconnect-$server");
579 if ( $dbName != '' ) {
580 if ( $this->mConn
!== false ) {
581 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
583 $error = "Error selecting database $dbName on server {$this->mServer} " .
584 "from client host {$wguname['nodename']}\n";
585 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
589 wfDebug( "DB connection error\n" );
590 wfDebug( "Server: $server, User: $user, Password: " .
591 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
596 $success = (bool)$this->mConn
;
602 // Tell the server we're communicating with it in UTF-8.
603 // This may engage various charset conversions.
604 $this->query( 'SET NAMES utf8' );
607 $this->reportConnectionError();
610 $this->mOpened
= $success;
611 wfProfileOut( __METHOD__
);
617 * Closes a database connection.
618 * if it is open : commits any open transactions
620 * @return bool operation success. true if already closed.
624 $this->mOpened
= false;
625 if ( $this->mConn
) {
626 if ( $this->trxLevel() ) {
627 $this->immediateCommit();
629 return mysql_close( $this->mConn
);
636 * @param string $error fallback error message, used if none is given by MySQL
638 function reportConnectionError( $error = 'Unknown error' ) {
639 $myError = $this->lastError();
644 if ( $this->mFailFunction
) {
645 # Legacy error handling method
646 if ( !is_int( $this->mFailFunction
) ) {
647 $ff = $this->mFailFunction
;
648 $ff( $this, $error );
652 wfLogDBError( "Connection error: $error\n" );
653 throw new DBConnectionError( $this, $error );
658 * Usually aborts on failure. If errors are explicitly ignored, returns success.
660 * @param $sql String: SQL query
661 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST comment (you can use __METHOD__ or add some extra info)
662 * @param $tempIgnore Bool: Whether to avoid throwing an exception on errors... maybe best to catch the exception instead?
663 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure if $tempIgnore set
664 * @throws DBQueryError Thrown when the database returns an error of any kind
666 public function query( $sql, $fname = '', $tempIgnore = false ) {
669 if ( $wgProfiling ) {
670 # generalizeSQL will probably cut down the query to reasonable
671 # logging size most of the time. The substr is really just a sanity check.
673 # Who's been wasting my precious column space? -- TS
674 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
676 if ( is_null( $this->getLBInfo( 'master' ) ) ) {
677 $queryProf = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
678 $totalProf = 'Database::query';
680 $queryProf = 'query-m: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
681 $totalProf = 'Database::query-master';
683 wfProfileIn( $totalProf );
684 wfProfileIn( $queryProf );
687 $this->mLastQuery
= $sql;
689 # Add a comment for easy SHOW PROCESSLIST interpretation
691 $commentedSql = preg_replace('/\s/', " /* $fname */ ", $sql, 1);
693 $commentedSql = $sql;
696 # If DBO_TRX is set, start a transaction
697 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
698 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK'
703 if ( $this->debug() ) {
704 $sqlx = substr( $commentedSql, 0, 500 );
705 $sqlx = strtr( $sqlx, "\t\n", ' ' );
706 wfDebug( "SQL: $sqlx\n" );
709 # Do the query and handle errors
710 $ret = $this->doQuery( $commentedSql );
712 # Try reconnecting if the connection was lost
713 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
714 # Transaction is gone, like it or not
715 $this->mTrxLevel
= 0;
716 wfDebug( "Connection lost, reconnecting...\n" );
717 if ( $this->ping() ) {
718 wfDebug( "Reconnected\n" );
719 $sqlx = substr( $commentedSql, 0, 500 );
720 $sqlx = strtr( $sqlx, "\t\n", ' ' );
721 global $wgRequestTime;
722 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
723 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
724 $ret = $this->doQuery( $commentedSql );
726 wfDebug( "Failed\n" );
730 if ( false === $ret ) {
731 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
734 if ( $wgProfiling ) {
735 wfProfileOut( $queryProf );
736 wfProfileOut( $totalProf );
742 * The DBMS-dependent part of query()
743 * @param $sql String: SQL query.
744 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
747 /*private*/ function doQuery( $sql ) {
748 if( $this->bufferResults() ) {
749 $ret = mysql_query( $sql, $this->mConn
);
751 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
760 * @param string $fname
761 * @param bool $tempIgnore
763 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
764 global $wgCommandLineMode;
765 # Ignore errors during error handling to avoid infinite recursion
766 $ignore = $this->ignoreErrors( true );
767 ++
$this->mErrorCount
;
769 if( $ignore ||
$tempIgnore ) {
770 wfDebug("SQL ERROR (ignored): $error\n");
771 $this->ignoreErrors( $ignore );
773 $sql1line = str_replace( "\n", "\\n", $sql );
774 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
775 wfDebug("SQL ERROR: " . $error . "\n");
776 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
782 * Intended to be compatible with the PEAR::DB wrapper functions.
783 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
785 * ? = scalar value, quoted as necessary
786 * ! = raw SQL bit (a function for instance)
787 * & = filename; reads the file and inserts as a blob
788 * (we don't use this though...)
790 function prepare( $sql, $func = 'Database::prepare' ) {
791 /* MySQL doesn't support prepared statements (yet), so just
792 pack up the query for reference. We'll manually replace
794 return array( 'query' => $sql, 'func' => $func );
797 function freePrepared( $prepared ) {
798 /* No-op for MySQL */
802 * Execute a prepared query with the various arguments
803 * @param string $prepared the prepared sql
804 * @param mixed $args Either an array here, or put scalars as varargs
806 function execute( $prepared, $args = null ) {
807 if( !is_array( $args ) ) {
809 $args = func_get_args();
810 array_shift( $args );
812 $sql = $this->fillPrepared( $prepared['query'], $args );
813 return $this->query( $sql, $prepared['func'] );
817 * Prepare & execute an SQL statement, quoting and inserting arguments
818 * in the appropriate places.
819 * @param string $query
820 * @param string $args ...
822 function safeQuery( $query, $args = null ) {
823 $prepared = $this->prepare( $query, 'Database::safeQuery' );
824 if( !is_array( $args ) ) {
826 $args = func_get_args();
827 array_shift( $args );
829 $retval = $this->execute( $prepared, $args );
830 $this->freePrepared( $prepared );
835 * For faking prepared SQL statements on DBs that don't support
837 * @param string $preparedSql - a 'preparable' SQL statement
838 * @param array $args - array of arguments to fill it with
839 * @return string executable SQL
841 function fillPrepared( $preparedQuery, $args ) {
843 $this->preparedArgs
=& $args;
844 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
845 array( &$this, 'fillPreparedArg' ), $preparedQuery );
849 * preg_callback func for fillPrepared()
850 * The arguments should be in $this->preparedArgs and must not be touched
851 * while we're doing this.
853 * @param array $matches
857 function fillPreparedArg( $matches ) {
858 switch( $matches[1] ) {
859 case '\\?': return '?';
860 case '\\!': return '!';
861 case '\\&': return '&';
863 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
864 switch( $matches[1] ) {
865 case '?': return $this->addQuotes( $arg );
866 case '!': return $arg;
868 # return $this->addQuotes( file_get_contents( $arg ) );
869 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
871 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
876 * @param mixed $res A SQL result
879 * Free a result object
881 function freeResult( $res ) {
882 if ( !@/**/mysql_free_result( $res ) ) {
883 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
888 * Fetch the next row from the given result object, in object form.
889 * Fields can be retrieved with $row->fieldname, with fields acting like
892 * @param $res SQL result object as returned from Database::query(), etc.
893 * @return MySQL row object
894 * @throws DBUnexpectedError Thrown if the database returns an error
896 function fetchObject( $res ) {
897 @/**/$row = mysql_fetch_object( $res );
898 if( $this->lastErrno() ) {
899 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
905 * Fetch the next row from the given result object, in associative array
906 * form. Fields are retrieved with $row['fieldname'].
908 * @param $res SQL result object as returned from Database::query(), etc.
909 * @return MySQL row object
910 * @throws DBUnexpectedError Thrown if the database returns an error
912 function fetchRow( $res ) {
913 @/**/$row = mysql_fetch_array( $res );
914 if ( $this->lastErrno() ) {
915 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
921 * Get the number of rows in a result object
923 function numRows( $res ) {
924 @/**/$n = mysql_num_rows( $res );
925 if( $this->lastErrno() ) {
926 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
932 * Get the number of fields in a result object
933 * See documentation for mysql_num_fields()
935 function numFields( $res ) { return mysql_num_fields( $res ); }
938 * Get a field name in a result object
939 * See documentation for mysql_field_name():
940 * http://www.php.net/mysql_field_name
942 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
945 * Get the inserted value of an auto-increment row
947 * The value inserted should be fetched from nextSequenceValue()
950 * $id = $dbw->nextSequenceValue('page_page_id_seq');
951 * $dbw->insert('page',array('page_id' => $id));
952 * $id = $dbw->insertId();
954 function insertId() { return mysql_insert_id( $this->mConn
); }
957 * Change the position of the cursor in a result object
958 * See mysql_data_seek()
960 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
963 * Get the last error number
966 function lastErrno() {
967 if ( $this->mConn
) {
968 return mysql_errno( $this->mConn
);
970 return mysql_errno();
975 * Get a description of the last error
976 * See mysql_error() for more details
978 function lastError() {
979 if ( $this->mConn
) {
980 # Even if it's non-zero, it can still be invalid
981 wfSuppressWarnings();
982 $error = mysql_error( $this->mConn
);
984 $error = mysql_error();
988 $error = mysql_error();
991 $error .= ' (' . $this->mServer
. ')';
996 * Get the number of rows affected by the last write query
997 * See mysql_affected_rows() for more details
999 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
1000 /**#@-*/ // end of template : @param $result
1003 * Simple UPDATE wrapper
1004 * Usually aborts on failure
1005 * If errors are explicitly ignored, returns success
1007 * This function exists for historical reasons, Database::update() has a more standard
1008 * calling convention and feature set
1010 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
1012 $table = $this->tableName( $table );
1013 $sql = "UPDATE $table SET $var = '" .
1014 $this->strencode( $value ) . "' WHERE ($cond)";
1015 return (bool)$this->query( $sql, $fname );
1019 * Simple SELECT wrapper, returns a single field, input must be encoded
1020 * Usually aborts on failure
1021 * If errors are explicitly ignored, returns FALSE on failure
1023 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
1024 if ( !is_array( $options ) ) {
1025 $options = array( $options );
1027 $options['LIMIT'] = 1;
1029 $res = $this->select( $table, $var, $cond, $fname, $options );
1030 if ( $res === false ||
!$this->numRows( $res ) ) {
1033 $row = $this->fetchRow( $res );
1034 if ( $row !== false ) {
1035 $this->freeResult( $res );
1043 * Returns an optional USE INDEX clause to go after the table, and a
1044 * string to go at the end of the query
1048 * @param array $options an associative array of options to be turned into
1049 * an SQL query, valid keys are listed in the function.
1052 function makeSelectOptions( $options ) {
1053 $preLimitTail = $postLimitTail = '';
1056 $noKeyOptions = array();
1057 foreach ( $options as $key => $option ) {
1058 if ( is_numeric( $key ) ) {
1059 $noKeyOptions[$option] = true;
1063 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1064 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1066 //if (isset($options['LIMIT'])) {
1067 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1068 // isset($options['OFFSET']) ? $options['OFFSET']
1072 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1073 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1074 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1076 # Various MySQL extensions
1077 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
1078 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
1079 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
1080 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
1081 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
1082 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
1083 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
1084 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
1086 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1087 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1092 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1098 * @param mixed $table Array or string, table name(s) (prefix auto-added)
1099 * @param mixed $vars Array or string, field name(s) to be retrieved
1100 * @param mixed $conds Array or string, condition(s) for WHERE
1101 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1102 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1103 * see Database::makeSelectOptions code for list of supported stuff
1104 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
1106 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
1108 if( is_array( $vars ) ) {
1109 $vars = implode( ',', $vars );
1111 if( !is_array( $options ) ) {
1112 $options = array( $options );
1114 if( is_array( $table ) ) {
1115 if ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1116 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
1118 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1119 } elseif ($table!='') {
1120 if ($table{0}==' ') {
1121 $from = ' FROM ' . $table;
1123 $from = ' FROM ' . $this->tableName( $table );
1129 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1131 if( !empty( $conds ) ) {
1132 if ( is_array( $conds ) ) {
1133 $conds = $this->makeList( $conds, LIST_AND
);
1135 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1137 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1140 if (isset($options['LIMIT']))
1141 $sql = $this->limitResult($sql, $options['LIMIT'],
1142 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
1143 $sql = "$sql $postLimitTail";
1145 if (isset($options['EXPLAIN'])) {
1146 $sql = 'EXPLAIN ' . $sql;
1149 return $this->query( $sql, $fname );
1153 * Single row SELECT wrapper
1154 * Aborts or returns FALSE on error
1156 * $vars: the selected variables
1157 * $conds: a condition map, terms are ANDed together.
1158 * Items with numeric keys are taken to be literal conditions
1159 * Takes an array of selected variables, and a condition map, which is ANDed
1160 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1161 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1162 * $obj- >page_id is the ID of the Astronomy article
1164 * @todo migrate documentation to phpdocumentor format
1166 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
1167 $options['LIMIT'] = 1;
1168 $res = $this->select( $table, $vars, $conds, $fname, $options );
1169 if ( $res === false )
1171 if ( !$this->numRows($res) ) {
1172 $this->freeResult($res);
1175 $obj = $this->fetchObject( $res );
1176 $this->freeResult( $res );
1182 * Estimate rows in dataset
1183 * Returns estimated count, based on EXPLAIN output
1184 * Takes same arguments as Database::select()
1187 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
1188 $options['EXPLAIN']=true;
1189 $res = $this->select ($table, $vars, $conds, $fname, $options );
1190 if ( $res === false )
1192 if (!$this->numRows($res)) {
1193 $this->freeResult($res);
1199 while( $plan = $this->fetchObject( $res ) ) {
1200 $rows *= ($plan->rows
> 0)?
$plan->rows
:1; // avoid resetting to zero
1203 $this->freeResult($res);
1209 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1210 * It's only slightly flawed. Don't use for anything important.
1212 * @param string $sql A SQL Query
1215 static function generalizeSQL( $sql ) {
1216 # This does the same as the regexp below would do, but in such a way
1217 # as to avoid crashing php on some large strings.
1218 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1220 $sql = str_replace ( "\\\\", '', $sql);
1221 $sql = str_replace ( "\\'", '', $sql);
1222 $sql = str_replace ( "\\\"", '', $sql);
1223 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1224 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1226 # All newlines, tabs, etc replaced by single space
1227 $sql = preg_replace ( '/\s+/', ' ', $sql);
1230 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1236 * Determines whether a field exists in a table
1237 * Usually aborts on failure
1238 * If errors are explicitly ignored, returns NULL on failure
1240 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1241 $table = $this->tableName( $table );
1242 $res = $this->query( 'DESCRIBE '.$table, $fname );
1249 while ( $row = $this->fetchObject( $res ) ) {
1250 if ( $row->Field
== $field ) {
1259 * Determines whether an index exists
1260 * Usually aborts on failure
1261 * If errors are explicitly ignored, returns NULL on failure
1263 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1264 $info = $this->indexInfo( $table, $index, $fname );
1265 if ( is_null( $info ) ) {
1268 return $info !== false;
1274 * Get information about an index into an object
1275 * Returns false if the index does not exist
1277 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1278 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1279 # SHOW INDEX should work for 3.x and up:
1280 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1281 $table = $this->tableName( $table );
1282 $sql = 'SHOW INDEX FROM '.$table;
1283 $res = $this->query( $sql, $fname );
1289 while ( $row = $this->fetchObject( $res ) ) {
1290 if ( $row->Key_name
== $index ) {
1294 $this->freeResult($res);
1296 return empty($result) ?
false : $result;
1300 * Query whether a given table exists
1302 function tableExists( $table ) {
1303 $table = $this->tableName( $table );
1304 $old = $this->ignoreErrors( true );
1305 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1306 $this->ignoreErrors( $old );
1308 $this->freeResult( $res );
1316 * mysql_fetch_field() wrapper
1317 * Returns false if the field doesn't exist
1322 function fieldInfo( $table, $field ) {
1323 $table = $this->tableName( $table );
1324 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1325 $n = mysql_num_fields( $res );
1326 for( $i = 0; $i < $n; $i++
) {
1327 $meta = mysql_fetch_field( $res, $i );
1328 if( $field == $meta->name
) {
1329 return new MySQLField($meta);
1336 * mysql_field_type() wrapper
1338 function fieldType( $res, $index ) {
1339 return mysql_field_type( $res, $index );
1343 * Determines if a given index is unique
1345 function indexUnique( $table, $index ) {
1346 $indexInfo = $this->indexInfo( $table, $index );
1347 if ( !$indexInfo ) {
1350 return !$indexInfo[0]->Non_unique
;
1354 * INSERT wrapper, inserts an array into a table
1356 * $a may be a single associative array, or an array of these with numeric keys, for
1359 * Usually aborts on failure
1360 * If errors are explicitly ignored, returns success
1362 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1363 # No rows to insert, easy just return now
1364 if ( !count( $a ) ) {
1368 $table = $this->tableName( $table );
1369 if ( !is_array( $options ) ) {
1370 $options = array( $options );
1372 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1374 $keys = array_keys( $a[0] );
1377 $keys = array_keys( $a );
1380 $sql = 'INSERT ' . implode( ' ', $options ) .
1381 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1385 foreach ( $a as $row ) {
1391 $sql .= '(' . $this->makeList( $row ) . ')';
1394 $sql .= '(' . $this->makeList( $a ) . ')';
1396 return (bool)$this->query( $sql, $fname );
1400 * Make UPDATE options for the Database::update function
1403 * @param array $options The options passed to Database::update
1406 function makeUpdateOptions( $options ) {
1407 if( !is_array( $options ) ) {
1408 $options = array( $options );
1411 if ( in_array( 'LOW_PRIORITY', $options ) )
1412 $opts[] = $this->lowPriorityOption();
1413 if ( in_array( 'IGNORE', $options ) )
1415 return implode(' ', $opts);
1419 * UPDATE wrapper, takes a condition array and a SET array
1421 * @param string $table The table to UPDATE
1422 * @param array $values An array of values to SET
1423 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1424 * @param string $fname The Class::Function calling this function
1426 * @param array $options An array of UPDATE options, can be one or
1427 * more of IGNORE, LOW_PRIORITY
1429 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1430 $table = $this->tableName( $table );
1431 $opts = $this->makeUpdateOptions( $options );
1432 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1433 if ( $conds != '*' ) {
1434 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1436 $this->query( $sql, $fname );
1440 * Makes an encoded list of strings from an array
1442 * LIST_COMMA - comma separated, no field names
1443 * LIST_AND - ANDed WHERE clause (without the WHERE)
1444 * LIST_OR - ORed WHERE clause (without the WHERE)
1445 * LIST_SET - comma separated with field names, like a SET clause
1446 * LIST_NAMES - comma separated field names
1448 function makeList( $a, $mode = LIST_COMMA
) {
1449 if ( !is_array( $a ) ) {
1450 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1455 foreach ( $a as $field => $value ) {
1457 if ( $mode == LIST_AND
) {
1459 } elseif($mode == LIST_OR
) {
1467 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1468 $list .= "($value)";
1469 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
1471 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array ($value) ) {
1472 $list .= $field." IN (".$this->makeList($value).") ";
1474 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1475 $list .= "$field = ";
1477 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1484 * Change the current database
1486 function selectDB( $db ) {
1487 $this->mDBname
= $db;
1488 return mysql_select_db( $db, $this->mConn
);
1492 * Format a table name ready for use in constructing an SQL query
1494 * This does two important things: it quotes table names which as necessary,
1495 * and it adds a table prefix if there is one.
1497 * All functions of this object which require a table name call this function
1498 * themselves. Pass the canonical name to such functions. This is only needed
1499 * when calling query() directly.
1501 * @param string $name database table name
1503 function tableName( $name ) {
1505 # Skip quoted literals
1506 if ( $name{0} != '`' ) {
1507 if ( $this->mTablePrefix
!== '' && strpos( '.', $name ) === false ) {
1508 $name = "{$this->mTablePrefix}$name";
1510 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1511 $name = "`$wgSharedDB`.`$name`";
1521 * Fetch a number of table names into an array
1522 * This is handy when you need to construct SQL for joins
1525 * extract($dbr->tableNames('user','watchlist'));
1526 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1527 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1529 public function tableNames() {
1530 $inArray = func_get_args();
1532 foreach ( $inArray as $name ) {
1533 $retVal[$name] = $this->tableName( $name );
1539 * Fetch a number of table names into an zero-indexed numerical array
1540 * This is handy when you need to construct SQL for joins
1543 * list( $user, $watchlist ) = $dbr->tableNames('user','watchlist');
1544 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1545 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1547 public function tableNamesN() {
1548 $inArray = func_get_args();
1550 foreach ( $inArray as $name ) {
1551 $retVal[] = $this->tableName( $name );
1559 function tableNamesWithUseIndex( $tables, $use_index ) {
1562 foreach ( $tables as $table )
1563 if ( @$use_index[$table] !== null )
1564 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1566 $ret[] = $this->tableName( $table );
1568 return implode( ',', $ret );
1572 * Wrapper for addslashes()
1573 * @param string $s String to be slashed.
1574 * @return string slashed string.
1576 function strencode( $s ) {
1577 return mysql_real_escape_string( $s, $this->mConn
);
1581 * If it's a string, adds quotes and backslashes
1582 * Otherwise returns as-is
1584 function addQuotes( $s ) {
1585 if ( is_null( $s ) ) {
1588 # This will also quote numeric values. This should be harmless,
1589 # and protects against weird problems that occur when they really
1590 # _are_ strings such as article titles and string->number->string
1591 # conversion is not 1:1.
1592 return "'" . $this->strencode( $s ) . "'";
1597 * Escape string for safe LIKE usage
1599 function escapeLike( $s ) {
1600 $s=$this->strencode( $s );
1601 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1606 * Returns an appropriately quoted sequence value for inserting a new row.
1607 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1608 * subclass will return an integer, and save the value for insertId()
1610 function nextSequenceValue( $seqName ) {
1616 * PostgreSQL doesn't have them and returns ""
1618 function useIndexClause( $index ) {
1619 return "FORCE INDEX ($index)";
1623 * REPLACE query wrapper
1624 * PostgreSQL simulates this with a DELETE followed by INSERT
1625 * $row is the row to insert, an associative array
1626 * $uniqueIndexes is an array of indexes. Each element may be either a
1627 * field name or an array of field names
1629 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1630 * However if you do this, you run the risk of encountering errors which wouldn't have
1633 * @todo migrate comment to phodocumentor format
1635 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1636 $table = $this->tableName( $table );
1639 if ( !is_array( reset( $rows ) ) ) {
1640 $rows = array( $rows );
1643 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1645 foreach ( $rows as $row ) {
1651 $sql .= '(' . $this->makeList( $row ) . ')';
1653 return $this->query( $sql, $fname );
1657 * DELETE where the condition is a join
1658 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1660 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1661 * join condition matches, set $conds='*'
1663 * DO NOT put the join condition in $conds
1665 * @param string $delTable The table to delete from.
1666 * @param string $joinTable The other table.
1667 * @param string $delVar The variable to join on, in the first table.
1668 * @param string $joinVar The variable to join on, in the second table.
1669 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1671 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1673 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1676 $delTable = $this->tableName( $delTable );
1677 $joinTable = $this->tableName( $joinTable );
1678 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1679 if ( $conds != '*' ) {
1680 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1683 return $this->query( $sql, $fname );
1687 * Returns the size of a text field, or -1 for "unlimited"
1689 function textFieldSize( $table, $field ) {
1690 $table = $this->tableName( $table );
1691 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1692 $res = $this->query( $sql, 'Database::textFieldSize' );
1693 $row = $this->fetchObject( $res );
1694 $this->freeResult( $res );
1697 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1706 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1708 function lowPriorityOption() {
1709 return 'LOW_PRIORITY';
1713 * DELETE query wrapper
1715 * Use $conds == "*" to delete all rows
1717 function delete( $table, $conds, $fname = 'Database::delete' ) {
1719 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1721 $table = $this->tableName( $table );
1722 $sql = "DELETE FROM $table";
1723 if ( $conds != '*' ) {
1724 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1726 return $this->query( $sql, $fname );
1730 * INSERT SELECT wrapper
1731 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1732 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1733 * $conds may be "*" to copy the whole table
1734 * srcTable may be an array of tables.
1736 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1737 $insertOptions = array(), $selectOptions = array() )
1739 $destTable = $this->tableName( $destTable );
1740 if ( is_array( $insertOptions ) ) {
1741 $insertOptions = implode( ' ', $insertOptions );
1743 if( !is_array( $selectOptions ) ) {
1744 $selectOptions = array( $selectOptions );
1746 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1747 if( is_array( $srcTable ) ) {
1748 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1750 $srcTable = $this->tableName( $srcTable );
1752 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1753 " SELECT $startOpts " . implode( ',', $varMap ) .
1754 " FROM $srcTable $useIndex ";
1755 if ( $conds != '*' ) {
1756 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1758 $sql .= " $tailOpts";
1759 return $this->query( $sql, $fname );
1763 * Construct a LIMIT query with optional offset
1764 * This is used for query pages
1765 * $sql string SQL query we will append the limit too
1766 * $limit integer the SQL limit
1767 * $offset integer the SQL offset (default false)
1769 function limitResult($sql, $limit, $offset=false) {
1770 if( !is_numeric($limit) ) {
1771 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1773 return " $sql LIMIT "
1774 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1777 function limitResultForUpdate($sql, $num) {
1778 return $this->limitResult($sql, $num, 0);
1782 * Returns an SQL expression for a simple conditional.
1785 * @param string $cond SQL expression which will result in a boolean value
1786 * @param string $trueVal SQL expression to return if true
1787 * @param string $falseVal SQL expression to return if false
1788 * @return string SQL fragment
1790 function conditional( $cond, $trueVal, $falseVal ) {
1791 return " IF($cond, $trueVal, $falseVal) ";
1795 * Determines if the last failure was due to a deadlock
1797 function wasDeadlock() {
1798 return $this->lastErrno() == 1213;
1802 * Perform a deadlock-prone transaction.
1804 * This function invokes a callback function to perform a set of write
1805 * queries. If a deadlock occurs during the processing, the transaction
1806 * will be rolled back and the callback function will be called again.
1809 * $dbw->deadlockLoop( callback, ... );
1811 * Extra arguments are passed through to the specified callback function.
1813 * Returns whatever the callback function returned on its successful,
1814 * iteration, or false on error, for example if the retry limit was
1817 function deadlockLoop() {
1818 $myFname = 'Database::deadlockLoop';
1821 $args = func_get_args();
1822 $function = array_shift( $args );
1823 $oldIgnore = $this->ignoreErrors( true );
1824 $tries = DEADLOCK_TRIES
;
1825 if ( is_array( $function ) ) {
1826 $fname = $function[0];
1831 $retVal = call_user_func_array( $function, $args );
1832 $error = $this->lastError();
1833 $errno = $this->lastErrno();
1834 $sql = $this->lastQuery();
1837 if ( $this->wasDeadlock() ) {
1839 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1841 $this->reportQueryError( $error, $errno, $sql, $fname );
1844 } while( $this->wasDeadlock() && --$tries > 0 );
1845 $this->ignoreErrors( $oldIgnore );
1846 if ( $tries <= 0 ) {
1847 $this->query( 'ROLLBACK', $myFname );
1848 $this->reportQueryError( $error, $errno, $sql, $fname );
1851 $this->query( 'COMMIT', $myFname );
1857 * Do a SELECT MASTER_POS_WAIT()
1859 * @param string $file the binlog file
1860 * @param string $pos the binlog position
1861 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1863 function masterPosWait( $file, $pos, $timeout ) {
1864 $fname = 'Database::masterPosWait';
1865 wfProfileIn( $fname );
1868 # Commit any open transactions
1869 $this->immediateCommit();
1871 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1872 $encFile = $this->strencode( $file );
1873 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1874 $res = $this->doQuery( $sql );
1875 if ( $res && $row = $this->fetchRow( $res ) ) {
1876 $this->freeResult( $res );
1877 wfProfileOut( $fname );
1880 wfProfileOut( $fname );
1886 * Get the position of the master from SHOW SLAVE STATUS
1888 function getSlavePos() {
1889 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1890 $row = $this->fetchObject( $res );
1892 return array( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1894 return array( false, false );
1899 * Get the position of the master from SHOW MASTER STATUS
1901 function getMasterPos() {
1902 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1903 $row = $this->fetchObject( $res );
1905 return array( $row->File
, $row->Position
);
1907 return array( false, false );
1912 * Begin a transaction, committing any previously open transaction
1914 function begin( $fname = 'Database::begin' ) {
1915 $this->query( 'BEGIN', $fname );
1916 $this->mTrxLevel
= 1;
1922 function commit( $fname = 'Database::commit' ) {
1923 $this->query( 'COMMIT', $fname );
1924 $this->mTrxLevel
= 0;
1928 * Rollback a transaction
1930 function rollback( $fname = 'Database::rollback' ) {
1931 $this->query( 'ROLLBACK', $fname );
1932 $this->mTrxLevel
= 0;
1936 * Begin a transaction, committing any previously open transaction
1937 * @deprecated use begin()
1939 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1944 * Commit transaction, if one is open
1945 * @deprecated use commit()
1947 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1952 * Return MW-style timestamp used for MySQL schema
1954 function timestamp( $ts=0 ) {
1955 return wfTimestamp(TS_MW
,$ts);
1959 * Local database timestamp format or null
1961 function timestampOrNull( $ts = null ) {
1962 if( is_null( $ts ) ) {
1965 return $this->timestamp( $ts );
1972 function resultObject( $result ) {
1973 if( empty( $result ) ) {
1976 return new ResultWrapper( $this, $result );
1981 * Return aggregated value alias
1983 function aggregateValue ($valuedata,$valuename='value') {
1988 * @return string wikitext of a link to the server software's web site
1990 function getSoftwareLink() {
1991 return "[http://www.mysql.com/ MySQL]";
1995 * @return string Version information from the database
1997 function getServerVersion() {
1998 return mysql_get_server_info( $this->mConn
);
2002 * Ping the server and try to reconnect if it there is no connection
2005 if( function_exists( 'mysql_ping' ) ) {
2006 return mysql_ping( $this->mConn
);
2008 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
2015 * At the moment, this will only work if the DB user has the PROCESS privilege
2018 $res = $this->query( 'SHOW PROCESSLIST' );
2019 # Find slave SQL thread. Assumed to be the second one running, which is a bit
2020 # dubious, but unfortunately there's no easy rigorous way
2021 while ( $row = $this->fetchObject( $res ) ) {
2022 /* This should work for most situations - when default db
2023 * for thread is not specified, it had no events executed,
2024 * and therefore it doesn't know yet how lagged it is.
2026 * Relay log I/O thread does not select databases.
2028 if ( $row->User
== 'system user' &&
2029 $row->State
!= 'Waiting for master to send event' &&
2030 $row->State
!= 'Connecting to master' &&
2031 $row->State
!= 'Queueing master event to the relay log' &&
2032 $row->State
!= 'Waiting for master update' &&
2033 $row->State
!= 'Requesting binlog dump'
2035 # This is it, return the time (except -ve)
2036 if ( $row->Time
> 0x7fffffff ) {
2047 * Get status information from SHOW STATUS in an associative array
2049 function getStatus($which="%") {
2050 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2052 while ( $row = $this->fetchObject( $res ) ) {
2053 $status[$row->Variable_name
] = $row->Value
;
2059 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2061 function maxListLen() {
2065 function encodeBlob($b) {
2069 function decodeBlob($b) {
2074 * Override database's default connection timeout.
2075 * May be useful for very long batch queries such as
2076 * full-wiki dumps, where a single query reads out
2077 * over hours or days.
2078 * @param int $timeout in seconds
2080 public function setTimeout( $timeout ) {
2081 $this->query( "SET net_read_timeout=$timeout" );
2082 $this->query( "SET net_write_timeout=$timeout" );
2086 * Read and execute SQL commands from a file.
2087 * Returns true on success, error string on failure
2089 function sourceFile( $filename ) {
2090 $fp = fopen( $filename, 'r' );
2091 if ( false === $fp ) {
2092 return "Could not open \"{$filename}\".\n";
2097 $dollarquote = false;
2099 while ( ! feof( $fp ) ) {
2100 $line = trim( fgets( $fp, 1024 ) );
2101 $sl = strlen( $line ) - 1;
2103 if ( $sl < 0 ) { continue; }
2104 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2106 ## Allow dollar quoting for function declarations
2107 if (substr($line,0,4) == '$mw$') {
2109 $dollarquote = false;
2113 $dollarquote = true;
2116 else if (!$dollarquote) {
2117 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
2119 $line = substr( $line, 0, $sl );
2123 if ( '' != $cmd ) { $cmd .= ' '; }
2127 $cmd = str_replace(';;', ";", $cmd);
2128 $cmd = $this->replaceVars( $cmd );
2129 $res = $this->query( $cmd, 'dbsource', true );
2131 if ( false === $res ) {
2132 $err = $this->lastError();
2133 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2145 * Replace variables in sourced SQL
2147 protected function replaceVars( $ins ) {
2149 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2150 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2151 'wgDBadminuser', 'wgDBadminpassword',
2154 // Ordinary variables
2155 foreach ( $varnames as $var ) {
2156 if( isset( $GLOBALS[$var] ) ) {
2157 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2158 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2159 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2160 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2165 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
2166 array( &$this, 'tableNameCallback' ), $ins );
2171 * Table name callback
2174 protected function tableNameCallback( $matches ) {
2175 return $this->tableName( $matches[1] );
2181 * Database abstraction object for mySQL
2182 * Inherit all methods and properties of Database::Database()
2186 class DatabaseMysql
extends Database
{
2192 * Result wrapper for grabbing data queried by someone else
2195 class ResultWrapper
{
2201 function ResultWrapper( &$database, $result ) {
2202 $this->db
=& $database;
2203 $this->result
=& $result;
2209 function numRows() {
2210 return $this->db
->numRows( $this->result
);
2216 function fetchObject() {
2217 return $this->db
->fetchObject( $this->result
);
2223 function fetchRow() {
2224 return $this->db
->fetchRow( $this->result
);
2231 $this->db
->freeResult( $this->result
);
2232 unset( $this->result
);
2236 function seek( $row ) {
2237 $this->db
->dataSeek( $this->result
, $row );
2241 if ($this->numRows()) {
2242 $this->db
->dataSeek($this->result
, 0);