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__
);
616 * Closes a database connection.
617 * if it is open : commits any open transactions
619 * @return bool operation success. true if already closed.
623 $this->mOpened
= false;
624 if ( $this->mConn
) {
625 if ( $this->trxLevel() ) {
626 $this->immediateCommit();
628 return mysql_close( $this->mConn
);
635 * @param string $error fallback error message, used if none is given by MySQL
637 function reportConnectionError( $error = 'Unknown error' ) {
638 $myError = $this->lastError();
643 if ( $this->mFailFunction
) {
644 # Legacy error handling method
645 if ( !is_int( $this->mFailFunction
) ) {
646 $ff = $this->mFailFunction
;
647 $ff( $this, $error );
651 wfLogDBError( "Connection error: $error\n" );
652 throw new DBConnectionError( $this, $error );
657 * Usually aborts on failure
658 * If errors are explicitly ignored, returns success
660 function query( $sql, $fname = '', $tempIgnore = false ) {
663 if ( $wgProfiling ) {
664 # generalizeSQL will probably cut down the query to reasonable
665 # logging size most of the time. The substr is really just a sanity check.
667 # Who's been wasting my precious column space? -- TS
668 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
670 if ( is_null( $this->getLBInfo( 'master' ) ) ) {
671 $queryProf = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
672 $totalProf = 'Database::query';
674 $queryProf = 'query-m: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
675 $totalProf = 'Database::query-master';
677 wfProfileIn( $totalProf );
678 wfProfileIn( $queryProf );
681 $this->mLastQuery
= $sql;
683 # Add a comment for easy SHOW PROCESSLIST interpretation
685 $commentedSql = preg_replace('/\s/', " /* $fname */ ", $sql, 1);
687 $commentedSql = $sql;
690 # If DBO_TRX is set, start a transaction
691 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
692 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK'
697 if ( $this->debug() ) {
698 $sqlx = substr( $commentedSql, 0, 500 );
699 $sqlx = strtr( $sqlx, "\t\n", ' ' );
700 wfDebug( "SQL: $sqlx\n" );
703 # Do the query and handle errors
704 $ret = $this->doQuery( $commentedSql );
706 # Try reconnecting if the connection was lost
707 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
708 # Transaction is gone, like it or not
709 $this->mTrxLevel
= 0;
710 wfDebug( "Connection lost, reconnecting...\n" );
711 if ( $this->ping() ) {
712 wfDebug( "Reconnected\n" );
713 $sqlx = substr( $commentedSql, 0, 500 );
714 $sqlx = strtr( $sqlx, "\t\n", ' ' );
715 global $wgRequestTime;
716 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
717 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
718 $ret = $this->doQuery( $commentedSql );
720 wfDebug( "Failed\n" );
724 if ( false === $ret ) {
725 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
728 if ( $wgProfiling ) {
729 wfProfileOut( $queryProf );
730 wfProfileOut( $totalProf );
736 * The DBMS-dependent part of query()
737 * @param string $sql SQL query.
739 function doQuery( $sql ) {
740 if( $this->bufferResults() ) {
741 $ret = mysql_query( $sql, $this->mConn
);
743 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
752 * @param string $fname
753 * @param bool $tempIgnore
755 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
756 global $wgCommandLineMode;
757 # Ignore errors during error handling to avoid infinite recursion
758 $ignore = $this->ignoreErrors( true );
759 ++
$this->mErrorCount
;
761 if( $ignore ||
$tempIgnore ) {
762 wfDebug("SQL ERROR (ignored): $error\n");
763 $this->ignoreErrors( $ignore );
765 $sql1line = str_replace( "\n", "\\n", $sql );
766 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
767 wfDebug("SQL ERROR: " . $error . "\n");
768 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
774 * Intended to be compatible with the PEAR::DB wrapper functions.
775 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
777 * ? = scalar value, quoted as necessary
778 * ! = raw SQL bit (a function for instance)
779 * & = filename; reads the file and inserts as a blob
780 * (we don't use this though...)
782 function prepare( $sql, $func = 'Database::prepare' ) {
783 /* MySQL doesn't support prepared statements (yet), so just
784 pack up the query for reference. We'll manually replace
786 return array( 'query' => $sql, 'func' => $func );
789 function freePrepared( $prepared ) {
790 /* No-op for MySQL */
794 * Execute a prepared query with the various arguments
795 * @param string $prepared the prepared sql
796 * @param mixed $args Either an array here, or put scalars as varargs
798 function execute( $prepared, $args = null ) {
799 if( !is_array( $args ) ) {
801 $args = func_get_args();
802 array_shift( $args );
804 $sql = $this->fillPrepared( $prepared['query'], $args );
805 return $this->query( $sql, $prepared['func'] );
809 * Prepare & execute an SQL statement, quoting and inserting arguments
810 * in the appropriate places.
811 * @param string $query
812 * @param string $args ...
814 function safeQuery( $query, $args = null ) {
815 $prepared = $this->prepare( $query, 'Database::safeQuery' );
816 if( !is_array( $args ) ) {
818 $args = func_get_args();
819 array_shift( $args );
821 $retval = $this->execute( $prepared, $args );
822 $this->freePrepared( $prepared );
827 * For faking prepared SQL statements on DBs that don't support
829 * @param string $preparedSql - a 'preparable' SQL statement
830 * @param array $args - array of arguments to fill it with
831 * @return string executable SQL
833 function fillPrepared( $preparedQuery, $args ) {
835 $this->preparedArgs
=& $args;
836 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
837 array( &$this, 'fillPreparedArg' ), $preparedQuery );
841 * preg_callback func for fillPrepared()
842 * The arguments should be in $this->preparedArgs and must not be touched
843 * while we're doing this.
845 * @param array $matches
849 function fillPreparedArg( $matches ) {
850 switch( $matches[1] ) {
851 case '\\?': return '?';
852 case '\\!': return '!';
853 case '\\&': return '&';
855 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
856 switch( $matches[1] ) {
857 case '?': return $this->addQuotes( $arg );
858 case '!': return $arg;
860 # return $this->addQuotes( file_get_contents( $arg ) );
861 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
863 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
868 * @param mixed $res A SQL result
871 * Free a result object
873 function freeResult( $res ) {
874 if ( !@/**/mysql_free_result( $res ) ) {
875 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
880 * Fetch the next row from the given result object, in object form
882 function fetchObject( $res ) {
883 @/**/$row = mysql_fetch_object( $res );
884 if( $this->lastErrno() ) {
885 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
891 * Fetch the next row from the given result object
894 function fetchRow( $res ) {
895 @/**/$row = mysql_fetch_array( $res );
896 if ( $this->lastErrno() ) {
897 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
903 * Get the number of rows in a result object
905 function numRows( $res ) {
906 @/**/$n = mysql_num_rows( $res );
907 if( $this->lastErrno() ) {
908 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
914 * Get the number of fields in a result object
915 * See documentation for mysql_num_fields()
917 function numFields( $res ) { return mysql_num_fields( $res ); }
920 * Get a field name in a result object
921 * See documentation for mysql_field_name():
922 * http://www.php.net/mysql_field_name
924 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
927 * Get the inserted value of an auto-increment row
929 * The value inserted should be fetched from nextSequenceValue()
932 * $id = $dbw->nextSequenceValue('page_page_id_seq');
933 * $dbw->insert('page',array('page_id' => $id));
934 * $id = $dbw->insertId();
936 function insertId() { return mysql_insert_id( $this->mConn
); }
939 * Change the position of the cursor in a result object
940 * See mysql_data_seek()
942 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
945 * Get the last error number
948 function lastErrno() {
949 if ( $this->mConn
) {
950 return mysql_errno( $this->mConn
);
952 return mysql_errno();
957 * Get a description of the last error
958 * See mysql_error() for more details
960 function lastError() {
961 if ( $this->mConn
) {
962 # Even if it's non-zero, it can still be invalid
963 wfSuppressWarnings();
964 $error = mysql_error( $this->mConn
);
966 $error = mysql_error();
970 $error = mysql_error();
973 $error .= ' (' . $this->mServer
. ')';
978 * Get the number of rows affected by the last write query
979 * See mysql_affected_rows() for more details
981 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
982 /**#@-*/ // end of template : @param $result
985 * Simple UPDATE wrapper
986 * Usually aborts on failure
987 * If errors are explicitly ignored, returns success
989 * This function exists for historical reasons, Database::update() has a more standard
990 * calling convention and feature set
992 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
994 $table = $this->tableName( $table );
995 $sql = "UPDATE $table SET $var = '" .
996 $this->strencode( $value ) . "' WHERE ($cond)";
997 return (bool)$this->query( $sql, $fname );
1001 * Simple SELECT wrapper, returns a single field, input must be encoded
1002 * Usually aborts on failure
1003 * If errors are explicitly ignored, returns FALSE on failure
1005 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
1006 if ( !is_array( $options ) ) {
1007 $options = array( $options );
1009 $options['LIMIT'] = 1;
1011 $res = $this->select( $table, $var, $cond, $fname, $options );
1012 if ( $res === false ||
!$this->numRows( $res ) ) {
1015 $row = $this->fetchRow( $res );
1016 if ( $row !== false ) {
1017 $this->freeResult( $res );
1025 * Returns an optional USE INDEX clause to go after the table, and a
1026 * string to go at the end of the query
1030 * @param array $options an associative array of options to be turned into
1031 * an SQL query, valid keys are listed in the function.
1034 function makeSelectOptions( $options ) {
1035 $preLimitTail = $postLimitTail = '';
1038 $noKeyOptions = array();
1039 foreach ( $options as $key => $option ) {
1040 if ( is_numeric( $key ) ) {
1041 $noKeyOptions[$option] = true;
1045 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1046 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1048 //if (isset($options['LIMIT'])) {
1049 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1050 // isset($options['OFFSET']) ? $options['OFFSET']
1054 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1055 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1056 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1058 # Various MySQL extensions
1059 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
1060 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
1061 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
1062 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
1063 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
1064 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
1065 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
1066 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
1068 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1069 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1074 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1080 * @param mixed $table Array or string, table name(s) (prefix auto-added)
1081 * @param mixed $vars Array or string, field name(s) to be retrieved
1082 * @param mixed $conds Array or string, condition(s) for WHERE
1083 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1084 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1085 * see Database::makeSelectOptions code for list of supported stuff
1086 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
1088 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
1090 if( is_array( $vars ) ) {
1091 $vars = implode( ',', $vars );
1093 if( !is_array( $options ) ) {
1094 $options = array( $options );
1096 if( is_array( $table ) ) {
1097 if ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1098 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
1100 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1101 } elseif ($table!='') {
1102 if ($table{0}==' ') {
1103 $from = ' FROM ' . $table;
1105 $from = ' FROM ' . $this->tableName( $table );
1111 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1113 if( !empty( $conds ) ) {
1114 if ( is_array( $conds ) ) {
1115 $conds = $this->makeList( $conds, LIST_AND
);
1117 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1119 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1122 if (isset($options['LIMIT']))
1123 $sql = $this->limitResult($sql, $options['LIMIT'],
1124 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
1125 $sql = "$sql $postLimitTail";
1127 return $this->query( $sql, $fname );
1131 * Single row SELECT wrapper
1132 * Aborts or returns FALSE on error
1134 * $vars: the selected variables
1135 * $conds: a condition map, terms are ANDed together.
1136 * Items with numeric keys are taken to be literal conditions
1137 * Takes an array of selected variables, and a condition map, which is ANDed
1138 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1139 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1140 * $obj- >page_id is the ID of the Astronomy article
1142 * @todo migrate documentation to phpdocumentor format
1144 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
1145 $options['LIMIT'] = 1;
1146 $res = $this->select( $table, $vars, $conds, $fname, $options );
1147 if ( $res === false )
1149 if ( !$this->numRows($res) ) {
1150 $this->freeResult($res);
1153 $obj = $this->fetchObject( $res );
1154 $this->freeResult( $res );
1160 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1161 * It's only slightly flawed. Don't use for anything important.
1163 * @param string $sql A SQL Query
1166 static function generalizeSQL( $sql ) {
1167 # This does the same as the regexp below would do, but in such a way
1168 # as to avoid crashing php on some large strings.
1169 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1171 $sql = str_replace ( "\\\\", '', $sql);
1172 $sql = str_replace ( "\\'", '', $sql);
1173 $sql = str_replace ( "\\\"", '', $sql);
1174 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1175 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1177 # All newlines, tabs, etc replaced by single space
1178 $sql = preg_replace ( '/\s+/', ' ', $sql);
1181 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1187 * Determines whether a field exists in a table
1188 * Usually aborts on failure
1189 * If errors are explicitly ignored, returns NULL on failure
1191 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1192 $table = $this->tableName( $table );
1193 $res = $this->query( 'DESCRIBE '.$table, $fname );
1200 while ( $row = $this->fetchObject( $res ) ) {
1201 if ( $row->Field
== $field ) {
1210 * Determines whether an index exists
1211 * Usually aborts on failure
1212 * If errors are explicitly ignored, returns NULL on failure
1214 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1215 $info = $this->indexInfo( $table, $index, $fname );
1216 if ( is_null( $info ) ) {
1219 return $info !== false;
1225 * Get information about an index into an object
1226 * Returns false if the index does not exist
1228 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1229 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1230 # SHOW INDEX should work for 3.x and up:
1231 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1232 $table = $this->tableName( $table );
1233 $sql = 'SHOW INDEX FROM '.$table;
1234 $res = $this->query( $sql, $fname );
1240 while ( $row = $this->fetchObject( $res ) ) {
1241 if ( $row->Key_name
== $index ) {
1245 $this->freeResult($res);
1247 return empty($result) ?
false : $result;
1251 * Query whether a given table exists
1253 function tableExists( $table ) {
1254 $table = $this->tableName( $table );
1255 $old = $this->ignoreErrors( true );
1256 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1257 $this->ignoreErrors( $old );
1259 $this->freeResult( $res );
1267 * mysql_fetch_field() wrapper
1268 * Returns false if the field doesn't exist
1273 function fieldInfo( $table, $field ) {
1274 $table = $this->tableName( $table );
1275 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1276 $n = mysql_num_fields( $res );
1277 for( $i = 0; $i < $n; $i++
) {
1278 $meta = mysql_fetch_field( $res, $i );
1279 if( $field == $meta->name
) {
1280 return new MySQLField($meta);
1287 * mysql_field_type() wrapper
1289 function fieldType( $res, $index ) {
1290 return mysql_field_type( $res, $index );
1294 * Determines if a given index is unique
1296 function indexUnique( $table, $index ) {
1297 $indexInfo = $this->indexInfo( $table, $index );
1298 if ( !$indexInfo ) {
1301 return !$indexInfo[0]->Non_unique
;
1305 * INSERT wrapper, inserts an array into a table
1307 * $a may be a single associative array, or an array of these with numeric keys, for
1310 * Usually aborts on failure
1311 * If errors are explicitly ignored, returns success
1313 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1314 # No rows to insert, easy just return now
1315 if ( !count( $a ) ) {
1319 $table = $this->tableName( $table );
1320 if ( !is_array( $options ) ) {
1321 $options = array( $options );
1323 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1325 $keys = array_keys( $a[0] );
1328 $keys = array_keys( $a );
1331 $sql = 'INSERT ' . implode( ' ', $options ) .
1332 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1336 foreach ( $a as $row ) {
1342 $sql .= '(' . $this->makeList( $row ) . ')';
1345 $sql .= '(' . $this->makeList( $a ) . ')';
1347 return (bool)$this->query( $sql, $fname );
1351 * Make UPDATE options for the Database::update function
1354 * @param array $options The options passed to Database::update
1357 function makeUpdateOptions( $options ) {
1358 if( !is_array( $options ) ) {
1359 $options = array( $options );
1362 if ( in_array( 'LOW_PRIORITY', $options ) )
1363 $opts[] = $this->lowPriorityOption();
1364 if ( in_array( 'IGNORE', $options ) )
1366 return implode(' ', $opts);
1370 * UPDATE wrapper, takes a condition array and a SET array
1372 * @param string $table The table to UPDATE
1373 * @param array $values An array of values to SET
1374 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1375 * @param string $fname The Class::Function calling this function
1377 * @param array $options An array of UPDATE options, can be one or
1378 * more of IGNORE, LOW_PRIORITY
1380 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1381 $table = $this->tableName( $table );
1382 $opts = $this->makeUpdateOptions( $options );
1383 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1384 if ( $conds != '*' ) {
1385 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1387 $this->query( $sql, $fname );
1391 * Makes an encoded list of strings from an array
1393 * LIST_COMMA - comma separated, no field names
1394 * LIST_AND - ANDed WHERE clause (without the WHERE)
1395 * LIST_OR - ORed WHERE clause (without the WHERE)
1396 * LIST_SET - comma separated with field names, like a SET clause
1397 * LIST_NAMES - comma separated field names
1399 function makeList( $a, $mode = LIST_COMMA
) {
1400 if ( !is_array( $a ) ) {
1401 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1406 foreach ( $a as $field => $value ) {
1408 if ( $mode == LIST_AND
) {
1410 } elseif($mode == LIST_OR
) {
1418 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1419 $list .= "($value)";
1420 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
1422 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array ($value) ) {
1423 $list .= $field." IN (".$this->makeList($value).") ";
1425 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1426 $list .= "$field = ";
1428 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1435 * Change the current database
1437 function selectDB( $db ) {
1438 $this->mDBname
= $db;
1439 return mysql_select_db( $db, $this->mConn
);
1443 * Format a table name ready for use in constructing an SQL query
1445 * This does two important things: it quotes table names which as necessary,
1446 * and it adds a table prefix if there is one.
1448 * All functions of this object which require a table name call this function
1449 * themselves. Pass the canonical name to such functions. This is only needed
1450 * when calling query() directly.
1452 * @param string $name database table name
1454 function tableName( $name ) {
1456 # Skip quoted literals
1457 if ( $name{0} != '`' ) {
1458 if ( $this->mTablePrefix
!== '' && strpos( '.', $name ) === false ) {
1459 $name = "{$this->mTablePrefix}$name";
1461 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1462 $name = "`$wgSharedDB`.`$name`";
1472 * Fetch a number of table names into an array
1473 * This is handy when you need to construct SQL for joins
1476 * extract($dbr->tableNames('user','watchlist'));
1477 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1478 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1480 public function tableNames() {
1481 $inArray = func_get_args();
1483 foreach ( $inArray as $name ) {
1484 $retVal[$name] = $this->tableName( $name );
1490 * Fetch a number of table names into an zero-indexed numerical array
1491 * This is handy when you need to construct SQL for joins
1494 * list( $user, $watchlist ) = $dbr->tableNames('user','watchlist');
1495 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1496 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1498 public function tableNamesN() {
1499 $inArray = func_get_args();
1501 foreach ( $inArray as $name ) {
1502 $retVal[] = $this->tableName( $name );
1510 function tableNamesWithUseIndex( $tables, $use_index ) {
1513 foreach ( $tables as $table )
1514 if ( @$use_index[$table] !== null )
1515 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1517 $ret[] = $this->tableName( $table );
1519 return implode( ',', $ret );
1523 * Wrapper for addslashes()
1524 * @param string $s String to be slashed.
1525 * @return string slashed string.
1527 function strencode( $s ) {
1528 return mysql_real_escape_string( $s, $this->mConn
);
1532 * If it's a string, adds quotes and backslashes
1533 * Otherwise returns as-is
1535 function addQuotes( $s ) {
1536 if ( is_null( $s ) ) {
1539 # This will also quote numeric values. This should be harmless,
1540 # and protects against weird problems that occur when they really
1541 # _are_ strings such as article titles and string->number->string
1542 # conversion is not 1:1.
1543 return "'" . $this->strencode( $s ) . "'";
1548 * Escape string for safe LIKE usage
1550 function escapeLike( $s ) {
1551 $s=$this->strencode( $s );
1552 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1557 * Returns an appropriately quoted sequence value for inserting a new row.
1558 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1559 * subclass will return an integer, and save the value for insertId()
1561 function nextSequenceValue( $seqName ) {
1567 * PostgreSQL doesn't have them and returns ""
1569 function useIndexClause( $index ) {
1570 return "FORCE INDEX ($index)";
1574 * REPLACE query wrapper
1575 * PostgreSQL simulates this with a DELETE followed by INSERT
1576 * $row is the row to insert, an associative array
1577 * $uniqueIndexes is an array of indexes. Each element may be either a
1578 * field name or an array of field names
1580 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1581 * However if you do this, you run the risk of encountering errors which wouldn't have
1584 * @todo migrate comment to phodocumentor format
1586 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1587 $table = $this->tableName( $table );
1590 if ( !is_array( reset( $rows ) ) ) {
1591 $rows = array( $rows );
1594 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1596 foreach ( $rows as $row ) {
1602 $sql .= '(' . $this->makeList( $row ) . ')';
1604 return $this->query( $sql, $fname );
1608 * DELETE where the condition is a join
1609 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1611 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1612 * join condition matches, set $conds='*'
1614 * DO NOT put the join condition in $conds
1616 * @param string $delTable The table to delete from.
1617 * @param string $joinTable The other table.
1618 * @param string $delVar The variable to join on, in the first table.
1619 * @param string $joinVar The variable to join on, in the second table.
1620 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1622 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1624 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1627 $delTable = $this->tableName( $delTable );
1628 $joinTable = $this->tableName( $joinTable );
1629 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1630 if ( $conds != '*' ) {
1631 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1634 return $this->query( $sql, $fname );
1638 * Returns the size of a text field, or -1 for "unlimited"
1640 function textFieldSize( $table, $field ) {
1641 $table = $this->tableName( $table );
1642 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1643 $res = $this->query( $sql, 'Database::textFieldSize' );
1644 $row = $this->fetchObject( $res );
1645 $this->freeResult( $res );
1648 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1657 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1659 function lowPriorityOption() {
1660 return 'LOW_PRIORITY';
1664 * DELETE query wrapper
1666 * Use $conds == "*" to delete all rows
1668 function delete( $table, $conds, $fname = 'Database::delete' ) {
1670 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1672 $table = $this->tableName( $table );
1673 $sql = "DELETE FROM $table";
1674 if ( $conds != '*' ) {
1675 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1677 return $this->query( $sql, $fname );
1681 * INSERT SELECT wrapper
1682 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1683 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1684 * $conds may be "*" to copy the whole table
1685 * srcTable may be an array of tables.
1687 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1688 $insertOptions = array(), $selectOptions = array() )
1690 $destTable = $this->tableName( $destTable );
1691 if ( is_array( $insertOptions ) ) {
1692 $insertOptions = implode( ' ', $insertOptions );
1694 if( !is_array( $selectOptions ) ) {
1695 $selectOptions = array( $selectOptions );
1697 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1698 if( is_array( $srcTable ) ) {
1699 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1701 $srcTable = $this->tableName( $srcTable );
1703 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1704 " SELECT $startOpts " . implode( ',', $varMap ) .
1705 " FROM $srcTable $useIndex ";
1706 if ( $conds != '*' ) {
1707 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1709 $sql .= " $tailOpts";
1710 return $this->query( $sql, $fname );
1714 * Construct a LIMIT query with optional offset
1715 * This is used for query pages
1716 * $sql string SQL query we will append the limit too
1717 * $limit integer the SQL limit
1718 * $offset integer the SQL offset (default false)
1720 function limitResult($sql, $limit, $offset=false) {
1721 if( !is_numeric($limit) ) {
1722 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1724 return " $sql LIMIT "
1725 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1728 function limitResultForUpdate($sql, $num) {
1729 return $this->limitResult($sql, $num, 0);
1733 * Returns an SQL expression for a simple conditional.
1736 * @param string $cond SQL expression which will result in a boolean value
1737 * @param string $trueVal SQL expression to return if true
1738 * @param string $falseVal SQL expression to return if false
1739 * @return string SQL fragment
1741 function conditional( $cond, $trueVal, $falseVal ) {
1742 return " IF($cond, $trueVal, $falseVal) ";
1746 * Determines if the last failure was due to a deadlock
1748 function wasDeadlock() {
1749 return $this->lastErrno() == 1213;
1753 * Perform a deadlock-prone transaction.
1755 * This function invokes a callback function to perform a set of write
1756 * queries. If a deadlock occurs during the processing, the transaction
1757 * will be rolled back and the callback function will be called again.
1760 * $dbw->deadlockLoop( callback, ... );
1762 * Extra arguments are passed through to the specified callback function.
1764 * Returns whatever the callback function returned on its successful,
1765 * iteration, or false on error, for example if the retry limit was
1768 function deadlockLoop() {
1769 $myFname = 'Database::deadlockLoop';
1772 $args = func_get_args();
1773 $function = array_shift( $args );
1774 $oldIgnore = $this->ignoreErrors( true );
1775 $tries = DEADLOCK_TRIES
;
1776 if ( is_array( $function ) ) {
1777 $fname = $function[0];
1782 $retVal = call_user_func_array( $function, $args );
1783 $error = $this->lastError();
1784 $errno = $this->lastErrno();
1785 $sql = $this->lastQuery();
1788 if ( $this->wasDeadlock() ) {
1790 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1792 $this->reportQueryError( $error, $errno, $sql, $fname );
1795 } while( $this->wasDeadlock() && --$tries > 0 );
1796 $this->ignoreErrors( $oldIgnore );
1797 if ( $tries <= 0 ) {
1798 $this->query( 'ROLLBACK', $myFname );
1799 $this->reportQueryError( $error, $errno, $sql, $fname );
1802 $this->query( 'COMMIT', $myFname );
1808 * Do a SELECT MASTER_POS_WAIT()
1810 * @param string $file the binlog file
1811 * @param string $pos the binlog position
1812 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1814 function masterPosWait( $file, $pos, $timeout ) {
1815 $fname = 'Database::masterPosWait';
1816 wfProfileIn( $fname );
1819 # Commit any open transactions
1820 $this->immediateCommit();
1822 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1823 $encFile = $this->strencode( $file );
1824 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1825 $res = $this->doQuery( $sql );
1826 if ( $res && $row = $this->fetchRow( $res ) ) {
1827 $this->freeResult( $res );
1828 wfProfileOut( $fname );
1831 wfProfileOut( $fname );
1837 * Get the position of the master from SHOW SLAVE STATUS
1839 function getSlavePos() {
1840 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1841 $row = $this->fetchObject( $res );
1843 return array( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1845 return array( false, false );
1850 * Get the position of the master from SHOW MASTER STATUS
1852 function getMasterPos() {
1853 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1854 $row = $this->fetchObject( $res );
1856 return array( $row->File
, $row->Position
);
1858 return array( false, false );
1863 * Begin a transaction, committing any previously open transaction
1865 function begin( $fname = 'Database::begin' ) {
1866 $this->query( 'BEGIN', $fname );
1867 $this->mTrxLevel
= 1;
1873 function commit( $fname = 'Database::commit' ) {
1874 $this->query( 'COMMIT', $fname );
1875 $this->mTrxLevel
= 0;
1879 * Rollback a transaction
1881 function rollback( $fname = 'Database::rollback' ) {
1882 $this->query( 'ROLLBACK', $fname );
1883 $this->mTrxLevel
= 0;
1887 * Begin a transaction, committing any previously open transaction
1888 * @deprecated use begin()
1890 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1895 * Commit transaction, if one is open
1896 * @deprecated use commit()
1898 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1903 * Return MW-style timestamp used for MySQL schema
1905 function timestamp( $ts=0 ) {
1906 return wfTimestamp(TS_MW
,$ts);
1910 * Local database timestamp format or null
1912 function timestampOrNull( $ts = null ) {
1913 if( is_null( $ts ) ) {
1916 return $this->timestamp( $ts );
1923 function resultObject( $result ) {
1924 if( empty( $result ) ) {
1927 return new ResultWrapper( $this, $result );
1932 * Return aggregated value alias
1934 function aggregateValue ($valuedata,$valuename='value') {
1939 * @return string wikitext of a link to the server software's web site
1941 function getSoftwareLink() {
1942 return "[http://www.mysql.com/ MySQL]";
1946 * @return string Version information from the database
1948 function getServerVersion() {
1949 return mysql_get_server_info( $this->mConn
);
1953 * Ping the server and try to reconnect if it there is no connection
1956 if( function_exists( 'mysql_ping' ) ) {
1957 return mysql_ping( $this->mConn
);
1959 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1966 * At the moment, this will only work if the DB user has the PROCESS privilege
1969 $res = $this->query( 'SHOW PROCESSLIST' );
1970 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1971 # dubious, but unfortunately there's no easy rigorous way
1972 while ( $row = $this->fetchObject( $res ) ) {
1973 /* This should work for most situations - when default db
1974 * for thread is not specified, it had no events executed,
1975 * and therefore it doesn't know yet how lagged it is.
1977 * Relay log I/O thread does not select databases.
1979 if ( $row->User
== 'system user' &&
1980 $row->State
!= 'Waiting for master to send event' &&
1981 $row->State
!= 'Connecting to master' &&
1982 $row->State
!= 'Queueing master event to the relay log' &&
1983 $row->State
!= 'Waiting for master update' &&
1984 $row->State
!= 'Requesting binlog dump'
1986 # This is it, return the time (except -ve)
1987 if ( $row->Time
> 0x7fffffff ) {
1998 * Get status information from SHOW STATUS in an associative array
2000 function getStatus($which="%") {
2001 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2003 while ( $row = $this->fetchObject( $res ) ) {
2004 $status[$row->Variable_name
] = $row->Value
;
2010 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2012 function maxListLen() {
2016 function encodeBlob($b) {
2020 function decodeBlob($b) {
2025 * Override database's default connection timeout.
2026 * May be useful for very long batch queries such as
2027 * full-wiki dumps, where a single query reads out
2028 * over hours or days.
2029 * @param int $timeout in seconds
2031 public function setTimeout( $timeout ) {
2032 $this->query( "SET net_read_timeout=$timeout" );
2033 $this->query( "SET net_write_timeout=$timeout" );
2037 * Read and execute SQL commands from a file.
2038 * Returns true on success, error string on failure
2040 function sourceFile( $filename ) {
2041 $fp = fopen( $filename, 'r' );
2042 if ( false === $fp ) {
2043 return "Could not open \"{$filename}\".\n";
2048 $dollarquote = false;
2050 while ( ! feof( $fp ) ) {
2051 $line = trim( fgets( $fp, 1024 ) );
2052 $sl = strlen( $line ) - 1;
2054 if ( $sl < 0 ) { continue; }
2055 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2057 ## Allow dollar quoting for function declarations
2058 if (substr($line,0,4) == '$mw$') {
2060 $dollarquote = false;
2064 $dollarquote = true;
2067 else if (!$dollarquote) {
2068 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
2070 $line = substr( $line, 0, $sl );
2074 if ( '' != $cmd ) { $cmd .= ' '; }
2078 $cmd = str_replace(';;', ";", $cmd);
2079 $cmd = $this->replaceVars( $cmd );
2080 $res = $this->query( $cmd, 'dbsource', true );
2082 if ( false === $res ) {
2083 $err = $this->lastError();
2084 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2096 * Replace variables in sourced SQL
2098 protected function replaceVars( $ins ) {
2100 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2101 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2102 'wgDBadminuser', 'wgDBadminpassword',
2105 // Ordinary variables
2106 foreach ( $varnames as $var ) {
2107 if( isset( $GLOBALS[$var] ) ) {
2108 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2109 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2110 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2111 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2116 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
2117 array( &$this, 'tableNameCallback' ), $ins );
2122 * Table name callback
2125 protected function tableNameCallback( $matches ) {
2126 return $this->tableName( $matches[1] );
2132 * Database abstraction object for mySQL
2133 * Inherit all methods and properties of Database::Database()
2137 class DatabaseMysql
extends Database
{
2143 * Result wrapper for grabbing data queried by someone else
2146 class ResultWrapper
{
2152 function ResultWrapper( &$database, $result ) {
2153 $this->db
=& $database;
2154 $this->result
=& $result;
2160 function numRows() {
2161 return $this->db
->numRows( $this->result
);
2167 function fetchObject() {
2168 return $this->db
->fetchObject( $this->result
);
2174 function fetchRow() {
2175 return $this->db
->fetchRow( $this->result
);
2182 $this->db
->freeResult( $this->result
);
2183 unset( $this->result
);
2187 function seek( $row ) {
2188 $this->db
->dataSeek( $this->result
, $row );
2192 if ($this->numRows()) {
2193 $this->db
->dataSeek($this->result
, 0);