* Installer for Oracle fixes
[mediawiki.git] / includes / db / Database.php
blobe6a461d73d2c749d911ec9ae1187bc115dd2a2a8
1 <?php
2 /**
3 * @defgroup Database Database
5 * @file
6 * @ingroup Database
7 * This file deals with database interface functions
8 * and query specifics/optimisations
9 */
11 /** Number of times to re-try an operation in case of deadlock */
12 define( 'DEADLOCK_TRIES', 4 );
13 /** Minimum time to wait before retry, in microseconds */
14 define( 'DEADLOCK_DELAY_MIN', 500000 );
15 /** Maximum time to wait before retry */
16 define( 'DEADLOCK_DELAY_MAX', 1500000 );
18 /**
19 * Base interface for all DBMS-specific code. At a bare minimum, all of the
20 * following must be implemented to support MediaWiki
22 * @file
23 * @ingroup Database
25 interface DatabaseType {
26 /**
27 * Get the type of the DBMS, as it appears in $wgDBtype.
29 * @return string
31 public function getType();
33 /**
34 * Open a connection to the database. Usually aborts on failure
36 * @param $server String: database server host
37 * @param $user String: database user name
38 * @param $password String: database user password
39 * @param $dbName String: database name
40 * @return bool
41 * @throws DBConnectionError
43 public function open( $server, $user, $password, $dbName );
45 /**
46 * The DBMS-dependent part of query()
47 * @todo @fixme Make this private someday
49 * @param $sql String: SQL query.
50 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
51 * @private
53 /*private*/ function doQuery( $sql );
55 /**
56 * Fetch the next row from the given result object, in object form.
57 * Fields can be retrieved with $row->fieldname, with fields acting like
58 * member variables.
60 * @param $res SQL result object as returned from DatabaseBase::query(), etc.
61 * @return Row object
62 * @throws DBUnexpectedError Thrown if the database returns an error
64 public function fetchObject( $res );
66 /**
67 * Fetch the next row from the given result object, in associative array
68 * form. Fields are retrieved with $row['fieldname'].
70 * @param $res SQL result object as returned from DatabaseBase::query(), etc.
71 * @return Row object
72 * @throws DBUnexpectedError Thrown if the database returns an error
74 public function fetchRow( $res );
76 /**
77 * Get the number of rows in a result object
79 * @param $res Mixed: A SQL result
80 * @return int
82 public function numRows( $res );
84 /**
85 * Get the number of fields in a result object
86 * @see http://www.php.net/mysql_num_fields
88 * @param $res Mixed: A SQL result
89 * @return int
91 public function numFields( $res );
93 /**
94 * Get a field name in a result object
95 * @see http://www.php.net/mysql_field_name
97 * @param $res Mixed: A SQL result
98 * @param $n Integer
99 * @return string
101 public function fieldName( $res, $n );
104 * Get the inserted value of an auto-increment row
106 * The value inserted should be fetched from nextSequenceValue()
108 * Example:
109 * $id = $dbw->nextSequenceValue('page_page_id_seq');
110 * $dbw->insert('page',array('page_id' => $id));
111 * $id = $dbw->insertId();
113 * @return int
115 public function insertId();
118 * Change the position of the cursor in a result object
119 * @see http://www.php.net/mysql_data_seek
121 * @param $res Mixed: A SQL result
122 * @param $row Mixed: Either MySQL row or ResultWrapper
124 public function dataSeek( $res, $row );
127 * Get the last error number
128 * @see http://www.php.net/mysql_errno
130 * @return int
132 public function lastErrno();
135 * Get a description of the last error
136 * @see http://www.php.net/mysql_error
138 * @return string
140 public function lastError();
143 * mysql_fetch_field() wrapper
144 * Returns false if the field doesn't exist
146 * @param $table string: table name
147 * @param $field string: field name
149 public function fieldInfo( $table, $field );
152 * Get the number of rows affected by the last write query
153 * @see http://www.php.net/mysql_affected_rows
155 * @return int
157 public function affectedRows();
160 * Wrapper for addslashes()
162 * @param $s string: to be slashed.
163 * @return string: slashed string.
165 public function strencode( $s );
168 * Returns a wikitext link to the DB's website, e.g.,
169 * return "[http://www.mysql.com/ MySQL]";
170 * Should at least contain plain text, if for some reason
171 * your database has no website.
173 * @return string: wikitext of a link to the server software's web site
175 public static function getSoftwareLink();
178 * A string describing the current software version, like from
179 * mysql_get_server_info().
181 * @return string: Version information from the database server.
183 public function getServerVersion();
186 * A string describing the current software version, and possibly
187 * other details in a user-friendly way. Will be listed on Special:Version, etc.
188 * Use getServerVersion() to get machine-friendly information.
190 * @return string: Version information from the database server
192 public function getServerInfo();
196 * Database abstraction object
197 * @ingroup Database
199 abstract class DatabaseBase implements DatabaseType {
201 # ------------------------------------------------------------------------------
202 # Variables
203 # ------------------------------------------------------------------------------
205 protected $mLastQuery = '';
206 protected $mDoneWrites = false;
207 protected $mPHPError = false;
209 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
210 protected $mOpened = false;
212 protected $mTablePrefix;
213 protected $mFlags;
214 protected $mTrxLevel = 0;
215 protected $mErrorCount = 0;
216 protected $mLBInfo = array();
217 protected $mFakeSlaveLag = null, $mFakeMaster = false;
218 protected $mDefaultBigSelects = null;
220 # ------------------------------------------------------------------------------
221 # Accessors
222 # ------------------------------------------------------------------------------
223 # These optionally set a variable and return the previous state
226 * A string describing the current software version, and possibly
227 * other details in a user-friendly way. Will be listed on Special:Version, etc.
228 * Use getServerVersion() to get machine-friendly information.
230 * @return string: Version information from the database server
232 public function getServerInfo() {
233 return $this->getServerVersion();
237 * Boolean, controls output of large amounts of debug information
239 function debug( $debug = null ) {
240 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
244 * Turns buffering of SQL result sets on (true) or off (false).
245 * Default is "on" and it should not be changed without good reasons.
247 function bufferResults( $buffer = null ) {
248 if ( is_null( $buffer ) ) {
249 return !(bool)( $this->mFlags & DBO_NOBUFFER );
250 } else {
251 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
256 * Turns on (false) or off (true) the automatic generation and sending
257 * of a "we're sorry, but there has been a database error" page on
258 * database errors. Default is on (false). When turned off, the
259 * code should use lastErrno() and lastError() to handle the
260 * situation as appropriate.
262 function ignoreErrors( $ignoreErrors = null ) {
263 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
267 * The current depth of nested transactions
268 * @param $level Integer: , default NULL.
270 function trxLevel( $level = null ) {
271 return wfSetVar( $this->mTrxLevel, $level );
275 * Number of errors logged, only useful when errors are ignored
277 function errorCount( $count = null ) {
278 return wfSetVar( $this->mErrorCount, $count );
281 function tablePrefix( $prefix = null ) {
282 return wfSetVar( $this->mTablePrefix, $prefix );
286 * Properties passed down from the server info array of the load balancer
288 function getLBInfo( $name = null ) {
289 if ( is_null( $name ) ) {
290 return $this->mLBInfo;
291 } else {
292 if ( array_key_exists( $name, $this->mLBInfo ) ) {
293 return $this->mLBInfo[$name];
294 } else {
295 return null;
300 function setLBInfo( $name, $value = null ) {
301 if ( is_null( $value ) ) {
302 $this->mLBInfo = $name;
303 } else {
304 $this->mLBInfo[$name] = $value;
309 * Set lag time in seconds for a fake slave
311 function setFakeSlaveLag( $lag ) {
312 $this->mFakeSlaveLag = $lag;
316 * Make this connection a fake master
318 function setFakeMaster( $enabled = true ) {
319 $this->mFakeMaster = $enabled;
323 * Returns true if this database supports (and uses) cascading deletes
325 function cascadingDeletes() {
326 return false;
330 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
332 function cleanupTriggers() {
333 return false;
337 * Returns true if this database is strict about what can be put into an IP field.
338 * Specifically, it uses a NULL value instead of an empty string.
340 function strictIPs() {
341 return false;
345 * Returns true if this database uses timestamps rather than integers
347 function realTimestamps() {
348 return false;
352 * Returns true if this database does an implicit sort when doing GROUP BY
354 function implicitGroupby() {
355 return true;
359 * Returns true if this database does an implicit order by when the column has an index
360 * For example: SELECT page_title FROM page LIMIT 1
362 function implicitOrderby() {
363 return true;
367 * Returns true if this database requires that SELECT DISTINCT queries require that all
368 ORDER BY expressions occur in the SELECT list per the SQL92 standard
370 function standardSelectDistinct() {
371 return true;
375 * Returns true if this database can do a native search on IP columns
376 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
378 function searchableIPs() {
379 return false;
383 * Returns true if this database can use functional indexes
385 function functionalIndexes() {
386 return false;
390 * Return the last query that went through DatabaseBase::query()
391 * @return String
393 function lastQuery() { return $this->mLastQuery; }
397 * Returns true if the connection may have been used for write queries.
398 * Should return true if unsure.
400 function doneWrites() { return $this->mDoneWrites; }
403 * Is a connection to the database open?
404 * @return Boolean
406 function isOpen() { return $this->mOpened; }
409 * Set a flag for this connection
411 * @param $flag Integer: DBO_* constants from Defines.php:
412 * - DBO_DEBUG: output some debug info (same as debug())
413 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
414 * - DBO_IGNORE: ignore errors (same as ignoreErrors())
415 * - DBO_TRX: automatically start transactions
416 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
417 * and removes it in command line mode
418 * - DBO_PERSISTENT: use persistant database connection
420 function setFlag( $flag ) {
421 $this->mFlags |= $flag;
425 * Clear a flag for this connection
427 * @param $flag: same as setFlag()'s $flag param
429 function clearFlag( $flag ) {
430 $this->mFlags &= ~$flag;
434 * Returns a boolean whether the flag $flag is set for this connection
436 * @param $flag: same as setFlag()'s $flag param
437 * @return Boolean
439 function getFlag( $flag ) {
440 return !!( $this->mFlags & $flag );
444 * General read-only accessor
446 function getProperty( $name ) {
447 return $this->$name;
450 function getWikiID() {
451 if ( $this->mTablePrefix ) {
452 return "{$this->mDBname}-{$this->mTablePrefix}";
453 } else {
454 return $this->mDBname;
459 * Return a path to the DBMS-specific schema, otherwise default to tables.sql
461 public function getSchema() {
462 global $IP;
463 if ( file_exists( "$IP/maintenance/" . $this->getType() . "/tables.sql" ) ) {
464 return "$IP/maintenance/" . $this->getType() . "/tables.sql";
465 } else {
466 return "$IP/maintenance/tables.sql";
470 # ------------------------------------------------------------------------------
471 # Other functions
472 # ------------------------------------------------------------------------------
475 * Constructor.
476 * @param $server String: database server host
477 * @param $user String: database user name
478 * @param $password String: database user password
479 * @param $dbName String: database name
480 * @param $flags
481 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
483 function __construct( $server = false, $user = false, $password = false, $dbName = false,
484 $flags = 0, $tablePrefix = 'get from global'
486 global $wgOut, $wgDBprefix, $wgCommandLineMode;
488 # Can't get a reference if it hasn't been set yet
489 if ( !isset( $wgOut ) ) {
490 $wgOut = null;
492 $this->mFlags = $flags;
494 if ( $this->mFlags & DBO_DEFAULT ) {
495 if ( $wgCommandLineMode ) {
496 $this->mFlags &= ~DBO_TRX;
497 } else {
498 $this->mFlags |= DBO_TRX;
503 // Faster read-only access
504 if ( wfReadOnly() ) {
505 $this->mFlags |= DBO_PERSISTENT;
506 $this->mFlags &= ~DBO_TRX;
509 /** Get the default table prefix*/
510 if ( $tablePrefix == 'get from global' ) {
511 $this->mTablePrefix = $wgDBprefix;
512 } else {
513 $this->mTablePrefix = $tablePrefix;
516 if ( $server ) {
517 $this->open( $server, $user, $password, $dbName );
522 * Same as new DatabaseMysql( ... ), kept for backward compatibility
523 * @param $server String: database server host
524 * @param $user String: database user name
525 * @param $password String: database user password
526 * @param $dbName String: database name
527 * @param $flags
529 static function newFromParams( $server, $user, $password, $dbName, $flags = 0 ) {
530 wfDeprecated( __METHOD__ );
531 return new DatabaseMysql( $server, $user, $password, $dbName, $flags );
534 protected function installErrorHandler() {
535 $this->mPHPError = false;
536 $this->htmlErrors = ini_set( 'html_errors', '0' );
537 set_error_handler( array( $this, 'connectionErrorHandler' ) );
540 protected function restoreErrorHandler() {
541 restore_error_handler();
542 if ( $this->htmlErrors !== false ) {
543 ini_set( 'html_errors', $this->htmlErrors );
545 if ( $this->mPHPError ) {
546 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
547 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
548 return $error;
549 } else {
550 return false;
554 protected function connectionErrorHandler( $errno, $errstr ) {
555 $this->mPHPError = $errstr;
559 * Closes a database connection.
560 * if it is open : commits any open transactions
562 * @return Bool operation success. true if already closed.
564 function close() {
565 # Stub, should probably be overridden
566 return true;
570 * @param $error String: fallback error message, used if none is given by DB
572 function reportConnectionError( $error = 'Unknown error' ) {
573 $myError = $this->lastError();
574 if ( $myError ) {
575 $error = $myError;
578 # New method
579 throw new DBConnectionError( $this, $error );
583 * Determine whether a query writes to the DB.
584 * Should return true if unsure.
586 function isWriteQuery( $sql ) {
587 return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW|\(SELECT)\b/i', $sql );
591 * Usually aborts on failure. If errors are explicitly ignored, returns success.
593 * @param $sql String: SQL query
594 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
595 * comment (you can use __METHOD__ or add some extra info)
596 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
597 * maybe best to catch the exception instead?
598 * @return true for a successful write query, ResultWrapper object for a successful read query,
599 * or false on failure if $tempIgnore set
600 * @throws DBQueryError Thrown when the database returns an error of any kind
602 public function query( $sql, $fname = '', $tempIgnore = false ) {
603 global $wgProfiler;
605 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
606 if ( isset( $wgProfiler ) ) {
607 # generalizeSQL will probably cut down the query to reasonable
608 # logging size most of the time. The substr is really just a sanity check.
610 # Who's been wasting my precious column space? -- TS
611 # $profName = 'query: ' . $fname . ' ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
613 if ( $isMaster ) {
614 $queryProf = 'query-m: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
615 $totalProf = 'DatabaseBase::query-master';
616 } else {
617 $queryProf = 'query: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
618 $totalProf = 'DatabaseBase::query';
621 wfProfileIn( $totalProf );
622 wfProfileIn( $queryProf );
625 $this->mLastQuery = $sql;
626 if ( !$this->mDoneWrites && $this->isWriteQuery( $sql ) ) {
627 // Set a flag indicating that writes have been done
628 wfDebug( __METHOD__ . ": Writes done: $sql\n" );
629 $this->mDoneWrites = true;
632 # Add a comment for easy SHOW PROCESSLIST interpretation
633 # if ( $fname ) {
634 global $wgUser;
635 if ( is_object( $wgUser ) && $wgUser->mDataLoaded ) {
636 $userName = $wgUser->getName();
637 if ( mb_strlen( $userName ) > 15 ) {
638 $userName = mb_substr( $userName, 0, 15 ) . '...';
640 $userName = str_replace( '/', '', $userName );
641 } else {
642 $userName = '';
644 $commentedSql = preg_replace( '/\s/', " /* $fname $userName */ ", $sql, 1 );
645 # } else {
646 # $commentedSql = $sql;
649 # If DBO_TRX is set, start a transaction
650 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() &&
651 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' ) {
652 // avoid establishing transactions for SHOW and SET statements too -
653 // that would delay transaction initializations to once connection
654 // is really used by application
655 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
656 if ( strpos( $sqlstart, "SHOW " ) !== 0 and strpos( $sqlstart, "SET " ) !== 0 )
657 $this->begin();
660 if ( $this->debug() ) {
661 static $cnt = 0;
663 $cnt++;
664 $sqlx = substr( $commentedSql, 0, 500 );
665 $sqlx = strtr( $sqlx, "\t\n", ' ' );
667 if ( $isMaster ) {
668 wfDebug( "Query $cnt (master): $sqlx\n" );
669 } else {
670 wfDebug( "Query $cnt (slave): $sqlx\n" );
674 if ( istainted( $sql ) & TC_MYSQL ) {
675 throw new MWException( 'Tainted query found' );
678 # Do the query and handle errors
679 $ret = $this->doQuery( $commentedSql );
681 # Try reconnecting if the connection was lost
682 if ( false === $ret && $this->wasErrorReissuable() ) {
683 # Transaction is gone, like it or not
684 $this->mTrxLevel = 0;
685 wfDebug( "Connection lost, reconnecting...\n" );
687 if ( $this->ping() ) {
688 wfDebug( "Reconnected\n" );
689 $sqlx = substr( $commentedSql, 0, 500 );
690 $sqlx = strtr( $sqlx, "\t\n", ' ' );
691 global $wgRequestTime;
692 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
693 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
694 $ret = $this->doQuery( $commentedSql );
695 } else {
696 wfDebug( "Failed\n" );
700 if ( false === $ret ) {
701 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
704 if ( isset( $wgProfiler ) ) {
705 wfProfileOut( $queryProf );
706 wfProfileOut( $totalProf );
709 return $this->resultObject( $ret );
713 * @param $error String
714 * @param $errno Integer
715 * @param $sql String
716 * @param $fname String
717 * @param $tempIgnore Boolean
719 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
720 # Ignore errors during error handling to avoid infinite recursion
721 $ignore = $this->ignoreErrors( true );
722 ++$this->mErrorCount;
724 if ( $ignore || $tempIgnore ) {
725 wfDebug( "SQL ERROR (ignored): $error\n" );
726 $this->ignoreErrors( $ignore );
727 } else {
728 $sql1line = str_replace( "\n", "\\n", $sql );
729 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
730 wfDebug( "SQL ERROR: " . $error . "\n" );
731 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
737 * Intended to be compatible with the PEAR::DB wrapper functions.
738 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
740 * ? = scalar value, quoted as necessary
741 * ! = raw SQL bit (a function for instance)
742 * & = filename; reads the file and inserts as a blob
743 * (we don't use this though...)
745 function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
746 /* MySQL doesn't support prepared statements (yet), so just
747 pack up the query for reference. We'll manually replace
748 the bits later. */
749 return array( 'query' => $sql, 'func' => $func );
752 function freePrepared( $prepared ) {
753 /* No-op by default */
757 * Execute a prepared query with the various arguments
758 * @param $prepared String: the prepared sql
759 * @param $args Mixed: Either an array here, or put scalars as varargs
761 function execute( $prepared, $args = null ) {
762 if ( !is_array( $args ) ) {
763 # Pull the var args
764 $args = func_get_args();
765 array_shift( $args );
768 $sql = $this->fillPrepared( $prepared['query'], $args );
770 return $this->query( $sql, $prepared['func'] );
774 * Prepare & execute an SQL statement, quoting and inserting arguments
775 * in the appropriate places.
776 * @param $query String
777 * @param $args ...
779 function safeQuery( $query, $args = null ) {
780 $prepared = $this->prepare( $query, 'DatabaseBase::safeQuery' );
782 if ( !is_array( $args ) ) {
783 # Pull the var args
784 $args = func_get_args();
785 array_shift( $args );
788 $retval = $this->execute( $prepared, $args );
789 $this->freePrepared( $prepared );
791 return $retval;
795 * For faking prepared SQL statements on DBs that don't support
796 * it directly.
797 * @param $preparedQuery String: a 'preparable' SQL statement
798 * @param $args Array of arguments to fill it with
799 * @return string executable SQL
801 function fillPrepared( $preparedQuery, $args ) {
802 reset( $args );
803 $this->preparedArgs =& $args;
805 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
806 array( &$this, 'fillPreparedArg' ), $preparedQuery );
810 * preg_callback func for fillPrepared()
811 * The arguments should be in $this->preparedArgs and must not be touched
812 * while we're doing this.
814 * @param $matches Array
815 * @return String
816 * @private
818 function fillPreparedArg( $matches ) {
819 switch( $matches[1] ) {
820 case '\\?': return '?';
821 case '\\!': return '!';
822 case '\\&': return '&';
825 list( /* $n */ , $arg ) = each( $this->preparedArgs );
827 switch( $matches[1] ) {
828 case '?': return $this->addQuotes( $arg );
829 case '!': return $arg;
830 case '&':
831 # return $this->addQuotes( file_get_contents( $arg ) );
832 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
833 default:
834 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
839 * Free a result object
840 * @param $res Mixed: A SQL result
842 function freeResult( $res ) {
843 # Stub. Might not really need to be overridden, since results should
844 # be freed by PHP when the variable goes out of scope anyway.
848 * Simple UPDATE wrapper
849 * Usually aborts on failure
850 * If errors are explicitly ignored, returns success
852 * This function exists for historical reasons, DatabaseBase::update() has a more standard
853 * calling convention and feature set
855 function set( $table, $var, $value, $cond, $fname = 'DatabaseBase::set' ) {
856 $table = $this->tableName( $table );
857 $sql = "UPDATE $table SET $var = '" .
858 $this->strencode( $value ) . "' WHERE ($cond)";
860 return (bool)$this->query( $sql, $fname );
864 * Simple SELECT wrapper, returns a single field, input must be encoded
865 * Usually aborts on failure
866 * If errors are explicitly ignored, returns FALSE on failure
868 function selectField( $table, $var, $cond = '', $fname = 'DatabaseBase::selectField', $options = array() ) {
869 if ( !is_array( $options ) ) {
870 $options = array( $options );
873 $options['LIMIT'] = 1;
875 $res = $this->select( $table, $var, $cond, $fname, $options );
877 if ( $res === false || !$this->numRows( $res ) ) {
878 return false;
881 $row = $this->fetchRow( $res );
883 if ( $row !== false ) {
884 return reset( $row );
885 } else {
886 return false;
891 * Returns an optional USE INDEX clause to go after the table, and a
892 * string to go at the end of the query
894 * @private
896 * @param $options Array: associative array of options to be turned into
897 * an SQL query, valid keys are listed in the function.
898 * @return Array
900 function makeSelectOptions( $options ) {
901 $preLimitTail = $postLimitTail = '';
902 $startOpts = '';
904 $noKeyOptions = array();
906 foreach ( $options as $key => $option ) {
907 if ( is_numeric( $key ) ) {
908 $noKeyOptions[$option] = true;
912 if ( isset( $options['GROUP BY'] ) ) {
913 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
916 if ( isset( $options['HAVING'] ) ) {
917 $preLimitTail .= " HAVING {$options['HAVING']}";
920 if ( isset( $options['ORDER BY'] ) ) {
921 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
924 // if (isset($options['LIMIT'])) {
925 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
926 // isset($options['OFFSET']) ? $options['OFFSET']
927 // : false);
928 // }
930 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
931 $postLimitTail .= ' FOR UPDATE';
934 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
935 $postLimitTail .= ' LOCK IN SHARE MODE';
938 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
939 $startOpts .= 'DISTINCT';
942 # Various MySQL extensions
943 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
944 $startOpts .= ' /*! STRAIGHT_JOIN */';
947 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
948 $startOpts .= ' HIGH_PRIORITY';
951 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
952 $startOpts .= ' SQL_BIG_RESULT';
955 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
956 $startOpts .= ' SQL_BUFFER_RESULT';
959 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
960 $startOpts .= ' SQL_SMALL_RESULT';
963 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
964 $startOpts .= ' SQL_CALC_FOUND_ROWS';
967 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
968 $startOpts .= ' SQL_CACHE';
971 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
972 $startOpts .= ' SQL_NO_CACHE';
975 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
976 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
977 } else {
978 $useIndex = '';
981 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
985 * SELECT wrapper
987 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
988 * @param $vars Mixed: Array or string, field name(s) to be retrieved
989 * @param $conds Mixed: Array or string, condition(s) for WHERE
990 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
991 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
992 * see DatabaseBase::makeSelectOptions code for list of supported stuff
993 * @param $join_conds Array: Associative array of table join conditions (optional)
994 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
995 * @return mixed Database result resource (feed to DatabaseBase::fetchObject or whatever), or false on failure
997 function select( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
998 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1000 return $this->query( $sql, $fname );
1004 * SELECT wrapper
1006 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
1007 * @param $vars Mixed: Array or string, field name(s) to be retrieved
1008 * @param $conds Mixed: Array or string, condition(s) for WHERE
1009 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1010 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1011 * see DatabaseBase::makeSelectOptions code for list of supported stuff
1012 * @param $join_conds Array: Associative array of table join conditions (optional)
1013 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1014 * @return string, the SQL text
1016 function selectSQLText( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1017 if ( is_array( $vars ) ) {
1018 $vars = implode( ',', $vars );
1021 if ( !is_array( $options ) ) {
1022 $options = array( $options );
1025 if ( is_array( $table ) ) {
1026 if ( !empty( $join_conds ) || ( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) ) {
1027 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
1028 } else {
1029 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1031 } elseif ( $table != '' ) {
1032 if ( $table { 0 } == ' ' ) {
1033 $from = ' FROM ' . $table;
1034 } else {
1035 $from = ' FROM ' . $this->tableName( $table );
1037 } else {
1038 $from = '';
1041 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1043 if ( !empty( $conds ) ) {
1044 if ( is_array( $conds ) ) {
1045 $conds = $this->makeList( $conds, LIST_AND );
1047 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1048 } else {
1049 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1052 if ( isset( $options['LIMIT'] ) )
1053 $sql = $this->limitResult( $sql, $options['LIMIT'],
1054 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1055 $sql = "$sql $postLimitTail";
1057 if ( isset( $options['EXPLAIN'] ) ) {
1058 $sql = 'EXPLAIN ' . $sql;
1061 return $sql;
1065 * Single row SELECT wrapper
1066 * Aborts or returns FALSE on error
1068 * @param $table String: table name
1069 * @param $vars String: the selected variables
1070 * @param $conds Array: a condition map, terms are ANDed together.
1071 * Items with numeric keys are taken to be literal conditions
1072 * Takes an array of selected variables, and a condition map, which is ANDed
1073 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1074 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1075 * $obj- >page_id is the ID of the Astronomy article
1076 * @param $fname String: Calling function name
1077 * @param $options Array
1078 * @param $join_conds Array
1080 * @todo migrate documentation to phpdocumentor format
1082 function selectRow( $table, $vars, $conds, $fname = 'DatabaseBase::selectRow', $options = array(), $join_conds = array() ) {
1083 $options['LIMIT'] = 1;
1084 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1086 if ( $res === false ) {
1087 return false;
1090 if ( !$this->numRows( $res ) ) {
1091 return false;
1094 $obj = $this->fetchObject( $res );
1096 return $obj;
1100 * Estimate rows in dataset
1101 * Returns estimated count - not necessarily an accurate estimate across different databases,
1102 * so use sparingly
1103 * Takes same arguments as DatabaseBase::select()
1105 * @param $table String: table name
1106 * @param $vars Array: unused
1107 * @param $conds Array: filters on the table
1108 * @param $fname String: function name for profiling
1109 * @param $options Array: options for select
1110 * @return Integer: row count
1112 public function estimateRowCount( $table, $vars = '*', $conds = '', $fname = 'DatabaseBase::estimateRowCount', $options = array() ) {
1113 $rows = 0;
1114 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
1116 if ( $res ) {
1117 $row = $this->fetchRow( $res );
1118 $rows = ( isset( $row['rowcount'] ) ) ? $row['rowcount'] : 0;
1121 return $rows;
1125 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1126 * It's only slightly flawed. Don't use for anything important.
1128 * @param $sql String: A SQL Query
1130 static function generalizeSQL( $sql ) {
1131 # This does the same as the regexp below would do, but in such a way
1132 # as to avoid crashing php on some large strings.
1133 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1135 $sql = str_replace ( "\\\\", '', $sql );
1136 $sql = str_replace ( "\\'", '', $sql );
1137 $sql = str_replace ( "\\\"", '', $sql );
1138 $sql = preg_replace ( "/'.*'/s", "'X'", $sql );
1139 $sql = preg_replace ( '/".*"/s', "'X'", $sql );
1141 # All newlines, tabs, etc replaced by single space
1142 $sql = preg_replace ( '/\s+/', ' ', $sql );
1144 # All numbers => N
1145 $sql = preg_replace ( '/-?[0-9]+/s', 'N', $sql );
1147 return $sql;
1151 * Determines whether a field exists in a table
1153 * @param $table String: table name
1154 * @param $field String: filed to check on that table
1155 * @param $fname String: calling function name (optional)
1156 * @return Boolean: whether $table has filed $field
1158 function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
1159 $info = $this->fieldInfo( $table, $field );
1161 return (bool)$info;
1165 * Determines whether an index exists
1166 * Usually aborts on failure
1167 * If errors are explicitly ignored, returns NULL on failure
1169 function indexExists( $table, $index, $fname = 'DatabaseBase::indexExists' ) {
1170 $info = $this->indexInfo( $table, $index, $fname );
1171 if ( is_null( $info ) ) {
1172 return null;
1173 } else {
1174 return $info !== false;
1180 * Get information about an index into an object
1181 * Returns false if the index does not exist
1183 function indexInfo( $table, $index, $fname = 'DatabaseBase::indexInfo' ) {
1184 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1185 # SHOW INDEX should work for 3.x and up:
1186 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1187 $table = $this->tableName( $table );
1188 $index = $this->indexName( $index );
1189 $sql = 'SHOW INDEX FROM ' . $table;
1190 $res = $this->query( $sql, $fname );
1192 if ( !$res ) {
1193 return null;
1196 $result = array();
1198 foreach ( $res as $row ) {
1199 if ( $row->Key_name == $index ) {
1200 $result[] = $row;
1204 return empty( $result ) ? false : $result;
1208 * Query whether a given table exists
1210 function tableExists( $table ) {
1211 $table = $this->tableName( $table );
1212 $old = $this->ignoreErrors( true );
1213 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", __METHOD__ );
1214 $this->ignoreErrors( $old );
1216 return (bool)$res;
1220 * mysql_field_type() wrapper
1222 function fieldType( $res, $index ) {
1223 if ( $res instanceof ResultWrapper ) {
1224 $res = $res->result;
1227 return mysql_field_type( $res, $index );
1231 * Determines if a given index is unique
1233 function indexUnique( $table, $index ) {
1234 $indexInfo = $this->indexInfo( $table, $index );
1236 if ( !$indexInfo ) {
1237 return null;
1240 return !$indexInfo[0]->Non_unique;
1244 * INSERT wrapper, inserts an array into a table
1246 * $a may be a single associative array, or an array of these with numeric keys, for
1247 * multi-row insert.
1249 * Usually aborts on failure
1250 * If errors are explicitly ignored, returns success
1252 * @param $table String: table name (prefix auto-added)
1253 * @param $a Array: Array of rows to insert
1254 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1255 * @param $options Mixed: Associative array of options
1257 * @return bool
1259 function insert( $table, $a, $fname = 'DatabaseBase::insert', $options = array() ) {
1260 # No rows to insert, easy just return now
1261 if ( !count( $a ) ) {
1262 return true;
1265 $table = $this->tableName( $table );
1267 if ( !is_array( $options ) ) {
1268 $options = array( $options );
1271 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1272 $multi = true;
1273 $keys = array_keys( $a[0] );
1274 } else {
1275 $multi = false;
1276 $keys = array_keys( $a );
1279 $sql = 'INSERT ' . implode( ' ', $options ) .
1280 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1282 if ( $multi ) {
1283 $first = true;
1284 foreach ( $a as $row ) {
1285 if ( $first ) {
1286 $first = false;
1287 } else {
1288 $sql .= ',';
1290 $sql .= '(' . $this->makeList( $row ) . ')';
1292 } else {
1293 $sql .= '(' . $this->makeList( $a ) . ')';
1296 return (bool)$this->query( $sql, $fname );
1300 * Make UPDATE options for the DatabaseBase::update function
1302 * @private
1303 * @param $options Array: The options passed to DatabaseBase::update
1304 * @return string
1306 function makeUpdateOptions( $options ) {
1307 if ( !is_array( $options ) ) {
1308 $options = array( $options );
1311 $opts = array();
1313 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1314 $opts[] = $this->lowPriorityOption();
1317 if ( in_array( 'IGNORE', $options ) ) {
1318 $opts[] = 'IGNORE';
1321 return implode( ' ', $opts );
1325 * UPDATE wrapper, takes a condition array and a SET array
1327 * @param $table String: The table to UPDATE
1328 * @param $values Array: An array of values to SET
1329 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
1330 * @param $fname String: The Class::Function calling this function
1331 * (for the log)
1332 * @param $options Array: An array of UPDATE options, can be one or
1333 * more of IGNORE, LOW_PRIORITY
1334 * @return Boolean
1336 function update( $table, $values, $conds, $fname = 'DatabaseBase::update', $options = array() ) {
1337 $table = $this->tableName( $table );
1338 $opts = $this->makeUpdateOptions( $options );
1339 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1341 if ( $conds != '*' ) {
1342 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1345 return $this->query( $sql, $fname );
1349 * Makes an encoded list of strings from an array
1350 * $mode:
1351 * LIST_COMMA - comma separated, no field names
1352 * LIST_AND - ANDed WHERE clause (without the WHERE)
1353 * LIST_OR - ORed WHERE clause (without the WHERE)
1354 * LIST_SET - comma separated with field names, like a SET clause
1355 * LIST_NAMES - comma separated field names
1357 function makeList( $a, $mode = LIST_COMMA ) {
1358 if ( !is_array( $a ) ) {
1359 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1362 $first = true;
1363 $list = '';
1365 foreach ( $a as $field => $value ) {
1366 if ( !$first ) {
1367 if ( $mode == LIST_AND ) {
1368 $list .= ' AND ';
1369 } elseif ( $mode == LIST_OR ) {
1370 $list .= ' OR ';
1371 } else {
1372 $list .= ',';
1374 } else {
1375 $first = false;
1378 if ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_numeric( $field ) ) {
1379 $list .= "($value)";
1380 } elseif ( ( $mode == LIST_SET ) && is_numeric( $field ) ) {
1381 $list .= "$value";
1382 } elseif ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_array( $value ) ) {
1383 if ( count( $value ) == 0 ) {
1384 throw new MWException( __METHOD__ . ': empty input' );
1385 } elseif ( count( $value ) == 1 ) {
1386 // Special-case single values, as IN isn't terribly efficient
1387 // Don't necessarily assume the single key is 0; we don't
1388 // enforce linear numeric ordering on other arrays here.
1389 $value = array_values( $value );
1390 $list .= $field . " = " . $this->addQuotes( $value[0] );
1391 } else {
1392 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1394 } elseif ( $value === null ) {
1395 if ( $mode == LIST_AND || $mode == LIST_OR ) {
1396 $list .= "$field IS ";
1397 } elseif ( $mode == LIST_SET ) {
1398 $list .= "$field = ";
1400 $list .= 'NULL';
1401 } else {
1402 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1403 $list .= "$field = ";
1405 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1409 return $list;
1413 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1414 * The keys on each level may be either integers or strings.
1416 * @param $data Array: organized as 2-d array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1417 * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1418 * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1419 * @return Mixed: string SQL fragment, or false if no items in array.
1421 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1422 $conds = array();
1424 foreach ( $data as $base => $sub ) {
1425 if ( count( $sub ) ) {
1426 $conds[] = $this->makeList(
1427 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1428 LIST_AND );
1432 if ( $conds ) {
1433 return $this->makeList( $conds, LIST_OR );
1434 } else {
1435 // Nothing to search for...
1436 return false;
1441 * Bitwise operations
1444 function bitNot( $field ) {
1445 return "(~$field)";
1448 function bitAnd( $fieldLeft, $fieldRight ) {
1449 return "($fieldLeft & $fieldRight)";
1452 function bitOr( $fieldLeft, $fieldRight ) {
1453 return "($fieldLeft | $fieldRight)";
1457 * Change the current database
1459 * @todo Explain what exactly will fail if this is not overridden.
1460 * @return bool Success or failure
1462 function selectDB( $db ) {
1463 # Stub. Shouldn't cause serious problems if it's not overridden, but
1464 # if your database engine supports a concept similar to MySQL's
1465 # databases you may as well.
1466 return true;
1470 * Get the current DB name
1472 function getDBname() {
1473 return $this->mDBname;
1477 * Get the server hostname or IP address
1479 function getServer() {
1480 return $this->mServer;
1484 * Format a table name ready for use in constructing an SQL query
1486 * This does two important things: it quotes the table names to clean them up,
1487 * and it adds a table prefix if only given a table name with no quotes.
1489 * All functions of this object which require a table name call this function
1490 * themselves. Pass the canonical name to such functions. This is only needed
1491 * when calling query() directly.
1493 * @param $name String: database table name
1494 * @return String: full database name
1496 function tableName( $name ) {
1497 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1498 # Skip the entire process when we have a string quoted on both ends.
1499 # Note that we check the end so that we will still quote any use of
1500 # use of `database`.table. But won't break things if someone wants
1501 # to query a database table with a dot in the name.
1502 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) {
1503 return $name;
1506 # Lets test for any bits of text that should never show up in a table
1507 # name. Basically anything like JOIN or ON which are actually part of
1508 # SQL queries, but may end up inside of the table value to combine
1509 # sql. Such as how the API is doing.
1510 # Note that we use a whitespace test rather than a \b test to avoid
1511 # any remote case where a word like on may be inside of a table name
1512 # surrounded by symbols which may be considered word breaks.
1513 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1514 return $name;
1517 # Split database and table into proper variables.
1518 # We reverse the explode so that database.table and table both output
1519 # the correct table.
1520 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1521 if ( isset( $dbDetails[1] ) ) {
1522 @list( $table, $database ) = $dbDetails;
1523 } else {
1524 @list( $table ) = $dbDetails;
1526 $prefix = $this->mTablePrefix; # Default prefix
1528 # A database name has been specified in input. Quote the table name
1529 # because we don't want any prefixes added.
1530 if ( isset( $database ) ) {
1531 $table = ( $table[0] == '`' ? $table : "`{$table}`" );
1534 # Note that we use the long format because php will complain in in_array if
1535 # the input is not an array, and will complain in is_array if it is not set.
1536 if ( !isset( $database ) # Don't use shared database if pre selected.
1537 && isset( $wgSharedDB ) # We have a shared database
1538 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1539 && isset( $wgSharedTables )
1540 && is_array( $wgSharedTables )
1541 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1542 $database = $wgSharedDB;
1543 $prefix = isset( $wgSharedPrefix ) ? $wgSharedPrefix : $prefix;
1546 # Quote the $database and $table and apply the prefix if not quoted.
1547 if ( isset( $database ) ) {
1548 $database = ( $database[0] == '`' ? $database : "`{$database}`" );
1550 $table = ( $table[0] == '`' ? $table : "`{$prefix}{$table}`" );
1552 # Merge our database and table into our final table name.
1553 $tableName = ( isset( $database ) ? "{$database}.{$table}" : "{$table}" );
1555 return $tableName;
1559 * Fetch a number of table names into an array
1560 * This is handy when you need to construct SQL for joins
1562 * Example:
1563 * extract($dbr->tableNames('user','watchlist'));
1564 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1565 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1567 public function tableNames() {
1568 $inArray = func_get_args();
1569 $retVal = array();
1571 foreach ( $inArray as $name ) {
1572 $retVal[$name] = $this->tableName( $name );
1575 return $retVal;
1579 * Fetch a number of table names into an zero-indexed numerical array
1580 * This is handy when you need to construct SQL for joins
1582 * Example:
1583 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1584 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1585 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1587 public function tableNamesN() {
1588 $inArray = func_get_args();
1589 $retVal = array();
1591 foreach ( $inArray as $name ) {
1592 $retVal[] = $this->tableName( $name );
1595 return $retVal;
1599 * @private
1601 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1602 $ret = array();
1603 $retJOIN = array();
1604 $use_index_safe = is_array( $use_index ) ? $use_index : array();
1605 $join_conds_safe = is_array( $join_conds ) ? $join_conds : array();
1607 foreach ( $tables as $table ) {
1608 // Is there a JOIN and INDEX clause for this table?
1609 if ( isset( $join_conds_safe[$table] ) && isset( $use_index_safe[$table] ) ) {
1610 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1611 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1612 $on = $this->makeList( (array)$join_conds_safe[$table][1], LIST_AND );
1614 if ( $on != '' ) {
1615 $tableClause .= ' ON (' . $on . ')';
1618 $retJOIN[] = $tableClause;
1619 // Is there an INDEX clause?
1620 } else if ( isset( $use_index_safe[$table] ) ) {
1621 $tableClause = $this->tableName( $table );
1622 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1623 $ret[] = $tableClause;
1624 // Is there a JOIN clause?
1625 } else if ( isset( $join_conds_safe[$table] ) ) {
1626 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1627 $on = $this->makeList( (array)$join_conds_safe[$table][1], LIST_AND );
1629 if ( $on != '' ) {
1630 $tableClause .= ' ON (' . $on . ')';
1633 $retJOIN[] = $tableClause;
1634 } else {
1635 $tableClause = $this->tableName( $table );
1636 $ret[] = $tableClause;
1640 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1641 $straightJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
1642 $otherJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
1644 // Compile our final table clause
1645 return implode( ' ', array( $straightJoins, $otherJoins ) );
1649 * Get the name of an index in a given table
1651 function indexName( $index ) {
1652 // Backwards-compatibility hack
1653 $renamed = array(
1654 'ar_usertext_timestamp' => 'usertext_timestamp',
1655 'un_user_id' => 'user_id',
1656 'un_user_ip' => 'user_ip',
1659 if ( isset( $renamed[$index] ) ) {
1660 return $renamed[$index];
1661 } else {
1662 return $index;
1667 * If it's a string, adds quotes and backslashes
1668 * Otherwise returns as-is
1670 function addQuotes( $s ) {
1671 if ( $s === null ) {
1672 return 'NULL';
1673 } else {
1674 # This will also quote numeric values. This should be harmless,
1675 # and protects against weird problems that occur when they really
1676 # _are_ strings such as article titles and string->number->string
1677 # conversion is not 1:1.
1678 return "'" . $this->strencode( $s ) . "'";
1683 * Escape string for safe LIKE usage.
1684 * WARNING: you should almost never use this function directly,
1685 * instead use buildLike() that escapes everything automatically
1686 * Deprecated in 1.17, warnings in 1.17, removed in ???
1688 public function escapeLike( $s ) {
1689 wfDeprecated( __METHOD__ );
1690 return $this->escapeLikeInternal( $s );
1693 protected function escapeLikeInternal( $s ) {
1694 $s = str_replace( '\\', '\\\\', $s );
1695 $s = $this->strencode( $s );
1696 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
1698 return $s;
1702 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
1703 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
1704 * Alternatively, the function could be provided with an array of aforementioned parameters.
1706 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
1707 * for subpages of 'My page title'.
1708 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
1710 * @since 1.16
1711 * @return String: fully built LIKE statement
1713 function buildLike() {
1714 $params = func_get_args();
1716 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
1717 $params = $params[0];
1720 $s = '';
1722 foreach ( $params as $value ) {
1723 if ( $value instanceof LikeMatch ) {
1724 $s .= $value->toString();
1725 } else {
1726 $s .= $this->escapeLikeInternal( $value );
1730 return " LIKE '" . $s . "' ";
1734 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
1736 function anyChar() {
1737 return new LikeMatch( '_' );
1741 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
1743 function anyString() {
1744 return new LikeMatch( '%' );
1748 * Returns an appropriately quoted sequence value for inserting a new row.
1749 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1750 * subclass will return an integer, and save the value for insertId()
1752 function nextSequenceValue( $seqName ) {
1753 return null;
1757 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
1758 * is only needed because a) MySQL must be as efficient as possible due to
1759 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
1760 * which index to pick. Anyway, other databases might have different
1761 * indexes on a given table. So don't bother overriding this unless you're
1762 * MySQL.
1764 function useIndexClause( $index ) {
1765 return '';
1769 * REPLACE query wrapper
1770 * PostgreSQL simulates this with a DELETE followed by INSERT
1771 * $row is the row to insert, an associative array
1772 * $uniqueIndexes is an array of indexes. Each element may be either a
1773 * field name or an array of field names
1775 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1776 * However if you do this, you run the risk of encountering errors which wouldn't have
1777 * occurred in MySQL
1779 * @param $table String: The table to replace the row(s) in.
1780 * @param $uniqueIndexes Array: An associative array of indexes
1781 * @param $rows Array: Array of rows to replace
1782 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1784 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
1785 $table = $this->tableName( $table );
1787 # Single row case
1788 if ( !is_array( reset( $rows ) ) ) {
1789 $rows = array( $rows );
1792 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
1793 $first = true;
1795 foreach ( $rows as $row ) {
1796 if ( $first ) {
1797 $first = false;
1798 } else {
1799 $sql .= ',';
1802 $sql .= '(' . $this->makeList( $row ) . ')';
1805 return $this->query( $sql, $fname );
1809 * DELETE where the condition is a join
1810 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1812 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1813 * join condition matches, set $conds='*'
1815 * DO NOT put the join condition in $conds
1817 * @param $delTable String: The table to delete from.
1818 * @param $joinTable String: The other table.
1819 * @param $delVar String: The variable to join on, in the first table.
1820 * @param $joinVar String: The variable to join on, in the second table.
1821 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
1822 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1824 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseBase::deleteJoin' ) {
1825 if ( !$conds ) {
1826 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
1829 $delTable = $this->tableName( $delTable );
1830 $joinTable = $this->tableName( $joinTable );
1831 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1833 if ( $conds != '*' ) {
1834 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1837 return $this->query( $sql, $fname );
1841 * Returns the size of a text field, or -1 for "unlimited"
1843 function textFieldSize( $table, $field ) {
1844 $table = $this->tableName( $table );
1845 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1846 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
1847 $row = $this->fetchObject( $res );
1849 $m = array();
1851 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
1852 $size = $m[1];
1853 } else {
1854 $size = -1;
1857 return $size;
1861 * A string to insert into queries to show that they're low-priority, like
1862 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
1863 * string and nothing bad should happen.
1865 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1867 function lowPriorityOption() {
1868 return '';
1872 * DELETE query wrapper
1874 * Use $conds == "*" to delete all rows
1876 function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
1877 if ( !$conds ) {
1878 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
1881 $table = $this->tableName( $table );
1882 $sql = "DELETE FROM $table";
1884 if ( $conds != '*' ) {
1885 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1888 return $this->query( $sql, $fname );
1892 * INSERT SELECT wrapper
1893 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1894 * Source items may be literals rather than field names, but strings should be quoted with DatabaseBase::addQuotes()
1895 * $conds may be "*" to copy the whole table
1896 * srcTable may be an array of tables.
1898 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseBase::insertSelect',
1899 $insertOptions = array(), $selectOptions = array() )
1901 $destTable = $this->tableName( $destTable );
1903 if ( is_array( $insertOptions ) ) {
1904 $insertOptions = implode( ' ', $insertOptions );
1907 if ( !is_array( $selectOptions ) ) {
1908 $selectOptions = array( $selectOptions );
1911 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1913 if ( is_array( $srcTable ) ) {
1914 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1915 } else {
1916 $srcTable = $this->tableName( $srcTable );
1919 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1920 " SELECT $startOpts " . implode( ',', $varMap ) .
1921 " FROM $srcTable $useIndex ";
1923 if ( $conds != '*' ) {
1924 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1927 $sql .= " $tailOpts";
1929 return $this->query( $sql, $fname );
1933 * Construct a LIMIT query with optional offset. This is used for query
1934 * pages. The SQL should be adjusted so that only the first $limit rows
1935 * are returned. If $offset is provided as well, then the first $offset
1936 * rows should be discarded, and the next $limit rows should be returned.
1937 * If the result of the query is not ordered, then the rows to be returned
1938 * are theoretically arbitrary.
1940 * $sql is expected to be a SELECT, if that makes a difference. For
1941 * UPDATE, limitResultForUpdate should be used.
1943 * The version provided by default works in MySQL and SQLite. It will very
1944 * likely need to be overridden for most other DBMSes.
1946 * @param $sql String: SQL query we will append the limit too
1947 * @param $limit Integer: the SQL limit
1948 * @param $offset Integer the SQL offset (default false)
1950 function limitResult( $sql, $limit, $offset = false ) {
1951 if ( !is_numeric( $limit ) ) {
1952 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1955 return "$sql LIMIT "
1956 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
1957 . "{$limit} ";
1960 function limitResultForUpdate( $sql, $num ) {
1961 return $this->limitResult( $sql, $num, 0 );
1965 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
1966 * within the UNION construct.
1967 * @return Boolean
1969 function unionSupportsOrderAndLimit() {
1970 return true; // True for almost every DB supported
1974 * Construct a UNION query
1975 * This is used for providing overload point for other DB abstractions
1976 * not compatible with the MySQL syntax.
1977 * @param $sqls Array: SQL statements to combine
1978 * @param $all Boolean: use UNION ALL
1979 * @return String: SQL fragment
1981 function unionQueries( $sqls, $all ) {
1982 $glue = $all ? ') UNION ALL (' : ') UNION (';
1983 return '(' . implode( $glue, $sqls ) . ')';
1987 * Returns an SQL expression for a simple conditional. This doesn't need
1988 * to be overridden unless CASE isn't supported in your DBMS.
1990 * @param $cond String: SQL expression which will result in a boolean value
1991 * @param $trueVal String: SQL expression to return if true
1992 * @param $falseVal String: SQL expression to return if false
1993 * @return String: SQL fragment
1995 function conditional( $cond, $trueVal, $falseVal ) {
1996 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2000 * Returns a comand for str_replace function in SQL query.
2001 * Uses REPLACE() in MySQL
2003 * @param $orig String: column to modify
2004 * @param $old String: column to seek
2005 * @param $new String: column to replace with
2007 function strreplace( $orig, $old, $new ) {
2008 return "REPLACE({$orig}, {$old}, {$new})";
2012 * Determines if the last failure was due to a deadlock
2013 * STUB
2015 function wasDeadlock() {
2016 return false;
2020 * Determines if the last query error was something that should be dealt
2021 * with by pinging the connection and reissuing the query.
2022 * STUB
2024 function wasErrorReissuable() {
2025 return false;
2029 * Determines if the last failure was due to the database being read-only.
2030 * STUB
2032 function wasReadOnlyError() {
2033 return false;
2037 * Perform a deadlock-prone transaction.
2039 * This function invokes a callback function to perform a set of write
2040 * queries. If a deadlock occurs during the processing, the transaction
2041 * will be rolled back and the callback function will be called again.
2043 * Usage:
2044 * $dbw->deadlockLoop( callback, ... );
2046 * Extra arguments are passed through to the specified callback function.
2048 * Returns whatever the callback function returned on its successful,
2049 * iteration, or false on error, for example if the retry limit was
2050 * reached.
2052 function deadlockLoop() {
2053 $myFname = 'DatabaseBase::deadlockLoop';
2055 $this->begin();
2056 $args = func_get_args();
2057 $function = array_shift( $args );
2058 $oldIgnore = $this->ignoreErrors( true );
2059 $tries = DEADLOCK_TRIES;
2061 if ( is_array( $function ) ) {
2062 $fname = $function[0];
2063 } else {
2064 $fname = $function;
2067 do {
2068 $retVal = call_user_func_array( $function, $args );
2069 $error = $this->lastError();
2070 $errno = $this->lastErrno();
2071 $sql = $this->lastQuery();
2073 if ( $errno ) {
2074 if ( $this->wasDeadlock() ) {
2075 # Retry
2076 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
2077 } else {
2078 $this->reportQueryError( $error, $errno, $sql, $fname );
2081 } while ( $this->wasDeadlock() && --$tries > 0 );
2083 $this->ignoreErrors( $oldIgnore );
2085 if ( $tries <= 0 ) {
2086 $this->rollback( $myFname );
2087 $this->reportQueryError( $error, $errno, $sql, $fname );
2088 return false;
2089 } else {
2090 $this->commit( $myFname );
2091 return $retVal;
2096 * Do a SELECT MASTER_POS_WAIT()
2098 * @param $pos MySQLMasterPos object
2099 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
2101 function masterPosWait( MySQLMasterPos $pos, $timeout ) {
2102 $fname = 'DatabaseBase::masterPosWait';
2103 wfProfileIn( $fname );
2105 # Commit any open transactions
2106 if ( $this->mTrxLevel ) {
2107 $this->commit();
2110 if ( !is_null( $this->mFakeSlaveLag ) ) {
2111 $wait = intval( ( $pos->pos - microtime( true ) + $this->mFakeSlaveLag ) * 1e6 );
2113 if ( $wait > $timeout * 1e6 ) {
2114 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
2115 wfProfileOut( $fname );
2116 return -1;
2117 } elseif ( $wait > 0 ) {
2118 wfDebug( "Fake slave waiting $wait us\n" );
2119 usleep( $wait );
2120 wfProfileOut( $fname );
2121 return 1;
2122 } else {
2123 wfDebug( "Fake slave up to date ($wait us)\n" );
2124 wfProfileOut( $fname );
2125 return 0;
2129 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
2130 $encFile = $this->addQuotes( $pos->file );
2131 $encPos = intval( $pos->pos );
2132 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
2133 $res = $this->doQuery( $sql );
2135 if ( $res && $row = $this->fetchRow( $res ) ) {
2136 wfProfileOut( $fname );
2137 return $row[0];
2138 } else {
2139 wfProfileOut( $fname );
2140 return false;
2145 * Get the position of the master from SHOW SLAVE STATUS
2147 function getSlavePos() {
2148 if ( !is_null( $this->mFakeSlaveLag ) ) {
2149 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag );
2150 wfDebug( __METHOD__ . ": fake slave pos = $pos\n" );
2151 return $pos;
2154 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
2155 $row = $this->fetchObject( $res );
2157 if ( $row ) {
2158 $pos = isset( $row->Exec_master_log_pos ) ? $row->Exec_master_log_pos : $row->Exec_Master_Log_Pos;
2159 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
2160 } else {
2161 return false;
2166 * Get the position of the master from SHOW MASTER STATUS
2168 function getMasterPos() {
2169 if ( $this->mFakeMaster ) {
2170 return new MySQLMasterPos( 'fake', microtime( true ) );
2173 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
2174 $row = $this->fetchObject( $res );
2176 if ( $row ) {
2177 return new MySQLMasterPos( $row->File, $row->Position );
2178 } else {
2179 return false;
2184 * Begin a transaction, committing any previously open transaction
2186 function begin( $fname = 'DatabaseBase::begin' ) {
2187 $this->query( 'BEGIN', $fname );
2188 $this->mTrxLevel = 1;
2192 * End a transaction
2194 function commit( $fname = 'DatabaseBase::commit' ) {
2195 if ( $this->mTrxLevel ) {
2196 $this->query( 'COMMIT', $fname );
2197 $this->mTrxLevel = 0;
2202 * Rollback a transaction.
2203 * No-op on non-transactional databases.
2205 function rollback( $fname = 'DatabaseBase::rollback' ) {
2206 if ( $this->mTrxLevel ) {
2207 $this->query( 'ROLLBACK', $fname, true );
2208 $this->mTrxLevel = 0;
2213 * Begin a transaction, committing any previously open transaction
2214 * @deprecated use begin()
2216 function immediateBegin( $fname = 'DatabaseBase::immediateBegin' ) {
2217 wfDeprecated( __METHOD__ );
2218 $this->begin();
2222 * Commit transaction, if one is open
2223 * @deprecated use commit()
2225 function immediateCommit( $fname = 'DatabaseBase::immediateCommit' ) {
2226 wfDeprecated( __METHOD__ );
2227 $this->commit();
2231 * Creates a new table with structure copied from existing table
2232 * Note that unlike most database abstraction functions, this function does not
2233 * automatically append database prefix, because it works at a lower
2234 * abstraction level.
2236 * @param $oldName String: name of table whose structure should be copied
2237 * @param $newName String: name of table to be created
2238 * @param $temporary Boolean: whether the new table should be temporary
2239 * @param $fname String: calling function name
2240 * @return Boolean: true if operation was successful
2242 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseBase::duplicateTableStructure' ) {
2243 throw new MWException( 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2247 * Return MW-style timestamp used for MySQL schema
2249 function timestamp( $ts = 0 ) {
2250 return wfTimestamp( TS_MW, $ts );
2254 * Local database timestamp format or null
2256 function timestampOrNull( $ts = null ) {
2257 if ( is_null( $ts ) ) {
2258 return null;
2259 } else {
2260 return $this->timestamp( $ts );
2265 * @todo document
2267 function resultObject( $result ) {
2268 if ( empty( $result ) ) {
2269 return false;
2270 } elseif ( $result instanceof ResultWrapper ) {
2271 return $result;
2272 } elseif ( $result === true ) {
2273 // Successful write query
2274 return $result;
2275 } else {
2276 return new ResultWrapper( $this, $result );
2281 * Return aggregated value alias
2283 function aggregateValue ( $valuedata, $valuename = 'value' ) {
2284 return $valuename;
2288 * Ping the server and try to reconnect if it there is no connection
2290 * @return bool Success or failure
2292 function ping() {
2293 # Stub. Not essential to override.
2294 return true;
2298 * Get slave lag.
2299 * Currently supported only by MySQL
2300 * @return Database replication lag in seconds
2302 function getLag() {
2303 return intval( $this->mFakeSlaveLag );
2307 * Get status information from SHOW STATUS in an associative array
2309 function getStatus( $which = "%" ) {
2310 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2311 $status = array();
2313 foreach ( $res as $row ) {
2314 $status[$row->Variable_name] = $row->Value;
2317 return $status;
2321 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2323 function maxListLen() {
2324 return 0;
2327 function encodeBlob( $b ) {
2328 return $b;
2331 function decodeBlob( $b ) {
2332 return $b;
2336 * Override database's default connection timeout. May be useful for very
2337 * long batch queries such as full-wiki dumps, where a single query reads
2338 * out over hours or days. May or may not be necessary for non-MySQL
2339 * databases. For most purposes, leaving it as a no-op should be fine.
2341 * @param $timeout Integer in seconds
2343 public function setTimeout( $timeout ) {}
2346 * Read and execute SQL commands from a file.
2347 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2348 * @param $filename String: File name to open
2349 * @param $lineCallback Callback: Optional function called before reading each line
2350 * @param $resultCallback Callback: Optional function called for each MySQL result
2351 * @param $fname String: Calling function name or false if name should be generated dynamically
2352 * using $filename
2354 function sourceFile( $filename, $lineCallback = false, $resultCallback = false, $fname = false ) {
2355 $fp = fopen( $filename, 'r' );
2357 if ( false === $fp ) {
2358 if ( !defined( "MEDIAWIKI_INSTALL" ) )
2359 throw new MWException( "Could not open \"{$filename}\".\n" );
2360 else
2361 return "Could not open \"{$filename}\".\n";
2364 if ( !$fname ) {
2365 $fname = __METHOD__ . "( $filename )";
2368 try {
2369 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname );
2371 catch ( MWException $e ) {
2372 if ( defined( "MEDIAWIKI_INSTALL" ) ) {
2373 $error = $e->getMessage();
2374 } else {
2375 fclose( $fp );
2376 throw $e;
2380 fclose( $fp );
2382 return $error;
2386 * Get the full path of a patch file. Originally based on archive()
2387 * from updaters.inc. Keep in mind this always returns a patch, as
2388 * it fails back to MySQL if no DB-specific patch can be found
2390 * @param $patch String The name of the patch, like patch-something.sql
2391 * @return String Full path to patch file
2393 public function patchPath( $patch ) {
2394 global $IP;
2396 $dbType = $this->getType();
2397 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
2398 return "$IP/maintenance/$dbType/archives/$patch";
2399 } else {
2400 return "$IP/maintenance/archives/$patch";
2405 * Read and execute commands from an open file handle
2406 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2407 * @param $fp String: File handle
2408 * @param $lineCallback Callback: Optional function called before reading each line
2409 * @param $resultCallback Callback: Optional function called for each MySQL result
2410 * @param $fname String: Calling function name
2412 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseBase::sourceStream' ) {
2413 $cmd = "";
2414 $done = false;
2415 $dollarquote = false;
2417 while ( ! feof( $fp ) ) {
2418 if ( $lineCallback ) {
2419 call_user_func( $lineCallback );
2422 $line = trim( fgets( $fp, 1024 ) );
2423 $sl = strlen( $line ) - 1;
2425 if ( $sl < 0 ) {
2426 continue;
2429 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
2430 continue;
2433 # # Allow dollar quoting for function declarations
2434 if ( substr( $line, 0, 4 ) == '$mw$' ) {
2435 if ( $dollarquote ) {
2436 $dollarquote = false;
2437 $done = true;
2439 else {
2440 $dollarquote = true;
2443 else if ( !$dollarquote ) {
2444 if ( ';' == $line { $sl } && ( $sl < 2 || ';' != $line { $sl - 1 } ) ) {
2445 $done = true;
2446 $line = substr( $line, 0, $sl );
2450 if ( $cmd != '' ) {
2451 $cmd .= ' ';
2454 $cmd .= "$line\n";
2456 if ( $done ) {
2457 $cmd = str_replace( ';;', ";", $cmd );
2458 $cmd = $this->replaceVars( $cmd );
2459 $res = $this->query( $cmd, $fname );
2461 if ( $resultCallback ) {
2462 call_user_func( $resultCallback, $res, $this );
2465 if ( false === $res ) {
2466 $err = $this->lastError();
2467 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2470 $cmd = '';
2471 $done = false;
2475 return true;
2479 * Replace variables in sourced SQL
2481 protected function replaceVars( $ins ) {
2482 $varnames = array(
2483 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2484 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2485 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2488 // Ordinary variables
2489 foreach ( $varnames as $var ) {
2490 if ( isset( $GLOBALS[$var] ) ) {
2491 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2492 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2493 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2494 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2498 // Table prefixes
2499 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2500 array( $this, 'tableNameCallback' ), $ins );
2502 // Index names
2503 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2504 array( $this, 'indexNameCallback' ), $ins );
2506 return $ins;
2510 * Table name callback
2511 * @private
2513 protected function tableNameCallback( $matches ) {
2514 return $this->tableName( $matches[1] );
2518 * Index name callback
2520 protected function indexNameCallback( $matches ) {
2521 return $this->indexName( $matches[1] );
2525 * Build a concatenation list to feed into a SQL query
2526 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
2527 * @return String
2529 function buildConcat( $stringList ) {
2530 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2534 * Acquire a named lock
2536 * Abstracted from Filestore::lock() so child classes can implement for
2537 * their own needs.
2539 * @param $lockName String: name of lock to aquire
2540 * @param $method String: name of method calling us
2541 * @param $timeout Integer: timeout
2542 * @return Boolean
2544 public function lock( $lockName, $method, $timeout = 5 ) {
2545 return true;
2549 * Release a lock.
2551 * @param $lockName String: Name of lock to release
2552 * @param $method String: Name of method calling us
2554 * @return Returns 1 if the lock was released, 0 if the lock was not established
2555 * by this thread (in which case the lock is not released), and NULL if the named
2556 * lock did not exist
2558 public function unlock( $lockName, $method ) {
2559 return true;
2563 * Lock specific tables
2565 * @param $read Array of tables to lock for read access
2566 * @param $write Array of tables to lock for write access
2567 * @param $method String name of caller
2568 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
2570 public function lockTables( $read, $write, $method, $lowPriority = true ) {
2571 return true;
2575 * Unlock specific tables
2577 * @param $method String the caller
2579 public function unlockTables( $method ) {
2580 return true;
2584 * Get search engine class. All subclasses of this need to implement this
2585 * if they wish to use searching.
2587 * @return String
2589 public function getSearchEngine() {
2590 return 'SearchEngineDummy';
2594 * Allow or deny "big selects" for this session only. This is done by setting
2595 * the sql_big_selects session variable.
2597 * This is a MySQL-specific feature.
2599 * @param $value Mixed: true for allow, false for deny, or "default" to restore the initial value
2601 public function setBigSelects( $value = true ) {
2602 // no-op
2606 /******************************************************************************
2607 * Utility classes
2608 *****************************************************************************/
2611 * Utility class.
2612 * @ingroup Database
2614 class DBObject {
2615 public $mData;
2617 function __construct( $data ) {
2618 $this->mData = $data;
2621 function isLOB() {
2622 return false;
2625 function data() {
2626 return $this->mData;
2631 * Utility class
2632 * @ingroup Database
2634 * This allows us to distinguish a blob from a normal string and an array of strings
2636 class Blob {
2637 private $mData;
2639 function __construct( $data ) {
2640 $this->mData = $data;
2643 function fetch() {
2644 return $this->mData;
2649 * Utility class.
2650 * @ingroup Database
2652 class MySQLField {
2653 private $name, $tablename, $default, $max_length, $nullable,
2654 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2656 function __construct ( $info ) {
2657 $this->name = $info->name;
2658 $this->tablename = $info->table;
2659 $this->default = $info->def;
2660 $this->max_length = $info->max_length;
2661 $this->nullable = !$info->not_null;
2662 $this->is_pk = $info->primary_key;
2663 $this->is_unique = $info->unique_key;
2664 $this->is_multiple = $info->multiple_key;
2665 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
2666 $this->type = $info->type;
2669 function name() {
2670 return $this->name;
2673 function tableName() {
2674 return $this->tableName;
2677 function defaultValue() {
2678 return $this->default;
2681 function maxLength() {
2682 return $this->max_length;
2685 function nullable() {
2686 return $this->nullable;
2689 function isKey() {
2690 return $this->is_key;
2693 function isMultipleKey() {
2694 return $this->is_multiple;
2697 function type() {
2698 return $this->type;
2702 /******************************************************************************
2703 * Error classes
2704 *****************************************************************************/
2707 * Database error base class
2708 * @ingroup Database
2710 class DBError extends MWException {
2711 public $db;
2714 * Construct a database error
2715 * @param $db Database object which threw the error
2716 * @param $error A simple error message to be used for debugging
2718 function __construct( DatabaseBase &$db, $error ) {
2719 $this->db =& $db;
2720 parent::__construct( $error );
2723 function getText() {
2724 global $wgShowDBErrorBacktrace;
2726 $s = $this->getMessage() . "\n";
2728 if ( $wgShowDBErrorBacktrace ) {
2729 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2732 return $s;
2737 * @ingroup Database
2739 class DBConnectionError extends DBError {
2740 public $error;
2742 function __construct( DatabaseBase &$db, $error = 'unknown error' ) {
2743 $msg = 'DB connection error';
2745 if ( trim( $error ) != '' ) {
2746 $msg .= ": $error";
2749 $this->error = $error;
2751 parent::__construct( $db, $msg );
2754 function useOutputPage() {
2755 // Not likely to work
2756 return false;
2759 function useMessageCache() {
2760 // Not likely to work
2761 return false;
2764 function getLogMessage() {
2765 # Don't send to the exception log
2766 return false;
2769 function getPageTitle() {
2770 global $wgSitename, $wgLang;
2772 $header = "$wgSitename has a problem";
2774 if ( $wgLang instanceof Language ) {
2775 $header = htmlspecialchars( $wgLang->getMessage( 'dberr-header' ) );
2778 return $header;
2781 function getHTML() {
2782 global $wgLang, $wgMessageCache, $wgUseFileCache, $wgShowDBErrorBacktrace;
2784 $sorry = 'Sorry! This site is experiencing technical difficulties.';
2785 $again = 'Try waiting a few minutes and reloading.';
2786 $info = '(Can\'t contact the database server: $1)';
2788 if ( $wgLang instanceof Language ) {
2789 $sorry = htmlspecialchars( $wgLang->getMessage( 'dberr-problems' ) );
2790 $again = htmlspecialchars( $wgLang->getMessage( 'dberr-again' ) );
2791 $info = htmlspecialchars( $wgLang->getMessage( 'dberr-info' ) );
2794 # No database access
2795 if ( is_object( $wgMessageCache ) ) {
2796 $wgMessageCache->disable();
2799 if ( trim( $this->error ) == '' ) {
2800 $this->error = $this->db->getProperty( 'mServer' );
2803 $noconnect = "<p><strong>$sorry</strong><br />$again</p><p><small>$info</small></p>";
2804 $text = str_replace( '$1', $this->error, $noconnect );
2806 if ( $wgShowDBErrorBacktrace ) {
2807 $text .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2810 $extra = $this->searchForm();
2812 if ( $wgUseFileCache ) {
2813 try {
2814 $cache = $this->fileCachedPage();
2815 # Cached version on file system?
2816 if ( $cache !== null ) {
2817 # Hack: extend the body for error messages
2818 $cache = str_replace( array( '</html>', '</body>' ), '', $cache );
2819 # Add cache notice...
2820 $cachederror = "This is a cached copy of the requested page, and may not be up to date. ";
2822 # Localize it if possible...
2823 if ( $wgLang instanceof Language ) {
2824 $cachederror = htmlspecialchars( $wgLang->getMessage( 'dberr-cachederror' ) );
2827 $warning = "<div style='color:red;font-size:150%;font-weight:bold;'>$cachederror</div>";
2829 # Output cached page with notices on bottom and re-close body
2830 return "{$cache}{$warning}<hr />$text<hr />$extra</body></html>";
2832 } catch ( MWException $e ) {
2833 // Do nothing, just use the default page
2837 # Headers needed here - output is just the error message
2838 return $this->htmlHeader() . "$text<hr />$extra" . $this->htmlFooter();
2841 function searchForm() {
2842 global $wgSitename, $wgServer, $wgLang, $wgInputEncoding;
2844 $usegoogle = "You can try searching via Google in the meantime.";
2845 $outofdate = "Note that their indexes of our content may be out of date.";
2846 $googlesearch = "Search";
2848 if ( $wgLang instanceof Language ) {
2849 $usegoogle = htmlspecialchars( $wgLang->getMessage( 'dberr-usegoogle' ) );
2850 $outofdate = htmlspecialchars( $wgLang->getMessage( 'dberr-outofdate' ) );
2851 $googlesearch = htmlspecialchars( $wgLang->getMessage( 'searchbutton' ) );
2854 $search = htmlspecialchars( @$_REQUEST['search'] );
2856 $trygoogle = <<<EOT
2857 <div style="margin: 1.5em">$usegoogle<br />
2858 <small>$outofdate</small></div>
2859 <!-- SiteSearch Google -->
2860 <form method="get" action="http://www.google.com/search" id="googlesearch">
2861 <input type="hidden" name="domains" value="$wgServer" />
2862 <input type="hidden" name="num" value="50" />
2863 <input type="hidden" name="ie" value="$wgInputEncoding" />
2864 <input type="hidden" name="oe" value="$wgInputEncoding" />
2866 <input type="text" name="q" size="31" maxlength="255" value="$search" />
2867 <input type="submit" name="btnG" value="$googlesearch" />
2868 <div>
2869 <input type="radio" name="sitesearch" id="gwiki" value="$wgServer" checked="checked" /><label for="gwiki">$wgSitename</label>
2870 <input type="radio" name="sitesearch" id="gWWW" value="" /><label for="gWWW">WWW</label>
2871 </div>
2872 </form>
2873 <!-- SiteSearch Google -->
2874 EOT;
2875 return $trygoogle;
2878 function fileCachedPage() {
2879 global $wgTitle, $title, $wgLang, $wgOut;
2881 if ( $wgOut->isDisabled() ) {
2882 return; // Done already?
2885 $mainpage = 'Main Page';
2887 if ( $wgLang instanceof Language ) {
2888 $mainpage = htmlspecialchars( $wgLang->getMessage( 'mainpage' ) );
2891 if ( $wgTitle ) {
2892 $t =& $wgTitle;
2893 } elseif ( $title ) {
2894 $t = Title::newFromURL( $title );
2895 } else {
2896 $t = Title::newFromText( $mainpage );
2899 $cache = new HTMLFileCache( $t );
2900 if ( $cache->isFileCached() ) {
2901 return $cache->fetchPageText();
2902 } else {
2903 return '';
2907 function htmlBodyOnly() {
2908 return true;
2913 * @ingroup Database
2915 class DBQueryError extends DBError {
2916 public $error, $errno, $sql, $fname;
2918 function __construct( DatabaseBase &$db, $error, $errno, $sql, $fname ) {
2919 $message = "A database error has occurred. Did you forget to run maintenance/update.php after upgrading? See: http://www.mediawiki.org/wiki/Manual:Upgrading#Run_the_update_script\n" .
2920 "Query: $sql\n" .
2921 "Function: $fname\n" .
2922 "Error: $errno $error\n";
2924 parent::__construct( $db, $message );
2926 $this->error = $error;
2927 $this->errno = $errno;
2928 $this->sql = $sql;
2929 $this->fname = $fname;
2932 function getText() {
2933 global $wgShowDBErrorBacktrace;
2935 if ( $this->useMessageCache() ) {
2936 $s = wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2937 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) ) . "\n";
2939 if ( $wgShowDBErrorBacktrace ) {
2940 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2943 return $s;
2944 } else {
2945 return parent::getText();
2949 function getSQL() {
2950 global $wgShowSQLErrors;
2952 if ( !$wgShowSQLErrors ) {
2953 return $this->msg( 'sqlhidden', 'SQL hidden' );
2954 } else {
2955 return $this->sql;
2959 function getLogMessage() {
2960 # Don't send to the exception log
2961 return false;
2964 function getPageTitle() {
2965 return $this->msg( 'databaseerror', 'Database error' );
2968 function getHTML() {
2969 global $wgShowDBErrorBacktrace;
2971 if ( $this->useMessageCache() ) {
2972 $s = wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2973 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) );
2974 } else {
2975 $s = nl2br( htmlspecialchars( $this->getMessage() ) );
2978 if ( $wgShowDBErrorBacktrace ) {
2979 $s .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2982 return $s;
2987 * @ingroup Database
2989 class DBUnexpectedError extends DBError {}
2993 * Result wrapper for grabbing data queried by someone else
2994 * @ingroup Database
2996 class ResultWrapper implements Iterator {
2997 var $db, $result, $pos = 0, $currentRow = null;
3000 * Create a new result object from a result resource and a Database object
3002 function __construct( $database, $result ) {
3003 $this->db = $database;
3005 if ( $result instanceof ResultWrapper ) {
3006 $this->result = $result->result;
3007 } else {
3008 $this->result = $result;
3013 * Get the number of rows in a result object
3015 function numRows() {
3016 return $this->db->numRows( $this );
3020 * Fetch the next row from the given result object, in object form.
3021 * Fields can be retrieved with $row->fieldname, with fields acting like
3022 * member variables.
3024 * @return MySQL row object
3025 * @throws DBUnexpectedError Thrown if the database returns an error
3027 function fetchObject() {
3028 return $this->db->fetchObject( $this );
3032 * Fetch the next row from the given result object, in associative array
3033 * form. Fields are retrieved with $row['fieldname'].
3035 * @return MySQL row object
3036 * @throws DBUnexpectedError Thrown if the database returns an error
3038 function fetchRow() {
3039 return $this->db->fetchRow( $this );
3043 * Free a result object
3045 function free() {
3046 $this->db->freeResult( $this );
3047 unset( $this->result );
3048 unset( $this->db );
3052 * Change the position of the cursor in a result object
3053 * See mysql_data_seek()
3055 function seek( $row ) {
3056 $this->db->dataSeek( $this, $row );
3059 /*********************
3060 * Iterator functions
3061 * Note that using these in combination with the non-iterator functions
3062 * above may cause rows to be skipped or repeated.
3065 function rewind() {
3066 if ( $this->numRows() ) {
3067 $this->db->dataSeek( $this, 0 );
3069 $this->pos = 0;
3070 $this->currentRow = null;
3073 function current() {
3074 if ( is_null( $this->currentRow ) ) {
3075 $this->next();
3077 return $this->currentRow;
3080 function key() {
3081 return $this->pos;
3084 function next() {
3085 $this->pos++;
3086 $this->currentRow = $this->fetchObject();
3087 return $this->currentRow;
3090 function valid() {
3091 return $this->current() !== false;
3096 * Overloads the relevant methods of the real ResultsWrapper so it
3097 * doesn't go anywhere near an actual database.
3099 class FakeResultWrapper extends ResultWrapper {
3100 var $result = array();
3101 var $db = null; // And it's going to stay that way :D
3102 var $pos = 0;
3103 var $currentRow = null;
3105 function __construct( $array ) {
3106 $this->result = $array;
3109 function numRows() {
3110 return count( $this->result );
3113 function fetchRow() {
3114 $this->currentRow = $this->result[$this->pos++];
3115 return $this->currentRow;
3118 function seek( $row ) {
3119 $this->pos = $row;
3122 function free() {}
3124 // Callers want to be able to access fields with $this->fieldName
3125 function fetchObject() {
3126 $this->currentRow = $this->result[$this->pos++];
3127 return (object)$this->currentRow;
3130 function rewind() {
3131 $this->pos = 0;
3132 $this->currentRow = null;
3137 * Used by DatabaseBase::buildLike() to represent characters that have special meaning in SQL LIKE clauses
3138 * and thus need no escaping. Don't instantiate it manually, use DatabaseBase::anyChar() and anyString() instead.
3140 class LikeMatch {
3141 private $str;
3143 public function __construct( $s ) {
3144 $this->str = $s;
3147 public function toString() {
3148 return $this->str;