3 * @defgroup Database Database
7 * This file deals with database interface functions
8 * and query specifics/optimisations
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 );
19 * Base interface for all DBMS-specific code. At a bare minimum, all of the
20 * following must be implemented to support MediaWiki
25 interface DatabaseType
{
27 * Get the type of the DBMS, as it appears in $wgDBtype.
31 public function getType();
34 * Open a connection to the database. Usually aborts on failure
35 * If the failFunction is set to a non-zero integer, returns success
37 * @param $server String: database server host
38 * @param $user String: database user name
39 * @param $password String: database user password
40 * @param $dbName String: database name
42 * @throws DBConnectionError
44 public function open( $server, $user, $password, $dbName );
47 * The DBMS-dependent part of query()
48 * @todo @fixme Make this private someday
50 * @param $sql String: SQL query.
51 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
54 /*private*/ function doQuery( $sql );
57 * Fetch the next row from the given result object, in object form.
58 * Fields can be retrieved with $row->fieldname, with fields acting like
61 * @param $res SQL result object as returned from DatabaseBase::query(), etc.
63 * @throws DBUnexpectedError Thrown if the database returns an error
65 public function fetchObject( $res );
68 * Fetch the next row from the given result object, in associative array
69 * form. Fields are retrieved with $row['fieldname'].
71 * @param $res SQL result object as returned from DatabaseBase::query(), etc.
73 * @throws DBUnexpectedError Thrown if the database returns an error
75 public function fetchRow( $res );
78 * Get the number of rows in a result object
80 * @param $res Mixed: A SQL result
83 public function numRows( $res );
86 * Get the number of fields in a result object
87 * @see http://www.php.net/mysql_num_fields
89 * @param $res Mixed: A SQL result
92 public function numFields( $res );
95 * Get a field name in a result object
96 * @see http://www.php.net/mysql_field_name
98 * @param $res Mixed: A SQL result
102 public function fieldName( $res, $n );
105 * Get the inserted value of an auto-increment row
107 * The value inserted should be fetched from nextSequenceValue()
110 * $id = $dbw->nextSequenceValue('page_page_id_seq');
111 * $dbw->insert('page',array('page_id' => $id));
112 * $id = $dbw->insertId();
116 public function insertId();
119 * Change the position of the cursor in a result object
120 * @see http://www.php.net/mysql_data_seek
122 * @param $res Mixed: A SQL result
123 * @param $row Mixed: Either MySQL row or ResultWrapper
125 public function dataSeek( $res, $row );
128 * Get the last error number
129 * @see http://www.php.net/mysql_errno
133 public function lastErrno();
136 * Get a description of the last error
137 * @see http://www.php.net/mysql_error
141 public function lastError();
144 * mysql_fetch_field() wrapper
145 * Returns false if the field doesn't exist
147 * @param $table string: table name
148 * @param $field string: field name
150 public function fieldInfo( $table, $field );
153 * Get the number of rows affected by the last write query
154 * @see http://www.php.net/mysql_affected_rows
158 public function affectedRows();
161 * Wrapper for addslashes()
163 * @param $s string: to be slashed.
164 * @return string: slashed string.
166 public function strencode( $s );
169 * Returns a wikitext link to the DB's website, e.g.,
170 * return "[http://www.mysql.com/ MySQL]";
171 * Should at least contain plain text, if for some reason
172 * your database has no website.
174 * @return string: wikitext of a link to the server software's web site
176 public static function getSoftwareLink();
179 * A string describing the current software version, like from
180 * mysql_get_server_info(). Will be listed on Special:Version, etc.
182 * @return string: Version information from the database
184 public function getServerVersion();
188 * Database abstraction object
191 abstract class DatabaseBase
implements DatabaseType
{
193 # ------------------------------------------------------------------------------
195 # ------------------------------------------------------------------------------
197 protected $mLastQuery = '';
198 protected $mDoneWrites = false;
199 protected $mPHPError = false;
201 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
202 protected $mOpened = false;
204 protected $mFailFunction;
205 protected $mTablePrefix;
207 protected $mTrxLevel = 0;
208 protected $mErrorCount = 0;
209 protected $mLBInfo = array();
210 protected $mFakeSlaveLag = null, $mFakeMaster = false;
211 protected $mDefaultBigSelects = null;
213 # ------------------------------------------------------------------------------
215 # ------------------------------------------------------------------------------
216 # These optionally set a variable and return the previous state
219 * Fail function, takes a Database as a parameter
220 * Set to false for default, 1 for ignore errors
222 function failFunction( $function = null ) {
223 return wfSetVar( $this->mFailFunction
, $function );
227 * Boolean, controls output of large amounts of debug information
229 function debug( $debug = null ) {
230 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
234 * Turns buffering of SQL result sets on (true) or off (false).
235 * Default is "on" and it should not be changed without good reasons.
237 function bufferResults( $buffer = null ) {
238 if ( is_null( $buffer ) ) {
239 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
241 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
246 * Turns on (false) or off (true) the automatic generation and sending
247 * of a "we're sorry, but there has been a database error" page on
248 * database errors. Default is on (false). When turned off, the
249 * code should use lastErrno() and lastError() to handle the
250 * situation as appropriate.
252 function ignoreErrors( $ignoreErrors = null ) {
253 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
257 * The current depth of nested transactions
258 * @param $level Integer: , default NULL.
260 function trxLevel( $level = null ) {
261 return wfSetVar( $this->mTrxLevel
, $level );
265 * Number of errors logged, only useful when errors are ignored
267 function errorCount( $count = null ) {
268 return wfSetVar( $this->mErrorCount
, $count );
271 function tablePrefix( $prefix = null ) {
272 return wfSetVar( $this->mTablePrefix
, $prefix );
276 * Properties passed down from the server info array of the load balancer
278 function getLBInfo( $name = null ) {
279 if ( is_null( $name ) ) {
280 return $this->mLBInfo
;
282 if ( array_key_exists( $name, $this->mLBInfo
) ) {
283 return $this->mLBInfo
[$name];
290 function setLBInfo( $name, $value = null ) {
291 if ( is_null( $value ) ) {
292 $this->mLBInfo
= $name;
294 $this->mLBInfo
[$name] = $value;
299 * Set lag time in seconds for a fake slave
301 function setFakeSlaveLag( $lag ) {
302 $this->mFakeSlaveLag
= $lag;
306 * Make this connection a fake master
308 function setFakeMaster( $enabled = true ) {
309 $this->mFakeMaster
= $enabled;
313 * Returns true if this database supports (and uses) cascading deletes
315 function cascadingDeletes() {
320 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
322 function cleanupTriggers() {
327 * Returns true if this database is strict about what can be put into an IP field.
328 * Specifically, it uses a NULL value instead of an empty string.
330 function strictIPs() {
335 * Returns true if this database uses timestamps rather than integers
337 function realTimestamps() {
342 * Returns true if this database does an implicit sort when doing GROUP BY
344 function implicitGroupby() {
349 * Returns true if this database does an implicit order by when the column has an index
350 * For example: SELECT page_title FROM page LIMIT 1
352 function implicitOrderby() {
357 * Returns true if this database requires that SELECT DISTINCT queries require that all
358 ORDER BY expressions occur in the SELECT list per the SQL92 standard
360 function standardSelectDistinct() {
365 * Returns true if this database can do a native search on IP columns
366 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
368 function searchableIPs() {
373 * Returns true if this database can use functional indexes
375 function functionalIndexes() {
380 * Return the last query that went through DatabaseBase::query()
383 function lastQuery() { return $this->mLastQuery
; }
387 * Returns true if the connection may have been used for write queries.
388 * Should return true if unsure.
390 function doneWrites() { return $this->mDoneWrites
; }
393 * Is a connection to the database open?
396 function isOpen() { return $this->mOpened
; }
399 * Set a flag for this connection
401 * @param $flag Integer: DBO_* constants from Defines.php:
402 * - DBO_DEBUG: output some debug info (same as debug())
403 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
404 * - DBO_IGNORE: ignore errors (same as ignoreErrors())
405 * - DBO_TRX: automatically start transactions
406 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
407 * and removes it in command line mode
408 * - DBO_PERSISTENT: use persistant database connection
410 function setFlag( $flag ) {
411 $this->mFlags |
= $flag;
415 * Clear a flag for this connection
417 * @param $flag: same as setFlag()'s $flag param
419 function clearFlag( $flag ) {
420 $this->mFlags
&= ~
$flag;
424 * Returns a boolean whether the flag $flag is set for this connection
426 * @param $flag: same as setFlag()'s $flag param
429 function getFlag( $flag ) {
430 return !!( $this->mFlags
& $flag );
434 * General read-only accessor
436 function getProperty( $name ) {
440 function getWikiID() {
441 if ( $this->mTablePrefix
) {
442 return "{$this->mDBname}-{$this->mTablePrefix}";
444 return $this->mDBname
;
449 * Return a path to the DBMS-specific schema, otherwise default to tables.sql
451 public function getSchema() {
453 if ( file_exists( "$IP/maintenance/" . $this->getType() . "/tables.sql" ) ) {
454 return "$IP/maintenance/" . $this->getType() . "/tables.sql";
456 return "$IP/maintenance/tables.sql";
460 # ------------------------------------------------------------------------------
462 # ------------------------------------------------------------------------------
466 * @param $server String: database server host
467 * @param $user String: database user name
468 * @param $password String: database user password
469 * @param $dbName String: database name
470 * @param $failFunction
472 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
474 function __construct( $server = false, $user = false, $password = false, $dbName = false,
475 $failFunction = false, $flags = 0, $tablePrefix = 'get from global'
477 global $wgOut, $wgDBprefix, $wgCommandLineMode;
479 # Can't get a reference if it hasn't been set yet
480 if ( !isset( $wgOut ) ) {
484 $this->mFailFunction
= $failFunction;
485 $this->mFlags
= $flags;
487 if ( $this->mFlags
& DBO_DEFAULT
) {
488 if ( $wgCommandLineMode ) {
489 $this->mFlags
&= ~DBO_TRX
;
491 $this->mFlags |
= DBO_TRX
;
496 // Faster read-only access
497 if ( wfReadOnly() ) {
498 $this->mFlags |= DBO_PERSISTENT;
499 $this->mFlags &= ~DBO_TRX;
502 /** Get the default table prefix*/
503 if ( $tablePrefix == 'get from global' ) {
504 $this->mTablePrefix
= $wgDBprefix;
506 $this->mTablePrefix
= $tablePrefix;
510 $this->open( $server, $user, $password, $dbName );
515 * Same as new DatabaseMysql( ... ), kept for backward compatibility
516 * @param $server String: database server host
517 * @param $user String: database user name
518 * @param $password String: database user password
519 * @param $dbName String: database name
520 * @param failFunction
523 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 ) {
524 wfDeprecated( __METHOD__
);
525 return new DatabaseMysql( $server, $user, $password, $dbName, $failFunction, $flags );
528 protected function installErrorHandler() {
529 $this->mPHPError
= false;
530 $this->htmlErrors
= ini_set( 'html_errors', '0' );
531 set_error_handler( array( $this, 'connectionErrorHandler' ) );
534 protected function restoreErrorHandler() {
535 restore_error_handler();
536 if ( $this->htmlErrors
!== false ) {
537 ini_set( 'html_errors', $this->htmlErrors
);
539 if ( $this->mPHPError
) {
540 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
541 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
548 protected function connectionErrorHandler( $errno, $errstr ) {
549 $this->mPHPError
= $errstr;
553 * Closes a database connection.
554 * if it is open : commits any open transactions
556 * @return Bool operation success. true if already closed.
559 # Stub, should probably be overridden
564 * @param $error String: fallback error message, used if none is given by DB
566 function reportConnectionError( $error = 'Unknown error' ) {
567 $myError = $this->lastError();
572 if ( $this->mFailFunction
) {
573 # Legacy error handling method
574 if ( !is_int( $this->mFailFunction
) ) {
575 $ff = $this->mFailFunction
;
576 $ff( $this, $error );
580 throw new DBConnectionError( $this, $error );
585 * Determine whether a query writes to the DB.
586 * Should return true if unsure.
588 function isWriteQuery( $sql ) {
589 return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW|\(SELECT)\b/i', $sql );
593 * Usually aborts on failure. If errors are explicitly ignored, returns success.
595 * @param $sql String: SQL query
596 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
597 * comment (you can use __METHOD__ or add some extra info)
598 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
599 * maybe best to catch the exception instead?
600 * @return true for a successful write query, ResultWrapper object for a successful read query,
601 * or false on failure if $tempIgnore set
602 * @throws DBQueryError Thrown when the database returns an error of any kind
604 public function query( $sql, $fname = '', $tempIgnore = false ) {
607 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
608 if ( isset( $wgProfiler ) ) {
609 # generalizeSQL will probably cut down the query to reasonable
610 # logging size most of the time. The substr is really just a sanity check.
612 # Who's been wasting my precious column space? -- TS
613 # $profName = 'query: ' . $fname . ' ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
616 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
617 $totalProf = 'DatabaseBase::query-master';
619 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
620 $totalProf = 'DatabaseBase::query';
623 wfProfileIn( $totalProf );
624 wfProfileIn( $queryProf );
627 $this->mLastQuery
= $sql;
628 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
629 // Set a flag indicating that writes have been done
630 wfDebug( __METHOD__
. ": Writes done: $sql\n" );
631 $this->mDoneWrites
= true;
634 # Add a comment for easy SHOW PROCESSLIST interpretation
637 if ( is_object( $wgUser ) && !( $wgUser instanceof StubObject
) ) {
638 $userName = $wgUser->getName();
639 if ( mb_strlen( $userName ) > 15 ) {
640 $userName = mb_substr( $userName, 0, 15 ) . '...';
642 $userName = str_replace( '/', '', $userName );
646 $commentedSql = preg_replace( '/\s/', " /* $fname $userName */ ", $sql, 1 );
648 # $commentedSql = $sql;
651 # If DBO_TRX is set, start a transaction
652 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
653 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' ) {
654 // avoid establishing transactions for SHOW and SET statements too -
655 // that would delay transaction initializations to once connection
656 // is really used by application
657 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
658 if ( strpos( $sqlstart, "SHOW " ) !== 0 and strpos( $sqlstart, "SET " ) !== 0 )
662 if ( $this->debug() ) {
666 $sqlx = substr( $commentedSql, 0, 500 );
667 $sqlx = strtr( $sqlx, "\t\n", ' ' );
670 wfDebug( "Query $cnt (master): $sqlx\n" );
672 wfDebug( "Query $cnt (slave): $sqlx\n" );
676 if ( istainted( $sql ) & TC_MYSQL
) {
677 throw new MWException( 'Tainted query found' );
680 # Do the query and handle errors
681 $ret = $this->doQuery( $commentedSql );
683 # Try reconnecting if the connection was lost
684 if ( false === $ret && $this->wasErrorReissuable() ) {
685 # Transaction is gone, like it or not
686 $this->mTrxLevel
= 0;
687 wfDebug( "Connection lost, reconnecting...\n" );
689 if ( $this->ping() ) {
690 wfDebug( "Reconnected\n" );
691 $sqlx = substr( $commentedSql, 0, 500 );
692 $sqlx = strtr( $sqlx, "\t\n", ' ' );
693 global $wgRequestTime;
694 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
695 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
696 $ret = $this->doQuery( $commentedSql );
698 wfDebug( "Failed\n" );
702 if ( false === $ret ) {
703 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
706 if ( isset( $wgProfiler ) ) {
707 wfProfileOut( $queryProf );
708 wfProfileOut( $totalProf );
711 return $this->resultObject( $ret );
715 * @param $error String
716 * @param $errno Integer
718 * @param $fname String
719 * @param $tempIgnore Boolean
721 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
722 # Ignore errors during error handling to avoid infinite recursion
723 $ignore = $this->ignoreErrors( true );
724 ++
$this->mErrorCount
;
726 if ( $ignore ||
$tempIgnore ) {
727 wfDebug( "SQL ERROR (ignored): $error\n" );
728 $this->ignoreErrors( $ignore );
730 $sql1line = str_replace( "\n", "\\n", $sql );
731 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
732 wfDebug( "SQL ERROR: " . $error . "\n" );
733 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
739 * Intended to be compatible with the PEAR::DB wrapper functions.
740 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
742 * ? = scalar value, quoted as necessary
743 * ! = raw SQL bit (a function for instance)
744 * & = filename; reads the file and inserts as a blob
745 * (we don't use this though...)
747 function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
748 /* MySQL doesn't support prepared statements (yet), so just
749 pack up the query for reference. We'll manually replace
751 return array( 'query' => $sql, 'func' => $func );
754 function freePrepared( $prepared ) {
755 /* No-op by default */
759 * Execute a prepared query with the various arguments
760 * @param $prepared String: the prepared sql
761 * @param $args Mixed: Either an array here, or put scalars as varargs
763 function execute( $prepared, $args = null ) {
764 if ( !is_array( $args ) ) {
766 $args = func_get_args();
767 array_shift( $args );
770 $sql = $this->fillPrepared( $prepared['query'], $args );
772 return $this->query( $sql, $prepared['func'] );
776 * Prepare & execute an SQL statement, quoting and inserting arguments
777 * in the appropriate places.
778 * @param $query String
781 function safeQuery( $query, $args = null ) {
782 $prepared = $this->prepare( $query, 'DatabaseBase::safeQuery' );
784 if ( !is_array( $args ) ) {
786 $args = func_get_args();
787 array_shift( $args );
790 $retval = $this->execute( $prepared, $args );
791 $this->freePrepared( $prepared );
797 * For faking prepared SQL statements on DBs that don't support
799 * @param $preparedQuery String: a 'preparable' SQL statement
800 * @param $args Array of arguments to fill it with
801 * @return string executable SQL
803 function fillPrepared( $preparedQuery, $args ) {
805 $this->preparedArgs
=& $args;
807 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
808 array( &$this, 'fillPreparedArg' ), $preparedQuery );
812 * preg_callback func for fillPrepared()
813 * The arguments should be in $this->preparedArgs and must not be touched
814 * while we're doing this.
816 * @param $matches Array
820 function fillPreparedArg( $matches ) {
821 switch( $matches[1] ) {
822 case '\\?': return '?';
823 case '\\!': return '!';
824 case '\\&': return '&';
827 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
829 switch( $matches[1] ) {
830 case '?': return $this->addQuotes( $arg );
831 case '!': return $arg;
833 # return $this->addQuotes( file_get_contents( $arg ) );
834 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
836 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
841 * Free a result object
842 * @param $res Mixed: A SQL result
844 function freeResult( $res ) {
845 # Stub. Might not really need to be overridden, since results should
846 # be freed by PHP when the variable goes out of scope anyway.
850 * Simple UPDATE wrapper
851 * Usually aborts on failure
852 * If errors are explicitly ignored, returns success
854 * This function exists for historical reasons, DatabaseBase::update() has a more standard
855 * calling convention and feature set
857 function set( $table, $var, $value, $cond, $fname = 'DatabaseBase::set' ) {
858 $table = $this->tableName( $table );
859 $sql = "UPDATE $table SET $var = '" .
860 $this->strencode( $value ) . "' WHERE ($cond)";
862 return (bool)$this->query( $sql, $fname );
866 * Simple SELECT wrapper, returns a single field, input must be encoded
867 * Usually aborts on failure
868 * If errors are explicitly ignored, returns FALSE on failure
870 function selectField( $table, $var, $cond = '', $fname = 'DatabaseBase::selectField', $options = array() ) {
871 if ( !is_array( $options ) ) {
872 $options = array( $options );
875 $options['LIMIT'] = 1;
877 $res = $this->select( $table, $var, $cond, $fname, $options );
879 if ( $res === false ||
!$this->numRows( $res ) ) {
883 $row = $this->fetchRow( $res );
885 if ( $row !== false ) {
886 return reset( $row );
893 * Returns an optional USE INDEX clause to go after the table, and a
894 * string to go at the end of the query
898 * @param $options Array: associative array of options to be turned into
899 * an SQL query, valid keys are listed in the function.
902 function makeSelectOptions( $options ) {
903 $preLimitTail = $postLimitTail = '';
906 $noKeyOptions = array();
908 foreach ( $options as $key => $option ) {
909 if ( is_numeric( $key ) ) {
910 $noKeyOptions[$option] = true;
914 if ( isset( $options['GROUP BY'] ) ) {
915 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
918 if ( isset( $options['HAVING'] ) ) {
919 $preLimitTail .= " HAVING {$options['HAVING']}";
922 if ( isset( $options['ORDER BY'] ) ) {
923 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
926 // if (isset($options['LIMIT'])) {
927 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
928 // isset($options['OFFSET']) ? $options['OFFSET']
932 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
933 $postLimitTail .= ' FOR UPDATE';
936 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
937 $postLimitTail .= ' LOCK IN SHARE MODE';
940 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
941 $startOpts .= 'DISTINCT';
944 # Various MySQL extensions
945 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
946 $startOpts .= ' /*! STRAIGHT_JOIN */';
949 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
950 $startOpts .= ' HIGH_PRIORITY';
953 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
954 $startOpts .= ' SQL_BIG_RESULT';
957 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
958 $startOpts .= ' SQL_BUFFER_RESULT';
961 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
962 $startOpts .= ' SQL_SMALL_RESULT';
965 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
966 $startOpts .= ' SQL_CALC_FOUND_ROWS';
969 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
970 $startOpts .= ' SQL_CACHE';
973 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
974 $startOpts .= ' SQL_NO_CACHE';
977 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
978 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
983 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
989 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
990 * @param $vars Mixed: Array or string, field name(s) to be retrieved
991 * @param $conds Mixed: Array or string, condition(s) for WHERE
992 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
993 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
994 * see DatabaseBase::makeSelectOptions code for list of supported stuff
995 * @param $join_conds Array: Associative array of table join conditions (optional)
996 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
997 * @return mixed Database result resource (feed to DatabaseBase::fetchObject or whatever), or false on failure
999 function select( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1000 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1002 return $this->query( $sql, $fname );
1008 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
1009 * @param $vars Mixed: Array or string, field name(s) to be retrieved
1010 * @param $conds Mixed: Array or string, condition(s) for WHERE
1011 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1012 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1013 * see DatabaseBase::makeSelectOptions code for list of supported stuff
1014 * @param $join_conds Array: Associative array of table join conditions (optional)
1015 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1016 * @return string, the SQL text
1018 function selectSQLText( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1019 if ( is_array( $vars ) ) {
1020 $vars = implode( ',', $vars );
1023 if ( !is_array( $options ) ) {
1024 $options = array( $options );
1027 if ( is_array( $table ) ) {
1028 if ( !empty( $join_conds ) ||
( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) ) {
1029 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
1031 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1033 } elseif ( $table != '' ) {
1034 if ( $table { 0 } == ' ' ) {
1035 $from = ' FROM ' . $table;
1037 $from = ' FROM ' . $this->tableName( $table );
1043 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1045 if ( !empty( $conds ) ) {
1046 if ( is_array( $conds ) ) {
1047 $conds = $this->makeList( $conds, LIST_AND
);
1049 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1051 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1054 if ( isset( $options['LIMIT'] ) )
1055 $sql = $this->limitResult( $sql, $options['LIMIT'],
1056 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1057 $sql = "$sql $postLimitTail";
1059 if ( isset( $options['EXPLAIN'] ) ) {
1060 $sql = 'EXPLAIN ' . $sql;
1067 * Single row SELECT wrapper
1068 * Aborts or returns FALSE on error
1070 * @param $table String: table name
1071 * @param $vars String: the selected variables
1072 * @param $conds Array: a condition map, terms are ANDed together.
1073 * Items with numeric keys are taken to be literal conditions
1074 * Takes an array of selected variables, and a condition map, which is ANDed
1075 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1076 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1077 * $obj- >page_id is the ID of the Astronomy article
1078 * @param $fname String: Calling function name
1079 * @param $options Array
1080 * @param $join_conds Array
1082 * @todo migrate documentation to phpdocumentor format
1084 function selectRow( $table, $vars, $conds, $fname = 'DatabaseBase::selectRow', $options = array(), $join_conds = array() ) {
1085 $options['LIMIT'] = 1;
1086 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1088 if ( $res === false ) {
1092 if ( !$this->numRows( $res ) ) {
1096 $obj = $this->fetchObject( $res );
1102 * Estimate rows in dataset
1103 * Returns estimated count - not necessarily an accurate estimate across different databases,
1105 * Takes same arguments as DatabaseBase::select()
1107 * @param $table String: table name
1108 * @param $vars Array: unused
1109 * @param $conds Array: filters on the table
1110 * @param $fname String: function name for profiling
1111 * @param $options Array: options for select
1112 * @return Integer: row count
1114 public function estimateRowCount( $table, $vars = '*', $conds = '', $fname = 'DatabaseBase::estimateRowCount', $options = array() ) {
1116 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
1119 $row = $this->fetchRow( $res );
1120 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1127 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1128 * It's only slightly flawed. Don't use for anything important.
1130 * @param $sql String: A SQL Query
1132 static function generalizeSQL( $sql ) {
1133 # This does the same as the regexp below would do, but in such a way
1134 # as to avoid crashing php on some large strings.
1135 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1137 $sql = str_replace ( "\\\\", '', $sql );
1138 $sql = str_replace ( "\\'", '', $sql );
1139 $sql = str_replace ( "\\\"", '', $sql );
1140 $sql = preg_replace ( "/'.*'/s", "'X'", $sql );
1141 $sql = preg_replace ( '/".*"/s', "'X'", $sql );
1143 # All newlines, tabs, etc replaced by single space
1144 $sql = preg_replace ( '/\s+/', ' ', $sql );
1147 $sql = preg_replace ( '/-?[0-9]+/s', 'N', $sql );
1153 * Determines whether a field exists in a table
1155 * @param $table String: table name
1156 * @param $field String: filed to check on that table
1157 * @param $fname String: calling function name (optional)
1158 * @return Boolean: whether $table has filed $field
1160 function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
1161 $info = $this->fieldInfo( $table, $field );
1167 * Determines whether an index exists
1168 * Usually aborts on failure
1169 * If errors are explicitly ignored, returns NULL on failure
1171 function indexExists( $table, $index, $fname = 'DatabaseBase::indexExists' ) {
1172 $info = $this->indexInfo( $table, $index, $fname );
1173 if ( is_null( $info ) ) {
1176 return $info !== false;
1182 * Get information about an index into an object
1183 * Returns false if the index does not exist
1185 function indexInfo( $table, $index, $fname = 'DatabaseBase::indexInfo' ) {
1186 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1187 # SHOW INDEX should work for 3.x and up:
1188 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1189 $table = $this->tableName( $table );
1190 $index = $this->indexName( $index );
1191 $sql = 'SHOW INDEX FROM ' . $table;
1192 $res = $this->query( $sql, $fname );
1200 while ( $row = $this->fetchObject( $res ) ) {
1201 if ( $row->Key_name
== $index ) {
1206 return empty( $result ) ?
false : $result;
1210 * Query whether a given table exists
1212 function tableExists( $table ) {
1213 $table = $this->tableName( $table );
1214 $old = $this->ignoreErrors( true );
1215 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1216 $this->ignoreErrors( $old );
1222 * mysql_field_type() wrapper
1224 function fieldType( $res, $index ) {
1225 if ( $res instanceof ResultWrapper
) {
1226 $res = $res->result
;
1229 return mysql_field_type( $res, $index );
1233 * Determines if a given index is unique
1235 function indexUnique( $table, $index ) {
1236 $indexInfo = $this->indexInfo( $table, $index );
1238 if ( !$indexInfo ) {
1242 return !$indexInfo[0]->Non_unique
;
1246 * INSERT wrapper, inserts an array into a table
1248 * $a may be a single associative array, or an array of these with numeric keys, for
1251 * Usually aborts on failure
1252 * If errors are explicitly ignored, returns success
1254 * @param $table String: table name (prefix auto-added)
1255 * @param $a Array: Array of rows to insert
1256 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1257 * @param $options Mixed: Associative array of options
1261 function insert( $table, $a, $fname = 'DatabaseBase::insert', $options = array() ) {
1262 # No rows to insert, easy just return now
1263 if ( !count( $a ) ) {
1267 $table = $this->tableName( $table );
1269 if ( !is_array( $options ) ) {
1270 $options = array( $options );
1273 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1275 $keys = array_keys( $a[0] );
1278 $keys = array_keys( $a );
1281 $sql = 'INSERT ' . implode( ' ', $options ) .
1282 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1286 foreach ( $a as $row ) {
1292 $sql .= '(' . $this->makeList( $row ) . ')';
1295 $sql .= '(' . $this->makeList( $a ) . ')';
1298 return (bool)$this->query( $sql, $fname );
1302 * Make UPDATE options for the DatabaseBase::update function
1305 * @param $options Array: The options passed to DatabaseBase::update
1308 function makeUpdateOptions( $options ) {
1309 if ( !is_array( $options ) ) {
1310 $options = array( $options );
1315 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1316 $opts[] = $this->lowPriorityOption();
1319 if ( in_array( 'IGNORE', $options ) ) {
1323 return implode( ' ', $opts );
1327 * UPDATE wrapper, takes a condition array and a SET array
1329 * @param $table String: The table to UPDATE
1330 * @param $values Array: An array of values to SET
1331 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
1332 * @param $fname String: The Class::Function calling this function
1334 * @param $options Array: An array of UPDATE options, can be one or
1335 * more of IGNORE, LOW_PRIORITY
1338 function update( $table, $values, $conds, $fname = 'DatabaseBase::update', $options = array() ) {
1339 $table = $this->tableName( $table );
1340 $opts = $this->makeUpdateOptions( $options );
1341 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1343 if ( $conds != '*' ) {
1344 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1347 return $this->query( $sql, $fname );
1351 * Makes an encoded list of strings from an array
1353 * LIST_COMMA - comma separated, no field names
1354 * LIST_AND - ANDed WHERE clause (without the WHERE)
1355 * LIST_OR - ORed WHERE clause (without the WHERE)
1356 * LIST_SET - comma separated with field names, like a SET clause
1357 * LIST_NAMES - comma separated field names
1359 function makeList( $a, $mode = LIST_COMMA
) {
1360 if ( !is_array( $a ) ) {
1361 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1367 foreach ( $a as $field => $value ) {
1369 if ( $mode == LIST_AND
) {
1371 } elseif ( $mode == LIST_OR
) {
1380 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1381 $list .= "($value)";
1382 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1384 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1385 if ( count( $value ) == 0 ) {
1386 throw new MWException( __METHOD__
. ': empty input' );
1387 } elseif ( count( $value ) == 1 ) {
1388 // Special-case single values, as IN isn't terribly efficient
1389 // Don't necessarily assume the single key is 0; we don't
1390 // enforce linear numeric ordering on other arrays here.
1391 $value = array_values( $value );
1392 $list .= $field . " = " . $this->addQuotes( $value[0] );
1394 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1396 } elseif ( $value === null ) {
1397 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1398 $list .= "$field IS ";
1399 } elseif ( $mode == LIST_SET
) {
1400 $list .= "$field = ";
1404 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1405 $list .= "$field = ";
1407 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1415 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1416 * The keys on each level may be either integers or strings.
1418 * @param $data Array: organized as 2-d array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1419 * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1420 * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1421 * @return Mixed: string SQL fragment, or false if no items in array.
1423 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1426 foreach ( $data as $base => $sub ) {
1427 if ( count( $sub ) ) {
1428 $conds[] = $this->makeList(
1429 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1435 return $this->makeList( $conds, LIST_OR
);
1437 // Nothing to search for...
1443 * Bitwise operations
1446 function bitNot( $field ) {
1450 function bitAnd( $fieldLeft, $fieldRight ) {
1451 return "($fieldLeft & $fieldRight)";
1454 function bitOr( $fieldLeft, $fieldRight ) {
1455 return "($fieldLeft | $fieldRight)";
1459 * Change the current database
1461 * @todo Explain what exactly will fail if this is not overridden.
1462 * @return bool Success or failure
1464 function selectDB( $db ) {
1465 # Stub. Shouldn't cause serious problems if it's not overridden, but
1466 # if your database engine supports a concept similar to MySQL's
1467 # databases you may as well.
1472 * Get the current DB name
1474 function getDBname() {
1475 return $this->mDBname
;
1479 * Get the server hostname or IP address
1481 function getServer() {
1482 return $this->mServer
;
1486 * Format a table name ready for use in constructing an SQL query
1488 * This does two important things: it quotes the table names to clean them up,
1489 * and it adds a table prefix if only given a table name with no quotes.
1491 * All functions of this object which require a table name call this function
1492 * themselves. Pass the canonical name to such functions. This is only needed
1493 * when calling query() directly.
1495 * @param $name String: database table name
1496 * @return String: full database name
1498 function tableName( $name ) {
1499 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1500 # Skip the entire process when we have a string quoted on both ends.
1501 # Note that we check the end so that we will still quote any use of
1502 # use of `database`.table. But won't break things if someone wants
1503 # to query a database table with a dot in the name.
1504 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) {
1508 # Lets test for any bits of text that should never show up in a table
1509 # name. Basically anything like JOIN or ON which are actually part of
1510 # SQL queries, but may end up inside of the table value to combine
1511 # sql. Such as how the API is doing.
1512 # Note that we use a whitespace test rather than a \b test to avoid
1513 # any remote case where a word like on may be inside of a table name
1514 # surrounded by symbols which may be considered word breaks.
1515 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1519 # Split database and table into proper variables.
1520 # We reverse the explode so that database.table and table both output
1521 # the correct table.
1522 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1523 if ( isset( $dbDetails[1] ) ) {
1524 @list
( $table, $database ) = $dbDetails;
1526 @list
( $table ) = $dbDetails;
1528 $prefix = $this->mTablePrefix
; # Default prefix
1530 # A database name has been specified in input. Quote the table name
1531 # because we don't want any prefixes added.
1532 if ( isset( $database ) ) {
1533 $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
1536 # Note that we use the long format because php will complain in in_array if
1537 # the input is not an array, and will complain in is_array if it is not set.
1538 if ( !isset( $database ) # Don't use shared database if pre selected.
1539 && isset( $wgSharedDB ) # We have a shared database
1540 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1541 && isset( $wgSharedTables )
1542 && is_array( $wgSharedTables )
1543 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1544 $database = $wgSharedDB;
1545 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1548 # Quote the $database and $table and apply the prefix if not quoted.
1549 if ( isset( $database ) ) {
1550 $database = ( $database[0] == '`' ?
$database : "`{$database}`" );
1552 $table = ( $table[0] == '`' ?
$table : "`{$prefix}{$table}`" );
1554 # Merge our database and table into our final table name.
1555 $tableName = ( isset( $database ) ?
"{$database}.{$table}" : "{$table}" );
1561 * Fetch a number of table names into an array
1562 * This is handy when you need to construct SQL for joins
1565 * extract($dbr->tableNames('user','watchlist'));
1566 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1567 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1569 public function tableNames() {
1570 $inArray = func_get_args();
1573 foreach ( $inArray as $name ) {
1574 $retVal[$name] = $this->tableName( $name );
1581 * Fetch a number of table names into an zero-indexed numerical array
1582 * This is handy when you need to construct SQL for joins
1585 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1586 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1587 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1589 public function tableNamesN() {
1590 $inArray = func_get_args();
1593 foreach ( $inArray as $name ) {
1594 $retVal[] = $this->tableName( $name );
1603 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1606 $use_index_safe = is_array( $use_index ) ?
$use_index : array();
1607 $join_conds_safe = is_array( $join_conds ) ?
$join_conds : array();
1609 foreach ( $tables as $table ) {
1610 // Is there a JOIN and INDEX clause for this table?
1611 if ( isset( $join_conds_safe[$table] ) && isset( $use_index_safe[$table] ) ) {
1612 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1613 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1614 $on = $this->makeList( (array)$join_conds_safe[$table][1], LIST_AND
);
1617 $tableClause .= ' ON (' . $on . ')';
1620 $retJOIN[] = $tableClause;
1621 // Is there an INDEX clause?
1622 } else if ( isset( $use_index_safe[$table] ) ) {
1623 $tableClause = $this->tableName( $table );
1624 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1625 $ret[] = $tableClause;
1626 // Is there a JOIN clause?
1627 } else if ( isset( $join_conds_safe[$table] ) ) {
1628 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1629 $on = $this->makeList( (array)$join_conds_safe[$table][1], LIST_AND
);
1632 $tableClause .= ' ON (' . $on . ')';
1635 $retJOIN[] = $tableClause;
1637 $tableClause = $this->tableName( $table );
1638 $ret[] = $tableClause;
1642 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1643 $straightJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
1644 $otherJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
1646 // Compile our final table clause
1647 return implode( ' ', array( $straightJoins, $otherJoins ) );
1651 * Get the name of an index in a given table
1653 function indexName( $index ) {
1654 // Backwards-compatibility hack
1656 'ar_usertext_timestamp' => 'usertext_timestamp',
1657 'un_user_id' => 'user_id',
1658 'un_user_ip' => 'user_ip',
1661 if ( isset( $renamed[$index] ) ) {
1662 return $renamed[$index];
1669 * If it's a string, adds quotes and backslashes
1670 * Otherwise returns as-is
1672 function addQuotes( $s ) {
1673 if ( $s === null ) {
1676 # This will also quote numeric values. This should be harmless,
1677 # and protects against weird problems that occur when they really
1678 # _are_ strings such as article titles and string->number->string
1679 # conversion is not 1:1.
1680 return "'" . $this->strencode( $s ) . "'";
1685 * Escape string for safe LIKE usage.
1686 * WARNING: you should almost never use this function directly,
1687 * instead use buildLike() that escapes everything automatically
1688 * Deprecated in 1.17, warnings in 1.17, removed in ???
1690 public function escapeLike( $s ) {
1691 wfDeprecated( __METHOD__
);
1692 return $this->escapeLikeInternal( $s );
1695 protected function escapeLikeInternal( $s ) {
1696 $s = str_replace( '\\', '\\\\', $s );
1697 $s = $this->strencode( $s );
1698 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
1704 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
1705 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
1706 * Alternatively, the function could be provided with an array of aforementioned parameters.
1708 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
1709 * for subpages of 'My page title'.
1710 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
1713 * @return String: fully built LIKE statement
1715 function buildLike() {
1716 $params = func_get_args();
1718 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
1719 $params = $params[0];
1724 foreach ( $params as $value ) {
1725 if ( $value instanceof LikeMatch
) {
1726 $s .= $value->toString();
1728 $s .= $this->escapeLikeInternal( $value );
1732 return " LIKE '" . $s . "' ";
1736 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
1738 function anyChar() {
1739 return new LikeMatch( '_' );
1743 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
1745 function anyString() {
1746 return new LikeMatch( '%' );
1750 * Returns an appropriately quoted sequence value for inserting a new row.
1751 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1752 * subclass will return an integer, and save the value for insertId()
1754 function nextSequenceValue( $seqName ) {
1759 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
1760 * is only needed because a) MySQL must be as efficient as possible due to
1761 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
1762 * which index to pick. Anyway, other databases might have different
1763 * indexes on a given table. So don't bother overriding this unless you're
1766 function useIndexClause( $index ) {
1771 * REPLACE query wrapper
1772 * PostgreSQL simulates this with a DELETE followed by INSERT
1773 * $row is the row to insert, an associative array
1774 * $uniqueIndexes is an array of indexes. Each element may be either a
1775 * field name or an array of field names
1777 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1778 * However if you do this, you run the risk of encountering errors which wouldn't have
1781 * @param $table String: The table to replace the row(s) in.
1782 * @param $uniqueIndexes Array: An associative array of indexes
1783 * @param $rows Array: Array of rows to replace
1784 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1786 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
1787 $table = $this->tableName( $table );
1790 if ( !is_array( reset( $rows ) ) ) {
1791 $rows = array( $rows );
1794 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
1797 foreach ( $rows as $row ) {
1804 $sql .= '(' . $this->makeList( $row ) . ')';
1807 return $this->query( $sql, $fname );
1811 * DELETE where the condition is a join
1812 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1814 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1815 * join condition matches, set $conds='*'
1817 * DO NOT put the join condition in $conds
1819 * @param $delTable String: The table to delete from.
1820 * @param $joinTable String: The other table.
1821 * @param $delVar String: The variable to join on, in the first table.
1822 * @param $joinVar String: The variable to join on, in the second table.
1823 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
1824 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1826 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseBase::deleteJoin' ) {
1828 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
1831 $delTable = $this->tableName( $delTable );
1832 $joinTable = $this->tableName( $joinTable );
1833 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1835 if ( $conds != '*' ) {
1836 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1839 return $this->query( $sql, $fname );
1843 * Returns the size of a text field, or -1 for "unlimited"
1845 function textFieldSize( $table, $field ) {
1846 $table = $this->tableName( $table );
1847 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1848 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
1849 $row = $this->fetchObject( $res );
1853 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1863 * A string to insert into queries to show that they're low-priority, like
1864 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
1865 * string and nothing bad should happen.
1867 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1869 function lowPriorityOption() {
1874 * DELETE query wrapper
1876 * Use $conds == "*" to delete all rows
1878 function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
1880 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
1883 $table = $this->tableName( $table );
1884 $sql = "DELETE FROM $table";
1886 if ( $conds != '*' ) {
1887 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1890 return $this->query( $sql, $fname );
1894 * INSERT SELECT wrapper
1895 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1896 * Source items may be literals rather than field names, but strings should be quoted with DatabaseBase::addQuotes()
1897 * $conds may be "*" to copy the whole table
1898 * srcTable may be an array of tables.
1900 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseBase::insertSelect',
1901 $insertOptions = array(), $selectOptions = array() )
1903 $destTable = $this->tableName( $destTable );
1905 if ( is_array( $insertOptions ) ) {
1906 $insertOptions = implode( ' ', $insertOptions );
1909 if ( !is_array( $selectOptions ) ) {
1910 $selectOptions = array( $selectOptions );
1913 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1915 if ( is_array( $srcTable ) ) {
1916 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1918 $srcTable = $this->tableName( $srcTable );
1921 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1922 " SELECT $startOpts " . implode( ',', $varMap ) .
1923 " FROM $srcTable $useIndex ";
1925 if ( $conds != '*' ) {
1926 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1929 $sql .= " $tailOpts";
1931 return $this->query( $sql, $fname );
1935 * Construct a LIMIT query with optional offset. This is used for query
1936 * pages. The SQL should be adjusted so that only the first $limit rows
1937 * are returned. If $offset is provided as well, then the first $offset
1938 * rows should be discarded, and the next $limit rows should be returned.
1939 * If the result of the query is not ordered, then the rows to be returned
1940 * are theoretically arbitrary.
1942 * $sql is expected to be a SELECT, if that makes a difference. For
1943 * UPDATE, limitResultForUpdate should be used.
1945 * The version provided by default works in MySQL and SQLite. It will very
1946 * likely need to be overridden for most other DBMSes.
1948 * @param $sql String: SQL query we will append the limit too
1949 * @param $limit Integer: the SQL limit
1950 * @param $offset Integer the SQL offset (default false)
1952 function limitResult( $sql, $limit, $offset = false ) {
1953 if ( !is_numeric( $limit ) ) {
1954 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1957 return "$sql LIMIT "
1958 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
1962 function limitResultForUpdate( $sql, $num ) {
1963 return $this->limitResult( $sql, $num, 0 );
1967 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
1968 * within the UNION construct.
1971 function unionSupportsOrderAndLimit() {
1972 return true; // True for almost every DB supported
1976 * Construct a UNION query
1977 * This is used for providing overload point for other DB abstractions
1978 * not compatible with the MySQL syntax.
1979 * @param $sqls Array: SQL statements to combine
1980 * @param $all Boolean: use UNION ALL
1981 * @return String: SQL fragment
1983 function unionQueries( $sqls, $all ) {
1984 $glue = $all ?
') UNION ALL (' : ') UNION (';
1985 return '(' . implode( $glue, $sqls ) . ')';
1989 * Returns an SQL expression for a simple conditional. This doesn't need
1990 * to be overridden unless CASE isn't supported in your DBMS.
1992 * @param $cond String: SQL expression which will result in a boolean value
1993 * @param $trueVal String: SQL expression to return if true
1994 * @param $falseVal String: SQL expression to return if false
1995 * @return String: SQL fragment
1997 function conditional( $cond, $trueVal, $falseVal ) {
1998 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2002 * Returns a comand for str_replace function in SQL query.
2003 * Uses REPLACE() in MySQL
2005 * @param $orig String: column to modify
2006 * @param $old String: column to seek
2007 * @param $new String: column to replace with
2009 function strreplace( $orig, $old, $new ) {
2010 return "REPLACE({$orig}, {$old}, {$new})";
2014 * Determines if the last failure was due to a deadlock
2017 function wasDeadlock() {
2022 * Determines if the last query error was something that should be dealt
2023 * with by pinging the connection and reissuing the query.
2026 function wasErrorReissuable() {
2031 * Determines if the last failure was due to the database being read-only.
2034 function wasReadOnlyError() {
2039 * Perform a deadlock-prone transaction.
2041 * This function invokes a callback function to perform a set of write
2042 * queries. If a deadlock occurs during the processing, the transaction
2043 * will be rolled back and the callback function will be called again.
2046 * $dbw->deadlockLoop( callback, ... );
2048 * Extra arguments are passed through to the specified callback function.
2050 * Returns whatever the callback function returned on its successful,
2051 * iteration, or false on error, for example if the retry limit was
2054 function deadlockLoop() {
2055 $myFname = 'DatabaseBase::deadlockLoop';
2058 $args = func_get_args();
2059 $function = array_shift( $args );
2060 $oldIgnore = $this->ignoreErrors( true );
2061 $tries = DEADLOCK_TRIES
;
2063 if ( is_array( $function ) ) {
2064 $fname = $function[0];
2070 $retVal = call_user_func_array( $function, $args );
2071 $error = $this->lastError();
2072 $errno = $this->lastErrno();
2073 $sql = $this->lastQuery();
2076 if ( $this->wasDeadlock() ) {
2078 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
2080 $this->reportQueryError( $error, $errno, $sql, $fname );
2083 } while ( $this->wasDeadlock() && --$tries > 0 );
2085 $this->ignoreErrors( $oldIgnore );
2087 if ( $tries <= 0 ) {
2088 $this->rollback( $myFname );
2089 $this->reportQueryError( $error, $errno, $sql, $fname );
2092 $this->commit( $myFname );
2098 * Do a SELECT MASTER_POS_WAIT()
2100 * @param $pos MySQLMasterPos object
2101 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
2103 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
2104 $fname = 'DatabaseBase::masterPosWait';
2105 wfProfileIn( $fname );
2107 # Commit any open transactions
2108 if ( $this->mTrxLevel
) {
2112 if ( !is_null( $this->mFakeSlaveLag
) ) {
2113 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
2115 if ( $wait > $timeout * 1e6
) {
2116 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
2117 wfProfileOut( $fname );
2119 } elseif ( $wait > 0 ) {
2120 wfDebug( "Fake slave waiting $wait us\n" );
2122 wfProfileOut( $fname );
2125 wfDebug( "Fake slave up to date ($wait us)\n" );
2126 wfProfileOut( $fname );
2131 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
2132 $encFile = $this->addQuotes( $pos->file
);
2133 $encPos = intval( $pos->pos
);
2134 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
2135 $res = $this->doQuery( $sql );
2137 if ( $res && $row = $this->fetchRow( $res ) ) {
2138 wfProfileOut( $fname );
2141 wfProfileOut( $fname );
2147 * Get the position of the master from SHOW SLAVE STATUS
2149 function getSlavePos() {
2150 if ( !is_null( $this->mFakeSlaveLag
) ) {
2151 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
2152 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
2156 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
2157 $row = $this->fetchObject( $res );
2160 $pos = isset( $row->Exec_master_log_pos
) ?
$row->Exec_master_log_pos
: $row->Exec_Master_Log_Pos
;
2161 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
2168 * Get the position of the master from SHOW MASTER STATUS
2170 function getMasterPos() {
2171 if ( $this->mFakeMaster
) {
2172 return new MySQLMasterPos( 'fake', microtime( true ) );
2175 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
2176 $row = $this->fetchObject( $res );
2179 return new MySQLMasterPos( $row->File
, $row->Position
);
2186 * Begin a transaction, committing any previously open transaction
2188 function begin( $fname = 'DatabaseBase::begin' ) {
2189 $this->query( 'BEGIN', $fname );
2190 $this->mTrxLevel
= 1;
2196 function commit( $fname = 'DatabaseBase::commit' ) {
2197 if ( $this->mTrxLevel
) {
2198 $this->query( 'COMMIT', $fname );
2199 $this->mTrxLevel
= 0;
2204 * Rollback a transaction.
2205 * No-op on non-transactional databases.
2207 function rollback( $fname = 'DatabaseBase::rollback' ) {
2208 if ( $this->mTrxLevel
) {
2209 $this->query( 'ROLLBACK', $fname, true );
2210 $this->mTrxLevel
= 0;
2215 * Begin a transaction, committing any previously open transaction
2216 * @deprecated use begin()
2218 function immediateBegin( $fname = 'DatabaseBase::immediateBegin' ) {
2219 wfDeprecated( __METHOD__
);
2224 * Commit transaction, if one is open
2225 * @deprecated use commit()
2227 function immediateCommit( $fname = 'DatabaseBase::immediateCommit' ) {
2228 wfDeprecated( __METHOD__
);
2233 * Creates a new table with structure copied from existing table
2234 * Note that unlike most database abstraction functions, this function does not
2235 * automatically append database prefix, because it works at a lower
2236 * abstraction level.
2238 * @param $oldName String: name of table whose structure should be copied
2239 * @param $newName String: name of table to be created
2240 * @param $temporary Boolean: whether the new table should be temporary
2241 * @param $fname String: calling function name
2242 * @return Boolean: true if operation was successful
2244 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseBase::duplicateTableStructure' ) {
2245 throw new MWException( 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2249 * Return MW-style timestamp used for MySQL schema
2251 function timestamp( $ts = 0 ) {
2252 return wfTimestamp( TS_MW
, $ts );
2256 * Local database timestamp format or null
2258 function timestampOrNull( $ts = null ) {
2259 if ( is_null( $ts ) ) {
2262 return $this->timestamp( $ts );
2269 function resultObject( $result ) {
2270 if ( empty( $result ) ) {
2272 } elseif ( $result instanceof ResultWrapper
) {
2274 } elseif ( $result === true ) {
2275 // Successful write query
2278 return new ResultWrapper( $this, $result );
2283 * Return aggregated value alias
2285 function aggregateValue ( $valuedata, $valuename = 'value' ) {
2290 * Ping the server and try to reconnect if it there is no connection
2292 * @return bool Success or failure
2295 # Stub. Not essential to override.
2301 * Currently supported only by MySQL
2302 * @return Database replication lag in seconds
2305 return $this->mFakeSlaveLag
;
2309 * Get status information from SHOW STATUS in an associative array
2311 function getStatus( $which = "%" ) {
2312 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2315 while ( $row = $this->fetchObject( $res ) ) {
2316 $status[$row->Variable_name
] = $row->Value
;
2323 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2325 function maxListLen() {
2329 function encodeBlob( $b ) {
2333 function decodeBlob( $b ) {
2338 * Override database's default connection timeout. May be useful for very
2339 * long batch queries such as full-wiki dumps, where a single query reads
2340 * out over hours or days. May or may not be necessary for non-MySQL
2341 * databases. For most purposes, leaving it as a no-op should be fine.
2343 * @param $timeout Integer in seconds
2345 public function setTimeout( $timeout ) {}
2348 * Read and execute SQL commands from a file.
2349 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2350 * @param $filename String: File name to open
2351 * @param $lineCallback Callback: Optional function called before reading each line
2352 * @param $resultCallback Callback: Optional function called for each MySQL result
2353 * @param $fname String: Calling function name or false if name should be generated dynamically
2356 function sourceFile( $filename, $lineCallback = false, $resultCallback = false, $fname = false ) {
2357 $fp = fopen( $filename, 'r' );
2359 if ( false === $fp ) {
2360 if ( !defined( "MEDIAWIKI_INSTALL" ) )
2361 throw new MWException( "Could not open \"{$filename}\".\n" );
2363 return "Could not open \"{$filename}\".\n";
2367 $fname = __METHOD__
. "( $filename )";
2371 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname );
2373 catch ( MWException
$e ) {
2374 if ( defined( "MEDIAWIKI_INSTALL" ) ) {
2375 $error = $e->getMessage();
2388 * Get the full path of a patch file. Originally based on archive()
2389 * from updaters.inc. Keep in mind this always returns a patch, as
2390 * it fails back to MySQL if no DB-specific patch can be found
2392 * @param $patch String The name of the patch, like patch-something.sql
2393 * @return String Full path to patch file
2395 public static function patchPath( $patch ) {
2396 global $wgDBtype, $IP;
2398 if ( file_exists( "$IP/maintenance/$wgDBtype/archives/$patch" ) ) {
2399 return "$IP/maintenance/$wgDBtype/archives/$patch";
2401 return "$IP/maintenance/archives/$patch";
2406 * Read and execute commands from an open file handle
2407 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2408 * @param $fp String: File handle
2409 * @param $lineCallback Callback: Optional function called before reading each line
2410 * @param $resultCallback Callback: Optional function called for each MySQL result
2411 * @param $fname String: Calling function name
2413 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseBase::sourceStream' ) {
2416 $dollarquote = false;
2418 while ( ! feof( $fp ) ) {
2419 if ( $lineCallback ) {
2420 call_user_func( $lineCallback );
2423 $line = trim( fgets( $fp, 1024 ) );
2424 $sl = strlen( $line ) - 1;
2430 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
2434 # # Allow dollar quoting for function declarations
2435 if ( substr( $line, 0, 4 ) == '$mw$' ) {
2436 if ( $dollarquote ) {
2437 $dollarquote = false;
2441 $dollarquote = true;
2444 else if ( !$dollarquote ) {
2445 if ( ';' == $line { $sl } && ( $sl < 2 ||
';' != $line { $sl - 1 } ) ) {
2447 $line = substr( $line, 0, $sl );
2458 $cmd = str_replace( ';;', ";", $cmd );
2459 $cmd = $this->replaceVars( $cmd );
2460 $res = $this->query( $cmd, $fname );
2462 if ( $resultCallback ) {
2463 call_user_func( $resultCallback, $res, $this );
2466 if ( false === $res ) {
2467 $err = $this->lastError();
2468 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2480 * Replace variables in sourced SQL
2482 protected function replaceVars( $ins ) {
2484 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2485 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2486 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2489 // Ordinary variables
2490 foreach ( $varnames as $var ) {
2491 if ( isset( $GLOBALS[$var] ) ) {
2492 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2493 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2494 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2495 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2500 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2501 array( $this, 'tableNameCallback' ), $ins );
2504 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2505 array( $this, 'indexNameCallback' ), $ins );
2511 * Table name callback
2514 protected function tableNameCallback( $matches ) {
2515 return $this->tableName( $matches[1] );
2519 * Index name callback
2521 protected function indexNameCallback( $matches ) {
2522 return $this->indexName( $matches[1] );
2526 * Build a concatenation list to feed into a SQL query
2527 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
2530 function buildConcat( $stringList ) {
2531 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2535 * Acquire a named lock
2537 * Abstracted from Filestore::lock() so child classes can implement for
2540 * @param $lockName String: name of lock to aquire
2541 * @param $method String: name of method calling us
2542 * @param $timeout Integer: timeout
2545 public function lock( $lockName, $method, $timeout = 5 ) {
2552 * @param $lockName String: Name of lock to release
2553 * @param $method String: Name of method calling us
2555 * @return Returns 1 if the lock was released, 0 if the lock was not established
2556 * by this thread (in which case the lock is not released), and NULL if the named
2557 * lock did not exist
2559 public function unlock( $lockName, $method ) {
2564 * Lock specific tables
2566 * @param $read Array of tables to lock for read access
2567 * @param $write Array of tables to lock for write access
2568 * @param $method String name of caller
2569 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
2571 public function lockTables( $read, $write, $method, $lowPriority = true ) {
2576 * Unlock specific tables
2578 * @param $method String the caller
2580 public function unlockTables( $method ) {
2585 * Get search engine class. All subclasses of this need to implement this
2586 * if they wish to use searching.
2590 public function getSearchEngine() {
2591 return 'SearchEngineDummy';
2595 * Allow or deny "big selects" for this session only. This is done by setting
2596 * the sql_big_selects session variable.
2598 * This is a MySQL-specific feature.
2600 * @param $value Mixed: true for allow, false for deny, or "default" to restore the initial value
2602 public function setBigSelects( $value = true ) {
2607 /******************************************************************************
2609 *****************************************************************************/
2618 function __construct( $data ) {
2619 $this->mData
= $data;
2627 return $this->mData
;
2635 * This allows us to distinguish a blob from a normal string and an array of strings
2640 function __construct( $data ) {
2641 $this->mData
= $data;
2645 return $this->mData
;
2654 private $name, $tablename, $default, $max_length, $nullable,
2655 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2657 function __construct ( $info ) {
2658 $this->name
= $info->name
;
2659 $this->tablename
= $info->table
;
2660 $this->default = $info->def
;
2661 $this->max_length
= $info->max_length
;
2662 $this->nullable
= !$info->not_null
;
2663 $this->is_pk
= $info->primary_key
;
2664 $this->is_unique
= $info->unique_key
;
2665 $this->is_multiple
= $info->multiple_key
;
2666 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
2667 $this->type
= $info->type
;
2674 function tableName() {
2675 return $this->tableName
;
2678 function defaultValue() {
2679 return $this->default;
2682 function maxLength() {
2683 return $this->max_length
;
2686 function nullable() {
2687 return $this->nullable
;
2691 return $this->is_key
;
2694 function isMultipleKey() {
2695 return $this->is_multiple
;
2703 /******************************************************************************
2705 *****************************************************************************/
2708 * Database error base class
2711 class DBError
extends MWException
{
2715 * Construct a database error
2716 * @param $db Database object which threw the error
2717 * @param $error A simple error message to be used for debugging
2719 function __construct( DatabaseBase
&$db, $error ) {
2721 parent
::__construct( $error );
2724 function getText() {
2725 global $wgShowDBErrorBacktrace;
2727 $s = $this->getMessage() . "\n";
2729 if ( $wgShowDBErrorBacktrace ) {
2730 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2740 class DBConnectionError
extends DBError
{
2743 function __construct( DatabaseBase
&$db, $error = 'unknown error' ) {
2744 $msg = 'DB connection error';
2746 if ( trim( $error ) != '' ) {
2750 $this->error
= $error;
2752 parent
::__construct( $db, $msg );
2755 function useOutputPage() {
2756 // Not likely to work
2760 function useMessageCache() {
2761 // Not likely to work
2765 function getLogMessage() {
2766 # Don't send to the exception log
2770 function getPageTitle() {
2771 global $wgSitename, $wgLang;
2773 $header = "$wgSitename has a problem";
2775 if ( $wgLang instanceof Language
) {
2776 $header = htmlspecialchars( $wgLang->getMessage( 'dberr-header' ) );
2782 function getHTML() {
2783 global $wgLang, $wgMessageCache, $wgUseFileCache, $wgShowDBErrorBacktrace;
2785 $sorry = 'Sorry! This site is experiencing technical difficulties.';
2786 $again = 'Try waiting a few minutes and reloading.';
2787 $info = '(Can\'t contact the database server: $1)';
2789 if ( $wgLang instanceof Language
) {
2790 $sorry = htmlspecialchars( $wgLang->getMessage( 'dberr-problems' ) );
2791 $again = htmlspecialchars( $wgLang->getMessage( 'dberr-again' ) );
2792 $info = htmlspecialchars( $wgLang->getMessage( 'dberr-info' ) );
2795 # No database access
2796 if ( is_object( $wgMessageCache ) ) {
2797 $wgMessageCache->disable();
2800 if ( trim( $this->error
) == '' ) {
2801 $this->error
= $this->db
->getProperty( 'mServer' );
2804 $noconnect = "<p><strong>$sorry</strong><br />$again</p><p><small>$info</small></p>";
2805 $text = str_replace( '$1', $this->error
, $noconnect );
2807 if ( $wgShowDBErrorBacktrace ) {
2808 $text .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2811 $extra = $this->searchForm();
2813 if ( $wgUseFileCache ) {
2815 $cache = $this->fileCachedPage();
2816 # Cached version on file system?
2817 if ( $cache !== null ) {
2818 # Hack: extend the body for error messages
2819 $cache = str_replace( array( '</html>', '</body>' ), '', $cache );
2820 # Add cache notice...
2821 $cachederror = "This is a cached copy of the requested page, and may not be up to date. ";
2823 # Localize it if possible...
2824 if ( $wgLang instanceof Language
) {
2825 $cachederror = htmlspecialchars( $wgLang->getMessage( 'dberr-cachederror' ) );
2828 $warning = "<div style='color:red;font-size:150%;font-weight:bold;'>$cachederror</div>";
2830 # Output cached page with notices on bottom and re-close body
2831 return "{$cache}{$warning}<hr />$text<hr />$extra</body></html>";
2833 } catch ( MWException
$e ) {
2834 // Do nothing, just use the default page
2838 # Headers needed here - output is just the error message
2839 return $this->htmlHeader() . "$text<hr />$extra" . $this->htmlFooter();
2842 function searchForm() {
2843 global $wgSitename, $wgServer, $wgLang, $wgInputEncoding;
2845 $usegoogle = "You can try searching via Google in the meantime.";
2846 $outofdate = "Note that their indexes of our content may be out of date.";
2847 $googlesearch = "Search";
2849 if ( $wgLang instanceof Language
) {
2850 $usegoogle = htmlspecialchars( $wgLang->getMessage( 'dberr-usegoogle' ) );
2851 $outofdate = htmlspecialchars( $wgLang->getMessage( 'dberr-outofdate' ) );
2852 $googlesearch = htmlspecialchars( $wgLang->getMessage( 'searchbutton' ) );
2855 $search = htmlspecialchars( @$_REQUEST['search'] );
2858 <div style="margin: 1.5em">$usegoogle<br />
2859 <small>$outofdate</small></div>
2860 <!-- SiteSearch Google -->
2861 <form method="get" action="http://www.google.com/search" id="googlesearch">
2862 <input type="hidden" name="domains" value="$wgServer" />
2863 <input type="hidden" name="num" value="50" />
2864 <input type="hidden" name="ie" value="$wgInputEncoding" />
2865 <input type="hidden" name="oe" value="$wgInputEncoding" />
2867 <input type="text" name="q" size="31" maxlength="255" value="$search" />
2868 <input type="submit" name="btnG" value="$googlesearch" />
2870 <input type="radio" name="sitesearch" id="gwiki" value="$wgServer" checked="checked" /><label for="gwiki">$wgSitename</label>
2871 <input type="radio" name="sitesearch" id="gWWW" value="" /><label for="gWWW">WWW</label>
2874 <!-- SiteSearch Google -->
2879 function fileCachedPage() {
2880 global $wgTitle, $title, $wgLang, $wgOut;
2882 if ( $wgOut->isDisabled() ) {
2883 return; // Done already?
2886 $mainpage = 'Main Page';
2888 if ( $wgLang instanceof Language
) {
2889 $mainpage = htmlspecialchars( $wgLang->getMessage( 'mainpage' ) );
2894 } elseif ( $title ) {
2895 $t = Title
::newFromURL( $title );
2897 $t = Title
::newFromText( $mainpage );
2900 $cache = new HTMLFileCache( $t );
2901 if ( $cache->isFileCached() ) {
2902 return $cache->fetchPageText();
2908 function htmlBodyOnly() {
2916 class DBQueryError
extends DBError
{
2917 public $error, $errno, $sql, $fname;
2919 function __construct( DatabaseBase
&$db, $error, $errno, $sql, $fname ) {
2920 $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" .
2922 "Function: $fname\n" .
2923 "Error: $errno $error\n";
2925 parent
::__construct( $db, $message );
2927 $this->error
= $error;
2928 $this->errno
= $errno;
2930 $this->fname
= $fname;
2933 function getText() {
2934 global $wgShowDBErrorBacktrace;
2936 if ( $this->useMessageCache() ) {
2937 $s = wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2938 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
2940 if ( $wgShowDBErrorBacktrace ) {
2941 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2946 return parent
::getText();
2951 global $wgShowSQLErrors;
2953 if ( !$wgShowSQLErrors ) {
2954 return $this->msg( 'sqlhidden', 'SQL hidden' );
2960 function getLogMessage() {
2961 # Don't send to the exception log
2965 function getPageTitle() {
2966 return $this->msg( 'databaseerror', 'Database error' );
2969 function getHTML() {
2970 global $wgShowDBErrorBacktrace;
2972 if ( $this->useMessageCache() ) {
2973 $s = wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2974 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
2976 $s = nl2br( htmlspecialchars( $this->getMessage() ) );
2979 if ( $wgShowDBErrorBacktrace ) {
2980 $s .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2990 class DBUnexpectedError
extends DBError
{}
2994 * Result wrapper for grabbing data queried by someone else
2997 class ResultWrapper
implements Iterator
{
2998 var $db, $result, $pos = 0, $currentRow = null;
3001 * Create a new result object from a result resource and a Database object
3003 function __construct( $database, $result ) {
3004 $this->db
= $database;
3006 if ( $result instanceof ResultWrapper
) {
3007 $this->result
= $result->result
;
3009 $this->result
= $result;
3014 * Get the number of rows in a result object
3016 function numRows() {
3017 return $this->db
->numRows( $this );
3021 * Fetch the next row from the given result object, in object form.
3022 * Fields can be retrieved with $row->fieldname, with fields acting like
3025 * @return MySQL row object
3026 * @throws DBUnexpectedError Thrown if the database returns an error
3028 function fetchObject() {
3029 return $this->db
->fetchObject( $this );
3033 * Fetch the next row from the given result object, in associative array
3034 * form. Fields are retrieved with $row['fieldname'].
3036 * @return MySQL row object
3037 * @throws DBUnexpectedError Thrown if the database returns an error
3039 function fetchRow() {
3040 return $this->db
->fetchRow( $this );
3044 * Free a result object
3047 $this->db
->freeResult( $this );
3048 unset( $this->result
);
3053 * Change the position of the cursor in a result object
3054 * See mysql_data_seek()
3056 function seek( $row ) {
3057 $this->db
->dataSeek( $this, $row );
3060 /*********************
3061 * Iterator functions
3062 * Note that using these in combination with the non-iterator functions
3063 * above may cause rows to be skipped or repeated.
3067 if ( $this->numRows() ) {
3068 $this->db
->dataSeek( $this, 0 );
3071 $this->currentRow
= null;
3074 function current() {
3075 if ( is_null( $this->currentRow
) ) {
3078 return $this->currentRow
;
3087 $this->currentRow
= $this->fetchObject();
3088 return $this->currentRow
;
3092 return $this->current() !== false;
3097 * Overloads the relevant methods of the real ResultsWrapper so it
3098 * doesn't go anywhere near an actual database.
3100 class FakeResultWrapper
extends ResultWrapper
{
3101 var $result = array();
3102 var $db = null; // And it's going to stay that way :D
3104 var $currentRow = null;
3106 function __construct( $array ) {
3107 $this->result
= $array;
3110 function numRows() {
3111 return count( $this->result
);
3114 function fetchRow() {
3115 $this->currentRow
= $this->result
[$this->pos++
];
3116 return $this->currentRow
;
3119 function seek( $row ) {
3125 // Callers want to be able to access fields with $this->fieldName
3126 function fetchObject() {
3127 $this->currentRow
= $this->result
[$this->pos++
];
3128 return (object)$this->currentRow
;
3133 $this->currentRow
= null;
3138 * Used by DatabaseBase::buildLike() to represent characters that have special meaning in SQL LIKE clauses
3139 * and thus need no escaping. Don't instantiate it manually, use DatabaseBase::anyChar() and anyString() instead.
3144 public function __construct( $s ) {
3148 public function toString() {