4bfc84b14d5f1239f9f3acda1e7d00e294623783
3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
7 /** Number of times to re-try an operation in case of deadlock */
8 define( 'DEADLOCK_TRIES', 4 );
9 /** Minimum time to wait before retry, in microseconds */
10 define( 'DEADLOCK_DELAY_MIN', 500000 );
11 /** Maximum time to wait before retry */
12 define( 'DEADLOCK_DELAY_MAX', 1500000 );
14 /******************************************************************************
16 *****************************************************************************/
21 function DBObject($data) {
35 private $name, $tablename, $default, $max_length, $nullable,
36 $is_pk, $is_unique, $is_key, $type;
37 function __construct ($info) {
38 $this->name
= $info->name
;
39 $this->tablename
= $info->table
;
40 $this->default = $info->def
;
41 $this->max_length
= $info->max_length
;
42 $this->nullable
= !$info->not_null
;
43 $this->is_pk
= $info->primary_key
;
44 $this->is_unique
= $info->unique_key
;
45 $this->is_multiple
= $info->multiple_key
;
46 $this->is_key
= ($this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
47 $this->type
= $info->type
;
54 function tableName() {
55 return $this->tableName
;
58 function defaultValue() {
59 return $this->default;
62 function maxLength() {
63 return $this->max_length
;
67 return $this->nullable
;
74 function isMultipleKey() {
75 return $this->is_multiple
;
83 /******************************************************************************
85 *****************************************************************************/
88 * Database error base class
90 class DBError
extends MWException
{
94 * Construct a database error
95 * @param Database $db The database object which threw the error
96 * @param string $error A simple error message to be used for debugging
98 function __construct( Database
&$db, $error ) {
100 parent
::__construct( $error );
104 class DBConnectionError
extends DBError
{
107 function __construct( Database
&$db, $error = 'unknown error' ) {
108 $msg = 'DB connection error';
109 if ( trim( $error ) != '' ) {
112 $this->error
= $error;
113 parent
::__construct( $db, $msg );
116 function useOutputPage() {
117 // Not likely to work
121 function useMessageCache() {
122 // Not likely to work
127 return $this->getMessage() . "\n";
130 function getLogMessage() {
131 # Don't send to the exception log
135 function getPageTitle() {
137 return "$wgSitename has a problem";
141 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding;
142 global $wgSitename, $wgServer, $wgMessageCache;
144 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
145 # Hard coding strings instead.
147 $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>";
148 $mainpage = 'Main Page';
149 $searchdisabled = <<<EOT
150 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
151 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
155 <!-- SiteSearch Google -->
156 <FORM method=GET action=\"http://www.google.com/search\">
157 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
158 <A HREF=\"http://www.google.com/\">
159 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
160 border=\"0\" ALT=\"Google\"></A>
163 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
164 <INPUT type=submit name=btnG VALUE=\"Google Search\">
166 <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 />
167 <input type='hidden' name='ie' value='$2'>
168 <input type='hidden' name='oe' value='$2'>
172 <!-- SiteSearch Google -->";
173 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
176 if ( is_object( $wgMessageCache ) ) {
177 $wgMessageCache->disable();
180 if ( trim( $this->error
) == '' ) {
181 $this->error
= $this->db
->getProperty('mServer');
184 $text = str_replace( '$1', $this->error
, $noconnect );
185 $text .= wfGetSiteNotice();
187 if($wgUseFileCache) {
192 $t = Title
::newFromURL( $title );
193 } elseif (@/**/$_REQUEST['search']) {
194 $search = $_REQUEST['search'];
195 return $searchdisabled .
196 str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
197 $wgInputEncoding ), $googlesearch );
199 $t = Title
::newFromText( $mainpage );
203 $cache = new HTMLFileCache( $t );
204 if( $cache->isFileCached() ) {
205 // FIXME: $msg is not defined on the next line.
206 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
207 $cachederror . "</b></p>\n";
209 $tag = '<div id="article">';
213 $cache->fetchPageText() );
221 class DBQueryError
extends DBError
{
222 public $error, $errno, $sql, $fname;
224 function __construct( Database
&$db, $error, $errno, $sql, $fname ) {
225 $message = "A database error has occurred\n" .
227 "Function: $fname\n" .
228 "Error: $errno $error\n";
230 parent
::__construct( $db, $message );
231 $this->error
= $error;
232 $this->errno
= $errno;
234 $this->fname
= $fname;
238 if ( $this->useMessageCache() ) {
239 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
240 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
242 return $this->getMessage();
247 global $wgShowSQLErrors;
248 if( !$wgShowSQLErrors ) {
249 return $this->msg( 'sqlhidden', 'SQL hidden' );
255 function getLogMessage() {
256 # Don't send to the exception log
260 function getPageTitle() {
261 return $this->msg( 'databaseerror', 'Database error' );
265 if ( $this->useMessageCache() ) {
266 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
267 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
269 return nl2br( htmlspecialchars( $this->getMessage() ) );
274 class DBUnexpectedError
extends DBError
{}
276 /******************************************************************************/
279 * Database abstraction object
283 #------------------------------------------------------------------------------
285 #------------------------------------------------------------------------------
287 protected $mLastQuery = '';
289 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
290 protected $mOut, $mOpened = false;
292 protected $mFailFunction;
293 protected $mTablePrefix;
295 protected $mTrxLevel = 0;
296 protected $mErrorCount = 0;
297 protected $mLBInfo = array();
299 #------------------------------------------------------------------------------
301 #------------------------------------------------------------------------------
302 # These optionally set a variable and return the previous state
305 * Fail function, takes a Database as a parameter
306 * Set to false for default, 1 for ignore errors
308 function failFunction( $function = NULL ) {
309 return wfSetVar( $this->mFailFunction
, $function );
313 * Output page, used for reporting errors
314 * FALSE means discard output
316 function setOutputPage( $out ) {
321 * Boolean, controls output of large amounts of debug information
323 function debug( $debug = NULL ) {
324 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
328 * Turns buffering of SQL result sets on (true) or off (false).
329 * Default is "on" and it should not be changed without good reasons.
331 function bufferResults( $buffer = NULL ) {
332 if ( is_null( $buffer ) ) {
333 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
335 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
340 * Turns on (false) or off (true) the automatic generation and sending
341 * of a "we're sorry, but there has been a database error" page on
342 * database errors. Default is on (false). When turned off, the
343 * code should use lastErrno() and lastError() to handle the
344 * situation as appropriate.
346 function ignoreErrors( $ignoreErrors = NULL ) {
347 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
351 * The current depth of nested transactions
352 * @param $level Integer: , default NULL.
354 function trxLevel( $level = NULL ) {
355 return wfSetVar( $this->mTrxLevel
, $level );
359 * Number of errors logged, only useful when errors are ignored
361 function errorCount( $count = NULL ) {
362 return wfSetVar( $this->mErrorCount
, $count );
366 * Properties passed down from the server info array of the load balancer
368 function getLBInfo( $name = NULL ) {
369 if ( is_null( $name ) ) {
370 return $this->mLBInfo
;
372 if ( array_key_exists( $name, $this->mLBInfo
) ) {
373 return $this->mLBInfo
[$name];
380 function setLBInfo( $name, $value = NULL ) {
381 if ( is_null( $value ) ) {
382 $this->mLBInfo
= $name;
384 $this->mLBInfo
[$name] = $value;
389 * Returns true if this database supports (and uses) cascading deletes
391 function cascadingDeletes() {
396 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
398 function cleanupTriggers() {
403 * Returns true if this database is strict about what can be put into an IP field.
404 * Specifically, it uses a NULL value instead of an empty string.
406 function strictIPs() {
411 * Returns true if this database uses timestamps rather than integers
413 function realTimestamps() {
418 * Returns true if this database does an implicit sort when doing GROUP BY
420 function implicitGroupby() {
425 * Returns true if this database can do a native search on IP columns
426 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
428 function searchableIPs() {
435 function lastQuery() { return $this->mLastQuery
; }
436 function isOpen() { return $this->mOpened
; }
439 function setFlag( $flag ) {
440 $this->mFlags |
= $flag;
443 function clearFlag( $flag ) {
444 $this->mFlags
&= ~
$flag;
447 function getFlag( $flag ) {
448 return !!($this->mFlags
& $flag);
452 * General read-only accessor
454 function getProperty( $name ) {
458 #------------------------------------------------------------------------------
460 #------------------------------------------------------------------------------
463 * @param string $server database server host
464 * @param string $user database user name
465 * @param string $password database user password
466 * @param string $dbname database name
470 * @param failFunction
472 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
474 function __construct( $server = false, $user = false, $password = false, $dbName = false,
475 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
477 global $wgOut, $wgDBprefix, $wgCommandLineMode;
478 # Can't get a reference if it hasn't been set yet
479 if ( !isset( $wgOut ) ) {
482 $this->mOut
=& $wgOut;
484 $this->mFailFunction
= $failFunction;
485 $this->mFlags
= $flags;
487 if ( $this->mFlags
& DBO_DEFAULT
) {
488 if ( $wgCommandLineMode ) {
489 $this->mFlags
&= ~DBO_TRX
;
491 $this->mFlags |
= DBO_TRX
;
496 // Faster read-only access
497 if ( wfReadOnly() ) {
498 $this->mFlags |= DBO_PERSISTENT;
499 $this->mFlags &= ~DBO_TRX;
502 /** Get the default table prefix*/
503 if ( $tablePrefix == 'get from global' ) {
504 $this->mTablePrefix
= $wgDBprefix;
506 $this->mTablePrefix
= $tablePrefix;
510 $this->open( $server, $user, $password, $dbName );
516 * @param failFunction
519 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
521 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
525 * Usually aborts on failure
526 * If the failFunction is set to a non-zero integer, returns success
528 function open( $server, $user, $password, $dbName ) {
530 wfProfileIn( __METHOD__
);
532 # Test for missing mysql.so
533 # First try to load it
534 if (!@extension_loaded
('mysql')) {
539 # Otherwise we get a suppressed fatal error, which is very hard to track down
540 if ( !function_exists( 'mysql_connect' ) ) {
541 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
545 $this->mServer
= $server;
546 $this->mUser
= $user;
547 $this->mPassword
= $password;
548 $this->mDBname
= $dbName;
552 wfProfileIn("dbconnect-$server");
554 # LIVE PATCH by Tim, ask Domas for why: retry loop
555 $this->mConn
= false;
557 for ( $i = 0; $i < $max && !$this->mConn
; $i++
) {
561 if ( $this->mFlags
& DBO_PERSISTENT
) {
562 @/**/$this->mConn
= mysql_pconnect( $server, $user, $password );
564 # Create a new connection...
565 @/**/$this->mConn
= mysql_connect( $server, $user, $password, true );
567 if ($this->mConn
=== false) {
569 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
573 wfProfileOut("dbconnect-$server");
575 if ( $dbName != '' ) {
576 if ( $this->mConn
!== false ) {
577 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
579 $error = "Error selecting database $dbName on server {$this->mServer} " .
580 "from client host {$wguname['nodename']}\n";
581 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
585 wfDebug( "DB connection error\n" );
586 wfDebug( "Server: $server, User: $user, Password: " .
587 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
592 $success = (bool)$this->mConn
;
598 // Tell the server we're communicating with it in UTF-8.
599 // This may engage various charset conversions.
600 $this->query( 'SET NAMES utf8' );
603 $this->reportConnectionError();
606 $this->mOpened
= $success;
607 wfProfileOut( __METHOD__
);
613 * Closes a database connection.
614 * if it is open : commits any open transactions
616 * @return bool operation success. true if already closed.
620 $this->mOpened
= false;
621 if ( $this->mConn
) {
622 if ( $this->trxLevel() ) {
623 $this->immediateCommit();
625 return mysql_close( $this->mConn
);
632 * @param string $error fallback error message, used if none is given by MySQL
634 function reportConnectionError( $error = 'Unknown error' ) {
635 $myError = $this->lastError();
640 if ( $this->mFailFunction
) {
641 # Legacy error handling method
642 if ( !is_int( $this->mFailFunction
) ) {
643 $ff = $this->mFailFunction
;
644 $ff( $this, $error );
648 wfLogDBError( "Connection error: $error\n" );
649 throw new DBConnectionError( $this, $error );
654 * Usually aborts on failure
655 * If errors are explicitly ignored, returns success
657 function query( $sql, $fname = '', $tempIgnore = false ) {
660 if ( $wgProfiling ) {
661 # generalizeSQL will probably cut down the query to reasonable
662 # logging size most of the time. The substr is really just a sanity check.
664 # Who's been wasting my precious column space? -- TS
665 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
667 if ( is_null( $this->getLBInfo( 'master' ) ) ) {
668 $queryProf = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
669 $totalProf = 'Database::query';
671 $queryProf = 'query-m: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
672 $totalProf = 'Database::query-master';
674 wfProfileIn( $totalProf );
675 wfProfileIn( $queryProf );
678 $this->mLastQuery
= $sql;
680 # Add a comment for easy SHOW PROCESSLIST interpretation
682 $commentedSql = preg_replace('/\s/', " /* $fname */ ", $sql, 1);
684 $commentedSql = $sql;
687 # If DBO_TRX is set, start a transaction
688 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
689 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK'
694 if ( $this->debug() ) {
695 $sqlx = substr( $commentedSql, 0, 500 );
696 $sqlx = strtr( $sqlx, "\t\n", ' ' );
697 wfDebug( "SQL: $sqlx\n" );
700 # Do the query and handle errors
701 $ret = $this->doQuery( $commentedSql );
703 # Try reconnecting if the connection was lost
704 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
705 # Transaction is gone, like it or not
706 $this->mTrxLevel
= 0;
707 wfDebug( "Connection lost, reconnecting...\n" );
708 if ( $this->ping() ) {
709 wfDebug( "Reconnected\n" );
710 $sqlx = substr( $commentedSql, 0, 500 );
711 $sqlx = strtr( $sqlx, "\t\n", ' ' );
712 global $wgRequestTime;
713 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
714 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
715 $ret = $this->doQuery( $commentedSql );
717 wfDebug( "Failed\n" );
721 if ( false === $ret ) {
722 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
725 if ( $wgProfiling ) {
726 wfProfileOut( $queryProf );
727 wfProfileOut( $totalProf );
733 * The DBMS-dependent part of query()
734 * @param string $sql SQL query.
736 function doQuery( $sql ) {
737 if( $this->bufferResults() ) {
738 $ret = mysql_query( $sql, $this->mConn
);
740 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
749 * @param string $fname
750 * @param bool $tempIgnore
752 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
753 global $wgCommandLineMode;
754 # Ignore errors during error handling to avoid infinite recursion
755 $ignore = $this->ignoreErrors( true );
756 ++
$this->mErrorCount
;
758 if( $ignore ||
$tempIgnore ) {
759 wfDebug("SQL ERROR (ignored): $error\n");
760 $this->ignoreErrors( $ignore );
762 $sql1line = str_replace( "\n", "\\n", $sql );
763 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
764 wfDebug("SQL ERROR: " . $error . "\n");
765 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
771 * Intended to be compatible with the PEAR::DB wrapper functions.
772 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
774 * ? = scalar value, quoted as necessary
775 * ! = raw SQL bit (a function for instance)
776 * & = filename; reads the file and inserts as a blob
777 * (we don't use this though...)
779 function prepare( $sql, $func = 'Database::prepare' ) {
780 /* MySQL doesn't support prepared statements (yet), so just
781 pack up the query for reference. We'll manually replace
783 return array( 'query' => $sql, 'func' => $func );
786 function freePrepared( $prepared ) {
787 /* No-op for MySQL */
791 * Execute a prepared query with the various arguments
792 * @param string $prepared the prepared sql
793 * @param mixed $args Either an array here, or put scalars as varargs
795 function execute( $prepared, $args = null ) {
796 if( !is_array( $args ) ) {
798 $args = func_get_args();
799 array_shift( $args );
801 $sql = $this->fillPrepared( $prepared['query'], $args );
802 return $this->query( $sql, $prepared['func'] );
806 * Prepare & execute an SQL statement, quoting and inserting arguments
807 * in the appropriate places.
808 * @param string $query
809 * @param string $args ...
811 function safeQuery( $query, $args = null ) {
812 $prepared = $this->prepare( $query, 'Database::safeQuery' );
813 if( !is_array( $args ) ) {
815 $args = func_get_args();
816 array_shift( $args );
818 $retval = $this->execute( $prepared, $args );
819 $this->freePrepared( $prepared );
824 * For faking prepared SQL statements on DBs that don't support
826 * @param string $preparedSql - a 'preparable' SQL statement
827 * @param array $args - array of arguments to fill it with
828 * @return string executable SQL
830 function fillPrepared( $preparedQuery, $args ) {
832 $this->preparedArgs
=& $args;
833 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
834 array( &$this, 'fillPreparedArg' ), $preparedQuery );
838 * preg_callback func for fillPrepared()
839 * The arguments should be in $this->preparedArgs and must not be touched
840 * while we're doing this.
842 * @param array $matches
846 function fillPreparedArg( $matches ) {
847 switch( $matches[1] ) {
848 case '\\?': return '?';
849 case '\\!': return '!';
850 case '\\&': return '&';
852 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
853 switch( $matches[1] ) {
854 case '?': return $this->addQuotes( $arg );
855 case '!': return $arg;
857 # return $this->addQuotes( file_get_contents( $arg ) );
858 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
860 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
865 * @param mixed $res A SQL result
868 * Free a result object
870 function freeResult( $res ) {
871 if ( !@/**/mysql_free_result( $res ) ) {
872 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
877 * Fetch the next row from the given result object, in object form
879 function fetchObject( $res ) {
880 @/**/$row = mysql_fetch_object( $res );
881 if( $this->lastErrno() ) {
882 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
888 * Fetch the next row from the given result object
891 function fetchRow( $res ) {
892 @/**/$row = mysql_fetch_array( $res );
893 if ( $this->lastErrno() ) {
894 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
900 * Get the number of rows in a result object
902 function numRows( $res ) {
903 @/**/$n = mysql_num_rows( $res );
904 if( $this->lastErrno() ) {
905 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
911 * Get the number of fields in a result object
912 * See documentation for mysql_num_fields()
914 function numFields( $res ) { return mysql_num_fields( $res ); }
917 * Get a field name in a result object
918 * See documentation for mysql_field_name():
919 * http://www.php.net/mysql_field_name
921 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
924 * Get the inserted value of an auto-increment row
926 * The value inserted should be fetched from nextSequenceValue()
929 * $id = $dbw->nextSequenceValue('page_page_id_seq');
930 * $dbw->insert('page',array('page_id' => $id));
931 * $id = $dbw->insertId();
933 function insertId() { return mysql_insert_id( $this->mConn
); }
936 * Change the position of the cursor in a result object
937 * See mysql_data_seek()
939 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
942 * Get the last error number
945 function lastErrno() {
946 if ( $this->mConn
) {
947 return mysql_errno( $this->mConn
);
949 return mysql_errno();
954 * Get a description of the last error
955 * See mysql_error() for more details
957 function lastError() {
958 if ( $this->mConn
) {
959 # Even if it's non-zero, it can still be invalid
960 wfSuppressWarnings();
961 $error = mysql_error( $this->mConn
);
963 $error = mysql_error();
967 $error = mysql_error();
970 $error .= ' (' . $this->mServer
. ')';
975 * Get the number of rows affected by the last write query
976 * See mysql_affected_rows() for more details
978 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
979 /**#@-*/ // end of template : @param $result
982 * Simple UPDATE wrapper
983 * Usually aborts on failure
984 * If errors are explicitly ignored, returns success
986 * This function exists for historical reasons, Database::update() has a more standard
987 * calling convention and feature set
989 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
991 $table = $this->tableName( $table );
992 $sql = "UPDATE $table SET $var = '" .
993 $this->strencode( $value ) . "' WHERE ($cond)";
994 return (bool)$this->query( $sql, $fname );
998 * Simple SELECT wrapper, returns a single field, input must be encoded
999 * Usually aborts on failure
1000 * If errors are explicitly ignored, returns FALSE on failure
1002 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
1003 if ( !is_array( $options ) ) {
1004 $options = array( $options );
1006 $options['LIMIT'] = 1;
1008 $res = $this->select( $table, $var, $cond, $fname, $options );
1009 if ( $res === false ||
!$this->numRows( $res ) ) {
1012 $row = $this->fetchRow( $res );
1013 if ( $row !== false ) {
1014 $this->freeResult( $res );
1022 * Returns an optional USE INDEX clause to go after the table, and a
1023 * string to go at the end of the query
1027 * @param array $options an associative array of options to be turned into
1028 * an SQL query, valid keys are listed in the function.
1031 function makeSelectOptions( $options ) {
1032 $preLimitTail = $postLimitTail = '';
1035 $noKeyOptions = array();
1036 foreach ( $options as $key => $option ) {
1037 if ( is_numeric( $key ) ) {
1038 $noKeyOptions[$option] = true;
1042 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1043 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1045 //if (isset($options['LIMIT'])) {
1046 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1047 // isset($options['OFFSET']) ? $options['OFFSET']
1051 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1052 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1053 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1055 # Various MySQL extensions
1056 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
1057 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
1058 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
1059 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
1060 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
1061 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
1062 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
1063 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
1065 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1066 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1071 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1077 * @param mixed $table Array or string, table name(s) (prefix auto-added)
1078 * @param mixed $vars Array or string, field name(s) to be retrieved
1079 * @param mixed $conds Array or string, condition(s) for WHERE
1080 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1081 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1082 * see Database::makeSelectOptions code for list of supported stuff
1083 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
1085 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
1087 if( is_array( $vars ) ) {
1088 $vars = implode( ',', $vars );
1090 if( !is_array( $options ) ) {
1091 $options = array( $options );
1093 if( is_array( $table ) ) {
1094 if ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1095 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
1097 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1098 } elseif ($table!='') {
1099 if ($table{0}==' ') {
1100 $from = ' FROM ' . $table;
1102 $from = ' FROM ' . $this->tableName( $table );
1108 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1110 if( !empty( $conds ) ) {
1111 if ( is_array( $conds ) ) {
1112 $conds = $this->makeList( $conds, LIST_AND
);
1114 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1116 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1119 if (isset($options['LIMIT']))
1120 $sql = $this->limitResult($sql, $options['LIMIT'],
1121 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
1122 $sql = "$sql $postLimitTail";
1124 return $this->query( $sql, $fname );
1128 * Single row SELECT wrapper
1129 * Aborts or returns FALSE on error
1131 * $vars: the selected variables
1132 * $conds: a condition map, terms are ANDed together.
1133 * Items with numeric keys are taken to be literal conditions
1134 * Takes an array of selected variables, and a condition map, which is ANDed
1135 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1136 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1137 * $obj- >page_id is the ID of the Astronomy article
1139 * @todo migrate documentation to phpdocumentor format
1141 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
1142 $options['LIMIT'] = 1;
1143 $res = $this->select( $table, $vars, $conds, $fname, $options );
1144 if ( $res === false )
1146 if ( !$this->numRows($res) ) {
1147 $this->freeResult($res);
1150 $obj = $this->fetchObject( $res );
1151 $this->freeResult( $res );
1157 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1158 * It's only slightly flawed. Don't use for anything important.
1160 * @param string $sql A SQL Query
1163 static function generalizeSQL( $sql ) {
1164 # This does the same as the regexp below would do, but in such a way
1165 # as to avoid crashing php on some large strings.
1166 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1168 $sql = str_replace ( "\\\\", '', $sql);
1169 $sql = str_replace ( "\\'", '', $sql);
1170 $sql = str_replace ( "\\\"", '', $sql);
1171 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1172 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1174 # All newlines, tabs, etc replaced by single space
1175 $sql = preg_replace ( '/\s+/', ' ', $sql);
1178 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1184 * Determines whether a field exists in a table
1185 * Usually aborts on failure
1186 * If errors are explicitly ignored, returns NULL on failure
1188 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1189 $table = $this->tableName( $table );
1190 $res = $this->query( 'DESCRIBE '.$table, $fname );
1197 while ( $row = $this->fetchObject( $res ) ) {
1198 if ( $row->Field
== $field ) {
1207 * Determines whether an index exists
1208 * Usually aborts on failure
1209 * If errors are explicitly ignored, returns NULL on failure
1211 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1212 $info = $this->indexInfo( $table, $index, $fname );
1213 if ( is_null( $info ) ) {
1216 return $info !== false;
1222 * Get information about an index into an object
1223 * Returns false if the index does not exist
1225 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1226 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1227 # SHOW INDEX should work for 3.x and up:
1228 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1229 $table = $this->tableName( $table );
1230 $sql = 'SHOW INDEX FROM '.$table;
1231 $res = $this->query( $sql, $fname );
1237 while ( $row = $this->fetchObject( $res ) ) {
1238 if ( $row->Key_name
== $index ) {
1242 $this->freeResult($res);
1244 return empty($result) ?
false : $result;
1248 * Query whether a given table exists
1250 function tableExists( $table ) {
1251 $table = $this->tableName( $table );
1252 $old = $this->ignoreErrors( true );
1253 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1254 $this->ignoreErrors( $old );
1256 $this->freeResult( $res );
1264 * mysql_fetch_field() wrapper
1265 * Returns false if the field doesn't exist
1270 function fieldInfo( $table, $field ) {
1271 $table = $this->tableName( $table );
1272 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1273 $n = mysql_num_fields( $res );
1274 for( $i = 0; $i < $n; $i++
) {
1275 $meta = mysql_fetch_field( $res, $i );
1276 if( $field == $meta->name
) {
1277 return new MySQLField($meta);
1284 * mysql_field_type() wrapper
1286 function fieldType( $res, $index ) {
1287 return mysql_field_type( $res, $index );
1291 * Determines if a given index is unique
1293 function indexUnique( $table, $index ) {
1294 $indexInfo = $this->indexInfo( $table, $index );
1295 if ( !$indexInfo ) {
1298 return !$indexInfo[0]->Non_unique
;
1302 * INSERT wrapper, inserts an array into a table
1304 * $a may be a single associative array, or an array of these with numeric keys, for
1307 * Usually aborts on failure
1308 * If errors are explicitly ignored, returns success
1310 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1311 # No rows to insert, easy just return now
1312 if ( !count( $a ) ) {
1316 $table = $this->tableName( $table );
1317 if ( !is_array( $options ) ) {
1318 $options = array( $options );
1320 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1322 $keys = array_keys( $a[0] );
1325 $keys = array_keys( $a );
1328 $sql = 'INSERT ' . implode( ' ', $options ) .
1329 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1333 foreach ( $a as $row ) {
1339 $sql .= '(' . $this->makeList( $row ) . ')';
1342 $sql .= '(' . $this->makeList( $a ) . ')';
1344 return (bool)$this->query( $sql, $fname );
1348 * Make UPDATE options for the Database::update function
1351 * @param array $options The options passed to Database::update
1354 function makeUpdateOptions( $options ) {
1355 if( !is_array( $options ) ) {
1356 $options = array( $options );
1359 if ( in_array( 'LOW_PRIORITY', $options ) )
1360 $opts[] = $this->lowPriorityOption();
1361 if ( in_array( 'IGNORE', $options ) )
1363 return implode(' ', $opts);
1367 * UPDATE wrapper, takes a condition array and a SET array
1369 * @param string $table The table to UPDATE
1370 * @param array $values An array of values to SET
1371 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1372 * @param string $fname The Class::Function calling this function
1374 * @param array $options An array of UPDATE options, can be one or
1375 * more of IGNORE, LOW_PRIORITY
1377 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1378 $table = $this->tableName( $table );
1379 $opts = $this->makeUpdateOptions( $options );
1380 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1381 if ( $conds != '*' ) {
1382 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1384 $this->query( $sql, $fname );
1388 * Makes an encoded list of strings from an array
1390 * LIST_COMMA - comma separated, no field names
1391 * LIST_AND - ANDed WHERE clause (without the WHERE)
1392 * LIST_OR - ORed WHERE clause (without the WHERE)
1393 * LIST_SET - comma separated with field names, like a SET clause
1394 * LIST_NAMES - comma separated field names
1396 function makeList( $a, $mode = LIST_COMMA
) {
1397 if ( !is_array( $a ) ) {
1398 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1403 foreach ( $a as $field => $value ) {
1405 if ( $mode == LIST_AND
) {
1407 } elseif($mode == LIST_OR
) {
1415 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1416 $list .= "($value)";
1417 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
1419 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array ($value) ) {
1420 $list .= $field." IN (".$this->makeList($value).") ";
1422 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1423 $list .= "$field = ";
1425 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1432 * Change the current database
1434 function selectDB( $db ) {
1435 $this->mDBname
= $db;
1436 return mysql_select_db( $db, $this->mConn
);
1440 * Format a table name ready for use in constructing an SQL query
1442 * This does two important things: it quotes table names which as necessary,
1443 * and it adds a table prefix if there is one.
1445 * All functions of this object which require a table name call this function
1446 * themselves. Pass the canonical name to such functions. This is only needed
1447 * when calling query() directly.
1449 * @param string $name database table name
1451 function tableName( $name ) {
1453 # Skip quoted literals
1454 if ( $name{0} != '`' ) {
1455 if ( $this->mTablePrefix
!== '' && strpos( '.', $name ) === false ) {
1456 $name = "{$this->mTablePrefix}$name";
1458 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1459 $name = "`$wgSharedDB`.`$name`";
1469 * Fetch a number of table names into an array
1470 * This is handy when you need to construct SQL for joins
1473 * extract($dbr->tableNames('user','watchlist'));
1474 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1475 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1477 public function tableNames() {
1478 $inArray = func_get_args();
1480 foreach ( $inArray as $name ) {
1481 $retVal[$name] = $this->tableName( $name );
1487 * @desc: Fetch a number of table names into an zero-indexed numerical array
1488 * This is handy when you need to construct SQL for joins
1491 * list( $user, $watchlist ) = $dbr->tableNames('user','watchlist');
1492 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1493 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1495 public function tableNamesN() {
1496 $inArray = func_get_args();
1498 foreach ( $inArray as $name ) {
1499 $retVal[] = $this->tableName( $name );
1507 function tableNamesWithUseIndex( $tables, $use_index ) {
1510 foreach ( $tables as $table )
1511 if ( @$use_index[$table] !== null )
1512 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1514 $ret[] = $this->tableName( $table );
1516 return implode( ',', $ret );
1520 * Wrapper for addslashes()
1521 * @param string $s String to be slashed.
1522 * @return string slashed string.
1524 function strencode( $s ) {
1525 return mysql_real_escape_string( $s, $this->mConn
);
1529 * If it's a string, adds quotes and backslashes
1530 * Otherwise returns as-is
1532 function addQuotes( $s ) {
1533 if ( is_null( $s ) ) {
1536 # This will also quote numeric values. This should be harmless,
1537 # and protects against weird problems that occur when they really
1538 # _are_ strings such as article titles and string->number->string
1539 # conversion is not 1:1.
1540 return "'" . $this->strencode( $s ) . "'";
1545 * Escape string for safe LIKE usage
1547 function escapeLike( $s ) {
1548 $s=$this->strencode( $s );
1549 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1554 * Returns an appropriately quoted sequence value for inserting a new row.
1555 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1556 * subclass will return an integer, and save the value for insertId()
1558 function nextSequenceValue( $seqName ) {
1564 * PostgreSQL doesn't have them and returns ""
1566 function useIndexClause( $index ) {
1567 return "FORCE INDEX ($index)";
1571 * REPLACE query wrapper
1572 * PostgreSQL simulates this with a DELETE followed by INSERT
1573 * $row is the row to insert, an associative array
1574 * $uniqueIndexes is an array of indexes. Each element may be either a
1575 * field name or an array of field names
1577 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1578 * However if you do this, you run the risk of encountering errors which wouldn't have
1581 * @todo migrate comment to phodocumentor format
1583 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1584 $table = $this->tableName( $table );
1587 if ( !is_array( reset( $rows ) ) ) {
1588 $rows = array( $rows );
1591 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1593 foreach ( $rows as $row ) {
1599 $sql .= '(' . $this->makeList( $row ) . ')';
1601 return $this->query( $sql, $fname );
1605 * DELETE where the condition is a join
1606 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1608 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1609 * join condition matches, set $conds='*'
1611 * DO NOT put the join condition in $conds
1613 * @param string $delTable The table to delete from.
1614 * @param string $joinTable The other table.
1615 * @param string $delVar The variable to join on, in the first table.
1616 * @param string $joinVar The variable to join on, in the second table.
1617 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1619 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1621 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1624 $delTable = $this->tableName( $delTable );
1625 $joinTable = $this->tableName( $joinTable );
1626 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1627 if ( $conds != '*' ) {
1628 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1631 return $this->query( $sql, $fname );
1635 * Returns the size of a text field, or -1 for "unlimited"
1637 function textFieldSize( $table, $field ) {
1638 $table = $this->tableName( $table );
1639 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1640 $res = $this->query( $sql, 'Database::textFieldSize' );
1641 $row = $this->fetchObject( $res );
1642 $this->freeResult( $res );
1645 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1654 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1656 function lowPriorityOption() {
1657 return 'LOW_PRIORITY';
1661 * DELETE query wrapper
1663 * Use $conds == "*" to delete all rows
1665 function delete( $table, $conds, $fname = 'Database::delete' ) {
1667 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1669 $table = $this->tableName( $table );
1670 $sql = "DELETE FROM $table";
1671 if ( $conds != '*' ) {
1672 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1674 return $this->query( $sql, $fname );
1678 * INSERT SELECT wrapper
1679 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1680 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1681 * $conds may be "*" to copy the whole table
1682 * srcTable may be an array of tables.
1684 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1685 $insertOptions = array(), $selectOptions = array() )
1687 $destTable = $this->tableName( $destTable );
1688 if ( is_array( $insertOptions ) ) {
1689 $insertOptions = implode( ' ', $insertOptions );
1691 if( !is_array( $selectOptions ) ) {
1692 $selectOptions = array( $selectOptions );
1694 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1695 if( is_array( $srcTable ) ) {
1696 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1698 $srcTable = $this->tableName( $srcTable );
1700 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1701 " SELECT $startOpts " . implode( ',', $varMap ) .
1702 " FROM $srcTable $useIndex ";
1703 if ( $conds != '*' ) {
1704 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1706 $sql .= " $tailOpts";
1707 return $this->query( $sql, $fname );
1711 * Construct a LIMIT query with optional offset
1712 * This is used for query pages
1713 * $sql string SQL query we will append the limit too
1714 * $limit integer the SQL limit
1715 * $offset integer the SQL offset (default false)
1717 function limitResult($sql, $limit, $offset=false) {
1718 if( !is_numeric($limit) ) {
1719 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1721 return " $sql LIMIT "
1722 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1725 function limitResultForUpdate($sql, $num) {
1726 return $this->limitResult($sql, $num, 0);
1730 * Returns an SQL expression for a simple conditional.
1733 * @param string $cond SQL expression which will result in a boolean value
1734 * @param string $trueVal SQL expression to return if true
1735 * @param string $falseVal SQL expression to return if false
1736 * @return string SQL fragment
1738 function conditional( $cond, $trueVal, $falseVal ) {
1739 return " IF($cond, $trueVal, $falseVal) ";
1743 * Determines if the last failure was due to a deadlock
1745 function wasDeadlock() {
1746 return $this->lastErrno() == 1213;
1750 * Perform a deadlock-prone transaction.
1752 * This function invokes a callback function to perform a set of write
1753 * queries. If a deadlock occurs during the processing, the transaction
1754 * will be rolled back and the callback function will be called again.
1757 * $dbw->deadlockLoop( callback, ... );
1759 * Extra arguments are passed through to the specified callback function.
1761 * Returns whatever the callback function returned on its successful,
1762 * iteration, or false on error, for example if the retry limit was
1765 function deadlockLoop() {
1766 $myFname = 'Database::deadlockLoop';
1769 $args = func_get_args();
1770 $function = array_shift( $args );
1771 $oldIgnore = $this->ignoreErrors( true );
1772 $tries = DEADLOCK_TRIES
;
1773 if ( is_array( $function ) ) {
1774 $fname = $function[0];
1779 $retVal = call_user_func_array( $function, $args );
1780 $error = $this->lastError();
1781 $errno = $this->lastErrno();
1782 $sql = $this->lastQuery();
1785 if ( $this->wasDeadlock() ) {
1787 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1789 $this->reportQueryError( $error, $errno, $sql, $fname );
1792 } while( $this->wasDeadlock() && --$tries > 0 );
1793 $this->ignoreErrors( $oldIgnore );
1794 if ( $tries <= 0 ) {
1795 $this->query( 'ROLLBACK', $myFname );
1796 $this->reportQueryError( $error, $errno, $sql, $fname );
1799 $this->query( 'COMMIT', $myFname );
1805 * Do a SELECT MASTER_POS_WAIT()
1807 * @param string $file the binlog file
1808 * @param string $pos the binlog position
1809 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1811 function masterPosWait( $file, $pos, $timeout ) {
1812 $fname = 'Database::masterPosWait';
1813 wfProfileIn( $fname );
1816 # Commit any open transactions
1817 $this->immediateCommit();
1819 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1820 $encFile = $this->strencode( $file );
1821 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1822 $res = $this->doQuery( $sql );
1823 if ( $res && $row = $this->fetchRow( $res ) ) {
1824 $this->freeResult( $res );
1825 wfProfileOut( $fname );
1828 wfProfileOut( $fname );
1834 * Get the position of the master from SHOW SLAVE STATUS
1836 function getSlavePos() {
1837 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1838 $row = $this->fetchObject( $res );
1840 return array( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1842 return array( false, false );
1847 * Get the position of the master from SHOW MASTER STATUS
1849 function getMasterPos() {
1850 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1851 $row = $this->fetchObject( $res );
1853 return array( $row->File
, $row->Position
);
1855 return array( false, false );
1860 * Begin a transaction, committing any previously open transaction
1862 function begin( $fname = 'Database::begin' ) {
1863 $this->query( 'BEGIN', $fname );
1864 $this->mTrxLevel
= 1;
1870 function commit( $fname = 'Database::commit' ) {
1871 $this->query( 'COMMIT', $fname );
1872 $this->mTrxLevel
= 0;
1876 * Rollback a transaction
1878 function rollback( $fname = 'Database::rollback' ) {
1879 $this->query( 'ROLLBACK', $fname );
1880 $this->mTrxLevel
= 0;
1884 * Begin a transaction, committing any previously open transaction
1885 * @deprecated use begin()
1887 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1892 * Commit transaction, if one is open
1893 * @deprecated use commit()
1895 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1900 * Return MW-style timestamp used for MySQL schema
1902 function timestamp( $ts=0 ) {
1903 return wfTimestamp(TS_MW
,$ts);
1907 * Local database timestamp format or null
1909 function timestampOrNull( $ts = null ) {
1910 if( is_null( $ts ) ) {
1913 return $this->timestamp( $ts );
1920 function resultObject( $result ) {
1921 if( empty( $result ) ) {
1924 return new ResultWrapper( $this, $result );
1929 * Return aggregated value alias
1931 function aggregateValue ($valuedata,$valuename='value') {
1936 * @return string wikitext of a link to the server software's web site
1938 function getSoftwareLink() {
1939 return "[http://www.mysql.com/ MySQL]";
1943 * @return string Version information from the database
1945 function getServerVersion() {
1946 return mysql_get_server_info( $this->mConn
);
1950 * Ping the server and try to reconnect if it there is no connection
1953 if( function_exists( 'mysql_ping' ) ) {
1954 return mysql_ping( $this->mConn
);
1956 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1963 * At the moment, this will only work if the DB user has the PROCESS privilege
1966 $res = $this->query( 'SHOW PROCESSLIST' );
1967 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1968 # dubious, but unfortunately there's no easy rigorous way
1969 while ( $row = $this->fetchObject( $res ) ) {
1970 /* This should work for most situations - when default db
1971 * for thread is not specified, it had no events executed,
1972 * and therefore it doesn't know yet how lagged it is.
1974 * Relay log I/O thread does not select databases.
1976 if ( $row->User
== 'system user' &&
1977 $row->State
!= 'Waiting for master to send event' &&
1978 $row->State
!= 'Connecting to master' &&
1979 $row->State
!= 'Queueing master event to the relay log' &&
1980 $row->State
!= 'Waiting for master update' &&
1981 $row->State
!= 'Requesting binlog dump'
1983 # This is it, return the time (except -ve)
1984 if ( $row->Time
> 0x7fffffff ) {
1995 * Get status information from SHOW STATUS in an associative array
1997 function getStatus($which="%") {
1998 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2000 while ( $row = $this->fetchObject( $res ) ) {
2001 $status[$row->Variable_name
] = $row->Value
;
2007 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2009 function maxListLen() {
2013 function encodeBlob($b) {
2017 function decodeBlob($b) {
2022 * Override database's default connection timeout.
2023 * May be useful for very long batch queries such as
2024 * full-wiki dumps, where a single query reads out
2025 * over hours or days.
2026 * @param int $timeout in seconds
2028 public function setTimeout( $timeout ) {
2029 $this->query( "SET net_read_timeout=$timeout" );
2030 $this->query( "SET net_write_timeout=$timeout" );
2034 * Read and execute SQL commands from a file.
2035 * Returns true on success, error string on failure
2037 function sourceFile( $filename ) {
2038 $fp = fopen( $filename, 'r' );
2039 if ( false === $fp ) {
2040 return "Could not open \"{$filename}\".\n";
2045 $dollarquote = false;
2047 while ( ! feof( $fp ) ) {
2048 $line = trim( fgets( $fp, 1024 ) );
2049 $sl = strlen( $line ) - 1;
2051 if ( $sl < 0 ) { continue; }
2052 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2054 ## Allow dollar quoting for function declarations
2055 if (substr($line,0,4) == '$mw$') {
2057 $dollarquote = false;
2061 $dollarquote = true;
2064 else if (!$dollarquote) {
2065 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
2067 $line = substr( $line, 0, $sl );
2071 if ( '' != $cmd ) { $cmd .= ' '; }
2075 $cmd = str_replace(';;', ";", $cmd);
2076 $cmd = $this->replaceVars( $cmd );
2077 $res = $this->query( $cmd, 'dbsource', true );
2079 if ( false === $res ) {
2080 $err = $this->lastError();
2081 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2093 * Replace variables in sourced SQL
2095 protected function replaceVars( $ins ) {
2097 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2098 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2099 'wgDBadminuser', 'wgDBadminpassword',
2102 // Ordinary variables
2103 foreach ( $varnames as $var ) {
2104 if( isset( $GLOBALS[$var] ) ) {
2105 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2106 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2107 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2108 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2113 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
2114 array( &$this, 'tableNameCallback' ), $ins );
2119 * Table name callback
2122 protected function tableNameCallback( $matches ) {
2123 return $this->tableName( $matches[1] );
2129 * Database abstraction object for mySQL
2130 * Inherit all methods and properties of Database::Database()
2134 class DatabaseMysql
extends Database
{
2140 * Result wrapper for grabbing data queried by someone else
2143 class ResultWrapper
{
2149 function ResultWrapper( &$database, $result ) {
2150 $this->db
=& $database;
2151 $this->result
=& $result;
2157 function numRows() {
2158 return $this->db
->numRows( $this->result
);
2164 function fetchObject() {
2165 return $this->db
->fetchObject( $this->result
);
2171 function fetchRow() {
2172 return $this->db
->fetchRow( $this->result
);
2179 $this->db
->freeResult( $this->result
);
2180 unset( $this->result
);
2184 function seek( $row ) {
2185 $this->db
->dataSeek( $this->result
, $row );
2189 if ($this->numRows()) {
2190 $this->db
->dataSeek($this->result
, 0);