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 );
15 * Database abstraction object
16 * @addtogroup Database
20 #------------------------------------------------------------------------------
22 #------------------------------------------------------------------------------
24 protected $mLastQuery = '';
26 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
27 protected $mOut, $mOpened = false;
29 protected $mFailFunction;
30 protected $mTablePrefix;
32 protected $mTrxLevel = 0;
33 protected $mErrorCount = 0;
34 protected $mLBInfo = array();
35 protected $mFakeSlaveLag = null, $mFakeMaster = false;
37 #------------------------------------------------------------------------------
39 #------------------------------------------------------------------------------
40 # These optionally set a variable and return the previous state
43 * Fail function, takes a Database as a parameter
44 * Set to false for default, 1 for ignore errors
46 function failFunction( $function = NULL ) {
47 return wfSetVar( $this->mFailFunction
, $function );
51 * Output page, used for reporting errors
52 * FALSE means discard output
54 function setOutputPage( $out ) {
59 * Boolean, controls output of large amounts of debug information
61 function debug( $debug = NULL ) {
62 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
66 * Turns buffering of SQL result sets on (true) or off (false).
67 * Default is "on" and it should not be changed without good reasons.
69 function bufferResults( $buffer = NULL ) {
70 if ( is_null( $buffer ) ) {
71 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
73 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
78 * Turns on (false) or off (true) the automatic generation and sending
79 * of a "we're sorry, but there has been a database error" page on
80 * database errors. Default is on (false). When turned off, the
81 * code should use lastErrno() and lastError() to handle the
82 * situation as appropriate.
84 function ignoreErrors( $ignoreErrors = NULL ) {
85 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
89 * The current depth of nested transactions
90 * @param $level Integer: , default NULL.
92 function trxLevel( $level = NULL ) {
93 return wfSetVar( $this->mTrxLevel
, $level );
97 * Number of errors logged, only useful when errors are ignored
99 function errorCount( $count = NULL ) {
100 return wfSetVar( $this->mErrorCount
, $count );
103 function tablePrefix( $prefix = null ) {
104 return wfSetVar( $this->mTablePrefix
, $prefix );
108 * Properties passed down from the server info array of the load balancer
110 function getLBInfo( $name = NULL ) {
111 if ( is_null( $name ) ) {
112 return $this->mLBInfo
;
114 if ( array_key_exists( $name, $this->mLBInfo
) ) {
115 return $this->mLBInfo
[$name];
122 function setLBInfo( $name, $value = NULL ) {
123 if ( is_null( $value ) ) {
124 $this->mLBInfo
= $name;
126 $this->mLBInfo
[$name] = $value;
131 * Set lag time in seconds for a fake slave
133 function setFakeSlaveLag( $lag ) {
134 $this->mFakeSlaveLag
= $lag;
138 * Make this connection a fake master
140 function setFakeMaster( $enabled = true ) {
141 $this->mFakeMaster
= $enabled;
145 * Returns true if this database supports (and uses) cascading deletes
147 function cascadingDeletes() {
152 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
154 function cleanupTriggers() {
159 * Returns true if this database is strict about what can be put into an IP field.
160 * Specifically, it uses a NULL value instead of an empty string.
162 function strictIPs() {
167 * Returns true if this database uses timestamps rather than integers
169 function realTimestamps() {
174 * Returns true if this database does an implicit sort when doing GROUP BY
176 function implicitGroupby() {
181 * Returns true if this database does an implicit order by when the column has an index
182 * For example: SELECT page_title FROM page LIMIT 1
184 function implicitOrderby() {
189 * Returns true if this database can do a native search on IP columns
190 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
192 function searchableIPs() {
197 * Returns true if this database can use functional indexes
199 function functionalIndexes() {
206 function lastQuery() { return $this->mLastQuery
; }
207 function isOpen() { return $this->mOpened
; }
210 function setFlag( $flag ) {
211 $this->mFlags |
= $flag;
214 function clearFlag( $flag ) {
215 $this->mFlags
&= ~
$flag;
218 function getFlag( $flag ) {
219 return !!($this->mFlags
& $flag);
223 * General read-only accessor
225 function getProperty( $name ) {
229 function getWikiID() {
230 if( $this->mTablePrefix
) {
231 return "{$this->mDBname}-{$this->mTablePrefix}";
233 return $this->mDBname
;
237 #------------------------------------------------------------------------------
239 #------------------------------------------------------------------------------
243 * @param string $server database server host
244 * @param string $user database user name
245 * @param string $password database user password
246 * @param string $dbname database name
247 * @param failFunction
249 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
251 function __construct( $server = false, $user = false, $password = false, $dbName = false,
252 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
254 global $wgOut, $wgDBprefix, $wgCommandLineMode;
255 # Can't get a reference if it hasn't been set yet
256 if ( !isset( $wgOut ) ) {
259 $this->mOut
=& $wgOut;
261 $this->mFailFunction
= $failFunction;
262 $this->mFlags
= $flags;
264 if ( $this->mFlags
& DBO_DEFAULT
) {
265 if ( $wgCommandLineMode ) {
266 $this->mFlags
&= ~DBO_TRX
;
268 $this->mFlags |
= DBO_TRX
;
273 // Faster read-only access
274 if ( wfReadOnly() ) {
275 $this->mFlags |= DBO_PERSISTENT;
276 $this->mFlags &= ~DBO_TRX;
279 /** Get the default table prefix*/
280 if ( $tablePrefix == 'get from global' ) {
281 $this->mTablePrefix
= $wgDBprefix;
283 $this->mTablePrefix
= $tablePrefix;
287 $this->open( $server, $user, $password, $dbName );
293 * @param failFunction
296 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
298 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
302 * Usually aborts on failure
303 * If the failFunction is set to a non-zero integer, returns success
305 function open( $server, $user, $password, $dbName ) {
306 global $wguname, $wgAllDBsAreLocalhost;
307 wfProfileIn( __METHOD__
);
309 # Test for missing mysql.so
310 # First try to load it
311 if (!@extension_loaded
('mysql')) {
316 # Otherwise we get a suppressed fatal error, which is very hard to track down
317 if ( !function_exists( 'mysql_connect' ) ) {
318 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
321 # Debugging hack -- fake cluster
322 if ( $wgAllDBsAreLocalhost ) {
323 $realServer = 'localhost';
325 $realServer = $server;
328 $this->mServer
= $server;
329 $this->mUser
= $user;
330 $this->mPassword
= $password;
331 $this->mDBname
= $dbName;
335 wfProfileIn("dbconnect-$server");
337 # Try to connect up to three times
338 # The kernel's default SYN retransmission period is far too slow for us,
339 # so we use a short timeout plus a manual retry.
340 $this->mConn
= false;
342 for ( $i = 0; $i < $max && !$this->mConn
; $i++
) {
346 if ( $this->mFlags
& DBO_PERSISTENT
) {
347 @/**/$this->mConn
= mysql_pconnect( $realServer, $user, $password );
349 # Create a new connection...
350 @/**/$this->mConn
= mysql_connect( $realServer, $user, $password, true );
352 if ($this->mConn
=== false) {
354 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
358 wfProfileOut("dbconnect-$server");
360 if ( $dbName != '' ) {
361 if ( $this->mConn
!== false ) {
362 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
364 $error = "Error selecting database $dbName on server {$this->mServer} " .
365 "from client host {$wguname['nodename']}\n";
366 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
370 wfDebug( "DB connection error\n" );
371 wfDebug( "Server: $server, User: $user, Password: " .
372 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
377 $success = (bool)$this->mConn
;
381 $version = $this->getServerVersion();
382 if ( version_compare( $version, '4.1' ) >= 0 ) {
383 // Tell the server we're communicating with it in UTF-8.
384 // This may engage various charset conversions.
387 $this->query( 'SET NAMES utf8', __METHOD__
);
389 // Turn off strict mode
390 $this->query( "SET sql_mode = ''", __METHOD__
);
393 // Turn off strict mode if it is on
395 $this->reportConnectionError();
398 $this->mOpened
= $success;
399 wfProfileOut( __METHOD__
);
405 * Closes a database connection.
406 * if it is open : commits any open transactions
408 * @return bool operation success. true if already closed.
412 $this->mOpened
= false;
413 if ( $this->mConn
) {
414 if ( $this->trxLevel() ) {
415 $this->immediateCommit();
417 return mysql_close( $this->mConn
);
424 * @param string $error fallback error message, used if none is given by MySQL
426 function reportConnectionError( $error = 'Unknown error' ) {
427 $myError = $this->lastError();
432 if ( $this->mFailFunction
) {
433 # Legacy error handling method
434 if ( !is_int( $this->mFailFunction
) ) {
435 $ff = $this->mFailFunction
;
436 $ff( $this, $error );
440 wfLogDBError( "Connection error: $error\n" );
441 throw new DBConnectionError( $this, $error );
446 * Usually aborts on failure. If errors are explicitly ignored, returns success.
448 * @param $sql String: SQL query
449 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
450 * comment (you can use __METHOD__ or add some extra info)
451 * @param $tempIgnore Bool: Whether to avoid throwing an exception on errors...
452 * maybe best to catch the exception instead?
453 * @return true for a successful write query, ResultWrapper object for a successful read query,
454 * or false on failure if $tempIgnore set
455 * @throws DBQueryError Thrown when the database returns an error of any kind
457 public function query( $sql, $fname = '', $tempIgnore = false ) {
460 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
461 if ( isset( $wgProfiler ) ) {
462 # generalizeSQL will probably cut down the query to reasonable
463 # logging size most of the time. The substr is really just a sanity check.
465 # Who's been wasting my precious column space? -- TS
466 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
469 $queryProf = 'query-m: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
470 $totalProf = 'Database::query-master';
472 $queryProf = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
473 $totalProf = 'Database::query';
475 wfProfileIn( $totalProf );
476 wfProfileIn( $queryProf );
479 $this->mLastQuery
= $sql;
481 # Add a comment for easy SHOW PROCESSLIST interpretation
484 if ( is_object( $wgUser ) && !($wgUser instanceof StubObject
) ) {
485 $userName = $wgUser->getName();
486 if ( mb_strlen( $userName ) > 15 ) {
487 $userName = mb_substr( $userName, 0, 15 ) . '...';
489 $userName = str_replace( '/', '', $userName );
493 $commentedSql = preg_replace('/\s/', " /* $fname $userName */ ", $sql, 1);
495 # $commentedSql = $sql;
498 # If DBO_TRX is set, start a transaction
499 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
500 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK') {
501 // avoid establishing transactions for SHOW and SET statements too -
502 // that would delay transaction initializations to once connection
503 // is really used by application
504 $sqlstart = substr($sql,0,10); // very much worth it, benchmark certified(tm)
505 if (strpos($sqlstart,"SHOW ")!==0 and strpos($sqlstart,"SET ")!==0)
509 if ( $this->debug() ) {
510 $sqlx = substr( $commentedSql, 0, 500 );
511 $sqlx = strtr( $sqlx, "\t\n", ' ' );
513 wfDebug( "SQL-master: $sqlx\n" );
515 wfDebug( "SQL: $sqlx\n" );
519 # Do the query and handle errors
520 $ret = $this->doQuery( $commentedSql );
522 # Try reconnecting if the connection was lost
523 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
524 # Transaction is gone, like it or not
525 $this->mTrxLevel
= 0;
526 wfDebug( "Connection lost, reconnecting...\n" );
527 if ( $this->ping() ) {
528 wfDebug( "Reconnected\n" );
529 $sqlx = substr( $commentedSql, 0, 500 );
530 $sqlx = strtr( $sqlx, "\t\n", ' ' );
531 global $wgRequestTime;
532 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
533 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
534 $ret = $this->doQuery( $commentedSql );
536 wfDebug( "Failed\n" );
540 if ( false === $ret ) {
541 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
544 if ( isset( $wgProfiler ) ) {
545 wfProfileOut( $queryProf );
546 wfProfileOut( $totalProf );
548 return $this->resultObject( $ret );
552 * The DBMS-dependent part of query()
553 * @param $sql String: SQL query.
554 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
557 /*private*/ function doQuery( $sql ) {
558 if( $this->bufferResults() ) {
559 $ret = mysql_query( $sql, $this->mConn
);
561 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
570 * @param string $fname
571 * @param bool $tempIgnore
573 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
574 global $wgCommandLineMode;
575 # Ignore errors during error handling to avoid infinite recursion
576 $ignore = $this->ignoreErrors( true );
577 ++
$this->mErrorCount
;
579 if( $ignore ||
$tempIgnore ) {
580 wfDebug("SQL ERROR (ignored): $error\n");
581 $this->ignoreErrors( $ignore );
583 $sql1line = str_replace( "\n", "\\n", $sql );
584 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
585 wfDebug("SQL ERROR: " . $error . "\n");
586 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
592 * Intended to be compatible with the PEAR::DB wrapper functions.
593 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
595 * ? = scalar value, quoted as necessary
596 * ! = raw SQL bit (a function for instance)
597 * & = filename; reads the file and inserts as a blob
598 * (we don't use this though...)
600 function prepare( $sql, $func = 'Database::prepare' ) {
601 /* MySQL doesn't support prepared statements (yet), so just
602 pack up the query for reference. We'll manually replace
604 return array( 'query' => $sql, 'func' => $func );
607 function freePrepared( $prepared ) {
608 /* No-op for MySQL */
612 * Execute a prepared query with the various arguments
613 * @param string $prepared the prepared sql
614 * @param mixed $args Either an array here, or put scalars as varargs
616 function execute( $prepared, $args = null ) {
617 if( !is_array( $args ) ) {
619 $args = func_get_args();
620 array_shift( $args );
622 $sql = $this->fillPrepared( $prepared['query'], $args );
623 return $this->query( $sql, $prepared['func'] );
627 * Prepare & execute an SQL statement, quoting and inserting arguments
628 * in the appropriate places.
629 * @param string $query
630 * @param string $args ...
632 function safeQuery( $query, $args = null ) {
633 $prepared = $this->prepare( $query, 'Database::safeQuery' );
634 if( !is_array( $args ) ) {
636 $args = func_get_args();
637 array_shift( $args );
639 $retval = $this->execute( $prepared, $args );
640 $this->freePrepared( $prepared );
645 * For faking prepared SQL statements on DBs that don't support
647 * @param string $preparedSql - a 'preparable' SQL statement
648 * @param array $args - array of arguments to fill it with
649 * @return string executable SQL
651 function fillPrepared( $preparedQuery, $args ) {
653 $this->preparedArgs
=& $args;
654 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
655 array( &$this, 'fillPreparedArg' ), $preparedQuery );
659 * preg_callback func for fillPrepared()
660 * The arguments should be in $this->preparedArgs and must not be touched
661 * while we're doing this.
663 * @param array $matches
667 function fillPreparedArg( $matches ) {
668 switch( $matches[1] ) {
669 case '\\?': return '?';
670 case '\\!': return '!';
671 case '\\&': return '&';
673 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
674 switch( $matches[1] ) {
675 case '?': return $this->addQuotes( $arg );
676 case '!': return $arg;
678 # return $this->addQuotes( file_get_contents( $arg ) );
679 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
681 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
686 * @param mixed $res A SQL result
689 * Free a result object
691 function freeResult( $res ) {
692 if ( $res instanceof ResultWrapper
) {
695 if ( !@/**/mysql_free_result( $res ) ) {
696 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
701 * Fetch the next row from the given result object, in object form.
702 * Fields can be retrieved with $row->fieldname, with fields acting like
705 * @param $res SQL result object as returned from Database::query(), etc.
706 * @return MySQL row object
707 * @throws DBUnexpectedError Thrown if the database returns an error
709 function fetchObject( $res ) {
710 if ( $res instanceof ResultWrapper
) {
713 @/**/$row = mysql_fetch_object( $res );
714 if( $this->lastErrno() ) {
715 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
721 * Fetch the next row from the given result object, in associative array
722 * form. Fields are retrieved with $row['fieldname'].
724 * @param $res SQL result object as returned from Database::query(), etc.
725 * @return MySQL row object
726 * @throws DBUnexpectedError Thrown if the database returns an error
728 function fetchRow( $res ) {
729 if ( $res instanceof ResultWrapper
) {
732 @/**/$row = mysql_fetch_array( $res );
733 if ( $this->lastErrno() ) {
734 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
740 * Get the number of rows in a result object
742 function numRows( $res ) {
743 if ( $res instanceof ResultWrapper
) {
746 @/**/$n = mysql_num_rows( $res );
747 if( $this->lastErrno() ) {
748 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
754 * Get the number of fields in a result object
755 * See documentation for mysql_num_fields()
757 function numFields( $res ) {
758 if ( $res instanceof ResultWrapper
) {
761 return mysql_num_fields( $res );
765 * Get a field name in a result object
766 * See documentation for mysql_field_name():
767 * http://www.php.net/mysql_field_name
769 function fieldName( $res, $n ) {
770 if ( $res instanceof ResultWrapper
) {
773 return mysql_field_name( $res, $n );
777 * Get the inserted value of an auto-increment row
779 * The value inserted should be fetched from nextSequenceValue()
782 * $id = $dbw->nextSequenceValue('page_page_id_seq');
783 * $dbw->insert('page',array('page_id' => $id));
784 * $id = $dbw->insertId();
786 function insertId() { return mysql_insert_id( $this->mConn
); }
789 * Change the position of the cursor in a result object
790 * See mysql_data_seek()
792 function dataSeek( $res, $row ) {
793 if ( $res instanceof ResultWrapper
) {
796 return mysql_data_seek( $res, $row );
800 * Get the last error number
803 function lastErrno() {
804 if ( $this->mConn
) {
805 return mysql_errno( $this->mConn
);
807 return mysql_errno();
812 * Get a description of the last error
813 * See mysql_error() for more details
815 function lastError() {
816 if ( $this->mConn
) {
817 # Even if it's non-zero, it can still be invalid
818 wfSuppressWarnings();
819 $error = mysql_error( $this->mConn
);
821 $error = mysql_error();
825 $error = mysql_error();
828 $error .= ' (' . $this->mServer
. ')';
833 * Get the number of rows affected by the last write query
834 * See mysql_affected_rows() for more details
836 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
837 /**#@-*/ // end of template : @param $result
840 * Simple UPDATE wrapper
841 * Usually aborts on failure
842 * If errors are explicitly ignored, returns success
844 * This function exists for historical reasons, Database::update() has a more standard
845 * calling convention and feature set
847 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
849 $table = $this->tableName( $table );
850 $sql = "UPDATE $table SET $var = '" .
851 $this->strencode( $value ) . "' WHERE ($cond)";
852 return (bool)$this->query( $sql, $fname );
856 * Simple SELECT wrapper, returns a single field, input must be encoded
857 * Usually aborts on failure
858 * If errors are explicitly ignored, returns FALSE on failure
860 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
861 if ( !is_array( $options ) ) {
862 $options = array( $options );
864 $options['LIMIT'] = 1;
866 $res = $this->select( $table, $var, $cond, $fname, $options );
867 if ( $res === false ||
!$this->numRows( $res ) ) {
870 $row = $this->fetchRow( $res );
871 if ( $row !== false ) {
872 $this->freeResult( $res );
880 * Returns an optional USE INDEX clause to go after the table, and a
881 * string to go at the end of the query
885 * @param array $options an associative array of options to be turned into
886 * an SQL query, valid keys are listed in the function.
889 function makeSelectOptions( $options ) {
890 $preLimitTail = $postLimitTail = '';
893 $noKeyOptions = array();
894 foreach ( $options as $key => $option ) {
895 if ( is_numeric( $key ) ) {
896 $noKeyOptions[$option] = true;
900 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
901 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
902 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
904 //if (isset($options['LIMIT'])) {
905 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
906 // isset($options['OFFSET']) ? $options['OFFSET']
910 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
911 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
912 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
914 # Various MySQL extensions
915 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
916 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
917 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
918 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
919 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
920 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
921 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
922 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
924 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
925 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
930 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
936 * @param mixed $table Array or string, table name(s) (prefix auto-added)
937 * @param mixed $vars Array or string, field name(s) to be retrieved
938 * @param mixed $conds Array or string, condition(s) for WHERE
939 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
940 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
941 * see Database::makeSelectOptions code for list of supported stuff
942 * @param array $join_conds Associative array of table join conditions (optional)
943 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
944 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
946 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() )
948 if( is_array( $vars ) ) {
949 $vars = implode( ',', $vars );
951 if( !is_array( $options ) ) {
952 $options = array( $options );
954 if( is_array( $table ) ) {
955 if ( !empty($join_conds) ||
is_array( @$options['USE INDEX'] ) )
956 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
958 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
959 } elseif ($table!='') {
960 if ($table{0}==' ') {
961 $from = ' FROM ' . $table;
963 $from = ' FROM ' . $this->tableName( $table );
969 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
971 if( !empty( $conds ) ) {
972 if ( is_array( $conds ) ) {
973 $conds = $this->makeList( $conds, LIST_AND
);
975 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
977 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
980 if (isset($options['LIMIT']))
981 $sql = $this->limitResult($sql, $options['LIMIT'],
982 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
983 $sql = "$sql $postLimitTail";
985 if (isset($options['EXPLAIN'])) {
986 $sql = 'EXPLAIN ' . $sql;
988 return $this->query( $sql, $fname );
992 * Single row SELECT wrapper
993 * Aborts or returns FALSE on error
995 * $vars: the selected variables
996 * $conds: a condition map, terms are ANDed together.
997 * Items with numeric keys are taken to be literal conditions
998 * Takes an array of selected variables, and a condition map, which is ANDed
999 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1000 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1001 * $obj- >page_id is the ID of the Astronomy article
1003 * @todo migrate documentation to phpdocumentor format
1005 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
1006 $options['LIMIT'] = 1;
1007 $res = $this->select( $table, $vars, $conds, $fname, $options );
1008 if ( $res === false )
1010 if ( !$this->numRows($res) ) {
1011 $this->freeResult($res);
1014 $obj = $this->fetchObject( $res );
1015 $this->freeResult( $res );
1021 * Estimate rows in dataset
1022 * Returns estimated count, based on EXPLAIN output
1023 * Takes same arguments as Database::select()
1026 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
1027 $options['EXPLAIN']=true;
1028 $res = $this->select ($table, $vars, $conds, $fname, $options );
1029 if ( $res === false )
1031 if (!$this->numRows($res)) {
1032 $this->freeResult($res);
1038 while( $plan = $this->fetchObject( $res ) ) {
1039 $rows *= ($plan->rows
> 0)?
$plan->rows
:1; // avoid resetting to zero
1042 $this->freeResult($res);
1048 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1049 * It's only slightly flawed. Don't use for anything important.
1051 * @param string $sql A SQL Query
1054 static function generalizeSQL( $sql ) {
1055 # This does the same as the regexp below would do, but in such a way
1056 # as to avoid crashing php on some large strings.
1057 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1059 $sql = str_replace ( "\\\\", '', $sql);
1060 $sql = str_replace ( "\\'", '', $sql);
1061 $sql = str_replace ( "\\\"", '', $sql);
1062 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1063 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1065 # All newlines, tabs, etc replaced by single space
1066 $sql = preg_replace ( '/\s+/', ' ', $sql);
1069 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1075 * Determines whether a field exists in a table
1076 * Usually aborts on failure
1077 * If errors are explicitly ignored, returns NULL on failure
1079 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1080 $table = $this->tableName( $table );
1081 $res = $this->query( 'DESCRIBE '.$table, $fname );
1088 while ( $row = $this->fetchObject( $res ) ) {
1089 if ( $row->Field
== $field ) {
1098 * Determines whether an index exists
1099 * Usually aborts on failure
1100 * If errors are explicitly ignored, returns NULL on failure
1102 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1103 $info = $this->indexInfo( $table, $index, $fname );
1104 if ( is_null( $info ) ) {
1107 return $info !== false;
1113 * Get information about an index into an object
1114 * Returns false if the index does not exist
1116 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1117 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1118 # SHOW INDEX should work for 3.x and up:
1119 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1120 $table = $this->tableName( $table );
1121 $sql = 'SHOW INDEX FROM '.$table;
1122 $res = $this->query( $sql, $fname );
1128 while ( $row = $this->fetchObject( $res ) ) {
1129 if ( $row->Key_name
== $index ) {
1133 $this->freeResult($res);
1135 return empty($result) ?
false : $result;
1139 * Query whether a given table exists
1141 function tableExists( $table ) {
1142 $table = $this->tableName( $table );
1143 $old = $this->ignoreErrors( true );
1144 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1145 $this->ignoreErrors( $old );
1147 $this->freeResult( $res );
1155 * mysql_fetch_field() wrapper
1156 * Returns false if the field doesn't exist
1161 function fieldInfo( $table, $field ) {
1162 $table = $this->tableName( $table );
1163 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1164 $n = mysql_num_fields( $res->result
);
1165 for( $i = 0; $i < $n; $i++
) {
1166 $meta = mysql_fetch_field( $res->result
, $i );
1167 if( $field == $meta->name
) {
1168 return new MySQLField($meta);
1175 * mysql_field_type() wrapper
1177 function fieldType( $res, $index ) {
1178 if ( $res instanceof ResultWrapper
) {
1179 $res = $res->result
;
1181 return mysql_field_type( $res, $index );
1185 * Determines if a given index is unique
1187 function indexUnique( $table, $index ) {
1188 $indexInfo = $this->indexInfo( $table, $index );
1189 if ( !$indexInfo ) {
1192 return !$indexInfo[0]->Non_unique
;
1196 * INSERT wrapper, inserts an array into a table
1198 * $a may be a single associative array, or an array of these with numeric keys, for
1201 * Usually aborts on failure
1202 * If errors are explicitly ignored, returns success
1204 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1205 # No rows to insert, easy just return now
1206 if ( !count( $a ) ) {
1210 $table = $this->tableName( $table );
1211 if ( !is_array( $options ) ) {
1212 $options = array( $options );
1214 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1216 $keys = array_keys( $a[0] );
1219 $keys = array_keys( $a );
1222 $sql = 'INSERT ' . implode( ' ', $options ) .
1223 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1227 foreach ( $a as $row ) {
1233 $sql .= '(' . $this->makeList( $row ) . ')';
1236 $sql .= '(' . $this->makeList( $a ) . ')';
1238 return (bool)$this->query( $sql, $fname );
1242 * Make UPDATE options for the Database::update function
1245 * @param array $options The options passed to Database::update
1248 function makeUpdateOptions( $options ) {
1249 if( !is_array( $options ) ) {
1250 $options = array( $options );
1253 if ( in_array( 'LOW_PRIORITY', $options ) )
1254 $opts[] = $this->lowPriorityOption();
1255 if ( in_array( 'IGNORE', $options ) )
1257 return implode(' ', $opts);
1261 * UPDATE wrapper, takes a condition array and a SET array
1263 * @param string $table The table to UPDATE
1264 * @param array $values An array of values to SET
1265 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1266 * @param string $fname The Class::Function calling this function
1268 * @param array $options An array of UPDATE options, can be one or
1269 * more of IGNORE, LOW_PRIORITY
1272 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1273 $table = $this->tableName( $table );
1274 $opts = $this->makeUpdateOptions( $options );
1275 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1276 if ( $conds != '*' ) {
1277 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1279 return $this->query( $sql, $fname );
1283 * Makes an encoded list of strings from an array
1285 * LIST_COMMA - comma separated, no field names
1286 * LIST_AND - ANDed WHERE clause (without the WHERE)
1287 * LIST_OR - ORed WHERE clause (without the WHERE)
1288 * LIST_SET - comma separated with field names, like a SET clause
1289 * LIST_NAMES - comma separated field names
1291 function makeList( $a, $mode = LIST_COMMA
) {
1292 if ( !is_array( $a ) ) {
1293 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1298 foreach ( $a as $field => $value ) {
1300 if ( $mode == LIST_AND
) {
1302 } elseif($mode == LIST_OR
) {
1310 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1311 $list .= "($value)";
1312 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
1314 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array($value) ) {
1315 if( count( $value ) == 0 ) {
1316 throw new MWException( __METHOD__
.': empty input' );
1317 } elseif( count( $value ) == 1 ) {
1318 // Special-case single values, as IN isn't terribly efficient
1319 // Don't necessarily assume the single key is 0; we don't
1320 // enforce linear numeric ordering on other arrays here.
1321 $value = array_values( $value );
1322 $list .= $field." = ".$this->addQuotes( $value[0] );
1324 $list .= $field." IN (".$this->makeList($value).") ";
1326 } elseif( is_null($value) ) {
1327 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1328 $list .= "$field IS ";
1329 } elseif ( $mode == LIST_SET
) {
1330 $list .= "$field = ";
1334 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1335 $list .= "$field = ";
1337 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1344 * Change the current database
1346 function selectDB( $db ) {
1347 $this->mDBname
= $db;
1348 return mysql_select_db( $db, $this->mConn
);
1352 * Get the current DB name
1354 function getDBname() {
1355 return $this->mDBname
;
1359 * Get the server hostname or IP address
1361 function getServer() {
1362 return $this->mServer
;
1366 * Format a table name ready for use in constructing an SQL query
1368 * This does two important things: it quotes the table names to clean them up,
1369 * and it adds a table prefix if only given a table name with no quotes.
1371 * All functions of this object which require a table name call this function
1372 * themselves. Pass the canonical name to such functions. This is only needed
1373 * when calling query() directly.
1375 * @param string $name database table name
1376 * @return string full database name
1378 function tableName( $name ) {
1379 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1380 # Skip the entire process when we have a string quoted on both ends.
1381 # Note that we check the end so that we will still quote any use of
1382 # use of `database`.table. But won't break things if someone wants
1383 # to query a database table with a dot in the name.
1384 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) return $name;
1386 # Lets test for any bits of text that should never show up in a table
1387 # name. Basically anything like JOIN or ON which are actually part of
1388 # SQL queries, but may end up inside of the table value to combine
1389 # sql. Such as how the API is doing.
1390 # Note that we use a whitespace test rather than a \b test to avoid
1391 # any remote case where a word like on may be inside of a table name
1392 # surrounded by symbols which may be considered word breaks.
1393 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) return $name;
1395 # Split database and table into proper variables.
1396 # We reverse the explode so that database.table and table both output
1397 # the correct table.
1398 @list
( $table, $database ) = array_reverse( explode( '.', $name, 2 ) );
1399 $prefix = $this->mTablePrefix
; # Default prefix
1401 # A database name has been specified in input. Quote the table name
1402 # because we don't want any prefixes added.
1403 if( isset($database) ) $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
1405 # Note that we use the long format because php will complain in in_array if
1406 # the input is not an array, and will complain in is_array if it is not set.
1407 if( !isset( $database ) # Don't use shared database if pre selected.
1408 && isset( $wgSharedDB ) # We have a shared database
1409 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1410 && isset( $wgSharedTables )
1411 && is_array( $wgSharedTables )
1412 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1413 $database = $wgSharedDB;
1414 $prefix = isset( $wgSharedprefix ) ?
$wgSharedprefix : $prefix;
1417 # Quote the $database and $table and apply the prefix if not quoted.
1418 if( isset($database) ) $database = ( $database[0] == '`' ?
$database : "`{$database}`" );
1419 $table = ( $table[0] == '`' ?
$table : "`{$prefix}{$table}`" );
1421 # Merge our database and table into our final table name.
1422 $tableName = ( isset($database) ?
"{$database}.{$table}" : "{$table}" );
1424 # We're finished, return.
1429 * Fetch a number of table names into an array
1430 * This is handy when you need to construct SQL for joins
1433 * extract($dbr->tableNames('user','watchlist'));
1434 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1435 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1437 public function tableNames() {
1438 $inArray = func_get_args();
1440 foreach ( $inArray as $name ) {
1441 $retVal[$name] = $this->tableName( $name );
1447 * Fetch a number of table names into an zero-indexed numerical array
1448 * This is handy when you need to construct SQL for joins
1451 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1452 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1453 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1455 public function tableNamesN() {
1456 $inArray = func_get_args();
1458 foreach ( $inArray as $name ) {
1459 $retVal[] = $this->tableName( $name );
1467 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1470 $use_index_safe = is_array($use_index) ?
$use_index : array();
1471 $join_conds_safe = is_array($join_conds) ?
$join_conds : array();
1472 foreach ( $tables as $table ) {
1473 // Is there a JOIN and INDEX clause for this table?
1474 if ( isset($join_conds_safe[$table]) && isset($use_index_safe[$table]) ) {
1475 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1476 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1477 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
) . ')';
1478 $retJOIN[] = $tableClause;
1479 // Is there an INDEX clause?
1480 } else if ( isset($use_index_safe[$table]) ) {
1481 $tableClause = $this->tableName( $table );
1482 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1483 $ret[] = $tableClause;
1484 // Is there a JOIN clause?
1485 } else if ( isset($join_conds_safe[$table]) ) {
1486 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1487 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
) . ')';
1488 $retJOIN[] = $tableClause;
1490 $tableClause = $this->tableName( $table );
1491 $ret[] = $tableClause;
1494 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1495 $straightJoins = !empty($ret) ?
implode( ',', $ret ) : "";
1496 $otherJoins = !empty($retJOIN) ?
implode( ' ', $retJOIN ) : "";
1497 // Compile our final table clause
1498 return implode(' ',array($straightJoins,$otherJoins) );
1502 * Wrapper for addslashes()
1503 * @param string $s String to be slashed.
1504 * @return string slashed string.
1506 function strencode( $s ) {
1507 return mysql_real_escape_string( $s, $this->mConn
);
1511 * If it's a string, adds quotes and backslashes
1512 * Otherwise returns as-is
1514 function addQuotes( $s ) {
1515 if ( is_null( $s ) ) {
1518 # This will also quote numeric values. This should be harmless,
1519 # and protects against weird problems that occur when they really
1520 # _are_ strings such as article titles and string->number->string
1521 # conversion is not 1:1.
1522 return "'" . $this->strencode( $s ) . "'";
1527 * Escape string for safe LIKE usage
1529 function escapeLike( $s ) {
1530 $s=$this->strencode( $s );
1531 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1536 * Returns an appropriately quoted sequence value for inserting a new row.
1537 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1538 * subclass will return an integer, and save the value for insertId()
1540 function nextSequenceValue( $seqName ) {
1546 * PostgreSQL doesn't have them and returns ""
1548 function useIndexClause( $index ) {
1549 return "FORCE INDEX ($index)";
1553 * REPLACE query wrapper
1554 * PostgreSQL simulates this with a DELETE followed by INSERT
1555 * $row is the row to insert, an associative array
1556 * $uniqueIndexes is an array of indexes. Each element may be either a
1557 * field name or an array of field names
1559 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1560 * However if you do this, you run the risk of encountering errors which wouldn't have
1563 * @todo migrate comment to phodocumentor format
1565 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1566 $table = $this->tableName( $table );
1569 if ( !is_array( reset( $rows ) ) ) {
1570 $rows = array( $rows );
1573 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1575 foreach ( $rows as $row ) {
1581 $sql .= '(' . $this->makeList( $row ) . ')';
1583 return $this->query( $sql, $fname );
1587 * DELETE where the condition is a join
1588 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1590 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1591 * join condition matches, set $conds='*'
1593 * DO NOT put the join condition in $conds
1595 * @param string $delTable The table to delete from.
1596 * @param string $joinTable The other table.
1597 * @param string $delVar The variable to join on, in the first table.
1598 * @param string $joinVar The variable to join on, in the second table.
1599 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1601 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1603 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1606 $delTable = $this->tableName( $delTable );
1607 $joinTable = $this->tableName( $joinTable );
1608 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1609 if ( $conds != '*' ) {
1610 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1613 return $this->query( $sql, $fname );
1617 * Returns the size of a text field, or -1 for "unlimited"
1619 function textFieldSize( $table, $field ) {
1620 $table = $this->tableName( $table );
1621 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1622 $res = $this->query( $sql, 'Database::textFieldSize' );
1623 $row = $this->fetchObject( $res );
1624 $this->freeResult( $res );
1627 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1636 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1638 function lowPriorityOption() {
1639 return 'LOW_PRIORITY';
1643 * DELETE query wrapper
1645 * Use $conds == "*" to delete all rows
1647 function delete( $table, $conds, $fname = 'Database::delete' ) {
1649 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1651 $table = $this->tableName( $table );
1652 $sql = "DELETE FROM $table";
1653 if ( $conds != '*' ) {
1654 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1656 return $this->query( $sql, $fname );
1660 * INSERT SELECT wrapper
1661 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1662 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1663 * $conds may be "*" to copy the whole table
1664 * srcTable may be an array of tables.
1666 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1667 $insertOptions = array(), $selectOptions = array() )
1669 $destTable = $this->tableName( $destTable );
1670 if ( is_array( $insertOptions ) ) {
1671 $insertOptions = implode( ' ', $insertOptions );
1673 if( !is_array( $selectOptions ) ) {
1674 $selectOptions = array( $selectOptions );
1676 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1677 if( is_array( $srcTable ) ) {
1678 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1680 $srcTable = $this->tableName( $srcTable );
1682 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1683 " SELECT $startOpts " . implode( ',', $varMap ) .
1684 " FROM $srcTable $useIndex ";
1685 if ( $conds != '*' ) {
1686 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1688 $sql .= " $tailOpts";
1689 return $this->query( $sql, $fname );
1693 * Construct a LIMIT query with optional offset
1694 * This is used for query pages
1695 * $sql string SQL query we will append the limit too
1696 * $limit integer the SQL limit
1697 * $offset integer the SQL offset (default false)
1699 function limitResult($sql, $limit, $offset=false) {
1700 if( !is_numeric($limit) ) {
1701 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1703 return "$sql LIMIT "
1704 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1707 function limitResultForUpdate($sql, $num) {
1708 return $this->limitResult($sql, $num, 0);
1712 * Returns an SQL expression for a simple conditional.
1715 * @param string $cond SQL expression which will result in a boolean value
1716 * @param string $trueVal SQL expression to return if true
1717 * @param string $falseVal SQL expression to return if false
1718 * @return string SQL fragment
1720 function conditional( $cond, $trueVal, $falseVal ) {
1721 return " IF($cond, $trueVal, $falseVal) ";
1725 * Returns a comand for str_replace function in SQL query.
1726 * Uses REPLACE() in MySQL
1728 * @param string $orig String or column to modify
1729 * @param string $old String or column to seek
1730 * @param string $new String or column to replace with
1732 function strreplace( $orig, $old, $new ) {
1733 return "REPLACE({$orig}, {$old}, {$new})";
1737 * Determines if the last failure was due to a deadlock
1739 function wasDeadlock() {
1740 return $this->lastErrno() == 1213;
1744 * Perform a deadlock-prone transaction.
1746 * This function invokes a callback function to perform a set of write
1747 * queries. If a deadlock occurs during the processing, the transaction
1748 * will be rolled back and the callback function will be called again.
1751 * $dbw->deadlockLoop( callback, ... );
1753 * Extra arguments are passed through to the specified callback function.
1755 * Returns whatever the callback function returned on its successful,
1756 * iteration, or false on error, for example if the retry limit was
1759 function deadlockLoop() {
1760 $myFname = 'Database::deadlockLoop';
1763 $args = func_get_args();
1764 $function = array_shift( $args );
1765 $oldIgnore = $this->ignoreErrors( true );
1766 $tries = DEADLOCK_TRIES
;
1767 if ( is_array( $function ) ) {
1768 $fname = $function[0];
1773 $retVal = call_user_func_array( $function, $args );
1774 $error = $this->lastError();
1775 $errno = $this->lastErrno();
1776 $sql = $this->lastQuery();
1779 if ( $this->wasDeadlock() ) {
1781 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1783 $this->reportQueryError( $error, $errno, $sql, $fname );
1786 } while( $this->wasDeadlock() && --$tries > 0 );
1787 $this->ignoreErrors( $oldIgnore );
1788 if ( $tries <= 0 ) {
1789 $this->query( 'ROLLBACK', $myFname );
1790 $this->reportQueryError( $error, $errno, $sql, $fname );
1793 $this->query( 'COMMIT', $myFname );
1799 * Do a SELECT MASTER_POS_WAIT()
1801 * @param string $file the binlog file
1802 * @param string $pos the binlog position
1803 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1805 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
1806 $fname = 'Database::masterPosWait';
1807 wfProfileIn( $fname );
1809 # Commit any open transactions
1810 if ( $this->mTrxLevel
) {
1811 $this->immediateCommit();
1814 if ( !is_null( $this->mFakeSlaveLag
) ) {
1815 $wait = intval( ( $pos->pos
- microtime(true) +
$this->mFakeSlaveLag
) * 1e6
);
1816 if ( $wait > $timeout * 1e6
) {
1817 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1818 wfProfileOut( $fname );
1820 } elseif ( $wait > 0 ) {
1821 wfDebug( "Fake slave waiting $wait us\n" );
1823 wfProfileOut( $fname );
1826 wfDebug( "Fake slave up to date ($wait us)\n" );
1827 wfProfileOut( $fname );
1832 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1833 $encFile = $this->addQuotes( $pos->file
);
1834 $encPos = intval( $pos->pos
);
1835 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
1836 $res = $this->doQuery( $sql );
1837 if ( $res && $row = $this->fetchRow( $res ) ) {
1838 $this->freeResult( $res );
1839 wfProfileOut( $fname );
1842 wfProfileOut( $fname );
1848 * Get the position of the master from SHOW SLAVE STATUS
1850 function getSlavePos() {
1851 if ( !is_null( $this->mFakeSlaveLag
) ) {
1852 $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag
);
1853 wfDebug( __METHOD__
.": fake slave pos = $pos\n" );
1856 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1857 $row = $this->fetchObject( $res );
1859 return new MySQLMasterPos( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1866 * Get the position of the master from SHOW MASTER STATUS
1868 function getMasterPos() {
1869 if ( $this->mFakeMaster
) {
1870 return new MySQLMasterPos( 'fake', microtime( true ) );
1872 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1873 $row = $this->fetchObject( $res );
1875 return new MySQLMasterPos( $row->File
, $row->Position
);
1882 * Begin a transaction, committing any previously open transaction
1884 function begin( $fname = 'Database::begin' ) {
1885 $this->query( 'BEGIN', $fname );
1886 $this->mTrxLevel
= 1;
1892 function commit( $fname = 'Database::commit' ) {
1893 $this->query( 'COMMIT', $fname );
1894 $this->mTrxLevel
= 0;
1898 * Rollback a transaction.
1899 * No-op on non-transactional databases.
1901 function rollback( $fname = 'Database::rollback' ) {
1902 $this->query( 'ROLLBACK', $fname, true );
1903 $this->mTrxLevel
= 0;
1907 * Begin a transaction, committing any previously open transaction
1908 * @deprecated use begin()
1910 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1915 * Commit transaction, if one is open
1916 * @deprecated use commit()
1918 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1923 * Return MW-style timestamp used for MySQL schema
1925 function timestamp( $ts=0 ) {
1926 return wfTimestamp(TS_MW
,$ts);
1930 * Local database timestamp format or null
1932 function timestampOrNull( $ts = null ) {
1933 if( is_null( $ts ) ) {
1936 return $this->timestamp( $ts );
1943 function resultObject( $result ) {
1944 if( empty( $result ) ) {
1946 } elseif ( $result instanceof ResultWrapper
) {
1948 } elseif ( $result === true ) {
1949 // Successful write query
1952 return new ResultWrapper( $this, $result );
1957 * Return aggregated value alias
1959 function aggregateValue ($valuedata,$valuename='value') {
1964 * @return string wikitext of a link to the server software's web site
1966 function getSoftwareLink() {
1967 return "[http://www.mysql.com/ MySQL]";
1971 * @return string Version information from the database
1973 function getServerVersion() {
1974 return mysql_get_server_info( $this->mConn
);
1978 * Ping the server and try to reconnect if it there is no connection
1981 if( !function_exists( 'mysql_ping' ) ) {
1982 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1985 $ping = mysql_ping( $this->mConn
);
1990 // Need to reconnect manually in MySQL client 5.0.13+
1991 if ( version_compare( mysql_get_client_info(), '5.0.13', '>=' ) ) {
1992 mysql_close( $this->mConn
);
1993 $this->mOpened
= false;
1994 $this->mConn
= false;
1995 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
2003 * At the moment, this will only work if the DB user has the PROCESS privilege
2006 if ( !is_null( $this->mFakeSlaveLag
) ) {
2007 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
2008 return $this->mFakeSlaveLag
;
2010 $res = $this->query( 'SHOW PROCESSLIST' );
2011 # Find slave SQL thread
2012 while ( $row = $this->fetchObject( $res ) ) {
2013 /* This should work for most situations - when default db
2014 * for thread is not specified, it had no events executed,
2015 * and therefore it doesn't know yet how lagged it is.
2017 * Relay log I/O thread does not select databases.
2019 if ( $row->User
== 'system user' &&
2020 $row->State
!= 'Waiting for master to send event' &&
2021 $row->State
!= 'Connecting to master' &&
2022 $row->State
!= 'Queueing master event to the relay log' &&
2023 $row->State
!= 'Waiting for master update' &&
2024 $row->State
!= 'Requesting binlog dump'
2026 # This is it, return the time (except -ve)
2027 if ( $row->Time
> 0x7fffffff ) {
2038 * Get status information from SHOW STATUS in an associative array
2040 function getStatus($which="%") {
2041 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2043 while ( $row = $this->fetchObject( $res ) ) {
2044 $status[$row->Variable_name
] = $row->Value
;
2050 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2052 function maxListLen() {
2056 function encodeBlob($b) {
2060 function decodeBlob($b) {
2065 * Override database's default connection timeout.
2066 * May be useful for very long batch queries such as
2067 * full-wiki dumps, where a single query reads out
2068 * over hours or days.
2069 * @param int $timeout in seconds
2071 public function setTimeout( $timeout ) {
2072 $this->query( "SET net_read_timeout=$timeout" );
2073 $this->query( "SET net_write_timeout=$timeout" );
2077 * Read and execute SQL commands from a file.
2078 * Returns true on success, error string on failure
2079 * @param string $filename File name to open
2080 * @param callback $lineCallback Optional function called before reading each line
2081 * @param callback $resultCallback Optional function called for each MySQL result
2083 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2084 $fp = fopen( $filename, 'r' );
2085 if ( false === $fp ) {
2086 return "Could not open \"{$filename}\".\n";
2088 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2094 * Read and execute commands from an open file handle
2095 * Returns true on success, error string on failure
2096 * @param string $fp File handle
2097 * @param callback $lineCallback Optional function called before reading each line
2098 * @param callback $resultCallback Optional function called for each MySQL result
2100 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2103 $dollarquote = false;
2105 while ( ! feof( $fp ) ) {
2106 if ( $lineCallback ) {
2107 call_user_func( $lineCallback );
2109 $line = trim( fgets( $fp, 1024 ) );
2110 $sl = strlen( $line ) - 1;
2112 if ( $sl < 0 ) { continue; }
2113 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2115 ## Allow dollar quoting for function declarations
2116 if (substr($line,0,4) == '$mw$') {
2118 $dollarquote = false;
2122 $dollarquote = true;
2125 else if (!$dollarquote) {
2126 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
2128 $line = substr( $line, 0, $sl );
2132 if ( '' != $cmd ) { $cmd .= ' '; }
2136 $cmd = str_replace(';;', ";", $cmd);
2137 $cmd = $this->replaceVars( $cmd );
2138 $res = $this->query( $cmd, __METHOD__
, true );
2139 if ( $resultCallback ) {
2140 call_user_func( $resultCallback, $res );
2143 if ( false === $res ) {
2144 $err = $this->lastError();
2145 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2157 * Replace variables in sourced SQL
2159 protected function replaceVars( $ins ) {
2161 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2162 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2163 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2166 // Ordinary variables
2167 foreach ( $varnames as $var ) {
2168 if( isset( $GLOBALS[$var] ) ) {
2169 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2170 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2171 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2172 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2177 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
2178 array( &$this, 'tableNameCallback' ), $ins );
2183 * Table name callback
2186 protected function tableNameCallback( $matches ) {
2187 return $this->tableName( $matches[1] );
2191 * Build a concatenation list to feed into a SQL query
2193 function buildConcat( $stringList ) {
2194 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2200 * Database abstraction object for mySQL
2201 * Inherit all methods and properties of Database::Database()
2203 * @addtogroup Database
2206 class DatabaseMysql
extends Database
{
2210 /******************************************************************************
2212 *****************************************************************************/
2216 * @addtogroup Database
2221 function DBObject($data) {
2222 $this->mData
= $data;
2230 return $this->mData
;
2236 * @addtogroup Database
2238 * This allows us to distinguish a blob from a normal string and an array of strings
2242 function __construct($data) {
2243 $this->mData
= $data;
2246 return $this->mData
;
2252 * @addtogroup Database
2255 private $name, $tablename, $default, $max_length, $nullable,
2256 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2257 function __construct ($info) {
2258 $this->name
= $info->name
;
2259 $this->tablename
= $info->table
;
2260 $this->default = $info->def
;
2261 $this->max_length
= $info->max_length
;
2262 $this->nullable
= !$info->not_null
;
2263 $this->is_pk
= $info->primary_key
;
2264 $this->is_unique
= $info->unique_key
;
2265 $this->is_multiple
= $info->multiple_key
;
2266 $this->is_key
= ($this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
2267 $this->type
= $info->type
;
2274 function tableName() {
2275 return $this->tableName
;
2278 function defaultValue() {
2279 return $this->default;
2282 function maxLength() {
2283 return $this->max_length
;
2286 function nullable() {
2287 return $this->nullable
;
2291 return $this->is_key
;
2294 function isMultipleKey() {
2295 return $this->is_multiple
;
2303 /******************************************************************************
2305 *****************************************************************************/
2308 * Database error base class
2309 * @addtogroup Database
2311 class DBError
extends MWException
{
2315 * Construct a database error
2316 * @param Database $db The database object which threw the error
2317 * @param string $error A simple error message to be used for debugging
2319 function __construct( Database
&$db, $error ) {
2321 parent
::__construct( $error );
2326 * @addtogroup Database
2328 class DBConnectionError
extends DBError
{
2331 function __construct( Database
&$db, $error = 'unknown error' ) {
2332 $msg = 'DB connection error';
2333 if ( trim( $error ) != '' ) {
2336 $this->error
= $error;
2337 parent
::__construct( $db, $msg );
2340 function useOutputPage() {
2341 // Not likely to work
2345 function useMessageCache() {
2346 // Not likely to work
2350 function getText() {
2351 return $this->getMessage() . "\n";
2354 function getLogMessage() {
2355 # Don't send to the exception log
2359 function getPageTitle() {
2361 return "$wgSitename has a problem";
2364 function getHTML() {
2365 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding;
2366 global $wgSitename, $wgServer, $wgMessageCache;
2368 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
2369 # Hard coding strings instead.
2371 $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>";
2372 $mainpage = 'Main Page';
2373 $searchdisabled = <<<EOT
2374 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
2375 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
2379 <!-- SiteSearch Google -->
2380 <FORM method=GET action=\"http://www.google.com/search\">
2381 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
2382 <A HREF=\"http://www.google.com/\">
2383 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
2384 border=\"0\" ALT=\"Google\"></A>
2387 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
2388 <INPUT type=submit name=btnG VALUE=\"Google Search\">
2390 <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 />
2391 <input type='hidden' name='ie' value='$2'>
2392 <input type='hidden' name='oe' value='$2'>
2396 <!-- SiteSearch Google -->";
2397 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
2399 # No database access
2400 if ( is_object( $wgMessageCache ) ) {
2401 $wgMessageCache->disable();
2404 if ( trim( $this->error
) == '' ) {
2405 $this->error
= $this->db
->getProperty('mServer');
2408 $text = str_replace( '$1', $this->error
, $noconnect );
2409 $text .= wfGetSiteNotice();
2411 if($wgUseFileCache) {
2416 $t = Title
::newFromURL( $title );
2417 } elseif (@/**/$_REQUEST['search']) {
2418 $search = $_REQUEST['search'];
2419 return $searchdisabled .
2420 str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
2421 $wgInputEncoding ), $googlesearch );
2423 $t = Title
::newFromText( $mainpage );
2427 $cache = new HTMLFileCache( $t );
2428 if( $cache->isFileCached() ) {
2429 // @todo, FIXME: $msg is not defined on the next line.
2430 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
2431 $cachederror . "</b></p>\n";
2433 $tag = '<div id="article">';
2434 $text = str_replace(
2437 $cache->fetchPageText() );
2446 * @addtogroup Database
2448 class DBQueryError
extends DBError
{
2449 public $error, $errno, $sql, $fname;
2451 function __construct( Database
&$db, $error, $errno, $sql, $fname ) {
2452 $message = "A database error has occurred\n" .
2454 "Function: $fname\n" .
2455 "Error: $errno $error\n";
2457 parent
::__construct( $db, $message );
2458 $this->error
= $error;
2459 $this->errno
= $errno;
2461 $this->fname
= $fname;
2464 function getText() {
2465 if ( $this->useMessageCache() ) {
2466 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2467 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
2469 return $this->getMessage();
2474 global $wgShowSQLErrors;
2475 if( !$wgShowSQLErrors ) {
2476 return $this->msg( 'sqlhidden', 'SQL hidden' );
2482 function getLogMessage() {
2483 # Don't send to the exception log
2487 function getPageTitle() {
2488 return $this->msg( 'databaseerror', 'Database error' );
2491 function getHTML() {
2492 if ( $this->useMessageCache() ) {
2493 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2494 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
2496 return nl2br( htmlspecialchars( $this->getMessage() ) );
2502 * @addtogroup Database
2504 class DBUnexpectedError
extends DBError
{}
2508 * Result wrapper for grabbing data queried by someone else
2509 * @addtogroup Database
2511 class ResultWrapper
implements Iterator
{
2512 var $db, $result, $pos = 0, $currentRow = null;
2515 * Create a new result object from a result resource and a Database object
2517 function ResultWrapper( $database, $result ) {
2518 $this->db
= $database;
2519 if ( $result instanceof ResultWrapper
) {
2520 $this->result
= $result->result
;
2522 $this->result
= $result;
2527 * Get the number of rows in a result object
2529 function numRows() {
2530 return $this->db
->numRows( $this->result
);
2534 * Fetch the next row from the given result object, in object form.
2535 * Fields can be retrieved with $row->fieldname, with fields acting like
2538 * @param $res SQL result object as returned from Database::query(), etc.
2539 * @return MySQL row object
2540 * @throws DBUnexpectedError Thrown if the database returns an error
2542 function fetchObject() {
2543 return $this->db
->fetchObject( $this->result
);
2547 * Fetch the next row from the given result object, in associative array
2548 * form. Fields are retrieved with $row['fieldname'].
2550 * @param $res SQL result object as returned from Database::query(), etc.
2551 * @return MySQL row object
2552 * @throws DBUnexpectedError Thrown if the database returns an error
2554 function fetchRow() {
2555 return $this->db
->fetchRow( $this->result
);
2559 * Free a result object
2562 $this->db
->freeResult( $this->result
);
2563 unset( $this->result
);
2568 * Change the position of the cursor in a result object
2569 * See mysql_data_seek()
2571 function seek( $row ) {
2572 $this->db
->dataSeek( $this->result
, $row );
2575 /*********************
2576 * Iterator functions
2577 * Note that using these in combination with the non-iterator functions
2578 * above may cause rows to be skipped or repeated.
2582 if ($this->numRows()) {
2583 $this->db
->dataSeek($this->result
, 0);
2586 $this->currentRow
= null;
2589 function current() {
2590 if ( is_null( $this->currentRow
) ) {
2593 return $this->currentRow
;
2602 $this->currentRow
= $this->fetchObject();
2603 return $this->currentRow
;
2607 return $this->current() !== false;
2611 class MySQLMasterPos
{
2614 function __construct( $file, $pos ) {
2615 $this->file
= $file;
2619 function __toString() {
2620 return "{$this->file}/{$this->pos}";